@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/server.ts CHANGED
@@ -6,6 +6,8 @@ import type { AgentLoopEvent } from '../agentLoop.js';
6
6
  import { createApprovalScope } from '../approvalGrants.js';
7
7
  import type { ApprovalScope } from '../approvalGrants.js';
8
8
  import { createSession, getSession, saveSessionMessages, forkSession } from '../sessionJournal.js';
9
+ import { isBlockedWorkspaceRoot } from '../sandboxPolicy.js';
10
+ import { safeDisplay } from '../tui/text.js';
9
11
  import {
10
12
  ACP_ERROR_CODES,
11
13
  ACP_METHODS,
@@ -75,6 +77,7 @@ export interface AcpServerOptions {
75
77
  }
76
78
 
77
79
  interface PendingClientRequest {
80
+ sessionId: string;
78
81
  resolve: (value: unknown) => void;
79
82
  reject: (error: Error) => void;
80
83
  timer: NodeJS.Timeout;
@@ -96,9 +99,9 @@ interface AcpSession {
96
99
  }
97
100
 
98
101
  const MODE_TO_AUTONOMY: Record<string, 'A' | 'B' | 'C'> = {
99
- autonomous: 'A',
102
+ autonomous: 'C',
100
103
  standard: 'B',
101
- supervised: 'C'
104
+ supervised: 'A'
102
105
  };
103
106
 
104
107
  const MODES: SessionModeState = {
@@ -112,11 +115,15 @@ const MODES: SessionModeState = {
112
115
 
113
116
  const MAX_PROMPT_CHARS = 200_000;
114
117
  const MAX_RAW_CHARS = 4000;
118
+ const MAX_JSONRPC_BUFFER_BYTES = 8 * 1024 * 1024;
119
+ const MAX_SESSIONS = 128;
115
120
 
116
121
  function textFromPrompt(prompt: ContentBlock[]): string | null {
117
122
  const parts: string[] = [];
118
123
  for (const block of prompt) {
119
- if (block.type !== 'text') return null;
124
+ if (!block || typeof block !== 'object' || block.type !== 'text' || typeof block.text !== 'string') {
125
+ return null;
126
+ }
120
127
  parts.push(block.text);
121
128
  }
122
129
  return parts.join('\n').slice(0, MAX_PROMPT_CHARS);
@@ -159,8 +166,8 @@ function bounded(value: unknown, limit = MAX_RAW_CHARS): string {
159
166
 
160
167
  function toolTitle(name: string, args: Record<string, unknown>): string {
161
168
  const detail = args.path || args.file_path || args.command || args.cmd || args.query || args.url || args.action;
162
- const suffix = typeof detail === 'string' && detail.trim() ? ` ${detail.trim()}` : '';
163
- const title = `${name}${suffix}`;
169
+ const rawSuffix = typeof detail === 'string' && detail.trim() ? ` ${detail.trim()}` : '';
170
+ const title = safeDisplay(`${name}${rawSuffix}`).replace(/\s+/g, ' ').trim();
164
171
  return title.length > 200 ? `${title.slice(0, 200)}…` : title;
165
172
  }
166
173
 
@@ -187,13 +194,25 @@ export class AcpServer {
187
194
  this.loopFactory = options.loopFactory ?? null;
188
195
  this.agentName = options.agentName ?? 'Causyne Agent';
189
196
  this.agentVersion = options.agentVersion ?? '0.0.0';
190
- this.permissionTimeoutMs = options.permissionTimeoutMs ?? 10 * 60 * 1000;
197
+ const rawTimeout = options.permissionTimeoutMs;
198
+ this.permissionTimeoutMs = typeof rawTimeout === 'number' && Number.isFinite(rawTimeout)
199
+ ? Math.max(1_000, Math.min(3_600_000, Math.round(rawTimeout)))
200
+ : 10 * 60 * 1000;
191
201
  }
192
202
 
193
203
  start(): void {
194
204
  if (!this.input || this.dataListener) return;
195
205
  this.dataListener = (chunk: Buffer | string) => {
196
206
  this.buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
207
+ if (this.buffer.length > MAX_JSONRPC_BUFFER_BYTES) {
208
+ this.buffer = '';
209
+ this.write({
210
+ jsonrpc: '2.0',
211
+ id: null,
212
+ error: { code: ACP_ERROR_CODES.INVALID_REQUEST, message: 'Request frame exceeds maximum size' }
213
+ });
214
+ return;
215
+ }
197
216
  void this.drainBuffer();
198
217
  };
199
218
  this.endListener = () => { void this.stop(); };
@@ -209,13 +228,16 @@ export class AcpServer {
209
228
  if (this.input && this.dataListener) this.input.off('data', this.dataListener);
210
229
  if (this.input && this.endListener) this.input.off('end', this.endListener);
211
230
  if (this.input && this.errorListener) this.input.off('error', this.errorListener);
231
+ this.buffer = '';
212
232
  for (const session of this.sessions.values()) {
233
+ session.cancelled = true;
213
234
  try {
214
235
  session.loop?.abort();
215
236
  } catch {
216
237
  // Shutdown never blocks on a misbehaving tool.
217
238
  }
218
239
  }
240
+ this.sessions.clear();
219
241
  for (const [id, pending] of this.pending) {
220
242
  clearTimeout(pending.timer);
221
243
  pending.reject(new Error('server stopped'));
@@ -223,20 +245,33 @@ export class AcpServer {
223
245
  }
224
246
  }
225
247
 
226
- private async drainBuffer(): Promise<void> {
248
+ private drainBuffer(): void {
249
+ const lines: string[] = [];
227
250
  let index = this.buffer.indexOf('\n');
228
251
  while (index >= 0) {
229
252
  const line = this.buffer.slice(0, index).trim();
230
253
  this.buffer = this.buffer.slice(index + 1);
231
- if (line) await this.handleLine(line);
254
+ if (line) lines.push(line);
232
255
  index = this.buffer.indexOf('\n');
233
256
  }
257
+ for (const line of lines) {
258
+ void this.handleLine(line).catch(() => {});
259
+ }
234
260
  }
235
261
 
236
262
  async handleLine(line: string): Promise<void> {
263
+ const cleaned = line.replace(/^\uFEFF/, '').replace(/\r$/, '');
264
+ if (cleaned.length > MAX_JSONRPC_BUFFER_BYTES) {
265
+ this.write({
266
+ jsonrpc: '2.0',
267
+ id: null,
268
+ error: { code: ACP_ERROR_CODES.INVALID_REQUEST, message: 'Request frame exceeds maximum size' }
269
+ });
270
+ return;
271
+ }
237
272
  let parsed: unknown;
238
273
  try {
239
- parsed = JSON.parse(line);
274
+ parsed = JSON.parse(cleaned);
240
275
  } catch {
241
276
  this.write({ jsonrpc: '2.0', id: null, error: { code: ACP_ERROR_CODES.PARSE_ERROR, message: 'Parse error' } });
242
277
  return;
@@ -256,12 +291,19 @@ export class AcpServer {
256
291
  this.write({ jsonrpc: '2.0', id: null, error: { code: ACP_ERROR_CODES.INVALID_REQUEST, message: 'Invalid request' } });
257
292
  }
258
293
 
294
+ private isPlainParams(value: unknown): boolean {
295
+ return value === undefined || (value !== null && typeof value === 'object' && !Array.isArray(value));
296
+ }
297
+
259
298
  private async handleNotification(notification: JsonRpcNotification): Promise<void> {
299
+ if (!this.isPlainParams(notification.params)) return;
260
300
  if (notification.method === ACP_METHODS.CANCEL) {
261
301
  const params = notification.params as CancelNotification | undefined;
262
- const session = params && typeof params.sessionId === 'string' ? this.sessions.get(params.sessionId) : undefined;
302
+ const sid = params && typeof params.sessionId === 'string' ? params.sessionId.trim() : '';
303
+ const session = sid ? this.sessions.get(sid) : undefined;
263
304
  if (session) {
264
305
  session.cancelled = true;
306
+ this.rejectPendingForSession(session.id, 'session cancelled');
265
307
  try {
266
308
  session.loop?.abort();
267
309
  } catch {
@@ -273,6 +315,9 @@ export class AcpServer {
273
315
 
274
316
  private async handleRequest(request: JsonRpcRequest): Promise<void> {
275
317
  try {
318
+ if (!this.isPlainParams(request.params)) {
319
+ throw this.paramsError('params must be a JSON object');
320
+ }
276
321
  switch (request.method) {
277
322
  case ACP_METHODS.INITIALIZE:
278
323
  this.writeResult(request.id, this.initialize(request.params as InitializeRequest | undefined));
@@ -308,8 +353,13 @@ export class AcpServer {
308
353
  }
309
354
 
310
355
  private initialize(params: InitializeRequest | undefined): InitializeResult {
311
- if (!params || typeof params.protocolVersion !== 'number') {
312
- throw this.paramsError('initialize requires protocolVersion');
356
+ if (
357
+ !params ||
358
+ typeof params.protocolVersion !== 'number' ||
359
+ !Number.isInteger(params.protocolVersion) ||
360
+ params.protocolVersion < 1
361
+ ) {
362
+ throw this.paramsError('initialize requires a valid positive integer protocolVersion');
313
363
  }
314
364
  const capabilities: AgentCapabilities = {
315
365
  loadSession: true,
@@ -349,13 +399,17 @@ export class AcpServer {
349
399
 
350
400
  private resolveWorkspace(cwd: unknown): string {
351
401
  if (typeof cwd !== 'string' || !cwd.trim()) throw this.paramsError('cwd is required');
402
+ let resolved: string;
352
403
  try {
353
- const resolved = fs.realpathSync(path.resolve(cwd));
404
+ resolved = fs.realpathSync(path.resolve(cwd));
354
405
  if (!fs.statSync(resolved).isDirectory()) throw new Error('not a directory');
355
- return resolved;
356
406
  } catch {
357
407
  throw this.paramsError(`cwd is not an accessible directory: ${cwd}`);
358
408
  }
409
+ if (isBlockedWorkspaceRoot(resolved)) {
410
+ throw this.paramsError(`cwd points to a blocked system directory: ${cwd}`);
411
+ }
412
+ return resolved;
359
413
  }
360
414
 
361
415
  private bindWorkspace(cwd: string): void {
@@ -368,10 +422,13 @@ export class AcpServer {
368
422
  }
369
423
 
370
424
  private addSession(id: string, cwd: string, title: string, modeId: string): AcpSession {
425
+ if (!this.sessions.has(id) && this.sessions.size >= MAX_SESSIONS) {
426
+ throw this.paramsError(`Maximum concurrent sessions (${MAX_SESSIONS}) exceeded`);
427
+ }
371
428
  const session: AcpSession = {
372
429
  id,
373
430
  memorySessionId: id,
374
- title,
431
+ title: safeDisplay(title).replace(/\s+/g, ' ').trim() || 'Untitled',
375
432
  cwd,
376
433
  modeId,
377
434
  loop: null,
@@ -428,6 +485,9 @@ export class AcpServer {
428
485
  }
429
486
 
430
487
  private async runTurn(session: AcpSession, text: string): Promise<StopReason> {
488
+ if (this.closed || !this.sessions.has(session.id)) {
489
+ return 'cancelled';
490
+ }
431
491
  session.updatedAt = Date.now();
432
492
  session.cancelled = false;
433
493
  session.busy = true;
@@ -470,8 +530,10 @@ export class AcpServer {
470
530
  } finally {
471
531
  session.loop = null;
472
532
  session.busy = false;
473
- const record = getSession(session.memorySessionId);
474
- if (record) session.title = record.title;
533
+ if (this.sessions.has(session.id)) {
534
+ const record = getSession(session.memorySessionId);
535
+ if (record) session.title = safeDisplay(record.title).replace(/\s+/g, ' ').trim() || session.title;
536
+ }
475
537
  if (session.cancelled) stopReason = 'cancelled';
476
538
  }
477
539
  return stopReason;
@@ -504,8 +566,12 @@ export class AcpServer {
504
566
  toolCall,
505
567
  options: permissionOptions
506
568
  }).then((response) => {
507
- if (!response || response.outcome.outcome !== 'selected') return null;
508
- const optionId = response.outcome.optionId;
569
+ if (session.cancelled || !this.sessions.has(session.id)) return null;
570
+ const outcome = response && typeof response.outcome === 'object' && response.outcome !== null
571
+ ? response.outcome
572
+ : null;
573
+ if (!outcome || outcome.outcome !== 'selected' || typeof outcome.optionId !== 'string') return null;
574
+ const optionId = outcome.optionId;
509
575
  const label = labels.get(optionId);
510
576
  if (!label) return null;
511
577
  return { optionId, label };
@@ -628,8 +694,18 @@ export class AcpServer {
628
694
  toolCall,
629
695
  options
630
696
  }).then((response) => {
631
- const selected = response?.outcome.outcome === 'selected' ? response.outcome.optionId : '';
632
- if (selected === 'allow_always') session.approvalScope.grantAlways(tool);
697
+ if (session.cancelled || !this.sessions.has(session.id)) {
698
+ session.loop?.handleApprovalResponse(toolCallId, false);
699
+ return;
700
+ }
701
+ const outcome = response && typeof response.outcome === 'object' && response.outcome !== null
702
+ ? response.outcome
703
+ : null;
704
+ const selected = outcome && outcome.outcome === 'selected' && typeof outcome.optionId === 'string'
705
+ ? outcome.optionId
706
+ : '';
707
+ const canonicalTool = tool.replace(/\./g, '_');
708
+ if (selected === 'allow_always') session.approvalScope.grantAlways(canonicalTool);
633
709
  const approved = selected === 'allow_once' || selected === 'allow_always';
634
710
  session.loop?.handleApprovalResponse(toolCallId, approved);
635
711
  }).catch(() => {
@@ -671,8 +747,17 @@ export class AcpServer {
671
747
  return {};
672
748
  }
673
749
 
750
+ private canonicalizePath(targetPath: string): string {
751
+ const resolved = path.resolve(targetPath);
752
+ try {
753
+ return fs.realpathSync(resolved);
754
+ } catch {
755
+ return resolved;
756
+ }
757
+ }
758
+
674
759
  private listSessions(params: ListSessionsRequest | undefined): ListSessionsResponse {
675
- const filter = params && typeof params.cwd === 'string' ? path.resolve(params.cwd) : null;
760
+ const filter = params && typeof params.cwd === 'string' ? this.canonicalizePath(params.cwd) : null;
676
761
  const sessions: SessionInfo[] = [];
677
762
  for (const session of this.sessions.values()) {
678
763
  if (filter && session.cwd !== filter) continue;
@@ -690,6 +775,7 @@ export class AcpServer {
690
775
  private closeSession(params: CloseSessionRequest | undefined): Record<string, never> {
691
776
  const session = this.requireSession(params?.sessionId);
692
777
  session.cancelled = true;
778
+ this.rejectPendingForSession(session.id, 'session closed');
693
779
  try {
694
780
  session.loop?.abort();
695
781
  } catch {
@@ -704,6 +790,9 @@ export class AcpServer {
704
790
  if (!params || typeof params.sessionId !== 'string' || !params.sessionId) {
705
791
  throw this.paramsError('session/load requires sessionId');
706
792
  }
793
+ if (Array.isArray(params.mcpServers) && params.mcpServers.length > 0) {
794
+ throw this.paramsError('MCP servers are not supported by this agent');
795
+ }
707
796
  const live = this.sessions.get(params.sessionId);
708
797
  if (live) {
709
798
  this.bindWorkspace(live.cwd);
@@ -714,7 +803,7 @@ export class AcpServer {
714
803
  if (!record) throw this.notFound(`Unknown session: ${params.sessionId}`);
715
804
  const requested = params.cwd ?? record.workspace;
716
805
  const cwd = this.resolveWorkspace(requested);
717
- if (record.workspace && path.resolve(record.workspace) !== cwd) {
806
+ if (record.workspace && this.canonicalizePath(record.workspace) !== cwd) {
718
807
  throw this.paramsError('session workspace does not match cwd');
719
808
  }
720
809
  this.bindWorkspace(cwd);
@@ -739,7 +828,7 @@ export class AcpServer {
739
828
  const requested = params.cwd ?? source?.cwd ?? sourceRecord?.workspace;
740
829
  const cwd = this.resolveWorkspace(requested);
741
830
  if (source && source.cwd !== cwd) throw this.paramsError('fork must stay in the source workspace');
742
- if (sourceRecord?.workspace && path.resolve(sourceRecord.workspace) !== cwd) {
831
+ if (sourceRecord?.workspace && this.canonicalizePath(sourceRecord.workspace) !== cwd) {
743
832
  throw this.paramsError('fork must stay in the source workspace');
744
833
  }
745
834
  this.bindWorkspace(cwd);
@@ -769,6 +858,15 @@ export class AcpServer {
769
858
  return error;
770
859
  }
771
860
 
861
+ private rejectPendingForSession(sessionId: string, reason: string): void {
862
+ for (const [id, pending] of this.pending) {
863
+ if (pending.sessionId !== sessionId) continue;
864
+ clearTimeout(pending.timer);
865
+ this.pending.delete(id);
866
+ pending.reject(new Error(reason));
867
+ }
868
+ }
869
+
772
870
  private sendClientRequest<T>(session: AcpSession, method: string, params: Record<string, unknown>): Promise<T> {
773
871
  const id = `server-${this.nextClientRequestId++}`;
774
872
  return new Promise<T>((resolve, reject) => {
@@ -776,7 +874,9 @@ export class AcpServer {
776
874
  this.pending.delete(id);
777
875
  reject(new Error(`${method} timed out`));
778
876
  }, this.permissionTimeoutMs);
877
+ if (typeof timer.unref === 'function') timer.unref();
779
878
  this.pending.set(id, {
879
+ sessionId: session.id,
780
880
  resolve: (value) => resolve(value as T),
781
881
  reject,
782
882
  timer
@@ -16,8 +16,12 @@ export function classifyAgentError(error) {
16
16
  }
17
17
  // A provider may have charged for completed steps before the turn failed.
18
18
  // Replaying that turn can repeat actions and spend the same tokens again.
19
- const spent = Number(errObj?.partialUsage?.promptTokens || 0) +
20
- Number(errObj?.partialUsage?.completionTokens || 0);
19
+ const posTokens = (v) => {
20
+ const n = Number(v);
21
+ return Number.isFinite(n) && n > 0 ? n : 0;
22
+ };
23
+ const spent = posTokens(errObj?.partialUsage?.promptTokens) +
24
+ posTokens(errObj?.partialUsage?.completionTokens);
21
25
  if (spent > 0)
22
26
  return 'fatal';
23
27
  const msg = (typeof error === 'string'
@@ -43,9 +43,13 @@ export function classifyAgentError(error: unknown): AgentErrorClass {
43
43
 
44
44
  // A provider may have charged for completed steps before the turn failed.
45
45
  // Replaying that turn can repeat actions and spend the same tokens again.
46
+ const posTokens = (v: unknown): number => {
47
+ const n = Number(v);
48
+ return Number.isFinite(n) && n > 0 ? n : 0;
49
+ };
46
50
  const spent =
47
- Number(errObj?.partialUsage?.promptTokens || 0) +
48
- Number(errObj?.partialUsage?.completionTokens || 0);
51
+ posTokens(errObj?.partialUsage?.promptTokens) +
52
+ posTokens(errObj?.partialUsage?.completionTokens);
49
53
  if (spent > 0) return 'fatal';
50
54
 
51
55
  const msg = (
package/src/agentLoop.js CHANGED
@@ -566,6 +566,9 @@ export class AgentLoop {
566
566
  this.approvalScope = createApprovalScope();
567
567
  this.autonomyOverride = null;
568
568
  this.circuitBreakerUnlocked = false;
569
+ for (const toolCallId of [...this.pendingApprovals.keys()]) {
570
+ this.handleApprovalResponse(toolCallId, false);
571
+ }
569
572
  this.pendingApprovals.clear();
570
573
  }
571
574
  // V6: Adaptive Temperature based on task intent
@@ -4379,7 +4382,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4379
4382
  this._lastToolResult = observedResult;
4380
4383
  // Active Inference: Record step prediction error into VFE rolling tracker
4381
4384
  if (this.vfeTracker) {
4382
- const isThrash = isThrashing((this._planSteps || []).map((s) => s.tool), functionName);
4385
+ const isThrash = isThrashing((this._planSteps || []).map((s) => s.tool));
4383
4386
  const vfeOutcome = this.vfeTracker.recordStep({
4384
4387
  tool: functionName,
4385
4388
  success: stepSuccess,
@@ -4643,13 +4646,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
4643
4646
  // wall-clock limits, before deciding whether recovery is possible.
4644
4647
  if (e?.partialUsage) {
4645
4648
  const usage = e.partialUsage;
4646
- if (usage.promptTokens + usage.completionTokens > 0) {
4647
- await this.tokenTracker.trackUsage(usage.promptTokens, usage.completionTokens, (message) => this.emitEvent({ type: 'budget_warning', message }), usage);
4649
+ const promptTokens = Number.isFinite(Number(usage.promptTokens)) ? Math.max(0, Number(usage.promptTokens)) : 0;
4650
+ const completionTokens = Number.isFinite(Number(usage.completionTokens)) ? Math.max(0, Number(usage.completionTokens)) : 0;
4651
+ const cachedPromptTokens = Number.isFinite(Number(usage.cachedPromptTokens)) ? Math.max(0, Number(usage.cachedPromptTokens)) : 0;
4652
+ if (promptTokens + completionTokens > 0) {
4653
+ await this.tokenTracker.trackUsage(promptTokens, completionTokens, (message) => this.emitEvent({ type: 'budget_warning', message }), usage);
4648
4654
  auditLog.log({
4649
4655
  event: 'model_usage', scope: 'agent_loop_primary', taskId: this.taskId,
4650
4656
  step: this.stepsCompleted, provider: this.config.provider || 'unknown',
4651
- promptTokens: usage.promptTokens, completionTokens: usage.completionTokens,
4652
- cachedPromptTokens: usage.cachedPromptTokens || 0,
4657
+ promptTokens, completionTokens,
4658
+ cachedPromptTokens,
4653
4659
  measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
4654
4660
  });
4655
4661
  }
package/src/agentLoop.ts CHANGED
@@ -692,6 +692,9 @@ export class AgentLoop {
692
692
  this.approvalScope = createApprovalScope();
693
693
  this.autonomyOverride = null;
694
694
  this.circuitBreakerUnlocked = false;
695
+ for (const toolCallId of [...this.pendingApprovals.keys()]) {
696
+ this.handleApprovalResponse(toolCallId, false);
697
+ }
695
698
  this.pendingApprovals.clear();
696
699
  }
697
700
 
@@ -4621,7 +4624,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4621
4624
 
4622
4625
  // Active Inference: Record step prediction error into VFE rolling tracker
4623
4626
  if (this.vfeTracker) {
4624
- const isThrash = isThrashing((this._planSteps || []).map((s) => s.tool), functionName);
4627
+ const isThrash = isThrashing((this._planSteps || []).map((s) => s.tool));
4625
4628
  const vfeOutcome = this.vfeTracker.recordStep({
4626
4629
  tool: functionName,
4627
4630
  success: stepSuccess,
@@ -4894,16 +4897,19 @@ You are operating in a text-and-code modality without direct image pixel renderi
4894
4897
  // wall-clock limits, before deciding whether recovery is possible.
4895
4898
  if (e?.partialUsage) {
4896
4899
  const usage = e.partialUsage;
4897
- if (usage.promptTokens + usage.completionTokens > 0) {
4900
+ const promptTokens = Number.isFinite(Number(usage.promptTokens)) ? Math.max(0, Number(usage.promptTokens)) : 0;
4901
+ const completionTokens = Number.isFinite(Number(usage.completionTokens)) ? Math.max(0, Number(usage.completionTokens)) : 0;
4902
+ const cachedPromptTokens = Number.isFinite(Number(usage.cachedPromptTokens)) ? Math.max(0, Number(usage.cachedPromptTokens)) : 0;
4903
+ if (promptTokens + completionTokens > 0) {
4898
4904
  await this.tokenTracker.trackUsage(
4899
- usage.promptTokens, usage.completionTokens,
4905
+ promptTokens, completionTokens,
4900
4906
  (message: string) => this.emitEvent({ type: 'budget_warning', message }), usage
4901
4907
  );
4902
4908
  auditLog.log({
4903
4909
  event: 'model_usage', scope: 'agent_loop_primary', taskId: this.taskId,
4904
4910
  step: this.stepsCompleted, provider: this.config.provider || 'unknown',
4905
- promptTokens: usage.promptTokens, completionTokens: usage.completionTokens,
4906
- cachedPromptTokens: usage.cachedPromptTokens || 0,
4911
+ promptTokens, completionTokens,
4912
+ cachedPromptTokens,
4907
4913
  measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
4908
4914
  });
4909
4915
  }
@@ -19,18 +19,26 @@
19
19
  // side-effect of a keypress in a modal.
20
20
  /** Tool names approved for the rest of this process. Deliberately in memory. */
21
21
  const standingApprovals = new Set();
22
+ const MAX_STANDING_APPROVALS = 256;
22
23
  function normalizeToolName(toolName) {
23
- return String(toolName || '').trim();
24
+ if (typeof toolName !== 'string')
25
+ return '';
26
+ const trimmed = toolName.trim();
27
+ if (!trimmed || trimmed === '*' || trimmed.length > 128 || /[\r\n\0]/.test(trimmed))
28
+ return '';
29
+ return trimmed.replace(/\./g, '_');
24
30
  }
25
31
  /** Record a standing approval for one canonical tool name. */
26
32
  export function grantAlways(toolName) {
27
33
  const name = normalizeToolName(toolName);
28
- if (name)
34
+ if (name && (standingApprovals.has(name) || standingApprovals.size < MAX_STANDING_APPROVALS)) {
29
35
  standingApprovals.add(name);
36
+ }
30
37
  }
31
38
  /** True when this tool may run without asking again. */
32
39
  export function isAlwaysAllowed(toolName) {
33
- return standingApprovals.has(normalizeToolName(toolName));
40
+ const name = normalizeToolName(toolName);
41
+ return name.length > 0 && standingApprovals.has(name);
34
42
  }
35
43
  /** Every standing approval, for `/approvals` and for the audit trail. */
36
44
  export function listAlwaysAllowed() {
@@ -44,7 +52,8 @@ export function revokeAllAlways() {
44
52
  }
45
53
  /** Revoke one standing approval. */
46
54
  export function revokeAlways(toolName) {
47
- return standingApprovals.delete(normalizeToolName(toolName));
55
+ const name = normalizeToolName(toolName);
56
+ return name.length > 0 && standingApprovals.delete(name);
48
57
  }
49
58
  /** A fresh, empty standing-approval scope that is not shared with anything. */
50
59
  export function createApprovalScope() {
@@ -52,11 +61,13 @@ export function createApprovalScope() {
52
61
  return {
53
62
  grantAlways(toolName) {
54
63
  const name = normalizeToolName(toolName);
55
- if (name)
64
+ if (name && (approvals.has(name) || approvals.size < MAX_STANDING_APPROVALS)) {
56
65
  approvals.add(name);
66
+ }
57
67
  },
58
68
  isAlwaysAllowed(toolName) {
59
- return approvals.has(normalizeToolName(toolName));
69
+ const name = normalizeToolName(toolName);
70
+ return name.length > 0 && approvals.has(name);
60
71
  },
61
72
  listAlwaysAllowed() {
62
73
  return [...approvals].sort();
@@ -67,7 +78,8 @@ export function createApprovalScope() {
67
78
  return count;
68
79
  },
69
80
  revokeAlways(toolName) {
70
- return approvals.delete(normalizeToolName(toolName));
81
+ const name = normalizeToolName(toolName);
82
+ return name.length > 0 && approvals.delete(name);
71
83
  }
72
84
  };
73
85
  }
@@ -37,19 +37,27 @@ export interface ApprovalScope {
37
37
  /** Tool names approved for the rest of this process. Deliberately in memory. */
38
38
  const standingApprovals = new Set<string>();
39
39
 
40
+ const MAX_STANDING_APPROVALS = 256;
41
+
40
42
  function normalizeToolName(toolName: unknown): string {
41
- return String(toolName || '').trim();
43
+ if (typeof toolName !== 'string') return '';
44
+ const trimmed = toolName.trim();
45
+ if (!trimmed || trimmed === '*' || trimmed.length > 128 || /[\r\n\0]/.test(trimmed)) return '';
46
+ return trimmed.replace(/\./g, '_');
42
47
  }
43
48
 
44
49
  /** Record a standing approval for one canonical tool name. */
45
50
  export function grantAlways(toolName: unknown): void {
46
51
  const name = normalizeToolName(toolName);
47
- if (name) standingApprovals.add(name);
52
+ if (name && (standingApprovals.has(name) || standingApprovals.size < MAX_STANDING_APPROVALS)) {
53
+ standingApprovals.add(name);
54
+ }
48
55
  }
49
56
 
50
57
  /** True when this tool may run without asking again. */
51
58
  export function isAlwaysAllowed(toolName: unknown): boolean {
52
- return standingApprovals.has(normalizeToolName(toolName));
59
+ const name = normalizeToolName(toolName);
60
+ return name.length > 0 && standingApprovals.has(name);
53
61
  }
54
62
 
55
63
  /** Every standing approval, for `/approvals` and for the audit trail. */
@@ -66,7 +74,8 @@ export function revokeAllAlways(): number {
66
74
 
67
75
  /** Revoke one standing approval. */
68
76
  export function revokeAlways(toolName: unknown): boolean {
69
- return standingApprovals.delete(normalizeToolName(toolName));
77
+ const name = normalizeToolName(toolName);
78
+ return name.length > 0 && standingApprovals.delete(name);
70
79
  }
71
80
 
72
81
  /** A fresh, empty standing-approval scope that is not shared with anything. */
@@ -75,10 +84,13 @@ export function createApprovalScope(): ApprovalScope {
75
84
  return {
76
85
  grantAlways(toolName) {
77
86
  const name = normalizeToolName(toolName);
78
- if (name) approvals.add(name);
87
+ if (name && (approvals.has(name) || approvals.size < MAX_STANDING_APPROVALS)) {
88
+ approvals.add(name);
89
+ }
79
90
  },
80
91
  isAlwaysAllowed(toolName) {
81
- return approvals.has(normalizeToolName(toolName));
92
+ const name = normalizeToolName(toolName);
93
+ return name.length > 0 && approvals.has(name);
82
94
  },
83
95
  listAlwaysAllowed() {
84
96
  return [...approvals].sort();
@@ -89,7 +101,8 @@ export function createApprovalScope(): ApprovalScope {
89
101
  return count;
90
102
  },
91
103
  revokeAlways(toolName) {
92
- return approvals.delete(normalizeToolName(toolName));
104
+ const name = normalizeToolName(toolName);
105
+ return name.length > 0 && approvals.delete(name);
93
106
  }
94
107
  };
95
108
  }