@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
@@ -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,
@@ -7,6 +7,8 @@
7
7
  * Those come from the catalog presets or the user's `~/.causyne/peers.json`.
8
8
  */
9
9
 
10
+ import crypto from 'node:crypto';
11
+ import fs from 'node:fs';
10
12
  import path from 'node:path';
11
13
  import { execFile } from 'node:child_process';
12
14
  import { promisify } from 'node:util';
@@ -30,11 +32,54 @@ export interface PeerAgentArgs {
30
32
  const MAX_PROMPT_CHARS = 2_000_000;
31
33
  const READ_ONLY_KINDS = new Set(['read', 'search', 'fetch', 'think']);
32
34
 
33
- function selectPermission(
35
+ function resolveCanonicalPath(target: string): string {
36
+ const resolved = path.resolve(target);
37
+ try {
38
+ return fs.realpathSync(resolved);
39
+ } catch {
40
+ let current = resolved;
41
+ const missing: string[] = [];
42
+ for (let depth = 0; depth < 64; depth++) {
43
+ const parent = path.dirname(current);
44
+ if (parent === current) break;
45
+ missing.unshift(path.basename(current));
46
+ current = parent;
47
+ try {
48
+ return path.join(fs.realpathSync(current), ...missing);
49
+ } catch {
50
+ continue;
51
+ }
52
+ }
53
+ return resolved;
54
+ }
55
+ }
56
+
57
+ function isWithinWorkspaceRoot(workspaceRoot: string, candidatePath: string): boolean {
58
+ const canonicalRoot = resolveCanonicalPath(workspaceRoot);
59
+ const canonicalTarget = resolveCanonicalPath(path.resolve(canonicalRoot, candidatePath));
60
+ const rel = path.relative(canonicalRoot, canonicalTarget);
61
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
62
+ }
63
+
64
+ export interface PeerAgentContext {
65
+ workspaceRoot?: string;
66
+ workspacePaths?: string[];
67
+ signal?: AbortSignal;
68
+ waitForApproval?: (id: string) => Promise<boolean>;
69
+ emitEvent?: (event: Record<string, unknown>) => void;
70
+ parentLoop?: {
71
+ workspaceRoot?: string;
72
+ waitForApproval?: (id: string) => Promise<boolean>;
73
+ emitEvent?: (event: Record<string, unknown>) => void;
74
+ };
75
+ }
76
+
77
+ async function selectPermission(
34
78
  profile: PeerProfile,
35
79
  request: RequestPermissionRequest,
36
- workspaceRoot: string
37
- ): RequestPermissionResponse['outcome'] {
80
+ workspaceRoot: string,
81
+ context?: PeerAgentContext
82
+ ): Promise<RequestPermissionResponse['outcome']> {
38
83
  const kind = request.toolCall.kind;
39
84
  const readLike = typeof kind === 'string' && READ_ONLY_KINDS.has(kind);
40
85
 
@@ -48,12 +93,11 @@ function selectPermission(
48
93
  }
49
94
 
50
95
  if (profile.policy === 'workspace') {
51
- // If locations are provided, verify they are inside workspaceRoot
96
+ // If locations are provided, verify canonical realpaths stay inside workspaceRoot
52
97
  const locations = request.toolCall.locations || [];
53
- const isInsideWorkspace = locations.length === 0 || locations.every((loc) => {
54
- const resolved = path.resolve(workspaceRoot, loc.path);
55
- return !path.relative(workspaceRoot, resolved).startsWith('..') && !path.isAbsolute(path.relative(workspaceRoot, resolved));
56
- });
98
+ const isInsideWorkspace = locations.length === 0 || locations.every((loc) =>
99
+ typeof loc?.path === 'string' && loc.path.trim().length > 0 && isWithinWorkspaceRoot(workspaceRoot, loc.path.trim())
100
+ );
57
101
 
58
102
  if (isInsideWorkspace) {
59
103
  const allow = request.options.find((option) => option.kind === 'allow_once' || option.kind === 'allow_always');
@@ -70,9 +114,33 @@ function selectPermission(
70
114
  return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
71
115
  }
72
116
 
73
- // Mutating requests under 'ask' policy default to requiring confirmation
74
- const allow = request.options.find((option) => option.kind === 'allow_once');
75
- return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
117
+ // Mutating requests under 'ask' policy require explicit interactive user approval
118
+ const approver = typeof context?.waitForApproval === 'function'
119
+ ? context
120
+ : typeof context?.parentLoop?.waitForApproval === 'function'
121
+ ? context.parentLoop
122
+ : undefined;
123
+ if (approver?.waitForApproval) {
124
+ const approvalId = `peer_${crypto.randomUUID()}`;
125
+ approver.emitEvent?.({
126
+ type: 'approval_request',
127
+ toolCallId: approvalId,
128
+ tool: `peer_agent:${profile.id}:${request.toolCall.title || request.toolCall.kind || 'action'}`,
129
+ args: {
130
+ peer: profile.id,
131
+ kind: request.toolCall.kind,
132
+ locations: request.toolCall.locations
133
+ },
134
+ risk: 'high'
135
+ });
136
+ const approved = await approver.waitForApproval(approvalId);
137
+ if (approved) {
138
+ const allow = request.options.find((option) => option.kind === 'allow_once');
139
+ return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
140
+ }
141
+ }
142
+ const reject = request.options.find((option) => option.kind === 'reject_once' || option.kind === 'reject_always');
143
+ return reject ? { outcome: 'selected', optionId: reject.optionId } : { outcome: 'cancelled' };
76
144
  }
77
145
 
78
146
  export const peerAgentTool = {
@@ -110,7 +178,7 @@ export const peerAgentTool = {
110
178
  }
111
179
  }
112
180
  },
113
- async execute(args: PeerAgentArgs = {}): Promise<{
181
+ async execute(args: PeerAgentArgs = {}, context: PeerAgentContext = {}): Promise<{
114
182
  success: boolean;
115
183
  output?: string;
116
184
  error?: string;
@@ -118,7 +186,8 @@ export const peerAgentTool = {
118
186
  agent?: string;
119
187
  stopReason?: string;
120
188
  }> {
121
- const action = args.action || (args.peer || args.prompt !== undefined ? 'delegate' : 'list');
189
+ const safeArgs: PeerAgentArgs = args && typeof args === 'object' && !Array.isArray(args) ? args : {};
190
+ const action = safeArgs.action || (safeArgs.peer || safeArgs.prompt !== undefined ? 'delegate' : 'list');
122
191
 
123
192
  // 1. Action: list
124
193
  if (action === 'list' || action === 'status') {
@@ -139,8 +208,8 @@ export const peerAgentTool = {
139
208
  }
140
209
 
141
210
  // 2. Action: delegate
142
- const peerId = String(args.peer || '').trim();
143
- const prompt = String(args.prompt || '').trim().slice(0, MAX_PROMPT_CHARS);
211
+ const peerId = String(safeArgs.peer || '').trim();
212
+ const prompt = String(safeArgs.prompt || '').trim().slice(0, MAX_PROMPT_CHARS);
144
213
 
145
214
  if (!peerId) {
146
215
  const available = listAllPeers().map((p) => p.id);
@@ -159,29 +228,36 @@ export const peerAgentTool = {
159
228
  return { success: false, error: `Unknown peer profile: ${peerId}. Run with action "list" to see available peers.` };
160
229
  }
161
230
 
162
- const requestedTimeout = typeof args.timeoutSeconds === 'number' && Number.isFinite(args.timeoutSeconds)
163
- ? Math.round(args.timeoutSeconds)
231
+ const requestedTimeout = typeof safeArgs.timeoutSeconds === 'number' && Number.isFinite(safeArgs.timeoutSeconds)
232
+ ? Math.round(safeArgs.timeoutSeconds)
164
233
  : profile.timeoutSeconds;
165
234
  const timeoutSeconds = Math.max(5, Math.min(Math.min(profile.timeoutSeconds, requestedTimeout), 1800));
166
235
 
167
- const workspaceRoot = profile.cwd || process.cwd();
236
+ const workspaceRoot = profile.cwd
237
+ || context?.parentLoop?.workspaceRoot
238
+ || context?.workspaceRoot
239
+ || context?.workspacePaths?.find((entry): entry is string => typeof entry === 'string' && entry.trim().length > 0)
240
+ || process.cwd();
168
241
 
169
242
  if (peerId.toLowerCase() === 'antigravity') {
170
243
  try {
171
- const agyModel = args.model || 'Gemini 3.8 Flash (Low)';
172
- const { stdout } = await execFileAsync(profile.command, [
173
- '--output-format',
174
- 'json',
175
- `--model=${agyModel}`,
176
- `-p=${prompt}`
177
- ], {
244
+ const agyArgs = ['--output-format', 'json'];
245
+ if (typeof safeArgs.model === 'string' && safeArgs.model.trim()) {
246
+ agyArgs.push(`--model=${safeArgs.model.trim()}`);
247
+ }
248
+ agyArgs.push(`-p=${prompt}`);
249
+ const { stdout } = await execFileAsync(profile.command, agyArgs, {
178
250
  cwd: workspaceRoot,
179
- timeout: timeoutSeconds * 1000
251
+ env: peerEnvironment(profile),
252
+ timeout: timeoutSeconds * 1000,
253
+ maxBuffer: 16 * 1024 * 1024,
254
+ windowsHide: true,
255
+ ...(context?.signal ? { signal: context.signal } : {})
180
256
  });
181
257
  let outputText = stdout.trim();
182
258
  try {
183
- const parsed = JSON.parse(outputText);
184
- if (parsed.response) outputText = parsed.response.trim();
259
+ const parsed = JSON.parse(outputText) as { response?: unknown };
260
+ if (typeof parsed?.response === 'string') outputText = parsed.response.trim();
185
261
  } catch {
186
262
  // keep raw stdout
187
263
  }
@@ -202,32 +278,32 @@ export const peerAgentTool = {
202
278
  cwd: workspaceRoot,
203
279
  env: peerEnvironment(profile),
204
280
  promptTimeoutMs: timeoutSeconds * 1000,
205
- permissionHandler: async (request) => selectPermission(profile, request, workspaceRoot)
281
+ permissionHandler: async (request) => selectPermission(profile, request, workspaceRoot, context)
206
282
  });
207
283
 
208
284
  try {
209
- await client.start();
210
- const sessionId = await client.newSession(workspaceRoot);
285
+ await client.start(context?.signal);
286
+ const sessionId = await client.newSession(workspaceRoot, [], context?.signal);
211
287
 
212
288
  // Optional model selection if specified
213
- if (args.model && client.agentCapabilities?.promptCapabilities) {
289
+ if (typeof safeArgs.model === 'string' && safeArgs.model.trim()) {
214
290
  try {
215
- await client.setSessionModel(sessionId, args.model);
291
+ await client.setSessionModel(sessionId, safeArgs.model.trim(), context?.signal);
216
292
  } catch {
217
293
  // If model selection fails, continue with default model
218
294
  }
219
295
  }
220
296
 
221
297
  // Optional mode selection if specified
222
- if (args.mode) {
298
+ if (typeof safeArgs.mode === 'string' && safeArgs.mode.trim()) {
223
299
  try {
224
- await client.setSessionMode(sessionId, args.mode);
300
+ await client.setSessionMode(sessionId, safeArgs.mode.trim());
225
301
  } catch {
226
302
  // If mode selection fails, continue with default mode
227
303
  }
228
304
  }
229
305
 
230
- const result = await client.prompt(sessionId, prompt);
306
+ const result = await client.prompt(sessionId, prompt, context?.signal);
231
307
  if (result.stopReason === 'cancelled') {
232
308
  return { success: false, error: `The peer agent "${peerId}" cancelled the task.` };
233
309
  }
@@ -245,7 +321,8 @@ export const peerAgentTool = {
245
321
  } catch (error) {
246
322
  const msg = error instanceof Error ? error.message : String(error);
247
323
  const isAuthError = /auth|login|credentials|unauthorized/i.test(msg);
248
- const preset = BUILTIN_PEER_PRESETS[peerId.toLowerCase()];
324
+ const presetKey = peerId.toLowerCase();
325
+ const preset = Object.hasOwn(BUILTIN_PEER_PRESETS, presetKey) ? BUILTIN_PEER_PRESETS[presetKey] : undefined;
249
326
  const instruction = preset?.setupInstruction ? `\nGuidance: ${preset.setupInstruction}` : '';
250
327
 
251
328
  return {
@@ -1,6 +1,7 @@
1
1
  import { spawn } from 'child_process';
2
2
  import os from 'os';
3
3
  import path from 'path';
4
+ import { getEnhancedEnv } from './sysRun.js';
4
5
 
5
6
  // Singleton map of active persistent shell sessions
6
7
  const sessions = new Map();
@@ -55,9 +56,13 @@ export const persistentShell = {
55
56
  const shellBin = isWin ? 'powershell.exe' : (process.env.SHELL || '/bin/zsh');
56
57
  const shellArgs = isWin ? ['-NoLogo', '-NoExit', '-Command', '-'] : ['-l'];
57
58
 
59
+ const initialCwd = typeof args.cwd === 'string' && args.cwd.trim()
60
+ ? args.cwd.replace(/^~\//, os.homedir() + '/')
61
+ : process.cwd();
62
+
58
63
  const proc = spawn(shellBin, shellArgs, {
59
- cwd: process.cwd(),
60
- env: { ...process.env, CAUSYNE_PERSISTENT_SHELL: '1', PS1: '' },
64
+ cwd: initialCwd,
65
+ env: { ...getEnhancedEnv(), CAUSYNE_PERSISTENT_SHELL: '1', PS1: '' },
61
66
  stdio: ['pipe', 'pipe', 'pipe']
62
67
  });
63
68
 
@@ -71,7 +76,7 @@ export const persistentShell = {
71
76
 
72
77
  session = {
73
78
  process: proc,
74
- currentCwd: process.cwd()
79
+ currentCwd: initialCwd
75
80
  };
76
81
  sessions.set(sessionId, session);
77
82
  }