@causyne/agent 1.20.121 → 1.20.122

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +81 -26
  4. package/src/acp/agentCatalog.ts +73 -29
  5. package/src/acp/client.js +210 -53
  6. package/src/acp/client.ts +202 -52
  7. package/src/acp/peerProfiles.js +55 -22
  8. package/src/acp/peerProfiles.ts +51 -22
  9. package/src/acp/protocol.js +37 -8
  10. package/src/acp/protocol.ts +30 -8
  11. package/src/acp/server.js +123 -25
  12. package/src/acp/server.ts +124 -24
  13. package/src/agent/errorClassifier.js +6 -2
  14. package/src/agent/errorClassifier.ts +6 -2
  15. package/src/agentLoop.js +11 -5
  16. package/src/agentLoop.ts +11 -5
  17. package/src/approvalGrants.js +19 -7
  18. package/src/approvalGrants.ts +20 -7
  19. package/src/approvalPolicy.js +48 -15
  20. package/src/approvalPolicy.ts +46 -15
  21. package/src/autoUpdate.js +5 -2
  22. package/src/autoUpdate.ts +5 -2
  23. package/src/browser/causyneBrowser.js +3 -2
  24. package/src/browser/causyneBrowser.ts +3 -2
  25. package/src/browser/searchProviders.js +1 -1
  26. package/src/browser/searchProviders.ts +1 -1
  27. package/src/config.js +287 -250
  28. package/src/config.ts +342 -0
  29. package/src/configVault.js +84 -17
  30. package/src/configVault.ts +77 -17
  31. package/src/continuum/compactor.js +2 -1
  32. package/src/continuum/compactor.ts +2 -1
  33. package/src/continuum/sanitizer.js +10 -3
  34. package/src/continuum/sanitizer.ts +9 -3
  35. package/src/continuum/ui/continuumPickerView.js +3 -2
  36. package/src/continuum/ui/continuumPickerView.ts +3 -2
  37. package/src/cortex/vectorDb.js +26 -15
  38. package/src/cortex/vectorDb.ts +26 -16
  39. package/src/creative/liveBridge.js +7 -5
  40. package/src/creative/liveBridge.ts +7 -5
  41. package/src/creative/studioScripts.js +16 -5
  42. package/src/creative/studioScripts.ts +14 -5
  43. package/src/decisionPolicy.js +16 -4
  44. package/src/decisionPolicy.ts +14 -4
  45. package/src/documentEngine/antiSlopAuditor.js +10 -5
  46. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  47. package/src/documentEngine/documentForge.js +47 -15
  48. package/src/documentEngine/documentForge.ts +43 -14
  49. package/src/engines/design.js +2 -1
  50. package/src/engines/design.ts +2 -1
  51. package/src/engines/film.js +4 -4
  52. package/src/engines/film.ts +2 -2
  53. package/src/engines/light.js +2 -1
  54. package/src/engines/light.ts +2 -1
  55. package/src/engines/registry.js +1 -1
  56. package/src/engines/registry.ts +1 -1
  57. package/src/engines/reverseHarness.js +4 -3
  58. package/src/engines/reverseHarness.ts +4 -3
  59. package/src/headlessCli.js +2 -1
  60. package/src/headlessCli.ts +2 -1
  61. package/src/historyPruner.js +3 -2
  62. package/src/historyPruner.ts +3 -2
  63. package/src/hooks.js +3 -0
  64. package/src/hooks.ts +3 -0
  65. package/src/implementationPlan.js +21 -11
  66. package/src/implementationPlan.ts +21 -11
  67. package/src/infra/atomicWriter.js +4 -1
  68. package/src/infra/atomicWriter.ts +4 -1
  69. package/src/launchIntent.js +1 -1
  70. package/src/launchIntent.ts +1 -1
  71. package/src/memory/scopedFacts.js +1 -1
  72. package/src/memory/scopedFacts.ts +1 -1
  73. package/src/memory/symbolFolder.js +1 -1
  74. package/src/memory/symbolFolder.ts +1 -1
  75. package/src/modelRouter.js +1 -1
  76. package/src/modelRouter.ts +1 -1
  77. package/src/observer/evidence.js +10 -4
  78. package/src/observer/evidence.ts +10 -4
  79. package/src/osKeychain.js +62 -8
  80. package/src/osKeychain.ts +50 -8
  81. package/src/perception.js +3 -2
  82. package/src/perception.ts +3 -2
  83. package/src/planCache.js +2 -2
  84. package/src/planCache.ts +2 -2
  85. package/src/pluginsFactory/pluginsFactory.js +19 -11
  86. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  87. package/src/promptMentions.js +2 -2
  88. package/src/promptMentions.ts +2 -2
  89. package/src/providers/acp.js +1 -1
  90. package/src/providers/acp.ts +1 -1
  91. package/src/providers/anthropic.js +327 -401
  92. package/src/providers/anthropic.ts +386 -0
  93. package/src/providers/antigravity.js +10 -4
  94. package/src/providers/antigravity.ts +10 -4
  95. package/src/providers/base.js +221 -319
  96. package/src/providers/base.ts +340 -0
  97. package/src/providers/byokHttp.js +58 -15
  98. package/src/providers/byokHttp.ts +59 -16
  99. package/src/providers/byokStream.js +142 -51
  100. package/src/providers/byokStream.ts +146 -42
  101. package/src/providers/dashscope-byok.js +97 -89
  102. package/src/providers/dashscope-byok.ts +114 -0
  103. package/src/providers/deepseek.js +73 -72
  104. package/src/providers/deepseek.ts +99 -0
  105. package/src/providers/factory.js +35 -28
  106. package/src/providers/factory.ts +40 -0
  107. package/src/providers/gemini.js +227 -278
  108. package/src/providers/gemini.ts +261 -0
  109. package/src/providers/loopGuard.js +9 -5
  110. package/src/providers/loopGuard.ts +10 -5
  111. package/src/providers/moonshot.js +70 -72
  112. package/src/providers/moonshot.ts +93 -0
  113. package/src/providers/muse.js +82 -152
  114. package/src/providers/muse.ts +122 -0
  115. package/src/providers/ollama.js +114 -106
  116. package/src/providers/ollama.ts +135 -0
  117. package/src/providers/openai-compatible.js +113 -96
  118. package/src/providers/openai-compatible.ts +139 -0
  119. package/src/providers/openai.js +22 -15
  120. package/src/providers/openai.ts +30 -0
  121. package/src/providers/openrouter.js +136 -74
  122. package/src/providers/openrouter.ts +133 -72
  123. package/src/providers/pi.js +6 -0
  124. package/src/providers/pi.ts +6 -0
  125. package/src/providers/qwen-byok.js +96 -87
  126. package/src/providers/qwen-byok.ts +113 -0
  127. package/src/providers/toolContracts.js +40 -14
  128. package/src/providers/toolContracts.ts +35 -14
  129. package/src/providers/wireNormalizer.js +78 -11
  130. package/src/providers/wireNormalizer.ts +68 -12
  131. package/src/providers/xai.js +73 -72
  132. package/src/providers/xai.ts +97 -0
  133. package/src/reliability/assetEvidence.js +4 -2
  134. package/src/reliability/assetEvidence.ts +4 -2
  135. package/src/sandbox.js +489 -554
  136. package/src/sandbox.ts +552 -0
  137. package/src/sandboxPolicy.js +95 -16
  138. package/src/sandboxPolicy.ts +97 -16
  139. package/src/sessionJournal.js +8 -3
  140. package/src/sessionJournal.ts +9 -3
  141. package/src/skills/skillResourceSafety.js +19 -8
  142. package/src/skills/skillResourceSafety.ts +16 -7
  143. package/src/skillsManager.js +3 -3
  144. package/src/skillsManager.ts +3 -3
  145. package/src/smartToolsUse.js +28 -4
  146. package/src/smartToolsUse.ts +29 -7
  147. package/src/stallGuard.js +45 -22
  148. package/src/stallGuard.ts +46 -22
  149. package/src/subagentJournal.js +6 -4
  150. package/src/subagentJournal.ts +6 -4
  151. package/src/textDiff.js +6 -1
  152. package/src/textDiff.ts +6 -1
  153. package/src/timeMachine.js +7 -1
  154. package/src/timeMachine.ts +7 -1
  155. package/src/tokenTracker.js +43 -28
  156. package/src/tokenTracker.ts +44 -30
  157. package/src/toolPacks.js +3 -1
  158. package/src/toolPacks.ts +3 -1
  159. package/src/tools/archive.js +245 -35
  160. package/src/tools/archive.ts +244 -35
  161. package/src/tools/computerUse.js +7 -3
  162. package/src/tools/computerUse.ts +7 -3
  163. package/src/tools/creativeApps.js +13 -8
  164. package/src/tools/creativeApps.ts +22 -9
  165. package/src/tools/deferredMcpSearch.js +26 -14
  166. package/src/tools/deferredMcpSearch.ts +26 -14
  167. package/src/tools/desktopOpen.js +69 -10
  168. package/src/tools/desktopOpen.ts +70 -11
  169. package/src/tools/documentForge.js +167 -82
  170. package/src/tools/documentForge.ts +169 -84
  171. package/src/tools/fsEdit.js +101 -30
  172. package/src/tools/fsEdit.ts +105 -32
  173. package/src/tools/fsFind.js +8 -5
  174. package/src/tools/fsFind.ts +7 -4
  175. package/src/tools/fsRead.js +119 -13
  176. package/src/tools/fsRead.ts +124 -13
  177. package/src/tools/fsWrite.js +17 -5
  178. package/src/tools/fsWrite.ts +17 -7
  179. package/src/tools/generateMediaViaApi.js +82 -19
  180. package/src/tools/generateMediaViaApi.ts +80 -19
  181. package/src/tools/memoryRecall.js +62 -11
  182. package/src/tools/memoryRecall.ts +70 -13
  183. package/src/tools/memoryWrite.js +27 -14
  184. package/src/tools/memoryWrite.ts +30 -14
  185. package/src/tools/multiEdit.js +100 -30
  186. package/src/tools/multiEdit.ts +104 -32
  187. package/src/tools/nativeEngine.js +33 -18
  188. package/src/tools/nativeEngine.ts +31 -18
  189. package/src/tools/openSourceToolProvisioner.js +49 -14
  190. package/src/tools/openSourceToolProvisioner.ts +54 -15
  191. package/src/tools/osSandbox.js +54 -14
  192. package/src/tools/osSandbox.ts +48 -14
  193. package/src/tools/payloadSanitizer.js +40 -8
  194. package/src/tools/payloadSanitizer.ts +39 -8
  195. package/src/tools/peerAgent.js +96 -34
  196. package/src/tools/peerAgent.ts +114 -37
  197. package/src/tools/pluginsFactory.js +38 -6
  198. package/src/tools/pluginsFactory.ts +42 -6
  199. package/src/tools/readNativeSkill.js +10 -8
  200. package/src/tools/readNativeSkill.ts +10 -8
  201. package/src/tools/requestDecision.js +10 -3
  202. package/src/tools/requestDecision.ts +10 -3
  203. package/src/tools/resolveAutomator.js +91 -17
  204. package/src/tools/resolveAutomator.ts +102 -17
  205. package/src/tools/reverseEngineering.js +168 -41
  206. package/src/tools/reverseEngineering.ts +161 -41
  207. package/src/tools/sysRun.js +69 -29
  208. package/src/tools/sysRun.ts +66 -24
  209. package/src/tools/toolDispatch.js +24 -1
  210. package/src/tools/toolDispatch.ts +21 -1
  211. package/src/tools/toolOutputStore.js +62 -23
  212. package/src/tools/toolOutputStore.ts +56 -23
  213. package/src/tools/toolScanner.js +13 -10
  214. package/src/tools/toolScanner.ts +13 -10
  215. package/src/tools/toolSelfRepair.js +94 -28
  216. package/src/tools/toolSelfRepair.ts +96 -28
  217. package/src/tools/uiForge.js +71 -6
  218. package/src/tools/uiForge.ts +74 -6
  219. package/src/tools/viewImage.js +62 -17
  220. package/src/tools/viewImage.ts +57 -12
  221. package/src/tools/visionInspector.js +15 -3
  222. package/src/tools/visionInspector.ts +15 -3
  223. package/src/tools/walkerSafety.js +2 -0
  224. package/src/tools/walkerSafety.ts +1 -0
  225. package/src/tools/webFetch.js +105 -10
  226. package/src/tools/webFetch.ts +105 -11
  227. package/src/tui/banner.js +3 -2
  228. package/src/tui/banner.ts +3 -2
  229. package/src/tui/consoleGuard.js +12 -4
  230. package/src/tui/consoleGuard.ts +9 -4
  231. package/src/tui/messageInteraction.js +2 -3
  232. package/src/tui/messageInteraction.ts +2 -3
  233. package/src/tui/modelPicker.js +1 -0
  234. package/src/tui/modelPicker.ts +1 -0
  235. package/src/tui/overlay.js +3 -1
  236. package/src/tui/overlay.ts +3 -1
  237. package/src/tui/sessionPicker.js +3 -2
  238. package/src/tui/sessionPicker.ts +3 -2
  239. package/src/tui/sessionPickerView.js +7 -1
  240. package/src/tui/sessionPickerView.ts +6 -1
  241. package/src/tui/toolOutputNormalizer.js +2 -3
  242. package/src/tui/toolOutputNormalizer.ts +4 -3
  243. package/src/tui/viewport.js +4 -4
  244. package/src/tui/viewport.ts +5 -5
  245. package/src/tui/workspaceIdentity.js +2 -1
  246. package/src/tui/workspaceIdentity.ts +2 -1
  247. package/src/uncertainty.js +8 -3
  248. package/src/uncertainty.ts +8 -3
  249. package/src/utils/paths.js +8 -5
  250. package/src/utils/paths.ts +9 -7
  251. package/src/vfeTracker.js +9 -3
  252. package/src/vfeTracker.ts +9 -3
  253. package/src/config.d.ts +0 -2
  254. package/src/providers/base.d.ts +0 -94
  255. package/src/providers/factory.d.ts +0 -1
  256. package/src/sandbox.d.ts +0 -1
