@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
package/src/acp/client.ts CHANGED
@@ -4,6 +4,9 @@ import fsSync from 'node:fs';
4
4
  import fs from 'node:fs/promises';
5
5
  import os from 'node:os';
6
6
  import path from 'node:path';
7
+ import { isPhysicalPathAllowed } from '../agent/workspaceBoundary.js';
8
+ import { isCredentialPath } from '../sandbox.js';
9
+ import { redactProviderSecrets } from '../providers/byokHttp.js';
7
10
  import {
8
11
  ACP_ERROR_CODES,
9
12
  ACP_METHODS,
@@ -73,11 +76,16 @@ function createAbortError(message = 'ACP operation aborted by user'): Error {
73
76
 
74
77
  const MAX_STDERR_CHARS = 4000;
75
78
  const MAX_UPDATE_CHARS = 200_000;
79
+ const MAX_HOST_FILE_BYTES = 4 * 1024 * 1024;
80
+ const MAX_JSONRPC_BUFFER_BYTES = 16 * 1024 * 1024;
81
+ const MAX_TRACKED_SESSIONS = 128;
82
+ const MAX_OPEN_TOOL_CALLS = 512;
76
83
 
77
84
  export class AcpClient {
78
85
  private readonly options: AcpClientOptions;
79
86
  private child: ChildProcessWithoutNullStreams | null = null;
80
87
  private buffer = '';
88
+ private draining = false;
81
89
  private stderrTail = '';
82
90
  private readonly pending = new Map<string | number, PendingRequest>();
83
91
  private readonly openToolCalls = new Map<string, number>();
@@ -159,6 +167,10 @@ export class AcpClient {
159
167
  usesConfigOption: extracted.usesConfigOption || Boolean(existing?.usesConfigOption),
160
168
  configOptionId: extracted.configOptionId ?? existing?.configOptionId
161
169
  };
170
+ if (!this.sessionModels.has(sessionId) && this.sessionModels.size >= MAX_TRACKED_SESSIONS) {
171
+ const oldest = this.sessionModels.keys().next().value;
172
+ if (oldest !== undefined) this.sessionModels.delete(oldest);
173
+ }
162
174
  this.sessionModels.set(sessionId, merged);
163
175
  this.latestSessionModels = merged;
164
176
  }
@@ -167,9 +179,17 @@ export class AcpClient {
167
179
  if (signal?.aborted) throw createAbortError();
168
180
  if (this.child) throw new Error('client already started');
169
181
  const args = this.options.args ?? [];
182
+ let childEnv: NodeJS.ProcessEnv;
183
+ if (this.options.env) {
184
+ childEnv = this.options.env;
185
+ } else {
186
+ childEnv = { ...process.env };
187
+ delete childEnv.CAUSYNE_VAULT_KEY;
188
+ delete childEnv.CAUSYNE_DEV_SECRET;
189
+ }
170
190
  const child = spawn(this.options.command, args, {
171
191
  cwd: this.options.cwd,
172
- env: this.options.env ?? process.env,
192
+ env: childEnv,
173
193
  stdio: ['pipe', 'pipe', 'pipe'],
174
194
  windowsHide: true
175
195
  });
@@ -179,6 +199,11 @@ export class AcpClient {
179
199
  child.stdout.on('data', (chunk: string) => {
180
200
  if (this.closed) return;
181
201
  this.buffer += chunk;
202
+ if (this.buffer.length > MAX_JSONRPC_BUFFER_BYTES) {
203
+ this.buffer = '';
204
+ this.failAll(new Error('agent output frame exceeded maximum size'));
205
+ return;
206
+ }
182
207
  this.notifyPendingActivity();
183
208
  void this.drain();
184
209
  });
@@ -189,7 +214,8 @@ export class AcpClient {
189
214
  });
190
215
  child.on('error', (error) => this.failAll(new Error(`agent process failed: ${error.message}`)));
191
216
  child.on('exit', (code, exitSignal) => {
192
- const detail = this.stderrTail.trim() || `exit code ${code ?? 'null'}${exitSignal ? ` signal ${exitSignal}` : ''}`;
217
+ const cleanTail = redactProviderSecrets(this.stderrTail).trim();
218
+ const detail = cleanTail || `exit code ${code ?? 'null'}${exitSignal ? ` signal ${exitSignal}` : ''}`;
193
219
  this.failAll(new Error(`agent process exited: ${detail}`));
194
220
  });
195
221
 
@@ -212,6 +238,9 @@ export class AcpClient {
212
238
  }
213
239
 
214
240
  async newSession(cwd: string, mcpServers: unknown[] = [], signal?: AbortSignal): Promise<string> {
241
+ if (typeof cwd !== 'string' || !cwd.trim() || cwd.includes('\0')) {
242
+ throw new Error('newSession requires a valid cwd');
243
+ }
215
244
  const result = await this.request<{ sessionId?: unknown }>(ACP_METHODS.NEW_SESSION, {
216
245
  cwd,
217
246
  mcpServers
@@ -223,14 +252,20 @@ export class AcpClient {
223
252
  return result.sessionId;
224
253
  }
225
254
 
226
- async authenticate(methodId: string, params: Record<string, unknown> = {}): Promise<unknown> {
255
+ async authenticate(methodId: string, params: Record<string, unknown> = {}, signal?: AbortSignal): Promise<unknown> {
256
+ if (typeof methodId !== 'string' || !methodId.trim()) {
257
+ throw new Error('authenticate requires a non-empty methodId');
258
+ }
227
259
  return await this.request<unknown>(ACP_METHODS.AUTHENTICATE, {
228
- methodId,
260
+ methodId: methodId.trim(),
229
261
  params
230
- }, 30_000);
262
+ }, 30_000, signal);
231
263
  }
232
264
 
233
265
  async setSessionModel(sessionId: string, modelId: string, signal?: AbortSignal): Promise<void> {
266
+ if (typeof sessionId !== 'string' || !sessionId.trim() || typeof modelId !== 'string' || !modelId.trim()) {
267
+ throw new Error('setSessionModel requires non-empty sessionId and modelId');
268
+ }
234
269
  const state = this.sessionModels.get(sessionId) ?? this.latestSessionModels;
235
270
  try {
236
271
  const res = await this.request<unknown>(ACP_METHODS.SET_MODEL, {
@@ -261,18 +296,24 @@ export class AcpClient {
261
296
  }
262
297
  }
263
298
 
264
- async setSessionMode(sessionId: string, modeId: string): Promise<void> {
299
+ async setSessionMode(sessionId: string, modeId: string, signal?: AbortSignal): Promise<void> {
300
+ if (typeof sessionId !== 'string' || !sessionId.trim() || typeof modeId !== 'string' || !modeId.trim()) {
301
+ throw new Error('setSessionMode requires non-empty sessionId and modeId');
302
+ }
265
303
  await this.request<void>(ACP_METHODS.SET_MODE, {
266
304
  sessionId,
267
305
  modeId
268
- }, 30_000);
306
+ }, 30_000, signal);
269
307
  }
270
308
 
271
- async loadSession(sessionId: string, cwd?: string): Promise<unknown> {
309
+ async loadSession(sessionId: string, cwd?: string, signal?: AbortSignal): Promise<unknown> {
310
+ if (typeof sessionId !== 'string' || !sessionId.trim()) {
311
+ throw new Error('loadSession requires a non-empty sessionId');
312
+ }
272
313
  const res = await this.request<unknown>(ACP_METHODS.LOAD, {
273
314
  sessionId,
274
315
  cwd: cwd || this.options.cwd
275
- }, 30_000);
316
+ }, 30_000, signal);
276
317
  this.recordSessionModels(sessionId, res);
277
318
  return res;
278
319
  }
@@ -286,17 +327,22 @@ export class AcpClient {
286
327
  this.notifyPendingActivity();
287
328
  // handleLine already notifies options.onUpdate for this session. Calling
288
329
  // it again here duplicated every live chunk and file-action frame.
289
- if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {
330
+ if (
331
+ update.sessionUpdate === 'agent_message_chunk' &&
332
+ update.content !== null &&
333
+ typeof update.content === 'object' &&
334
+ update.content.type === 'text' &&
335
+ typeof update.content.text === 'string'
336
+ ) {
290
337
  collected = `${collected}${update.content.text}`.slice(0, MAX_UPDATE_CHARS);
291
338
  }
292
339
  };
293
- const previous = this.updateListener;
294
- this.updateListener = (sessionIdFromEvent, update) => {
340
+ const listener = (sessionIdFromEvent: string, update: SessionUpdate): void => {
295
341
  if (signal?.aborted) return;
296
342
  this.notifyPendingActivity();
297
- previous?.(sessionIdFromEvent, update);
298
343
  if (sessionIdFromEvent === sessionId) collector(update);
299
344
  };
345
+ this.updateListeners.add(listener);
300
346
  const onAbort = (): void => {
301
347
  try {
302
348
  this.notifyCancel(sessionId);
@@ -306,12 +352,20 @@ export class AcpClient {
306
352
  };
307
353
  signal?.addEventListener('abort', onAbort, { once: true });
308
354
  try {
355
+ const rawPromptTimeout = this.options.promptTimeoutMs;
356
+ const promptTimeoutMs = typeof rawPromptTimeout === 'number' && Number.isFinite(rawPromptTimeout) && rawPromptTimeout > 0
357
+ ? Math.max(10, Math.min(3_600_000, Math.round(rawPromptTimeout)))
358
+ : 15 * 60 * 1000;
359
+ const rawInactivityTimeout = this.options.inactivityTimeoutMs;
360
+ const inactivityTimeoutMs = typeof rawInactivityTimeout === 'number' && Number.isFinite(rawInactivityTimeout) && rawInactivityTimeout > 0
361
+ ? Math.max(10, Math.min(3_600_000, Math.round(rawInactivityTimeout)))
362
+ : 120_000;
309
363
  const response = await this.request<PromptResponse>(ACP_METHODS.PROMPT, {
310
364
  sessionId,
311
365
  prompt: blocks
312
- }, this.options.promptTimeoutMs ?? 15 * 60 * 1000, signal, {
366
+ }, promptTimeoutMs, signal, {
313
367
  sessionId,
314
- inactivityTimeoutMs: this.options.inactivityTimeoutMs ?? 120_000
368
+ inactivityTimeoutMs
315
369
  });
316
370
  return {
317
371
  stopReason: response?.stopReason ?? 'end_turn',
@@ -320,7 +374,7 @@ export class AcpClient {
320
374
  };
321
375
  } finally {
322
376
  signal?.removeEventListener('abort', onAbort);
323
- this.updateListener = previous;
377
+ this.updateListeners.delete(listener);
324
378
  this.clearOpenToolCalls(sessionId);
325
379
  }
326
380
  }
@@ -342,7 +396,13 @@ export class AcpClient {
342
396
  if (status === 'completed' || status === 'failed' || status === 'cancelled') {
343
397
  this.openToolCalls.delete(key);
344
398
  } else if (record.sessionUpdate === 'tool_call' || status === 'pending' || status === 'in_progress') {
345
- if (!this.openToolCalls.has(key)) this.openToolCalls.set(key, Date.now());
399
+ if (!this.openToolCalls.has(key)) {
400
+ if (this.openToolCalls.size >= MAX_OPEN_TOOL_CALLS) {
401
+ const oldest = this.openToolCalls.keys().next().value;
402
+ if (oldest !== undefined) this.openToolCalls.delete(oldest);
403
+ }
404
+ this.openToolCalls.set(key, Date.now());
405
+ }
346
406
  }
347
407
  }
348
408
 
@@ -375,6 +435,9 @@ export class AcpClient {
375
435
  this.closed = true;
376
436
  const child = this.child;
377
437
  this.child = null;
438
+ this.buffer = '';
439
+ this.openToolCalls.clear();
440
+ this.updateListeners.clear();
378
441
  this.failAll(new Error('client closed'));
379
442
  if (!child) return;
380
443
  if (child.exitCode !== null || child.signalCode !== null) return;
@@ -407,7 +470,7 @@ export class AcpClient {
407
470
  });
408
471
  }
409
472
 
410
- private updateListener: ((sessionId: string, update: SessionUpdate) => void) | null = null;
473
+ private readonly updateListeners = new Set<(sessionId: string, update: SessionUpdate) => void>();
411
474
 
412
475
  private write(message: JsonRpcRequest<unknown> | JsonRpcResponse | JsonRpcNotification<unknown>): void {
413
476
  if (!this.child || this.closed) return;
@@ -419,12 +482,18 @@ export class AcpClient {
419
482
  }
420
483
 
421
484
  private async drain(): Promise<void> {
422
- let index = this.buffer.indexOf('\n');
423
- while (index >= 0) {
424
- const line = this.buffer.slice(0, index).trim();
425
- this.buffer = this.buffer.slice(index + 1);
426
- if (line) await this.handleLine(line);
427
- index = this.buffer.indexOf('\n');
485
+ if (this.draining) return;
486
+ this.draining = true;
487
+ try {
488
+ let index = this.buffer.indexOf('\n');
489
+ while (index >= 0 && !this.closed) {
490
+ const line = this.buffer.slice(0, index).replace(/^\uFEFF/, '').trim();
491
+ this.buffer = this.buffer.slice(index + 1);
492
+ if (line) await this.handleLine(line);
493
+ index = this.buffer.indexOf('\n');
494
+ }
495
+ } finally {
496
+ this.draining = false;
428
497
  }
429
498
  }
430
499
 
@@ -446,10 +515,18 @@ export class AcpClient {
446
515
  const method = (parsed as { method?: unknown }).method;
447
516
  if (method === ACP_METHODS.UPDATE) {
448
517
  const params = (parsed as { params?: SessionNotification }).params;
449
- if (params && typeof params.sessionId === 'string' && params.update) {
518
+ if (
519
+ params &&
520
+ typeof params.sessionId === 'string' &&
521
+ params.update !== null &&
522
+ typeof params.update === 'object' &&
523
+ !Array.isArray(params.update)
524
+ ) {
450
525
  this.recordSessionModels(params.sessionId, params.update);
451
526
  this.trackToolCall(params.sessionId, params.update);
452
- this.updateListener?.(params.sessionId, params.update);
527
+ for (const listener of [...this.updateListeners]) {
528
+ listener(params.sessionId, params.update);
529
+ }
453
530
  this.options.onUpdate?.(params.sessionId, params.update);
454
531
  }
455
532
  }
@@ -473,8 +550,12 @@ export class AcpClient {
473
550
  return;
474
551
  }
475
552
  try {
476
- const outcome = await handler(request.params as unknown as RequestPermissionRequest);
477
- this.write({ jsonrpc: '2.0', id: request.id, result: { outcome } });
553
+ const rawOutcome = await handler(request.params as unknown as RequestPermissionRequest);
554
+ const validOutcome: RequestPermissionResponse['outcome'] =
555
+ rawOutcome && typeof rawOutcome === 'object' && rawOutcome.outcome === 'selected' && typeof rawOutcome.optionId === 'string'
556
+ ? { outcome: 'selected', optionId: rawOutcome.optionId }
557
+ : { outcome: 'cancelled' };
558
+ this.write({ jsonrpc: '2.0', id: request.id, result: { outcome: validOutcome } });
478
559
  } catch {
479
560
  this.write({ jsonrpc: '2.0', id: request.id, result: { outcome: { outcome: 'cancelled' } } });
480
561
  }
@@ -501,8 +582,36 @@ export class AcpClient {
501
582
  if (params?.limit !== undefined) readOpts.limit = params.limit;
502
583
  content = await this.options.fsReadHandler(targetPath, readOpts);
503
584
  } else {
585
+ if (targetPath.includes('\0')) {
586
+ throw new Error('File path contains invalid NUL byte');
587
+ }
504
588
  const resolved = path.resolve(this.options.cwd, targetPath);
505
- content = await fs.readFile(resolved, 'utf8');
589
+ if (!isPhysicalPathAllowed(resolved, [this.options.cwd], false)) {
590
+ throw new Error('File path is outside the allowed workspace');
591
+ }
592
+ if (isCredentialPath(resolved)) {
593
+ throw new Error('Reading credential files via ACP host bridge is prohibited');
594
+ }
595
+ const stat = await fs.lstat(resolved);
596
+ if (stat.isSymbolicLink() || !stat.isFile()) {
597
+ throw new Error('Refusing to read symlink or non-regular file');
598
+ }
599
+ if (stat.size > MAX_HOST_FILE_BYTES) {
600
+ throw new Error(`File exceeds maximum readable size (${MAX_HOST_FILE_BYTES} bytes)`);
601
+ }
602
+ const rawContent = await fs.readFile(resolved, 'utf8');
603
+ if (typeof params?.line === 'number' || typeof params?.limit === 'number') {
604
+ const lines = rawContent.split(/\r?\n/);
605
+ const start = typeof params?.line === 'number' && Number.isFinite(params.line)
606
+ ? Math.max(0, Math.floor(params.line) - 1)
607
+ : 0;
608
+ const count = typeof params?.limit === 'number' && Number.isFinite(params.limit) && params.limit > 0
609
+ ? Math.floor(params.limit)
610
+ : lines.length;
611
+ content = lines.slice(start, start + count).join('\n');
612
+ } else {
613
+ content = rawContent;
614
+ }
506
615
  }
507
616
  this.write({
508
617
  jsonrpc: '2.0',
@@ -537,7 +646,28 @@ export class AcpClient {
537
646
  if (this.options.fsWriteHandler) {
538
647
  await this.options.fsWriteHandler(targetPath, content);
539
648
  } else {
649
+ if (targetPath.includes('\0')) {
650
+ throw new Error('File path contains invalid NUL byte');
651
+ }
652
+ if (Buffer.byteLength(content, 'utf8') > MAX_HOST_FILE_BYTES) {
653
+ throw new Error(`File content exceeds maximum writable size (${MAX_HOST_FILE_BYTES} bytes)`);
654
+ }
540
655
  const resolved = path.resolve(this.options.cwd, targetPath);
656
+ if (!isPhysicalPathAllowed(resolved, [this.options.cwd], false)) {
657
+ throw new Error('File path is outside the allowed workspace');
658
+ }
659
+ if (isCredentialPath(resolved)) {
660
+ throw new Error('Writing credential files via ACP host bridge is prohibited');
661
+ }
662
+ try {
663
+ const existing = await fs.lstat(resolved);
664
+ if (existing.isSymbolicLink() || !existing.isFile()) {
665
+ throw new Error('Refusing to overwrite symlink or non-regular file');
666
+ }
667
+ } catch (statErr: unknown) {
668
+ const code = typeof statErr === 'object' && statErr !== null && 'code' in statErr ? String(statErr.code) : '';
669
+ if (code !== 'ENOENT') throw statErr;
670
+ }
541
671
  await fs.mkdir(path.dirname(resolved), { recursive: true });
542
672
  await fs.writeFile(resolved, content, 'utf8');
543
673
  }
@@ -612,7 +742,7 @@ export class AcpClient {
612
742
  for (const pat of fatalPatterns) {
613
743
  if (pat.test(this.stderrTail)) {
614
744
  const match = this.stderrTail.split('\n').find(l => pat.test(l));
615
- if (match) return match.trim();
745
+ if (match) return redactProviderSecrets(match).trim();
616
746
  }
617
747
  }
618
748
  }
@@ -628,10 +758,12 @@ export class AcpClient {
628
758
 
629
759
  private inspectOpencodeLog(sessionId?: string, sinceEpochMs?: number): string | null {
630
760
  try {
631
- const logPath = path.join(os.homedir(), '.local', 'share', 'opencode', 'log', 'opencode.log');
761
+ const home = os.homedir();
762
+ if (!home) return null;
763
+ const logPath = path.join(home, '.local', 'share', 'opencode', 'log', 'opencode.log');
632
764
  if (!fsSync.existsSync(logPath)) return null;
633
- const stat = fsSync.statSync(logPath);
634
- if (stat.size === 0) return null;
765
+ const stat = fsSync.lstatSync(logPath);
766
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size === 0) return null;
635
767
  const readBytes = Math.min(stat.size, 65536);
636
768
  const buffer = Buffer.alloc(readBytes);
637
769
  const fd = fsSync.openSync(logPath, 'r');
@@ -662,9 +794,9 @@ export class AcpClient {
662
794
  if (line.includes('level=ERROR') || line.includes('AI_APICallError') || line.includes('Free usage limit reached') || line.includes('AI_RetryError')) {
663
795
  const match = line.match(/error\.error="([^"]+)"/) || line.match(/message="([^"]+)"/);
664
796
  if (match && match[1]) {
665
- return match[1].replace(/\\n/g, ' ').trim();
797
+ return redactProviderSecrets(match[1].replace(/\\n/g, ' ')).trim();
666
798
  }
667
- return line.trim();
799
+ return redactProviderSecrets(line).trim();
668
800
  }
669
801
  }
670
802
  } catch {
@@ -686,63 +818,81 @@ export class AcpClient {
686
818
  const id = this.nextId++;
687
819
  const requestStartMs = Date.now();
688
820
  return new Promise<T>((resolve, reject) => {
821
+ let settled = false;
689
822
  let inactivityTimer: NodeJS.Timeout | undefined;
690
823
  let snifferInterval: NodeJS.Timeout | undefined;
691
824
 
692
825
  const cleanup = (): void => {
693
826
  signal?.removeEventListener('abort', onAbort);
694
- if (inactivityTimer) clearTimeout(inactivityTimer);
695
- if (snifferInterval) clearInterval(snifferInterval);
827
+ if (inactivityTimer) {
828
+ clearTimeout(inactivityTimer);
829
+ inactivityTimer = undefined;
830
+ }
831
+ if (snifferInterval) {
832
+ clearInterval(snifferInterval);
833
+ snifferInterval = undefined;
834
+ }
696
835
  };
697
- const onAbort = (): void => {
836
+ const settleResolve = (value: unknown): void => {
837
+ if (settled) return;
838
+ settled = true;
698
839
  clearTimeout(timer);
699
840
  cleanup();
700
841
  this.pending.delete(id);
701
- reject(createAbortError());
842
+ resolve(value as T);
702
843
  };
703
- const timer = setTimeout(() => {
844
+ const settleReject = (error: Error): void => {
845
+ if (settled) return;
846
+ settled = true;
847
+ clearTimeout(timer);
704
848
  cleanup();
705
849
  this.pending.delete(id);
850
+ reject(error);
851
+ };
852
+ const onAbort = (): void => {
853
+ settleReject(createAbortError());
854
+ };
855
+ const timer = setTimeout(() => {
706
856
  const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
707
857
  if (diag) {
708
- reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
858
+ settleReject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
709
859
  } else {
710
- reject(new Error(`${method} timed out after ${timeoutMs}ms`));
860
+ settleReject(new Error(`${method} timed out after ${timeoutMs}ms`));
711
861
  }
712
862
  }, timeoutMs);
713
863
  if (typeof timer.unref === 'function') timer.unref();
714
864
 
715
865
  const resetInactivity = (): void => {
866
+ if (settled) return;
716
867
  const timeoutMsInact = options?.inactivityTimeoutMs;
717
868
  if (!timeoutMsInact) return;
718
869
  if (inactivityTimer) clearTimeout(inactivityTimer);
719
870
  inactivityTimer = setTimeout(() => {
871
+ if (settled) return;
720
872
  if (this.hasOpenToolCall(options?.sessionId) && !this.inspectPeerDiagnostics(options?.sessionId, requestStartMs)) {
721
873
  resetInactivity();
722
874
  return;
723
875
  }
724
- cleanup();
725
- this.pending.delete(id);
726
876
  const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
727
877
  if (diag) {
728
- reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
878
+ settleReject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
729
879
  } else {
730
- reject(new Error(`${method} stalled: no activity from peer in ${Math.round(timeoutMsInact / 1000)}s`));
880
+ settleReject(new Error(`${method} stalled: no activity from peer in ${Math.round(timeoutMsInact / 1000)}s`));
731
881
  }
732
882
  }, timeoutMsInact);
733
883
  if (typeof inactivityTimer.unref === 'function') inactivityTimer.unref();
884
+ const entry = this.pending.get(id);
885
+ if (entry) entry.inactivityTimer = inactivityTimer;
734
886
  };
735
887
 
736
888
  const sid = options?.sessionId;
737
889
  if (sid) {
738
890
  snifferInterval = setInterval(() => {
891
+ if (settled) return;
739
892
  const fatalDiag = this.inspectPeerDiagnostics(sid, requestStartMs);
740
893
  if (fatalDiag) {
741
- cleanup();
742
- clearTimeout(timer);
743
- this.pending.delete(id);
744
894
  try { this.notifyCancel(sid); } catch { /* ignore */ }
745
- reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${fatalDiag}`));
895
+ settleReject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${fatalDiag}`));
746
896
  }
747
897
  }, 1500);
748
898
  if (typeof snifferInterval.unref === 'function') snifferInterval.unref();
@@ -751,8 +901,8 @@ export class AcpClient {
751
901
  resetInactivity();
752
902
  signal?.addEventListener('abort', onAbort, { once: true });
753
903
  this.pending.set(id, {
754
- resolve: (value) => resolve(value as T),
755
- reject,
904
+ resolve: settleResolve,
905
+ reject: settleReject,
756
906
  timer,
757
907
  inactivityTimer,
758
908
  snifferInterval,
@@ -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
  const PROFILE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
6
8
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
@@ -19,7 +21,7 @@ function asStringArray(value, limit, maxChars) {
19
21
  return null;
20
22
  const result = [];
21
23
  for (const item of value) {
22
- if (typeof item !== 'string')
24
+ if (typeof item !== 'string' || /[\r\n\0]/.test(item))
23
25
  return null;
24
26
  result.push(item.slice(0, maxChars));
25
27
  }
@@ -35,7 +37,7 @@ function asEnv(value) {
35
37
  break;
36
38
  if (!ENV_NAME.test(name))
37
39
  continue;
38
- if (typeof raw !== 'string')
40
+ if (typeof raw !== 'string' || raw.includes('\0'))
39
41
  continue;
40
42
  result[name] = raw.slice(0, MAX_ENV_VALUE_CHARS);
41
43
  count += 1;
@@ -50,38 +52,48 @@ function parseProfile(raw) {
50
52
  if (!PROFILE_ID.test(id))
51
53
  return null;
52
54
  const command = typeof record.command === 'string' ? record.command.trim() : '';
53
- if (!command || command.length > 500)
55
+ if (!command || command.length > 500 || /[\r\n\0]/.test(command))
54
56
  return null;
55
57
  const args = asStringArray(record.args ?? [], MAX_ARGS, MAX_ARG_CHARS);
56
58
  if (args === null)
57
59
  return null;
58
60
  let cwd = null;
59
61
  if (typeof record.cwd === 'string' && record.cwd.trim()) {
62
+ if (/[\r\n\0]/.test(record.cwd))
63
+ return null;
60
64
  const resolved = path.resolve(record.cwd.trim());
65
+ if (isBlockedWorkspaceRoot(resolved))
66
+ return null;
61
67
  try {
62
- if (!fs.statSync(resolved).isDirectory())
68
+ const real = fs.realpathSync(resolved);
69
+ if (isBlockedWorkspaceRoot(real))
63
70
  return null;
64
- cwd = resolved;
71
+ if (!fs.statSync(real).isDirectory())
72
+ return null;
73
+ cwd = real;
65
74
  }
66
75
  catch {
67
76
  return null;
68
77
  }
69
78
  }
70
- const policy = record.policy === 'read-only'
71
- ? 'read-only'
72
- : (record.policy === 'ask' ? 'ask' : 'workspace');
79
+ const policy = record.policy === undefined
80
+ ? 'workspace'
81
+ : (record.policy === 'read-only' ? 'read-only' : (record.policy === 'workspace' ? 'workspace' : 'ask'));
73
82
  const timeoutSeconds = typeof record.timeoutSeconds === 'number' && Number.isFinite(record.timeoutSeconds)
74
83
  ? Math.max(5, Math.min(1800, Math.round(record.timeoutSeconds)))
75
84
  : 120;
76
- const label = typeof record.label === 'string' && record.label.trim()
77
- ? record.label.trim().slice(0, 100)
78
- : id;
85
+ const rawLabel = typeof record.label === 'string' ? record.label.replace(/[\r\n\0]+/g, ' ').trim() : '';
86
+ const label = rawLabel ? rawLabel.slice(0, 100) : id;
79
87
  return { id, label, command, args, cwd, policy, timeoutSeconds, env: asEnv(record.env) };
80
88
  }
81
89
  export function loadPeerProfiles() {
82
90
  let raw;
83
91
  try {
84
- raw = JSON.parse(fs.readFileSync(peerProfilesPath(), 'utf8'));
92
+ const file = peerProfilesPath();
93
+ const stat = fs.lstatSync(file);
94
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1024 * 1024)
95
+ return [];
96
+ raw = JSON.parse(fs.readFileSync(file, 'utf8'));
85
97
  }
86
98
  catch {
87
99
  return [];
@@ -111,27 +123,27 @@ export function loadPeerProfiles() {
111
123
  }
112
124
  export function savePeerProfiles(profiles) {
113
125
  const file = peerProfilesPath();
114
- const dir = path.dirname(file);
115
- if (!fs.existsSync(dir)) {
116
- fs.mkdirSync(dir, { recursive: true });
117
- }
118
126
  const content = {
119
127
  schemaVersion: 1,
120
128
  peers: profiles
121
129
  };
122
- fs.writeFileSync(file, JSON.stringify(content, null, 2), 'utf8');
130
+ atomicWriteSecretFileSync(file, JSON.stringify(content, null, 2));
123
131
  }
124
132
  export function addPeerProfile(profile) {
133
+ const validated = parseProfile(profile);
134
+ if (!validated) {
135
+ return { ok: false, error: 'Invalid peer profile configuration.' };
136
+ }
125
137
  const current = loadPeerProfiles();
126
- const idx = current.findIndex((p) => p.id === profile.id);
138
+ const idx = current.findIndex((p) => p.id === validated.id);
127
139
  if (idx >= 0) {
128
- current[idx] = profile;
140
+ current[idx] = validated;
129
141
  }
130
142
  else {
131
143
  if (current.length >= MAX_PEERS) {
132
144
  return { ok: false, error: `Maximum of ${MAX_PEERS} peer profiles exceeded.` };
133
145
  }
134
- current.push(profile);
146
+ current.push(validated);
135
147
  }
136
148
  try {
137
149
  savePeerProfiles(current);
@@ -187,14 +199,35 @@ export function listAllPeers() {
187
199
  }
188
200
  return all;
189
201
  }
202
+ const BLOCKED_PEER_ENV_KEYS = new Set([
203
+ 'LD_PRELOAD',
204
+ 'LD_LIBRARY_PATH',
205
+ 'DYLD_INSERT_LIBRARIES',
206
+ 'DYLD_LIBRARY_PATH',
207
+ 'DYLD_FRAMEWORK_PATH',
208
+ 'NODE_OPTIONS',
209
+ 'BASH_ENV',
210
+ 'ENV',
211
+ 'PYTHONSTARTUP'
212
+ ]);
190
213
  export function peerEnvironment(profile) {
191
214
  const env = {};
192
- for (const name of ['PATH', 'HOME', 'USER', 'LOGNAME', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL', 'SYSTEMROOT']) {
215
+ const baseKeys = [
216
+ 'PATH', 'Path', 'PATHEXT', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA',
217
+ 'USER', 'LOGNAME', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL',
218
+ 'SYSTEMROOT', 'SystemRoot', 'COMSPEC', 'ComSpec', 'ProgramData'
219
+ ];
220
+ for (const name of baseKeys) {
193
221
  const value = process.env[name];
194
222
  if (typeof value === 'string')
195
223
  env[name] = value;
196
224
  }
197
- for (const [name, value] of Object.entries(profile.env))
225
+ for (const [name, value] of Object.entries(profile.env)) {
226
+ if (BLOCKED_PEER_ENV_KEYS.has(name.toUpperCase()))
227
+ continue;
228
+ if (!ENV_NAME.test(name) || typeof value !== 'string' || value.includes('\0'))
229
+ continue;
198
230
  env[name] = value;
231
+ }
199
232
  return env;
200
233
  }