@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
@@ -113,7 +113,7 @@ export function escapeSeatbeltPath(rawPath: string): string | null {
113
113
 
114
114
  function resolveCanonicalPaths(rawPath: string): string[] {
115
115
  const resolved = path.resolve(rawPath);
116
- const out = new Set<string>([resolved]);
116
+ const out = new Set<string>();
117
117
  try {
118
118
  const real = fs.realpathSync.native(resolved);
119
119
  out.add(real);
@@ -135,6 +135,7 @@ function resolveCanonicalPaths(rawPath: string): string[] {
135
135
  }
136
136
  }
137
137
  }
138
+ out.add(resolved);
138
139
  return [...out];
139
140
  }
140
141
 
@@ -318,9 +319,9 @@ export function buildSeatbeltProfile(options: OsSandboxWrapOptions): string {
318
319
  const mode = options.mode ?? 'workspace-write';
319
320
  const homeDir = options.homeDir ?? os.homedir();
320
321
  const tmpDir = options.tmpDir ?? os.tmpdir();
321
- const workspaces = options.workspaceRoots && options.workspaceRoots.length > 0
322
- ? [...options.workspaceRoots, options.cwd]
323
- : [options.cwd];
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];
324
325
 
325
326
  const lines: string[] = [
326
327
  '(version 1)',
@@ -435,9 +436,9 @@ export function buildBubblewrapArgs(
435
436
  ): string[] {
436
437
  const mode = options.mode ?? 'workspace-write';
437
438
  const homeDir = options.homeDir ?? os.homedir();
438
- const workspaces = options.workspaceRoots && options.workspaceRoots.length > 0
439
- ? [...options.workspaceRoots, options.cwd]
440
- : [options.cwd];
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];
441
442
 
442
443
  const args: string[] = [
443
444
  '--die-with-parent',
@@ -472,21 +473,54 @@ export function buildBubblewrapArgs(
472
473
  bindIfExists(path.join(homeDir, rel));
473
474
  }
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);
475
490
  }
476
491
 
477
- // Mask existing credential directories with empty tmpfs mounts unless inside selected workspace
478
- if (homeDir) {
479
- for (const rel of ['.ssh', '.aws', '.gnupg', '.kube', '.causyne']) {
480
- const full = path.join(homeDir, rel);
481
- if (workspaceOverlapsPath(workspaces, full)) continue;
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;
482
497
  try {
483
- if (fs.existsSync(full) && fs.statSync(full).isDirectory()) {
484
- args.push('--tmpfs', full);
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);
485
505
  }
486
506
  } catch {
487
507
  continue;
488
508
  }
489
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
+ }
490
524
  }
491
525
 
492
526
  args.push('--chdir', path.resolve(options.cwd), '--', shell, ...shellArgs);
@@ -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
  }