package/src/acp/client.js CHANGED
@@ -3,6 +3,9 @@ import fsSync from 'node:fs';
3
3
  import fs from 'node:fs/promises';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
+ import { isPhysicalPathAllowed } from '../agent/workspaceBoundary.js';
7
+ import { isCredentialPath } from '../sandbox.js';
8
+ import { redactProviderSecrets } from '../providers/byokHttp.js';
6
9
  import { ACP_ERROR_CODES, ACP_METHODS, ACP_PROTOCOL_VERSION, extractAcpSessionModels, isJsonRpcRequest, isJsonRpcResponse } from './protocol.js';
7
10
  function createAbortError(message = 'ACP operation aborted by user') {
8
11
  const err = new Error(message);
@@ -11,10 +14,15 @@ function createAbortError(message = 'ACP operation aborted by user') {
11
14
  }
12
15
  const MAX_STDERR_CHARS = 4000;
13
16
  const MAX_UPDATE_CHARS = 200_000;
17
+ const MAX_HOST_FILE_BYTES = 4 * 1024 * 1024;
18
+ const MAX_JSONRPC_BUFFER_BYTES = 16 * 1024 * 1024;
19
+ const MAX_TRACKED_SESSIONS = 128;
20
+ const MAX_OPEN_TOOL_CALLS = 512;
14
21
  export class AcpClient {
15
22
  options;
16
23
  child = null;
17
24
  buffer = '';
25
+ draining = false;
18
26
  stderrTail = '';
19
27
  pending = new Map();
20
28
  openToolCalls = new Map();
@@ -86,6 +94,11 @@ export class AcpClient {
86
94
  usesConfigOption: extracted.usesConfigOption || Boolean(existing?.usesConfigOption),
87
95
  configOptionId: extracted.configOptionId ?? existing?.configOptionId
88
96
  };
97
+ if (!this.sessionModels.has(sessionId) && this.sessionModels.size >= MAX_TRACKED_SESSIONS) {
98
+ const oldest = this.sessionModels.keys().next().value;
99
+ if (oldest !== undefined)
100
+ this.sessionModels.delete(oldest);
101
+ }
89
102
  this.sessionModels.set(sessionId, merged);
90
103
  this.latestSessionModels = merged;
91
104
  }
@@ -95,9 +108,18 @@ export class AcpClient {
95
108
  if (this.child)
96
109
  throw new Error('client already started');
97
110
  const args = this.options.args ?? [];
111
+ let childEnv;
112
+ if (this.options.env) {
113
+ childEnv = this.options.env;
114
+ }
115
+ else {
116
+ childEnv = { ...process.env };
117
+ delete childEnv.CAUSYNE_VAULT_KEY;
118
+ delete childEnv.CAUSYNE_DEV_SECRET;
119
+ }
98
120
  const child = spawn(this.options.command, args, {
99
121
  cwd: this.options.cwd,
100
- env: this.options.env ?? process.env,
122
+ env: childEnv,
101
123
  stdio: ['pipe', 'pipe', 'pipe'],
102
124
  windowsHide: true
103
125
  });
@@ -107,6 +129,11 @@ export class AcpClient {
107
129
  if (this.closed)
108
130
  return;
109
131
  this.buffer += chunk;
132
+ if (this.buffer.length > MAX_JSONRPC_BUFFER_BYTES) {
133
+ this.buffer = '';
134
+ this.failAll(new Error('agent output frame exceeded maximum size'));
135
+ return;
136
+ }
110
137
  this.notifyPendingActivity();
111
138
  void this.drain();
112
139
  });
@@ -117,7 +144,8 @@ export class AcpClient {
117
144
  });
