@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
@@ -1,6 +1,8 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { causyneHome } from '../utils/paths.js';
4
+ import { isBlockedWorkspaceRoot } from '../sandboxPolicy.js';
5
+ import { atomicWriteSecretFileSync } from '../configVault.js';
4
6
  import { getPresetProfile, BUILTIN_PEER_PRESETS } from './agentCatalog.js';
5
7
 
6
8
  export type PeerPolicy = 'read-only' | 'ask' | 'workspace';
@@ -38,7 +40,7 @@ function asStringArray(value: unknown, limit: number, maxChars: number): string[
38
40
  if (value.length > limit) return null;
39
41
  const result: string[] = [];
40
42
  for (const item of value) {
41
- if (typeof item !== 'string') return null;
43
+ if (typeof item !== 'string' || /[\r\n\0]/.test(item)) return null;
42
44
  result.push(item.slice(0, maxChars));
43
45
  }
44
46
  return result;
@@ -51,7 +53,7 @@ function asEnv(value: unknown): Record<string, string> {
51
53
  for (const [name, raw] of Object.entries(value as Record<string, unknown>)) {
52
54
  if (count >= MAX_ENV_ENTRIES) break;
53
55
  if (!ENV_NAME.test(name)) continue;
54
- if (typeof raw !== 'string') continue;
56
+ if (typeof raw !== 'string' || raw.includes('\0')) continue;
55
57
  result[name] = raw.slice(0, MAX_ENV_VALUE_CHARS);
56
58
  count += 1;
57
59
  }
@@ -64,35 +66,41 @@ function parseProfile(raw: unknown): PeerProfile | null {
64
66
  const id = typeof record.id === 'string' ? record.id.trim() : '';
65
67
  if (!PROFILE_ID.test(id)) return null;
66
68
  const command = typeof record.command === 'string' ? record.command.trim() : '';
67
- if (!command || command.length > 500) return null;
69
+ if (!command || command.length > 500 || /[\r\n\0]/.test(command)) return null;
68
70
  const args = asStringArray(record.args ?? [], MAX_ARGS, MAX_ARG_CHARS);
69
71
  if (args === null) return null;
70
72
  let cwd: string | null = null;
71
73
  if (typeof record.cwd === 'string' && record.cwd.trim()) {
74
+ if (/[\r\n\0]/.test(record.cwd)) return null;
72
75
  const resolved = path.resolve(record.cwd.trim());
76
+ if (isBlockedWorkspaceRoot(resolved)) return null;
73
77
  try {
74
- if (!fs.statSync(resolved).isDirectory()) return null;
75
- cwd = resolved;
78
+ const real = fs.realpathSync(resolved);
79
+ if (isBlockedWorkspaceRoot(real)) return null;
80
+ if (!fs.statSync(real).isDirectory()) return null;
81
+ cwd = real;
76
82
  } catch {
77
83
  return null;
78
84
  }
79
85
  }
80
- const policy: PeerPolicy = record.policy === 'read-only'
81
- ? 'read-only'
82
- : (record.policy === 'ask' ? 'ask' : 'workspace');
86
+ const policy: PeerPolicy = record.policy === undefined
87
+ ? 'workspace'
88
+ : (record.policy === 'read-only' ? 'read-only' : (record.policy === 'workspace' ? 'workspace' : 'ask'));
83
89
  const timeoutSeconds = typeof record.timeoutSeconds === 'number' && Number.isFinite(record.timeoutSeconds)
84
90
  ? Math.max(5, Math.min(1800, Math.round(record.timeoutSeconds)))
85
91
  : 120;
86
- const label = typeof record.label === 'string' && record.label.trim()
87
- ? record.label.trim().slice(0, 100)
88
- : id;
92
+ const rawLabel = typeof record.label === 'string' ? record.label.replace(/[\r\n\0]+/g, ' ').trim() : '';
93
+ const label = rawLabel ? rawLabel.slice(0, 100) : id;
89
94
  return { id, label, command, args, cwd, policy, timeoutSeconds, env: asEnv(record.env) };
90
95
  }
91
96
 
92
97
  export function loadPeerProfiles(): PeerProfile[] {
93
98
  let raw: unknown;
94
99
  try {
95
- raw = JSON.parse(fs.readFileSync(peerProfilesPath(), 'utf8'));
100
+ const file = peerProfilesPath();
101
+ const stat = fs.lstatSync(file);
102
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1024 * 1024) return [];
103
+ raw = JSON.parse(fs.readFileSync(file, 'utf8'));
96
104
  } catch {
97
105
  return [];
98
106
  }
@@ -118,27 +126,27 @@ export function loadPeerProfiles(): PeerProfile[] {
118
126
 
119
127
  export function savePeerProfiles(profiles: PeerProfile[]): void {
120
128
  const file = peerProfilesPath();
121
- const dir = path.dirname(file);
122
- if (!fs.existsSync(dir)) {
123
- fs.mkdirSync(dir, { recursive: true });
124
- }
125
129
  const content: PeerProfilesFile = {
126
130
  schemaVersion: 1,
127
131
  peers: profiles
128
132
  };
129
- fs.writeFileSync(file, JSON.stringify(content, null, 2), 'utf8');
133
+ atomicWriteSecretFileSync(file, JSON.stringify(content, null, 2));
130
134
  }
131
135
 
132
136
  export function addPeerProfile(profile: PeerProfile): { ok: boolean; error?: string } {
137
+ const validated = parseProfile(profile);
138
+ if (!validated) {
139
+ return { ok: false, error: 'Invalid peer profile configuration.' };
140
+ }
133
141
  const current = loadPeerProfiles();
134
- const idx = current.findIndex((p) => p.id === profile.id);
142
+ const idx = current.findIndex((p) => p.id === validated.id);
135
143
  if (idx >= 0) {
136
- current[idx] = profile;
144
+ current[idx] = validated;
137
145
  } else {
138
146
  if (current.length >= MAX_PEERS) {
139
147
  return { ok: false, error: `Maximum of ${MAX_PEERS} peer profiles exceeded.` };
140
148
  }
141
- current.push(profile);
149
+ current.push(validated);
142
150
  }
143
151
  try {
144
152
  savePeerProfiles(current);
@@ -198,12 +206,33 @@ export function listAllPeers(): PeerProfile[] {
198
206
  return all;
199
207
  }
200
208
 
209
+ const BLOCKED_PEER_ENV_KEYS = new Set([
210
+ 'LD_PRELOAD',
211
+ 'LD_LIBRARY_PATH',
212
+ 'DYLD_INSERT_LIBRARIES',
213
+ 'DYLD_LIBRARY_PATH',
214
+ 'DYLD_FRAMEWORK_PATH',
215
+ 'NODE_OPTIONS',
216
+ 'BASH_ENV',
217
+ 'ENV',
218
+ 'PYTHONSTARTUP'
219
+ ]);
220
+
201
221
  export function peerEnvironment(profile: PeerProfile): NodeJS.ProcessEnv {
202
222
  const env: NodeJS.ProcessEnv = {};
203
- for (const name of ['PATH', 'HOME', 'USER', 'LOGNAME', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL', 'SYSTEMROOT']) {
223
+ const baseKeys = [
224
+ 'PATH', 'Path', 'PATHEXT', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA',
225
+ 'USER', 'LOGNAME', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL',
226
+ 'SYSTEMROOT', 'SystemRoot', 'COMSPEC', 'ComSpec', 'ProgramData'
227
+ ];
228
+ for (const name of baseKeys) {
204
229
  const value = process.env[name];
205
230
  if (typeof value === 'string') env[name] = value;
206
231
  }
207
- for (const [name, value] of Object.entries(profile.env)) env[name] = value;
232
+ for (const [name, value] of Object.entries(profile.env)) {
233
+ if (BLOCKED_PEER_ENV_KEYS.has(name.toUpperCase())) continue;
234
+ if (!ENV_NAME.test(name) || typeof value !== 'string' || value.includes('\0')) continue;
235
+ env[name] = value;
236
+ }
208
237
  return env;
209
238
  }
@@ -38,23 +38,48 @@ export function isJsonRpcRequest(value) {
38
38
  if (value === null || typeof value !== 'object' || Array.isArray(value))
39
39
  return false;
40
40
  const record = value;
41
+ const validId = typeof record.id === 'string'
42
+ || (typeof record.id === 'number' && Number.isFinite(record.id));
41
43
  return record.jsonrpc === '2.0'
42
- && (typeof record.id === 'string' || typeof record.id === 'number')
43
- && typeof record.method === 'string';
44
+ && validId
45
+ && typeof record.method === 'string'
46
+ && record.method.trim().length > 0;
44
47
  }
45
48
  export function isJsonRpcResponse(value) {
46
49
  if (value === null || typeof value !== 'object' || Array.isArray(value))
47
50
  return false;
48
51
  const record = value;
49
- return record.jsonrpc === '2.0'
50
- && (typeof record.id === 'string' || typeof record.id === 'number' || record.id === null)
51
- && ('result' in record || 'error' in record);
52
+ if (record.jsonrpc !== '2.0')
53
+ return false;
54
+ const validId = typeof record.id === 'string'
55
+ || (typeof record.id === 'number' && Number.isFinite(record.id))
56
+ || record.id === null;
57
+ if (!validId)
58
+ return false;
59
+ const hasResult = 'result' in record;
60
+ const hasError = 'error' in record;
61
+ if (hasResult === hasError)
62
+ return false;
63
+ if (hasError) {
64
+ const err = record.error;
65
+ if (err === null || typeof err !== 'object' || Array.isArray(err))
66
+ return false;
67
+ const errObj = err;
68
+ if (typeof errObj.code !== 'number' || !Number.isFinite(errObj.code))
69
+ return false;
70
+ if (typeof errObj.message !== 'string')
71
+ return false;
72
+ }
73
+ return true;
52
74
  }
53
75
  export function isJsonRpcNotification(value) {
54
76
  if (value === null || typeof value !== 'object' || Array.isArray(value))
55
77
  return false;
56
78
  const record = value;
57
- return record.jsonrpc === '2.0' && typeof record.method === 'string' && !('id' in record);
79
+ return record.jsonrpc === '2.0'
80
+ && typeof record.method === 'string'
81
+ && record.method.trim().length > 0
82
+ && !('id' in record);
58
83
  }
59
84
  /**
60
85
  * Extract live available models and active model ID from any ACP session/new,
@@ -70,17 +95,21 @@ export function extractAcpSessionModels(payload) {
70
95
  return { availableModels, modelLabels, usesConfigOption };
71
96
  }
72
97
  const record = payload;
98
+ const MAX_DISCOVERED_MODELS = 500;
99
+ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
73
100
  const registerModel = (rawId, rawLabel) => {
74
101
  if (typeof rawId !== 'string')
75
102
  return;
76
103
  const id = rawId.trim();
77
- if (!id)
104
+ if (!id || id.length > 200 || FORBIDDEN_KEYS.has(id))
78
105
  return;
79
106
  if (!availableModels.includes(id)) {
107
+ if (availableModels.length >= MAX_DISCOVERED_MODELS)
108
+ return;
80
109
  availableModels.push(id);
81
110
  }
82
111
  if (typeof rawLabel === 'string' && rawLabel.trim()) {
83
- modelLabels[id] = rawLabel.trim();
112
+ modelLabels[id] = rawLabel.trim().slice(0, 200);
84
113
  }
85
114
  };
86
115
  // 1. Inspect ACP v1 configOptions (e.g. OpenCode, Claude Agent ACP, Codex ACP, Gemini ACP)
@@ -511,23 +511,42 @@ export type WriteTextFileResponse = Record<string, never>;
511
511
  export function isJsonRpcRequest(value: unknown): value is JsonRpcRequest {
512
512
  if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
513
513
  const record = value as Record<string, unknown>;
514
+ const validId = typeof record.id === 'string'
515
+ || (typeof record.id === 'number' && Number.isFinite(record.id));
514
516
  return record.jsonrpc === '2.0'
515
- && (typeof record.id === 'string' || typeof record.id === 'number')
516
- && typeof record.method === 'string';
517
+ && validId
518
+ && typeof record.method === 'string'
519
+ && record.method.trim().length > 0;
517
520
  }
518
521
 
519
522
  export function isJsonRpcResponse(value: unknown): value is JsonRpcResponse {
520
523
  if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
521
524
  const record = value as Record<string, unknown>;
522
- return record.jsonrpc === '2.0'
523
- && (typeof record.id === 'string' || typeof record.id === 'number' || record.id === null)
524
- && ('result' in record || 'error' in record);
525
+ if (record.jsonrpc !== '2.0') return false;
526
+ const validId = typeof record.id === 'string'
527
+ || (typeof record.id === 'number' && Number.isFinite(record.id))
528
+ || record.id === null;
529
+ if (!validId) return false;
530
+ const hasResult = 'result' in record;
531
+ const hasError = 'error' in record;
532
+ if (hasResult === hasError) return false;
533
+ if (hasError) {
534
+ const err = record.error;
535
+ if (err === null || typeof err !== 'object' || Array.isArray(err)) return false;
536
+ const errObj = err as Record<string, unknown>;
537
+ if (typeof errObj.code !== 'number' || !Number.isFinite(errObj.code)) return false;
538
+ if (typeof errObj.message !== 'string') return false;
539
+ }
540
+ return true;
525
541
  }
526
542
 
527
543
  export function isJsonRpcNotification(value: unknown): value is JsonRpcNotification {
528
544
  if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
529
545
  const record = value as Record<string, unknown>;
530
- return record.jsonrpc === '2.0' && typeof record.method === 'string' && !('id' in record);
546
+ return record.jsonrpc === '2.0'
547
+ && typeof record.method === 'string'
548
+ && record.method.trim().length > 0
549
+ && !('id' in record);
531
550
  }
532
551
 
533
552
  /**
@@ -547,15 +566,18 @@ export function extractAcpSessionModels(payload: unknown): AcpDiscoveredSessionM
547
566
 
548
567
  const record = payload as Record<string, unknown>;
549
568
 
569
+ const MAX_DISCOVERED_MODELS = 500;
570
+ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
550
571
  const registerModel = (rawId: unknown, rawLabel?: unknown): void => {
551
572
  if (typeof rawId !== 'string') return;
552
573
  const id = rawId.trim();
553
- if (!id) return;
574
+ if (!id || id.length > 200 || FORBIDDEN_KEYS.has(id)) return;
554
575
  if (!availableModels.includes(id)) {
576
+ if (availableModels.length >= MAX_DISCOVERED_MODELS) return;
555
577
  availableModels.push(id);
556
578
  }
557
579
  if (typeof rawLabel === 'string' && rawLabel.trim()) {
558
- modelLabels[id] = rawLabel.trim();
580
+ modelLabels[id] = rawLabel.trim().slice(0, 200);
559
581
  }
560
582
  };
561
583
 
package/src/acp/server.js CHANGED
@@ -4,11 +4,13 @@ import path from 'node:path';
4
4
  import { AgentLoop } from '../agentLoop.js';
5
5
  import { createApprovalScope } from '../approvalGrants.js';
6
6
  import { createSession, getSession, saveSessionMessages, forkSession } from '../sessionJournal.js';
7
+ import { isBlockedWorkspaceRoot } from '../sandboxPolicy.js';
8
+ import { safeDisplay } from '../tui/text.js';
7
9
  import { ACP_ERROR_CODES, ACP_METHODS, ACP_PROTOCOL_VERSION, isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse } from './protocol.js';
8
10
  const MODE_TO_AUTONOMY = {
9
- autonomous: 'A',
11
+ autonomous: 'C',
10
12
  standard: 'B',
11
- supervised: 'C'
13
+ supervised: 'A'
12
14
  };
13
15
  const MODES = {
14
16
  currentModeId: 'standard',
@@ -20,11 +22,14 @@ const MODES = {
20
22
  };
21
23
  const MAX_PROMPT_CHARS = 200_000;
22
24
  const MAX_RAW_CHARS = 4000;
25
+ const MAX_JSONRPC_BUFFER_BYTES = 8 * 1024 * 1024;
26
+ const MAX_SESSIONS = 128;
23
27
  function textFromPrompt(prompt) {
24
28
  const parts = [];
25
29
  for (const block of prompt) {
26
- if (block.type !== 'text')
30
+ if (!block || typeof block !== 'object' || block.type !== 'text' || typeof block.text !== 'string') {
27
31
  return null;
32
+ }
28
33
  parts.push(block.text);
29
34
  }
30
35
  return parts.join('\n').slice(0, MAX_PROMPT_CHARS);
@@ -75,8 +80,8 @@ function bounded(value, limit = MAX_RAW_CHARS) {
75
80
  }
76
81
  function toolTitle(name, args) {
77
82
  const detail = args.path || args.file_path || args.command || args.cmd || args.query || args.url || args.action;
78
- const suffix = typeof detail === 'string' && detail.trim() ? ` ${detail.trim()}` : '';
79
- const title = `${name}${suffix}`;
83
+ const rawSuffix = typeof detail === 'string' && detail.trim() ? ` ${detail.trim()}` : '';
84
+ const title = safeDisplay(`${name}${rawSuffix}`).replace(/\s+/g, ' ').trim();
80
85
  return title.length > 200 ? `${title.slice(0, 200)}…` : title;
81
86
  }
82
87
  export class AcpServer {
@@ -101,13 +106,25 @@ export class AcpServer {
101
106
  this.loopFactory = options.loopFactory ?? null;
102
107
  this.agentName = options.agentName ?? 'Causyne Agent';
103
108
  this.agentVersion = options.agentVersion ?? '0.0.0';
104
- this.permissionTimeoutMs = options.permissionTimeoutMs ?? 10 * 60 * 1000;
109
+ const rawTimeout = options.permissionTimeoutMs;
110
+ this.permissionTimeoutMs = typeof rawTimeout === 'number' && Number.isFinite(rawTimeout)
111
+ ? Math.max(1_000, Math.min(3_600_000, Math.round(rawTimeout)))
112
+ : 10 * 60 * 1000;
105
113
  }
106
114
  start() {
107
115
  if (!this.input || this.dataListener)
108
116
  return;
109
117
  this.dataListener = (chunk) => {
110
118
  this.buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
119
+ if (this.buffer.length > MAX_JSONRPC_BUFFER_BYTES) {
120
+ this.buffer = '';
121
+ this.write({
122
+ jsonrpc: '2.0',
123
+ id: null,
124
+ error: { code: ACP_ERROR_CODES.INVALID_REQUEST, message: 'Request frame exceeds maximum size' }
125
+ });
126
+ return;
127
+ }
111
128
  void this.drainBuffer();
112
129
  };
113
130
  this.endListener = () => { void this.stop(); };
@@ -126,7 +143,9 @@ export class AcpServer {
126
143
  this.input.off('end', this.endListener);
127
144
  if (this.input && this.errorListener)
128
145
  this.input.off('error', this.errorListener);
146
+ this.buffer = '';
129
147
  for (const session of this.sessions.values()) {
148
+ session.cancelled = true;
130
149
  try {
131
150
  session.loop?.abort();
132
151
  }
@@ -134,26 +153,40 @@ export class AcpServer {
134
153
  // Shutdown never blocks on a misbehaving tool.
135
154
  }
136
155
  }
156
+ this.sessions.clear();
137
157
  for (const [id, pending] of this.pending) {
138
158
  clearTimeout(pending.timer);
139
159
  pending.reject(new Error('server stopped'));
140
160
  this.pending.delete(id);
141
161
  }
142
162
  }
143
- async drainBuffer() {
163
+ drainBuffer() {
164
+ const lines = [];
144
165
  let index = this.buffer.indexOf('\n');
145
166
  while (index >= 0) {
146
167
  const line = this.buffer.slice(0, index).trim();
147
168
  this.buffer = this.buffer.slice(index + 1);
148
169
  if (line)
149
- await this.handleLine(line);
170
+ lines.push(line);
150
171
  index = this.buffer.indexOf('\n');
151
172
  }
173
+ for (const line of lines) {
174
+ void this.handleLine(line).catch(() => { });
175
+ }
152
176
  }
153
177
  async handleLine(line) {
178
+ const cleaned = line.replace(/^\uFEFF/, '').replace(/\r$/, '');
179
+ if (cleaned.length > MAX_JSONRPC_BUFFER_BYTES) {
180
+ this.write({
181
+ jsonrpc: '2.0',
182
+ id: null,
183
+ error: { code: ACP_ERROR_CODES.INVALID_REQUEST, message: 'Request frame exceeds maximum size' }
184
+ });
185
+ return;
186
+ }
154
187
  let parsed;
155
188
  try {
156
- parsed = JSON.parse(line);
189
+ parsed = JSON.parse(cleaned);
157
190
  }
158
191
  catch {
159
192
  this.write({ jsonrpc: '2.0', id: null, error: { code: ACP_ERROR_CODES.PARSE_ERROR, message: 'Parse error' } });
@@ -173,12 +206,19 @@ export class AcpServer {
173
206
  }
174
207
  this.write({ jsonrpc: '2.0', id: null, error: { code: ACP_ERROR_CODES.INVALID_REQUEST, message: 'Invalid request' } });
175
208
  }
209
+ isPlainParams(value) {
210
+ return value === undefined || (value !== null && typeof value === 'object' && !Array.isArray(value));
211
+ }
176
212
  async handleNotification(notification) {
213
+ if (!this.isPlainParams(notification.params))
214
+ return;
177
215
  if (notification.method === ACP_METHODS.CANCEL) {
178
216
  const params = notification.params;
179
- const session = params && typeof params.sessionId === 'string' ? this.sessions.get(params.sessionId) : undefined;
217
+ const sid = params && typeof params.sessionId === 'string' ? params.sessionId.trim() : '';
218
+ const session = sid ? this.sessions.get(sid) : undefined;
180
219
  if (session) {
181
220
  session.cancelled = true;
221
+ this.rejectPendingForSession(session.id, 'session cancelled');
182
222
  try {
183
223
  session.loop?.abort();
184
224
  }
@@ -190,6 +230,9 @@ export class AcpServer {
190
230
  }
191
231
  async handleRequest(request) {
192
232
  try {
233
+ if (!this.isPlainParams(request.params)) {
234
+ throw this.paramsError('params must be a JSON object');
235
+ }
193
236
  switch (request.method) {
194
237
  case ACP_METHODS.INITIALIZE:
195
238
  this.writeResult(request.id, this.initialize(request.params));
@@ -225,8 +268,11 @@ export class AcpServer {
225
268
  }
226
269
  }
227
270
  initialize(params) {
228
- if (!params || typeof params.protocolVersion !== 'number') {
229
- throw this.paramsError('initialize requires protocolVersion');
271
+ if (!params ||
272
+ typeof params.protocolVersion !== 'number' ||
273
+ !Number.isInteger(params.protocolVersion) ||
274
+ params.protocolVersion < 1) {
275
+ throw this.paramsError('initialize requires a valid positive integer protocolVersion');
230
276
  }
231
277
  const capabilities = {
232
278
  loadSession: true,
@@ -264,15 +310,19 @@ export class AcpServer {
264
310
  resolveWorkspace(cwd) {
265
311
  if (typeof cwd !== 'string' || !cwd.trim())
266
312
  throw this.paramsError('cwd is required');
313
+ let resolved;
267
314
  try {
268
- const resolved = fs.realpathSync(path.resolve(cwd));
315
+ resolved = fs.realpathSync(path.resolve(cwd));
269
316
  if (!fs.statSync(resolved).isDirectory())
270
317
  throw new Error('not a directory');
271
- return resolved;
272
318
  }
273
319
  catch {
274
320
  throw this.paramsError(`cwd is not an accessible directory: ${cwd}`);
275
321
  }
322
+ if (isBlockedWorkspaceRoot(resolved)) {
323
+ throw this.paramsError(`cwd points to a blocked system directory: ${cwd}`);
324
+ }
325
+ return resolved;
276
326
  }
277
327
  bindWorkspace(cwd) {
278
328
  if (this.workspaceRoot === null) {
@@ -284,10 +334,13 @@ export class AcpServer {
284
334
  }
285
335
  }
286
336
  addSession(id, cwd, title, modeId) {
337
+ if (!this.sessions.has(id) && this.sessions.size >= MAX_SESSIONS) {
338
+ throw this.paramsError(`Maximum concurrent sessions (${MAX_SESSIONS}) exceeded`);
339
+ }
287
340
  const session = {
288
341
  id,
289
342
  memorySessionId: id,
290
- title,
343
+ title: safeDisplay(title).replace(/\s+/g, ' ').trim() || 'Untitled',
291
344
  cwd,
292
345
  modeId,
293
346
  loop: null,
@@ -337,6 +390,9 @@ export class AcpServer {
337
390
  return { stopReason };
338
391
  }
339
392
  async runTurn(session, text) {
393
+ if (this.closed || !this.sessions.has(session.id)) {
394
+ return 'cancelled';
395
+ }
340
396
  session.updatedAt = Date.now();
341
397
  session.cancelled = false;
342
398
  session.busy = true;
@@ -382,9 +438,11 @@ export class AcpServer {
382
438
  finally {
383
439
  session.loop = null;
384
440
  session.busy = false;
385
- const record = getSession(session.memorySessionId);
386
- if (record)
387
- session.title = record.title;
441
+ if (this.sessions.has(session.id)) {
442
+ const record = getSession(session.memorySessionId);
443
+ if (record)
444
+ session.title = safeDisplay(record.title).replace(/\s+/g, ' ').trim() || session.title;
445
+ }
388
446
  if (session.cancelled)
389
447
  stopReason = 'cancelled';
390
448
  }
@@ -421,9 +479,14 @@ export class AcpServer {
421
479
  toolCall,
422
480
  options: permissionOptions
423
481
  }).then((response) => {
424
- if (!response || response.outcome.outcome !== 'selected')
482
+ if (session.cancelled || !this.sessions.has(session.id))
483
+ return null;
484
+ const outcome = response && typeof response.outcome === 'object' && response.outcome !== null
485
+ ? response.outcome
486
+ : null;
487
+ if (!outcome || outcome.outcome !== 'selected' || typeof outcome.optionId !== 'string')
425
488
  return null;
426
- const optionId = response.outcome.optionId;
489
+ const optionId = outcome.optionId;
427
490
  const label = labels.get(optionId);
428
491
  if (!label)
429
492
  return null;
@@ -551,9 +614,19 @@ export class AcpServer {
551
614
  toolCall,
552
615
  options
553
616
  }).then((response) => {
554
- const selected = response?.outcome.outcome === 'selected' ? response.outcome.optionId : '';
617
+ if (session.cancelled || !this.sessions.has(session.id)) {
618
+ session.loop?.handleApprovalResponse(toolCallId, false);
619
+ return;
620
+ }
621
+ const outcome = response && typeof response.outcome === 'object' && response.outcome !== null
622
+ ? response.outcome
623
+ : null;
624
+ const selected = outcome && outcome.outcome === 'selected' && typeof outcome.optionId === 'string'
625
+ ? outcome.optionId
626
+ : '';
627
+ const canonicalTool = tool.replace(/\./g, '_');
555
628
  if (selected === 'allow_always')
556
- session.approvalScope.grantAlways(tool);
629
+ session.approvalScope.grantAlways(canonicalTool);
557
630
  const approved = selected === 'allow_once' || selected === 'allow_always';
558
631
  session.loop?.handleApprovalResponse(toolCallId, approved);
559
632
  }).catch(() => {
@@ -594,8 +667,17 @@ export class AcpServer {
594
667
  this.notify(session.id, { sessionUpdate: 'current_mode_update', currentModeId: session.modeId });
595
668
  return {};
596
669
  }
670
+ canonicalizePath(targetPath) {
671
+ const resolved = path.resolve(targetPath);
672
+ try {
673
+ return fs.realpathSync(resolved);
674
+ }
675
+ catch {
676
+ return resolved;
677
+ }
678
+ }
597
679
  listSessions(params) {
598
- const filter = params && typeof params.cwd === 'string' ? path.resolve(params.cwd) : null;
680
+ const filter = params && typeof params.cwd === 'string' ? this.canonicalizePath(params.cwd) : null;
599
681
  const sessions = [];
600
682
  for (const session of this.sessions.values()) {
601
683
  if (filter && session.cwd !== filter)
@@ -613,6 +695,7 @@ export class AcpServer {
613
695
  closeSession(params) {
614
696
  const session = this.requireSession(params?.sessionId);
615
697
  session.cancelled = true;
698
+ this.rejectPendingForSession(session.id, 'session closed');
616
699
  try {
617
700
  session.loop?.abort();
618
701
  }
@@ -627,6 +710,9 @@ export class AcpServer {
627
710
  if (!params || typeof params.sessionId !== 'string' || !params.sessionId) {
628
711
  throw this.paramsError('session/load requires sessionId');
629
712
  }
713
+ if (Array.isArray(params.mcpServers) && params.mcpServers.length > 0) {
714
+ throw this.paramsError('MCP servers are not supported by this agent');
715
+ }
630
716
  const live = this.sessions.get(params.sessionId);
631
717
  if (live) {
632
718
  this.bindWorkspace(live.cwd);
@@ -638,7 +724,7 @@ export class AcpServer {
638
724
  throw this.notFound(`Unknown session: ${params.sessionId}`);
639
725
  const requested = params.cwd ?? record.workspace;
640
726
  const cwd = this.resolveWorkspace(requested);
641
- if (record.workspace && path.resolve(record.workspace) !== cwd) {
727
+ if (record.workspace && this.canonicalizePath(record.workspace) !== cwd) {
642
728
  throw this.paramsError('session workspace does not match cwd');
643
729
  }
644
730
  this.bindWorkspace(cwd);
@@ -665,7 +751,7 @@ export class AcpServer {
665
751
  const cwd = this.resolveWorkspace(requested);
666
752
  if (source && source.cwd !== cwd)
667
753
  throw this.paramsError('fork must stay in the source workspace');
668
- if (sourceRecord?.workspace && path.resolve(sourceRecord.workspace) !== cwd) {
754
+ if (sourceRecord?.workspace && this.canonicalizePath(sourceRecord.workspace) !== cwd) {
669
755
  throw this.paramsError('fork must stay in the source workspace');
670
756
  }
671
757
  this.bindWorkspace(cwd);
@@ -695,6 +781,15 @@ export class AcpServer {
695
781
  error.acpCode = ACP_ERROR_CODES.RESOURCE_NOT_FOUND;
696
782
  return error;
697
783
  }
784
+ rejectPendingForSession(sessionId, reason) {
785
+ for (const [id, pending] of this.pending) {
786
+ if (pending.sessionId !== sessionId)
787
+ continue;
788
+ clearTimeout(pending.timer);
789
+ this.pending.delete(id);
790
+ pending.reject(new Error(reason));
791
+ }
792
+ }
698
793
  sendClientRequest(session, method, params) {
699
794
  const id = `server-${this.nextClientRequestId++}`;
700
795
  return new Promise((resolve, reject) => {
@@ -702,7 +797,10 @@ export class AcpServer {
702
797
  this.pending.delete(id);
703
798
  reject(new Error(`${method} timed out`));
704
799
  }, this.permissionTimeoutMs);
800
+ if (typeof timer.unref === 'function')
801
+ timer.unref();
705
802
  this.pending.set(id, {
803
+ sessionId: session.id,
706
804
  resolve: (value) => resolve(value),
707
805
  reject,
708
806
  timer