@@ -43,12 +43,15 @@ export function detectMagicFormat(buffer: Buffer): string | null {
43
43
 
44
44
  // Audio
45
45
  if (hex.startsWith('52494646') && buffer.length >= 12 && buffer.toString('ascii', 8, 12) === 'WAVE') return 'wav';
46
- if (hex.startsWith('494433') || hex.startsWith('FFF3') || hex.startsWith('FFF2') || hex.startsWith('FFE3')) return 'mp3';
46
+ if (hex.startsWith('494433') || hex.startsWith('FFFB') || hex.startsWith('FFFA') || hex.startsWith('FFF3') || hex.startsWith('FFF2') || hex.startsWith('FFE3')) return 'mp3';
47
47
 
48
- // Video: box size followed by 'ftyp' or 'moov'
48
+ // Video: valid ISO BMFF box size followed by 'ftyp', 'moov', 'mdat', or 'free'
49
49
  if (buffer.length >= 8) {
50
+ const boxSize = buffer.readUInt32BE(0);
50
51
  const boxType = buffer.toString('ascii', 4, 8);
51
- if (['ftyp', 'moov', 'mdat', 'free'].includes(boxType)) return 'mp4';
52
+ // Reject printable ASCII prefixes (>= 0x20000000) while accepting header-only MP4 slices
53
+ const validBoxSize = boxSize === 0 || boxSize === 1 || (boxSize >= 8 && boxSize < 0x20000000);
54
+ if (validBoxSize && ['ftyp', 'moov', 'mdat', 'free'].includes(boxType)) return 'mp4';
52
55
  }
53
56
 
54
57
  return null;
@@ -60,7 +63,14 @@ export function validateMediaPayload(
60
63
  limits: Partial<PayloadLimits> = {}
61
64
  ): MediaValidationResult {
62
65
  const byteLength = buffer.length;
63
- const activeLimits: PayloadLimits = { ...DEFAULT_PAYLOAD_LIMITS, ...limits };
66
+ const safeLimit = (value: number | undefined, fallback: number): number =>
67
+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;
68
+ const activeLimits: PayloadLimits = {
69
+ maxImageBytes: safeLimit(limits.maxImageBytes, DEFAULT_PAYLOAD_LIMITS.maxImageBytes),
70
+ maxAudioBytes: safeLimit(limits.maxAudioBytes, DEFAULT_PAYLOAD_LIMITS.maxAudioBytes),
71
+ maxVideoBytes: safeLimit(limits.maxVideoBytes, DEFAULT_PAYLOAD_LIMITS.maxVideoBytes),
72
+ maxTextChars: safeLimit(limits.maxTextChars, DEFAULT_PAYLOAD_LIMITS.maxTextChars)
73
+ };
64
74
 
65
75
  let maxAllowed = activeLimits.maxImageBytes;
66
76
  if (kind === 'audio') maxAllowed = activeLimits.maxAudioBytes;
@@ -106,8 +116,29 @@ export function validateMediaPayload(
106
116
  }
107
117
 
108
118
  export function sanitizeTextPayload(text: string, maxChars: number = DEFAULT_PAYLOAD_LIMITS.maxTextChars): string {
109
- if (text.length <= maxChars) return text;
110
- const half = Math.floor(maxChars / 2);
111
- const omitted = text.length - maxChars;
112
- return text.slice(0, half) + `\n[... ${omitted} characters sanitized to protect context budget ...]\n` + text.slice(-half);
119
+ const limit = Number.isFinite(maxChars) ? Math.floor(maxChars) : DEFAULT_PAYLOAD_LIMITS.maxTextChars;
120
+ if (limit <= 0) return '';
121
+ if (text.length <= limit) return text;
122
+ const buildMarker = (count: number): string =>
123
+ `\n[... ${count} characters sanitized to protect context budget ...]\n`;
124
+ let marker = buildMarker(text.length);
125
+ if (limit <= marker.length) return text.slice(0, limit);
126
+ let keep = limit - marker.length;
127
+ let headLen = Math.ceil(keep / 2);
128
+ let tailLen = Math.floor(keep / 2);
129
+ let omitted = text.length - headLen - tailLen;
130
+ marker = buildMarker(omitted);
131
+ if (limit <= marker.length) return text.slice(0, limit);
132
+ keep = limit - marker.length;
133
+ headLen = Math.ceil(keep / 2);
134
+ tailLen = Math.floor(keep / 2);
135
+ omitted = text.length - headLen - tailLen;
136
+ const finalMarker = buildMarker(omitted);
137
+ if (headLen + finalMarker.length + tailLen > limit) {
138
+ const excess = headLen + finalMarker.length + tailLen - limit;
139
+ tailLen = Math.max(0, tailLen - excess);
140
+ omitted = text.length - headLen - tailLen;
141
+ }
142
+ const tail = tailLen > 0 ? text.slice(-tailLen) : '';
143
+ return text.slice(0, headLen) + buildMarker(omitted) + tail;
113
144
  }
@@ -6,6 +6,8 @@
6
6
  * a prompt; it never chooses the raw executable or unrestricted arguments.
7
7
  * Those come from the catalog presets or the user's `~/.causyne/peers.json`.
8
8
  */
9
+ import crypto from 'node:crypto';
10
+ import fs from 'node:fs';
9
11
  import path from 'node:path';
10
12
  import { execFile } from 'node:child_process';
11
13
  import { promisify } from 'node:util';
@@ -15,7 +17,37 @@ import { BUILTIN_PEER_PRESETS } from '../acp/agentCatalog.js';
15
17
  const execFileAsync = promisify(execFile);
16
18
  const MAX_PROMPT_CHARS = 2_000_000;
17
19
  const READ_ONLY_KINDS = new Set(['read', 'search', 'fetch', 'think']);
18
- function selectPermission(profile, request, workspaceRoot) {
20
+ function resolveCanonicalPath(target) {
21
+ const resolved = path.resolve(target);
22
+ try {
23
+ return fs.realpathSync(resolved);
24
+ }
25
+ catch {
26
+ let current = resolved;
27
+ const missing = [];
28
+ for (let depth = 0; depth < 64; depth++) {
29
+ const parent = path.dirname(current);
30
+ if (parent === current)
31
+ break;
32
+ missing.unshift(path.basename(current));
33
+ current = parent;
34
+ try {
35
+ return path.join(fs.realpathSync(current), ...missing);
36
+ }
37
+ catch {
38
+ continue;
39
+ }
40
+ }
41
+ return resolved;
42
+ }
43
+ }
44
+ function isWithinWorkspaceRoot(workspaceRoot, candidatePath) {
45
+ const canonicalRoot = resolveCanonicalPath(workspaceRoot);
46
+ const canonicalTarget = resolveCanonicalPath(path.resolve(canonicalRoot, candidatePath));
47
+ const rel = path.relative(canonicalRoot, canonicalTarget);
48
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
49
+ }
50
+ async function selectPermission(profile, request, workspaceRoot, context) {
19
51
  const kind = request.toolCall.kind;
20
52
  const readLike = typeof kind === 'string' && READ_ONLY_KINDS.has(kind);
21
53
  if (profile.policy === 'read-only') {
@@ -27,12 +59,9 @@ function selectPermission(profile, request, workspaceRoot) {
27
59
  return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
28
60
  }
29
61
  if (profile.policy === 'workspace') {
30
- // If locations are provided, verify they are inside workspaceRoot
62
+ // If locations are provided, verify canonical realpaths stay inside workspaceRoot
31
63
  const locations = request.toolCall.locations || [];
32
- const isInsideWorkspace = locations.length === 0 || locations.every((loc) => {
33
- const resolved = path.resolve(workspaceRoot, loc.path);
34
- return !path.relative(workspaceRoot, resolved).startsWith('..') && !path.isAbsolute(path.relative(workspaceRoot, resolved));
35
- });
64
+ const isInsideWorkspace = locations.length === 0 || locations.every((loc) => typeof loc?.path === 'string' && loc.path.trim().length > 0 && isWithinWorkspaceRoot(workspaceRoot, loc.path.trim()));
36
65
  if (isInsideWorkspace) {
37
66
  const allow = request.options.find((option) => option.kind === 'allow_once' || option.kind === 'allow_always');
38
67
  return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
@@ -47,9 +76,33 @@ function selectPermission(profile, request, workspaceRoot) {
47
76
  const allow = request.options.find((option) => option.kind === 'allow_once' || option.kind === 'allow_always');
48
77
  return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
49
78
  }
50
- // Mutating requests under 'ask' policy default to requiring confirmation
51
- const allow = request.options.find((option) => option.kind === 'allow_once');
52
- return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
79
+ // Mutating requests under 'ask' policy require explicit interactive user approval
80
+ const approver = typeof context?.waitForApproval === 'function'
81
+ ? context
82
+ : typeof context?.parentLoop?.waitForApproval === 'function'
83
+ ? context.parentLoop
84
+ : undefined;
85
+ if (approver?.waitForApproval) {
86
+ const approvalId = `peer_${crypto.randomUUID()}`;
87
+ approver.emitEvent?.({
88
+ type: 'approval_request',
89
+ toolCallId: approvalId,
90
+ tool: `peer_agent:${profile.id}:${request.toolCall.title || request.toolCall.kind || 'action'}`,
91
+ args: {
92
+ peer: profile.id,
93
+ kind: request.toolCall.kind,
94
+ locations: request.toolCall.locations
95
+ },
96
+ risk: 'high'
97
+ });
98
+ const approved = await approver.waitForApproval(approvalId);
99
+ if (approved) {
100
+ const allow = request.options.find((option) => option.kind === 'allow_once');
101
+ return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
102
+ }
103
+ }
104
+ const reject = request.options.find((option) => option.kind === 'reject_once' || option.kind === 'reject_always');
105
+ return reject ? { outcome: 'selected', optionId: reject.optionId } : { outcome: 'cancelled' };
53
106
  }
54
107
  export const peerAgentTool = {
55
108
  schema: {
@@ -86,8 +139,9 @@ export const peerAgentTool = {
86
139
  }
87
140
  }
88
141
  },
89
- async execute(args = {}) {
90
- const action = args.action || (args.peer || args.prompt !== undefined ? 'delegate' : 'list');
142
+ async execute(args = {}, context = {}) {
143
+ const safeArgs = args && typeof args === 'object' && !Array.isArray(args) ? args : {};
144
+ const action = safeArgs.action || (safeArgs.peer || safeArgs.prompt !== undefined ? 'delegate' : 'list');
91
145
  // 1. Action: list
92
146
  if (action === 'list' || action === 'status') {
93
147
  const allPeers = listAllPeers();
@@ -105,8 +159,8 @@ export const peerAgentTool = {
105
159
  };
106
160
  }
107
161
  // 2. Action: delegate
108
- const peerId = String(args.peer || '').trim();
109
- const prompt = String(args.prompt || '').trim().slice(0, MAX_PROMPT_CHARS);
162
+ const peerId = String(safeArgs.peer || '').trim();
163
+ const prompt = String(safeArgs.prompt || '').trim().slice(0, MAX_PROMPT_CHARS);
110
164
  if (!peerId) {
111
165
  const available = listAllPeers().map((p) => p.id);
112
166
  return {
@@ -121,27 +175,34 @@ export const peerAgentTool = {
121
175
  if (!profile) {
122
176
  return { success: false, error: `Unknown peer profile: ${peerId}. Run with action "list" to see available peers.` };
123
177
  }
124
- const requestedTimeout = typeof args.timeoutSeconds === 'number' && Number.isFinite(args.timeoutSeconds)
125
- ? Math.round(args.timeoutSeconds)
178
+ const requestedTimeout = typeof safeArgs.timeoutSeconds === 'number' && Number.isFinite(safeArgs.timeoutSeconds)
179
+ ? Math.round(safeArgs.timeoutSeconds)
126
180
  : profile.timeoutSeconds;
127
181
  const timeoutSeconds = Math.max(5, Math.min(Math.min(profile.timeoutSeconds, requestedTimeout), 1800));
128
- const workspaceRoot = profile.cwd || process.cwd();
182
+ const workspaceRoot = profile.cwd
183
+ || context?.parentLoop?.workspaceRoot
184
+ || context?.workspaceRoot
185
+ || context?.workspacePaths?.find((entry) => typeof entry === 'string' && entry.trim().length > 0)
186
+ || process.cwd();
129
187
  if (peerId.toLowerCase() === 'antigravity') {
130
188
  try {
131
- const agyModel = args.model || 'Gemini 3.8 Flash (Low)';
132
- const { stdout } = await execFileAsync(profile.command, [
133
- '--output-format',
134
- 'json',
135
- `--model=${agyModel}`,
136
- `-p=${prompt}`
137
- ], {
189
+ const agyArgs = ['--output-format', 'json'];
190
+ if (typeof safeArgs.model === 'string' && safeArgs.model.trim()) {
191
+ agyArgs.push(`--model=${safeArgs.model.trim()}`);
192
+ }
193
+ agyArgs.push(`-p=${prompt}`);
194
+ const { stdout } = await execFileAsync(profile.command, agyArgs, {
138
195
  cwd: workspaceRoot,
139
- timeout: timeoutSeconds * 1000
196
+ env: peerEnvironment(profile),
197
+ timeout: timeoutSeconds * 1000,
198
+ maxBuffer: 16 * 1024 * 1024,
199
+ windowsHide: true,
200
+ ...(context?.signal ? { signal: context.signal } : {})
140
201
  });
141
202
  let outputText = stdout.trim();
142
203
  try {
143
204
  const parsed = JSON.parse(outputText);
144
- if (parsed.response)
205
+ if (typeof parsed?.response === 'string')
145
206
  outputText = parsed.response.trim();
146
207
  }
147
208
  catch {
@@ -164,30 +225,30 @@ export const peerAgentTool = {
164
225
  cwd: workspaceRoot,
165
226
  env: peerEnvironment(profile),
166
227
  promptTimeoutMs: timeoutSeconds * 1000,
167
- permissionHandler: async (request) => selectPermission(profile, request, workspaceRoot)
228
+ permissionHandler: async (request) => selectPermission(profile, request, workspaceRoot, context)
168
229
  });
169
230
  try {
170
- await client.start();
171
- const sessionId = await client.newSession(workspaceRoot);
231
+ await client.start(context?.signal);
232
+ const sessionId = await client.newSession(workspaceRoot, [], context?.signal);
172
233
  // Optional model selection if specified
173
- if (args.model && client.agentCapabilities?.promptCapabilities) {
234
+ if (typeof safeArgs.model === 'string' && safeArgs.model.trim()) {
174
235
  try {
175
- await client.setSessionModel(sessionId, args.model);
236
+ await client.setSessionModel(sessionId, safeArgs.model.trim(), context?.signal);
176
237
  }
177
238
  catch {
178
239
  // If model selection fails, continue with default model
179
240
  }
180
241
  }
181
242
  // Optional mode selection if specified
182
- if (args.mode) {
243
+ if (typeof safeArgs.mode === 'string' && safeArgs.mode.trim()) {
183
244
  try {
184
- await client.setSessionMode(sessionId, args.mode);
245
+ await client.setSessionMode(sessionId, safeArgs.mode.trim());
185
246
  }
186
247
  catch {
187
248
  // If mode selection fails, continue with default mode
188
249
  }
189
250
  }
190
- const result = await client.prompt(sessionId, prompt);
251
+ const result = await client.prompt(sessionId, prompt, context?.signal);
191
252
  if (result.stopReason === 'cancelled') {
192
253
  return { success: false, error: `The peer agent "${peerId}" cancelled the task.` };
193
254
  }
@@ -205,7 +266,8 @@ export const peerAgentTool = {
205
266
  catch (error) {
206
267
  const msg = error instanceof Error ? error.message : String(error);
207
268
  const isAuthError = /auth|login|credentials|unauthorized/i.test(msg);
208
- const preset = BUILTIN_PEER_PRESETS[peerId.toLowerCase()];
269
+ const presetKey = peerId.toLowerCase();
270
+ const preset = Object.hasOwn(BUILTIN_PEER_PRESETS, presetKey) ? BUILTIN_PEER_PRESETS[presetKey] : undefined;
209
271
  const instruction = preset?.setupInstruction ? `\nGuidance: ${preset.setupInstruction}` : '';
210
272
  return {
211
273
  success: false,