118
145
  child.on('error', (error) => this.failAll(new Error(`agent process failed: ${error.message}`)));
119
146
  child.on('exit', (code, exitSignal) => {
120
- const detail = this.stderrTail.trim() || `exit code ${code ?? 'null'}${exitSignal ? ` signal ${exitSignal}` : ''}`;
147
+ const cleanTail = redactProviderSecrets(this.stderrTail).trim();
148
+ const detail = cleanTail || `exit code ${code ?? 'null'}${exitSignal ? ` signal ${exitSignal}` : ''}`;
121
149
  this.failAll(new Error(`agent process exited: ${detail}`));
122
150
  });
123
151
  const hasFsRead = this.options.allowHostTools !== false && Boolean(this.options.fsReadHandler || this.options.cwd);
@@ -136,6 +164,9 @@ export class AcpClient {
136
164
  return result;
137
165
  }
138
166
  async newSession(cwd, mcpServers = [], signal) {
167
+ if (typeof cwd !== 'string' || !cwd.trim() || cwd.includes('\0')) {
168
+ throw new Error('newSession requires a valid cwd');
169
+ }
139
170
  const result = await this.request(ACP_METHODS.NEW_SESSION, {
140
171
  cwd,
141
172
  mcpServers
@@ -146,13 +177,19 @@ export class AcpClient {
146
177
  this.recordSessionModels(result.sessionId, result);
147
178
  return result.sessionId;
148
179
  }
149
- async authenticate(methodId, params = {}) {
180
+ async authenticate(methodId, params = {}, signal) {
181
+ if (typeof methodId !== 'string' || !methodId.trim()) {
182
+ throw new Error('authenticate requires a non-empty methodId');
183
+ }
150
184
  return await this.request(ACP_METHODS.AUTHENTICATE, {
151
- methodId,
185
+ methodId: methodId.trim(),
152
186
  params
153
- }, 30_000);
187
+ }, 30_000, signal);
154
188
  }
155
189
  async setSessionModel(sessionId, modelId, signal) {
190
+ if (typeof sessionId !== 'string' || !sessionId.trim() || typeof modelId !== 'string' || !modelId.trim()) {
191
+ throw new Error('setSessionModel requires non-empty sessionId and modelId');
192
+ }
156
193
  const state = this.sessionModels.get(sessionId) ?? this.latestSessionModels;
157
194
  try {
158
195
  const res = await this.request(ACP_METHODS.SET_MODEL, {
@@ -183,17 +220,23 @@ export class AcpClient {
183
220
  throw err;
184
221
  }
185
222
  }
186
- async setSessionMode(sessionId, modeId) {
223
+ async setSessionMode(sessionId, modeId, signal) {
224
+ if (typeof sessionId !== 'string' || !sessionId.trim() || typeof modeId !== 'string' || !modeId.trim()) {
225
+ throw new Error('setSessionMode requires non-empty sessionId and modeId');
226
+ }
187
227
  await this.request(ACP_METHODS.SET_MODE, {
188
228
  sessionId,
189
229
  modeId
190
- }, 30_000);
230
+ }, 30_000, signal);
191
231
  }
192
- async loadSession(sessionId, cwd) {
232
+ async loadSession(sessionId, cwd, signal) {
233
+ if (typeof sessionId !== 'string' || !sessionId.trim()) {
234
+ throw new Error('loadSession requires a non-empty sessionId');
235
+ }
193
236
  const res = await this.request(ACP_METHODS.LOAD, {
194
237
  sessionId,
195
238
  cwd: cwd || this.options.cwd
196
- }, 30_000);
239
+ }, 30_000, signal);
197
240
  this.recordSessionModels(sessionId, res);
198
241
  return res;
199
242
  }
@@ -208,19 +251,22 @@ export class AcpClient {
208
251
  this.notifyPendingActivity();
209
252
  // handleLine already notifies options.onUpdate for this session. Calling
210
253
  // it again here duplicated every live chunk and file-action frame.
211
- if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {
254
+ if (update.sessionUpdate === 'agent_message_chunk' &&
255
+ update.content !== null &&
256
+ typeof update.content === 'object' &&
257
+ update.content.type === 'text' &&
258
+ typeof update.content.text === 'string') {
212
259
  collected = `${collected}${update.content.text}`.slice(0, MAX_UPDATE_CHARS);
213
260
  }
214
261
  };
215
- const previous = this.updateListener;
216
- this.updateListener = (sessionIdFromEvent, update) => {
262
+ const listener = (sessionIdFromEvent, update) => {
217
263
  if (signal?.aborted)
218
264
  return;
219
265
  this.notifyPendingActivity();
220
- previous?.(sessionIdFromEvent, update);
221
266
  if (sessionIdFromEvent === sessionId)
222
267
  collector(update);
223
268
  };
269
+ this.updateListeners.add(listener);
224
270
  const onAbort = () => {
225
271
  try {
226
272
  this.notifyCancel(sessionId);
@@ -231,12 +277,20 @@ export class AcpClient {
231
277
  };
232
278
  signal?.addEventListener('abort', onAbort, { once: true });
233
279
  try {
280
+ const rawPromptTimeout = this.options.promptTimeoutMs;
281
+ const promptTimeoutMs = typeof rawPromptTimeout === 'number' && Number.isFinite(rawPromptTimeout) && rawPromptTimeout > 0
282
+ ? Math.max(10, Math.min(3_600_000, Math.round(rawPromptTimeout)))
283
+ : 15 * 60 * 1000;
284
+ const rawInactivityTimeout = this.options.inactivityTimeoutMs;
285
+ const inactivityTimeoutMs = typeof rawInactivityTimeout === 'number' && Number.isFinite(rawInactivityTimeout) && rawInactivityTimeout > 0
286
+ ? Math.max(10, Math.min(3_600_000, Math.round(rawInactivityTimeout)))
287
+ : 120_000;
234
288
  const response = await this.request(ACP_METHODS.PROMPT, {
235
289
  sessionId,
236
290
  prompt: blocks
237
- }, this.options.promptTimeoutMs ?? 15 * 60 * 1000, signal, {
291
+ }, promptTimeoutMs, signal, {
238
292
  sessionId,
239
- inactivityTimeoutMs: this.options.inactivityTimeoutMs ?? 120_000
293
+ inactivityTimeoutMs
240
294
  });
241
295
  return {
242
296
  stopReason: response?.stopReason ?? 'end_turn',
@@ -246,7 +300,7 @@ export class AcpClient {
246
300
  }
247
301
  finally {
248
302
  signal?.removeEventListener('abort', onAbort);
249
- this.updateListener = previous;
303
+ this.updateListeners.delete(listener);
250
304
  this.clearOpenToolCalls(sessionId);
251
305
  }
252
306
  }
@@ -270,8 +324,14 @@ export class AcpClient {
270
324
  this.openToolCalls.delete(key);
271
325
  }
272
326
  else if (record.sessionUpdate === 'tool_call' || status === 'pending' || status === 'in_progress') {
273
- if (!this.openToolCalls.has(key))
327
+ if (!this.openToolCalls.has(key)) {
328
+ if (this.openToolCalls.size >= MAX_OPEN_TOOL_CALLS) {
329
+ const oldest = this.openToolCalls.keys().next().value;
330
+ if (oldest !== undefined)
331
+ this.openToolCalls.delete(oldest);
332
+ }
274
333
  this.openToolCalls.set(key, Date.now());
334
+ }
275
335
  }
276
336
  }
277
337
  clearOpenToolCalls(sessionId) {
@@ -304,6 +364,9 @@ export class AcpClient {
304
364
  this.closed = true;
305
365
  const child = this.child;
306
366
  this.child = null;
367
+ this.buffer = '';
368
+ this.openToolCalls.clear();
369
+ this.updateListeners.clear();
307
370
  this.failAll(new Error('client closed'));
308
371
  if (!child)
309
372
  return;
@@ -344,7 +407,7 @@ export class AcpClient {
344
407
  }
345
408
  });
346
409
  }
347
- updateListener = null;
410
+ updateListeners = new Set();
348
411
  write(message) {
349
412
  if (!this.child || this.closed)
350
413
  return;
@@ -356,13 +419,21 @@ export class AcpClient {
356
419
  }
357
420
  }
358
421
  async drain() {
359
- let index = this.buffer.indexOf('\n');
360
- while (index >= 0) {
361
- const line = this.buffer.slice(0, index).trim();
362
- this.buffer = this.buffer.slice(index + 1);
363
- if (line)
364
- await this.handleLine(line);
365
- index = this.buffer.indexOf('\n');
422
+ if (this.draining)
423
+ return;
424
+ this.draining = true;
425
+ try {
426
+ let index = this.buffer.indexOf('\n');
427
+ while (index >= 0 && !this.closed) {
428
+ const line = this.buffer.slice(0, index).replace(/^\uFEFF/, '').trim();
429
+ this.buffer = this.buffer.slice(index + 1);
430
+ if (line)
431
+ await this.handleLine(line);
432
+ index = this.buffer.indexOf('\n');
433
+ }
434
+ }
435
+ finally {
436
+ this.draining = false;
366
437
  }
367
438
  }
368
439
  async handleLine(line) {
@@ -384,10 +455,16 @@ export class AcpClient {
384
455
  const method = parsed.method;
385
456
  if (method === ACP_METHODS.UPDATE) {
386
457
  const params = parsed.params;
387
- if (params && typeof params.sessionId === 'string' && params.update) {
458
+ if (params &&
459
+ typeof params.sessionId === 'string' &&
460
+ params.update !== null &&
461
+ typeof params.update === 'object' &&
462
+ !Array.isArray(params.update)) {
388
463
  this.recordSessionModels(params.sessionId, params.update);
389
464
  this.trackToolCall(params.sessionId, params.update);
390
- this.updateListener?.(params.sessionId, params.update);
465
+ for (const listener of [...this.updateListeners]) {
466
+ listener(params.sessionId, params.update);
467
+ }
391
468
  this.options.onUpdate?.(params.sessionId, params.update);
392
469
  }
393
470
  }
@@ -410,8 +487,11 @@ export class AcpClient {
410
487
  return;
411
488
  }
412
489
  try {
413
- const outcome = await handler(request.params);
414
- this.write({ jsonrpc: '2.0', id: request.id, result: { outcome } });
490
+ const rawOutcome = await handler(request.params);
491
+ const validOutcome = rawOutcome && typeof rawOutcome === 'object' && rawOutcome.outcome === 'selected' && typeof rawOutcome.optionId === 'string'
492
+ ? { outcome: 'selected', optionId: rawOutcome.optionId }
493
+ : { outcome: 'cancelled' };
494
+ this.write({ jsonrpc: '2.0', id: request.id, result: { outcome: validOutcome } });
415
495
  }
416
496
  catch {
417
497
  this.write({ jsonrpc: '2.0', id: request.id, result: { outcome: { outcome: 'cancelled' } } });
@@ -440,8 +520,37 @@ export class AcpClient {
440
520
  content = await this.options.fsReadHandler(targetPath, readOpts);
441
521
  }
442
522
  else {
523
+ if (targetPath.includes('\0')) {
524
+ throw new Error('File path contains invalid NUL byte');
525
+ }
443
526
  const resolved = path.resolve(this.options.cwd, targetPath);
444
- content = await fs.readFile(resolved, 'utf8');
527
+ if (!isPhysicalPathAllowed(resolved, [this.options.cwd], false)) {
528
+ throw new Error('File path is outside the allowed workspace');
529
+ }
530
+ if (isCredentialPath(resolved)) {
531
+ throw new Error('Reading credential files via ACP host bridge is prohibited');
532
+ }
533
+ const stat = await fs.lstat(resolved);
534
+ if (stat.isSymbolicLink() || !stat.isFile()) {
535
+ throw new Error('Refusing to read symlink or non-regular file');
536
+ }
537
+ if (stat.size > MAX_HOST_FILE_BYTES) {
538
+ throw new Error(`File exceeds maximum readable size (${MAX_HOST_FILE_BYTES} bytes)`);
539
+ }
540
+ const rawContent = await fs.readFile(resolved, 'utf8');
541
+ if (typeof params?.line === 'number' || typeof params?.limit === 'number') {
542
+ const lines = rawContent.split(/\r?\n/);
543
+ const start = typeof params?.line === 'number' && Number.isFinite(params.line)
544
+ ? Math.max(0, Math.floor(params.line) - 1)
545
+ : 0;
546
+ const count = typeof params?.limit === 'number' && Number.isFinite(params.limit) && params.limit > 0
547
+ ? Math.floor(params.limit)
548
+ : lines.length;
549
+ content = lines.slice(start, start + count).join('\n');
550
+ }
551
+ else {
552
+ content = rawContent;
553
+ }
445
554
  }
446
555
  this.write({
447
556
  jsonrpc: '2.0',
@@ -476,7 +585,30 @@ export class AcpClient {
476
585
  await this.options.fsWriteHandler(targetPath, content);
477
586
  }
478
587
  else {
588
+ if (targetPath.includes('\0')) {
589
+ throw new Error('File path contains invalid NUL byte');
590
+ }
591
+ if (Buffer.byteLength(content, 'utf8') > MAX_HOST_FILE_BYTES) {
592
+ throw new Error(`File content exceeds maximum writable size (${MAX_HOST_FILE_BYTES} bytes)`);
593
+ }
479
594
  const resolved = path.resolve(this.options.cwd, targetPath);
595
+ if (!isPhysicalPathAllowed(resolved, [this.options.cwd], false)) {
596
+ throw new Error('File path is outside the allowed workspace');
597
+ }
598
+ if (isCredentialPath(resolved)) {
599
+ throw new Error('Writing credential files via ACP host bridge is prohibited');
600
+ }
601
+ try {
602
+ const existing = await fs.lstat(resolved);
603
+ if (existing.isSymbolicLink() || !existing.isFile()) {
604
+ throw new Error('Refusing to overwrite symlink or non-regular file');
605
+ }
606
+ }
607
+ catch (statErr) {
608
+ const code = typeof statErr === 'object' && statErr !== null && 'code' in statErr ? String(statErr.code) : '';
609
+ if (code !== 'ENOENT')
610
+ throw statErr;
611
+ }
480
612
  await fs.mkdir(path.dirname(resolved), { recursive: true });
481
613
  await fs.writeFile(resolved, content, 'utf8');
482
614
  }
@@ -553,7 +685,7 @@ export class AcpClient {
553
685
  if (pat.test(this.stderrTail)) {
554
686
  const match = this.stderrTail.split('\n').find(l => pat.test(l));
555
687
  if (match)
556
- return match.trim();
688
+ return redactProviderSecrets(match).trim();
557
689
  }
558
690
  }
559
691
  }
@@ -569,11 +701,14 @@ export class AcpClient {
569
701
  }
570
702
  inspectOpencodeLog(sessionId, sinceEpochMs) {
571
703
  try {
572
- const logPath = path.join(os.homedir(), '.local', 'share', 'opencode', 'log', 'opencode.log');
704
+ const home = os.homedir();
705
+ if (!home)
706
+ return null;
707
+ const logPath = path.join(home, '.local', 'share', 'opencode', 'log', 'opencode.log');
573
708
  if (!fsSync.existsSync(logPath))
574
709
  return null;
575
- const stat = fsSync.statSync(logPath);
576
- if (stat.size === 0)
710
+ const stat = fsSync.lstatSync(logPath);
711
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size === 0)
577
712
  return null;
578
713
  const readBytes = Math.min(stat.size, 65536);
579
714
  const buffer = Buffer.alloc(readBytes);
@@ -608,9 +743,9 @@ export class AcpClient {
608
743
  if (line.includes('level=ERROR') || line.includes('AI_APICallError') || line.includes('Free usage limit reached') || line.includes('AI_RetryError')) {
609
744
  const match = line.match(/error\.error="([^"]+)"/) || line.match(/message="([^"]+)"/);
610
745
  if (match && match[1]) {
611
- return match[1].replace(/\\n/g, ' ').trim();
746
+ return redactProviderSecrets(match[1].replace(/\\n/g, ' ')).trim();
612
747
  }
613
- return line.trim();
748
+ return redactProviderSecrets(line).trim();
614
749
  }
615
750
  }
616
751
  }
@@ -629,71 +764,93 @@ export class AcpClient {
629
764
  const id = this.nextId++;
630
765
  const requestStartMs = Date.now();
631
766
  return new Promise((resolve, reject) => {
767
+ let settled = false;
632
768
  let inactivityTimer;
633
769
  let snifferInterval;
634
770
  const cleanup = () => {
635
771
  signal?.removeEventListener('abort', onAbort);
636
- if (inactivityTimer)
772
+ if (inactivityTimer) {
637
773
  clearTimeout(inactivityTimer);
638
- if (snifferInterval)
774
+ inactivityTimer = undefined;
775
+ }
776
+ if (snifferInterval) {
639
777
  clearInterval(snifferInterval);
778
+ snifferInterval = undefined;
779
+ }
640
780
  };
641
- const onAbort = () => {
781
+ const settleResolve = (value) => {
782
+ if (settled)
783
+ return;
784
+ settled = true;
642
785
  clearTimeout(timer);
643
786
  cleanup();
644
787
  this.pending.delete(id);
645
- reject(createAbortError());
788
+ resolve(value);
646
789
  };
647
- const timer = setTimeout(() => {
790
+ const settleReject = (error) => {
791
+ if (settled)
792
+ return;
793
+ settled = true;
794
+ clearTimeout(timer);
648
795
  cleanup();
649
796
  this.pending.delete(id);
797
+ reject(error);
798
+ };
799
+ const onAbort = () => {
800
+ settleReject(createAbortError());
801
+ };
802
+ const timer = setTimeout(() => {
650
803
  const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
651
804
  if (diag) {
652
- reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
805
+ settleReject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
653
806
  }
654
807
  else {
655
- reject(new Error(`${method} timed out after ${timeoutMs}ms`));
808
+ settleReject(new Error(`${method} timed out after ${timeoutMs}ms`));
656
809
  }
657
810
  }, timeoutMs);
658
811
  if (typeof timer.unref === 'function')
659
812
  timer.unref();
660
813
  const resetInactivity = () => {
814
+ if (settled)
815
+ return;
661
816
  const timeoutMsInact = options?.inactivityTimeoutMs;
662
817
  if (!timeoutMsInact)
663
818
  return;
664
819
  if (inactivityTimer)
665
820
  clearTimeout(inactivityTimer);
666
821
  inactivityTimer = setTimeout(() => {
822
+ if (settled)
823
+ return;
667
824
  if (this.hasOpenToolCall(options?.sessionId) && !this.inspectPeerDiagnostics(options?.sessionId, requestStartMs)) {
668
825
  resetInactivity();
669
826
  return;
670
827
  }
671
- cleanup();
672
- this.pending.delete(id);
673
828
  const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
674
829
  if (diag) {
675
- reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
830
+ settleReject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
676
831
  }
677
832
  else {
678
- reject(new Error(`${method} stalled: no activity from peer in ${Math.round(timeoutMsInact / 1000)}s`));
833
+ settleReject(new Error(`${method} stalled: no activity from peer in ${Math.round(timeoutMsInact / 1000)}s`));
679
834
  }
680
835
  }, timeoutMsInact);
681
836
  if (typeof inactivityTimer.unref === 'function')
682
837
  inactivityTimer.unref();
838
+ const entry = this.pending.get(id);
839
+ if (entry)
840
+ entry.inactivityTimer = inactivityTimer;
683
841
  };
684
842
  const sid = options?.sessionId;
685
843
  if (sid) {
686
844
  snifferInterval = setInterval(() => {
845
+ if (settled)
846
+ return;
687
847
  const fatalDiag = this.inspectPeerDiagnostics(sid, requestStartMs);
688
848
  if (fatalDiag) {
689
- cleanup();
690
- clearTimeout(timer);
691
- this.pending.delete(id);
692
849
  try {
693
850
  this.notifyCancel(sid);
694
851
  }
695
852
  catch { /* ignore */ }
696
- reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${fatalDiag}`));
853
+ settleReject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${fatalDiag}`));
697
854
  }
698
855
  }, 1500);
699
856
  if (typeof snifferInterval.unref === 'function')
@@ -702,8 +859,8 @@ export class AcpClient {
702
859
  resetInactivity();
703
860
  signal?.addEventListener('abort', onAbort, { once: true });
704
861
  this.pending.set(id, {
705
- resolve: (value) => resolve(value),
706
- reject,
862
+ resolve: settleResolve,
863
+ reject: settleReject,
707
864
  timer,
708
865
  inactivityTimer,
709
866
  snifferInterval,