@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
@@ -3,6 +3,7 @@ import { pathToFileURL } from 'node:url';
3
3
  import { Client, SSEClientTransport, SdkError, SdkErrorCode, SdkHttpError, StreamableHTTPClientTransport, UnauthorizedError } from '@modelcontextprotocol/client';
4
4
  import { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotocol/client/stdio';
5
5
  import { getPackageVersion } from '../version.js';
6
+ import { MAX_GLOB_PATTERN_CHARS, MAX_MCP_SERVER_INSTRUCTIONS_CHARS, MAX_MCP_TOOL_DESCRIPTION_CHARS, MAX_TOOLS_PER_MCP_SERVER, sanitizeMcpInputSchema, sanitizeMcpMetadataText, sanitizeMcpToolName } from './mcpSecurity.js';
6
7
  const DEFAULT_TIMEOUT_MS = 30_000;
7
8
  const MAX_TIMEOUT_MS = 10 * 60_000;
8
9
  const STDERR_LIMIT_BYTES = 8 * 1024;
@@ -37,14 +38,13 @@ function validateStringArray(value, label) {
37
38
  return null;
38
39
  }
39
40
  function normalizeTool(tool) {
40
- if (typeof tool.name !== 'string' || tool.name.trim().length === 0)
41
+ const safeName = sanitizeMcpToolName(tool.name);
42
+ if (!safeName)
41
43
  return null;
42
- const inputSchema = isRecord(tool.inputSchema)
43
- ? tool.inputSchema
44
- : { type: 'object', properties: {} };
44
+ const inputSchema = sanitizeMcpInputSchema(tool.inputSchema);
45
45
  const normalized = {
46
- name: tool.name,
47
- description: typeof tool.description === 'string' ? tool.description : '',
46
+ name: safeName,
47
+ description: sanitizeMcpMetadataText(tool.description, MAX_MCP_TOOL_DESCRIPTION_CHARS),
48
48
  inputSchema
49
49
  };
50
50
  if (isRecord(tool.annotations))
@@ -221,6 +221,13 @@ export class McpClient {
221
221
  const problem = validateStringArray(definition.tools[key], `\`tools.${key}\``);
222
222
  if (problem)
223
223
  return problem;
224
+ const patterns = definition.tools[key];
225
+ if (patterns.length > 256) {
226
+ return `\`tools.${key}\` must contain at most 256 patterns`;
227
+ }
228
+ if (patterns.some(pattern => pattern.length > MAX_GLOB_PATTERN_CHARS)) {
229
+ return `\`tools.${key}\` patterns must be at most ${MAX_GLOB_PATTERN_CHARS} characters`;
230
+ }
224
231
  }
225
232
  }
226
233
  }
@@ -250,8 +257,9 @@ export class McpClient {
250
257
  catch (error) {
251
258
  await this.dispose();
252
259
  const state = isAuthenticationError(error) ? 'needs_auth' : 'failed';
253
- const suffix = this.stderrTail.trim() ? `: ${this.stderrTail.trim().slice(-600)}` : '';
254
- const message = `${errorMessage(error)}${suffix}`;
260
+ const safeTail = sanitizeMcpMetadataText(this.stderrTail.trim().slice(-600), 600);
261
+ const suffix = safeTail ? `: ${safeTail}` : '';
262
+ const message = `${sanitizeMcpMetadataText(errorMessage(error), 1000)}${suffix}`;
255
263
  this.setStatus({ state, error: message });
256
264
  throw new McpConnectionError(state, message, { cause: error });
257
265
  }
@@ -482,15 +490,34 @@ export class McpClient {
482
490
  }
483
491
  captureServer(client, transport) {
484
492
  const server = client.getServerVersion();
485
- this.serverInfo = server ? { name: server.name, version: server.version } : null;
486
- this.instructions = client.getInstructions()?.trim() || null;
493
+ this.serverInfo = server
494
+ ? {
495
+ name: sanitizeMcpMetadataText(server.name, 128),
496
+ version: sanitizeMcpMetadataText(server.version, 64)
497
+ }
498
+ : null;
499
+ const rawInstructions = client.getInstructions()?.trim();
500
+ this.instructions = rawInstructions
501
+ ? sanitizeMcpMetadataText(rawInstructions, MAX_MCP_SERVER_INSTRUCTIONS_CHARS)
502
+ : null;
487
503
  const status = { state: 'connected', connectedAt: Date.now() };
488
504
  if (transport)
489
505
  status.transport = transport;
490
506
  this.setStatus(status);
491
507
  }
492
508
  replaceTools(tools) {
493
- this.tools = tools.map(normalizeTool).filter((tool) => tool !== null);
509
+ const nextTools = [];
510
+ const seenNames = new Set();
511
+ for (const rawTool of tools) {
512
+ if (nextTools.length >= MAX_TOOLS_PER_MCP_SERVER)
513
+ break;
514
+ const normalized = normalizeTool(rawTool);
515
+ if (!normalized || seenNames.has(normalized.name))
516
+ continue;
517
+ seenNames.add(normalized.name);
518
+ nextTools.push(normalized);
519
+ }
520
+ this.tools = nextTools;
494
521
  this.onToolsChanged?.([...this.tools]);
495
522
  }
496
523
  setStatus(status) {
@@ -16,6 +16,15 @@ import {
16
16
  import { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotocol/client/stdio';
17
17
 
18
18
  import { getPackageVersion } from '../version.js';
19
+ import {
20
+ MAX_GLOB_PATTERN_CHARS,
21
+ MAX_MCP_SERVER_INSTRUCTIONS_CHARS,
22
+ MAX_MCP_TOOL_DESCRIPTION_CHARS,
23
+ MAX_TOOLS_PER_MCP_SERVER,
24
+ sanitizeMcpInputSchema,
25
+ sanitizeMcpMetadataText,
26
+ sanitizeMcpToolName
27
+ } from './mcpSecurity.js';
19
28
 
20
29
  const DEFAULT_TIMEOUT_MS = 30_000;
21
30
  const MAX_TIMEOUT_MS = 10 * 60_000;
@@ -105,13 +114,12 @@ function validateStringArray(value: unknown, label: string): string | null {
105
114
  }
106
115
 
107
116
  function normalizeTool(tool: Tool): McpToolDefinition | null {
108
- if (typeof tool.name !== 'string' || tool.name.trim().length === 0) return null;
109
- const inputSchema = isRecord(tool.inputSchema)
110
- ? tool.inputSchema
111
- : { type: 'object', properties: {} };
117
+ const safeName = sanitizeMcpToolName(tool.name);
118
+ if (!safeName) return null;
119
+ const inputSchema = sanitizeMcpInputSchema(tool.inputSchema);
112
120
  const normalized: McpToolDefinition = {
113
- name: tool.name,
114
- description: typeof tool.description === 'string' ? tool.description : '',
121
+ name: safeName,
122
+ description: sanitizeMcpMetadataText(tool.description, MAX_MCP_TOOL_DESCRIPTION_CHARS),
115
123
  inputSchema
116
124
  };
117
125
  if (isRecord(tool.annotations)) normalized.annotations = tool.annotations;
@@ -293,6 +301,13 @@ export class McpClient {
293
301
  if (definition.tools[key] !== undefined) {
294
302
  const problem = validateStringArray(definition.tools[key], `\`tools.${key}\``);
295
303
  if (problem) return problem;
304
+ const patterns = definition.tools[key] as string[];
305
+ if (patterns.length > 256) {
306
+ return `\`tools.${key}\` must contain at most 256 patterns`;
307
+ }
308
+ if (patterns.some(pattern => pattern.length > MAX_GLOB_PATTERN_CHARS)) {
309
+ return `\`tools.${key}\` patterns must be at most ${MAX_GLOB_PATTERN_CHARS} characters`;
310
+ }
296
311
  }
297
312
  }
298
313
  }
@@ -322,8 +337,9 @@ export class McpClient {
322
337
  } catch (error) {
323
338
  await this.dispose();
324
339
  const state = isAuthenticationError(error) ? 'needs_auth' : 'failed';
325
- const suffix = this.stderrTail.trim() ? `: ${this.stderrTail.trim().slice(-600)}` : '';
326
- const message = `${errorMessage(error)}${suffix}`;
340
+ const safeTail = sanitizeMcpMetadataText(this.stderrTail.trim().slice(-600), 600);
341
+ const suffix = safeTail ? `: ${safeTail}` : '';
342
+ const message = `${sanitizeMcpMetadataText(errorMessage(error), 1000)}${suffix}`;
327
343
  this.setStatus({ state, error: message });
328
344
  throw new McpConnectionError(state, message, { cause: error });
329
345
  }
@@ -550,15 +566,32 @@ export class McpClient {
550
566
 
551
567
  private captureServer(client: Client, transport: McpConnectionStatus['transport']): void {
552
568
  const server = client.getServerVersion();
553
- this.serverInfo = server ? { name: server.name, version: server.version } : null;
554
- this.instructions = client.getInstructions()?.trim() || null;
569
+ this.serverInfo = server
570
+ ? {
571
+ name: sanitizeMcpMetadataText(server.name, 128),
572
+ version: sanitizeMcpMetadataText(server.version, 64)
573
+ }
574
+ : null;
575
+ const rawInstructions = client.getInstructions()?.trim();
576
+ this.instructions = rawInstructions
577
+ ? sanitizeMcpMetadataText(rawInstructions, MAX_MCP_SERVER_INSTRUCTIONS_CHARS)
578
+ : null;
555
579
  const status: McpConnectionStatus = { state: 'connected', connectedAt: Date.now() };
556
580
  if (transport) status.transport = transport;
557
581
  this.setStatus(status);
558
582
  }
559
583
 
560
584
  private replaceTools(tools: Tool[]): void {
561
- this.tools = tools.map(normalizeTool).filter((tool): tool is McpToolDefinition => tool !== null);
585
+ const nextTools: McpToolDefinition[] = [];
586
+ const seenNames = new Set<string>();
587
+ for (const rawTool of tools) {
588
+ if (nextTools.length >= MAX_TOOLS_PER_MCP_SERVER) break;
589
+ const normalized = normalizeTool(rawTool);
590
+ if (!normalized || seenNames.has(normalized.name)) continue;
591
+ seenNames.add(normalized.name);
592
+ nextTools.push(normalized);
593
+ }
594
+ this.tools = nextTools;
562
595
  this.onToolsChanged?.([...this.tools]);
563
596
  }
564
597
 
@@ -1,5 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { McpClient, McpConnectionError } from './mcpClient.js';
3
+ import { globMatchesSafe } from './mcpSecurity.js';
3
4
  import { loadConfig, saveConfig } from '../config.js';
4
5
  import { auditLog } from '../auditLog.js';
5
6
  const NAMESPACE = 'mcp__';
@@ -83,11 +84,7 @@ function consentRecord(value) {
83
84
  return { digest: value.digest, grantedAt: value.grantedAt };
84
85
  }
85
86
  function globMatches(name, pattern) {
86
- const source = pattern
87
- .replace(/[.+^${}()|[\]\\]/g, '\\$&')
88
- .replaceAll('*', '.*')
89
- .replaceAll('?', '.');
90
- return new RegExp(`^${source}$`, 'u').test(name);
87
+ return globMatchesSafe(name, pattern);
91
88
  }
92
89
  function toolAllowed(server, toolName) {
93
90
  const include = server.tools?.include;
@@ -8,6 +8,7 @@ import {
8
8
  type McpToolCallResult,
9
9
  type McpToolDefinition
10
10
  } from './mcpClient.js';
11
+ import { globMatchesSafe } from './mcpSecurity.js';
11
12
  import { loadConfig, saveConfig } from '../config.js';
12
13
  import { auditLog } from '../auditLog.js';
13
14
 
@@ -101,11 +102,7 @@ function consentRecord(value: unknown): ConsentRecord | null {
101
102
  }
102
103
 
103
104
  function globMatches(name: string, pattern: string): boolean {
104
- const source = pattern
105
- .replace(/[.+^${}()|[\]\\]/g, '\\$&')
106
- .replaceAll('*', '.*')
107
- .replaceAll('?', '.');
108
- return new RegExp(`^${source}$`, 'u').test(name);
105
+ return globMatchesSafe(name, pattern);
109
106
  }
110
107
 
111
108
  function toolAllowed(server: McpServerDefinition, toolName: string): boolean {
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Causyne Agent — MCP Protocol Security & Untrusted Metadata Bounds
3
+ *
4
+ * Hardens external MCP server integration against:
5
+ * 1. Polynomial / catastrophic ReDoS (CWE-1333) in `tools.include` / `tools.exclude`
6
+ * glob filters by replacing dynamic `new RegExp()` compilation with a strictly
7
+ * linear-space iterative wildcard matcher.
8
+ * 2. Context-window flooding & schema bombs (CWE-400) via per-server tool caps,
9
+ * description/instruction length ceilings, and bounded JSON schema sanitization.
10
+ * 3. Terminal escape injection & Trojan Source hidden Unicode bidi/zero-width
11
+ * control characters inside untrusted MCP tool names, descriptions, schema
12
+ * annotations, and server instructions.
13
+ */
14
+ import { safeDisplay } from '../tui/text.js';
15
+ export const MAX_GLOB_PATTERN_CHARS = 256;
16
+ export const MAX_TOOLS_PER_MCP_SERVER = 256;
17
+ export const MAX_MCP_TOOL_NAME_CHARS = 128;
18
+ export const MAX_MCP_TOOL_DESCRIPTION_CHARS = 2048;
19
+ export const MAX_MCP_SERVER_INSTRUCTIONS_CHARS = 4096;
20
+ export const MAX_MCP_SCHEMA_STRING_CHARS = 1024;
21
+ export const MAX_MCP_SCHEMA_DEPTH = 16;
22
+ export const MAX_MCP_SCHEMA_JSON_BYTES = 65_536;
23
+ function isRecord(value) {
24
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
25
+ }
26
+ /**
27
+ * Strips invisible zero-width and Unicode bidirectional override/isolate format
28
+ * characters (Trojan Source vectors: U+202A–U+202E, U+2066–U+2069, U+200B–U+200F,
29
+ * U+061C, U+2060, U+FEFF) in a single linear O(n) pass.
30
+ */
31
+ export function stripInvisibleAndBidi(text) {
32
+ if (!text)
33
+ return '';
34
+ let out = '';
35
+ for (let i = 0; i < text.length; i++) {
36
+ const code = text.charCodeAt(i);
37
+ if (code === 0x061c ||
38
+ (code >= 0x200b && code <= 0x200f) ||
39
+ (code >= 0x202a && code <= 0x202e) ||
40
+ code === 0x2060 ||
41
+ (code >= 0x2066 && code <= 0x2069) ||
42
+ code === 0xfeff) {
43
+ continue;
44
+ }
45
+ out += text[i];
46
+ }
47
+ return out;
48
+ }
49
+ /**
50
+ * ReDoS-free iterative wildcard matcher supporting `*` (0+ code points) and
51
+ * `?` (exactly 1 code point). Uses Unicode code points (`Array.from`) so
52
+ * surrogate pairs match identically to Unicode-mode regexes without constructing
53
+ * any `RegExp`. Guaranteed O(n * m) worst-case time, O(n + m) memory.
54
+ */
55
+ export function globMatchesSafe(name, pattern) {
56
+ if (typeof name !== 'string' || typeof pattern !== 'string')
57
+ return false;
58
+ if (pattern.length > MAX_GLOB_PATTERN_CHARS)
59
+ return false;
60
+ const textChars = Array.from(name);
61
+ const rawPatChars = Array.from(pattern);
62
+ // Collapse consecutive `*` wildcards to prevent redundant backtracking steps
63
+ const patChars = [];
64
+ for (const ch of rawPatChars) {
65
+ if (ch === '*' && patChars[patChars.length - 1] === '*')
66
+ continue;
67
+ patChars.push(ch);
68
+ }
69
+ let t = 0;
70
+ let p = 0;
71
+ let starIdx = -1;
72
+ let matchIdx = 0;
73
+ while (t < textChars.length) {
74
+ if (p < patChars.length && (patChars[p] === '?' || patChars[p] === textChars[t])) {
75
+ t++;
76
+ p++;
77
+ }
78
+ else if (p < patChars.length && patChars[p] === '*') {
79
+ starIdx = p;
80
+ matchIdx = t;
81
+ p++;
82
+ }
83
+ else if (starIdx !== -1) {
84
+ p = starIdx + 1;
85
+ matchIdx++;
86
+ t = matchIdx;
87
+ }
88
+ else {
89
+ return false;
90
+ }
91
+ }
92
+ while (p < patChars.length && patChars[p] === '*') {
93
+ p++;
94
+ }
95
+ return p === patChars.length;
96
+ }
97
+ /**
98
+ * Sanitizes untrusted text received from an MCP server (descriptions, server
99
+ * instructions, error strings) via canonical `safeDisplay()`, strips invisible
100
+ * Unicode bidi/zero-width characters, and enforces a strict character cap.
101
+ */
102
+ export function sanitizeMcpMetadataText(value, maxChars) {
103
+ if (typeof value !== 'string')
104
+ return '';
105
+ const cleaned = stripInvisibleAndBidi(safeDisplay(value)).trim();
106
+ if (cleaned.length <= maxChars)
107
+ return cleaned;
108
+ const suffix = '… [truncated]';
109
+ const keep = Math.max(0, maxChars - suffix.length);
110
+ return `${cleaned.slice(0, keep).trimEnd()}${suffix}`;
111
+ }
112
+ /**
113
+ * Validates and sanitizes an MCP tool name. Rejects empty names, names with
114
+ * ASCII control characters / NUL bytes, or names exceeding the length ceiling.
115
+ */
116
+ export function sanitizeMcpToolName(value) {
117
+ if (typeof value !== 'string')
118
+ return null;
119
+ const stripped = stripInvisibleAndBidi(value).trim();
120
+ if (stripped.length === 0 || stripped.length > MAX_MCP_TOOL_NAME_CHARS)
121
+ return null;
122
+ for (let i = 0; i < stripped.length; i++) {
123
+ const code = stripped.charCodeAt(i);
124
+ if (code < 0x20 || code === 0x7f)
125
+ return null;
126
+ }
127
+ return stripped;
128
+ }
129
+ function sanitizeSchemaNode(value, depth) {
130
+ if (depth > MAX_MCP_SCHEMA_DEPTH) {
131
+ return { type: 'object', description: 'Nested schema truncated at maximum depth.' };
132
+ }
133
+ if (typeof value === 'string') {
134
+ return sanitizeMcpMetadataText(value, MAX_MCP_SCHEMA_STRING_CHARS);
135
+ }
136
+ if (typeof value === 'number' || typeof value === 'boolean' || value === null) {
137
+ return value;
138
+ }
139
+ if (Array.isArray(value)) {
140
+ const maxItems = 128;
141
+ return value.slice(0, maxItems).map(item => sanitizeSchemaNode(item, depth + 1));
142
+ }
143
+ if (isRecord(value)) {
144
+ const out = {};
145
+ let count = 0;
146
+ for (const [key, item] of Object.entries(value)) {
147
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype')
148
+ continue;
149
+ if (count >= 256)
150
+ break;
151
+ const safeKey = stripInvisibleAndBidi(safeDisplay(key));
152
+ if (!safeKey)
153
+ continue;
154
+ out[safeKey] = sanitizeSchemaNode(item, depth + 1);
155
+ count++;
156
+ }
157
+ return out;
158
+ }
159
+ return undefined;
160
+ }
161
+ /**
162
+ * Sanitizes and size-bounds an untrusted MCP tool JSON input schema.
163
+ * Strips ANSI escapes and bidi characters from nested property descriptions,
164
+ * prevents prototype pollution keys, caps nesting depth, and falls back to an
165
+ * empty object schema if serialized size exceeds `MAX_MCP_SCHEMA_JSON_BYTES`.
166
+ */
167
+ export function sanitizeMcpInputSchema(schema) {
168
+ if (!isRecord(schema)) {
169
+ return { type: 'object', properties: {} };
170
+ }
171
+ const sanitized = sanitizeSchemaNode(schema, 0);
172
+ if (!isRecord(sanitized)) {
173
+ return { type: 'object', properties: {} };
174
+ }
175
+ try {
176
+ const serialized = JSON.stringify(sanitized);
177
+ if (Buffer.byteLength(serialized, 'utf8') > MAX_MCP_SCHEMA_JSON_BYTES) {
178
+ return {
179
+ type: 'object',
180
+ properties: {},
181
+ description: 'MCP tool input schema omitted because it exceeded the 64 KiB safety limit.'
182
+ };
183
+ }
184
+ }
185
+ catch {
186
+ return { type: 'object', properties: {} };
187
+ }
188
+ return sanitized;
189
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Causyne Agent — MCP Protocol Security & Untrusted Metadata Bounds
3
+ *
4
+ * Hardens external MCP server integration against:
5
+ * 1. Polynomial / catastrophic ReDoS (CWE-1333) in `tools.include` / `tools.exclude`
6
+ * glob filters by replacing dynamic `new RegExp()` compilation with a strictly
7
+ * linear-space iterative wildcard matcher.
8
+ * 2. Context-window flooding & schema bombs (CWE-400) via per-server tool caps,
9
+ * description/instruction length ceilings, and bounded JSON schema sanitization.
10
+ * 3. Terminal escape injection & Trojan Source hidden Unicode bidi/zero-width
11
+ * control characters inside untrusted MCP tool names, descriptions, schema
12
+ * annotations, and server instructions.
13
+ */
14
+
15
+ import { safeDisplay } from '../tui/text.js';
16
+
17
+ export const MAX_GLOB_PATTERN_CHARS = 256;
18
+ export const MAX_TOOLS_PER_MCP_SERVER = 256;
19
+ export const MAX_MCP_TOOL_NAME_CHARS = 128;
20
+ export const MAX_MCP_TOOL_DESCRIPTION_CHARS = 2048;
21
+ export const MAX_MCP_SERVER_INSTRUCTIONS_CHARS = 4096;
22
+ export const MAX_MCP_SCHEMA_STRING_CHARS = 1024;
23
+ export const MAX_MCP_SCHEMA_DEPTH = 16;
24
+ export const MAX_MCP_SCHEMA_JSON_BYTES = 65_536;
25
+
26
+ function isRecord(value: unknown): value is Record<string, unknown> {
27
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
28
+ }
29
+
30
+ /**
31
+ * Strips invisible zero-width and Unicode bidirectional override/isolate format
32
+ * characters (Trojan Source vectors: U+202A–U+202E, U+2066–U+2069, U+200B–U+200F,
33
+ * U+061C, U+2060, U+FEFF) in a single linear O(n) pass.
34
+ */
35
+ export function stripInvisibleAndBidi(text: string): string {
36
+ if (!text) return '';
37
+ let out = '';
38
+ for (let i = 0; i < text.length; i++) {
39
+ const code = text.charCodeAt(i);
40
+ if (
41
+ code === 0x061c ||
42
+ (code >= 0x200b && code <= 0x200f) ||
43
+ (code >= 0x202a && code <= 0x202e) ||
44
+ code === 0x2060 ||
45
+ (code >= 0x2066 && code <= 0x2069) ||
46
+ code === 0xfeff
47
+ ) {
48
+ continue;
49
+ }
50
+ out += text[i];
51
+ }
52
+ return out;
53
+ }
54
+
55
+ /**
56
+ * ReDoS-free iterative wildcard matcher supporting `*` (0+ code points) and
57
+ * `?` (exactly 1 code point). Uses Unicode code points (`Array.from`) so
58
+ * surrogate pairs match identically to Unicode-mode regexes without constructing
59
+ * any `RegExp`. Guaranteed O(n * m) worst-case time, O(n + m) memory.
60
+ */
61
+ export function globMatchesSafe(name: string, pattern: string): boolean {
62
+ if (typeof name !== 'string' || typeof pattern !== 'string') return false;
63
+ if (pattern.length > MAX_GLOB_PATTERN_CHARS) return false;
64
+
65
+ const textChars = Array.from(name);
66
+ const rawPatChars = Array.from(pattern);
67
+
68
+ // Collapse consecutive `*` wildcards to prevent redundant backtracking steps
69
+ const patChars: string[] = [];
70
+ for (const ch of rawPatChars) {
71
+ if (ch === '*' && patChars[patChars.length - 1] === '*') continue;
72
+ patChars.push(ch);
73
+ }
74
+
75
+ let t = 0;
76
+ let p = 0;
77
+ let starIdx = -1;
78
+ let matchIdx = 0;
79
+
80
+ while (t < textChars.length) {
81
+ if (p < patChars.length && (patChars[p] === '?' || patChars[p] === textChars[t])) {
82
+ t++;
83
+ p++;
84
+ } else if (p < patChars.length && patChars[p] === '*') {
85
+ starIdx = p;
86
+ matchIdx = t;
87
+ p++;
88
+ } else if (starIdx !== -1) {
89
+ p = starIdx + 1;
90
+ matchIdx++;
91
+ t = matchIdx;
92
+ } else {
93
+ return false;
94
+ }
95
+ }
96
+
97
+ while (p < patChars.length && patChars[p] === '*') {
98
+ p++;
99
+ }
100
+
101
+ return p === patChars.length;
102
+ }
103
+
104
+ /**
105
+ * Sanitizes untrusted text received from an MCP server (descriptions, server
106
+ * instructions, error strings) via canonical `safeDisplay()`, strips invisible
107
+ * Unicode bidi/zero-width characters, and enforces a strict character cap.
108
+ */
109
+ export function sanitizeMcpMetadataText(value: unknown, maxChars: number): string {
110
+ if (typeof value !== 'string') return '';
111
+ const cleaned = stripInvisibleAndBidi(safeDisplay(value)).trim();
112
+ if (cleaned.length <= maxChars) return cleaned;
113
+ const suffix = '… [truncated]';
114
+ const keep = Math.max(0, maxChars - suffix.length);
115
+ return `${cleaned.slice(0, keep).trimEnd()}${suffix}`;
116
+ }
117
+
118
+ /**
119
+ * Validates and sanitizes an MCP tool name. Rejects empty names, names with
120
+ * ASCII control characters / NUL bytes, or names exceeding the length ceiling.
121
+ */
122
+ export function sanitizeMcpToolName(value: unknown): string | null {
123
+ if (typeof value !== 'string') return null;
124
+ const stripped = stripInvisibleAndBidi(value).trim();
125
+ if (stripped.length === 0 || stripped.length > MAX_MCP_TOOL_NAME_CHARS) return null;
126
+ for (let i = 0; i < stripped.length; i++) {
127
+ const code = stripped.charCodeAt(i);
128
+ if (code < 0x20 || code === 0x7f) return null;
129
+ }
130
+ return stripped;
131
+ }
132
+
133
+ function sanitizeSchemaNode(value: unknown, depth: number): unknown {
134
+ if (depth > MAX_MCP_SCHEMA_DEPTH) {
135
+ return { type: 'object', description: 'Nested schema truncated at maximum depth.' };
136
+ }
137
+ if (typeof value === 'string') {
138
+ return sanitizeMcpMetadataText(value, MAX_MCP_SCHEMA_STRING_CHARS);
139
+ }
140
+ if (typeof value === 'number' || typeof value === 'boolean' || value === null) {
141
+ return value;
142
+ }
143
+ if (Array.isArray(value)) {
144
+ const maxItems = 128;
145
+ return value.slice(0, maxItems).map(item => sanitizeSchemaNode(item, depth + 1));
146
+ }
147
+ if (isRecord(value)) {
148
+ const out: Record<string, unknown> = {};
149
+ let count = 0;
150
+ for (const [key, item] of Object.entries(value)) {
151
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
152
+ if (count >= 256) break;
153
+ const safeKey = stripInvisibleAndBidi(safeDisplay(key));
154
+ if (!safeKey) continue;
155
+ out[safeKey] = sanitizeSchemaNode(item, depth + 1);
156
+ count++;
157
+ }
158
+ return out;
159
+ }
160
+ return undefined;
161
+ }
162
+
163
+ /**
164
+ * Sanitizes and size-bounds an untrusted MCP tool JSON input schema.
165
+ * Strips ANSI escapes and bidi characters from nested property descriptions,
166
+ * prevents prototype pollution keys, caps nesting depth, and falls back to an
167
+ * empty object schema if serialized size exceeds `MAX_MCP_SCHEMA_JSON_BYTES`.
168
+ */
169
+ export function sanitizeMcpInputSchema(schema: unknown): Record<string, unknown> {
170
+ if (!isRecord(schema)) {
171
+ return { type: 'object', properties: {} };
172
+ }
173
+ const sanitized = sanitizeSchemaNode(schema, 0);
174
+ if (!isRecord(sanitized)) {
175
+ return { type: 'object', properties: {} };
176
+ }
177
+ try {
178
+ const serialized = JSON.stringify(sanitized);
179
+ if (Buffer.byteLength(serialized, 'utf8') > MAX_MCP_SCHEMA_JSON_BYTES) {
180
+ return {
181
+ type: 'object',
182
+ properties: {},
183
+ description: 'MCP tool input schema omitted because it exceeded the 64 KiB safety limit.'
184
+ };
185
+ }
186
+ } catch {
187
+ return { type: 'object', properties: {} };
188
+ }
189
+ return sanitized;
190
+ }
@@ -15,7 +15,7 @@ function normalizeWorkspace(workspace) {
15
15
  }
16
16
  function isPathWithinOrSame(candidatePath, rootPath) {
17
17
  const rel = path.relative(path.resolve(rootPath), path.resolve(candidatePath));
18
- return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
18
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
19
19
  }
20
20
  function extractEmbeddedAbsolutePaths(text) {
21
21
  const found = [];
@@ -40,7 +40,7 @@ function normalizeWorkspace(workspace?: string | null): string | undefined {
40
40
 
41
41
  function isPathWithinOrSame(candidatePath: string, rootPath: string): boolean {
42
42
  const rel = path.relative(path.resolve(rootPath), path.resolve(candidatePath));
43
- return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
43
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
44
44
  }
45
45
 
46
46
  function extractEmbeddedAbsolutePaths(text: string): string[] {
@@ -161,6 +161,7 @@ function extractCollapsedSignature(lines, startIndex, kind) {
161
161
  function findBraceBlockEnd(lines, startIndex, kind) {
162
162
  const isCallable = kind === 'function' || kind === 'method';
163
163
  let inBlockComment = false;
164
+ let inTemplate = false;
164
165
  let parenDepth = 0;
165
166
  let seenParamsOpen = false;
166
167
  let seenParamsClose = !isCallable;
@@ -172,7 +173,6 @@ function findBraceBlockEnd(lines, startIndex, kind) {
172
173
  const line = lines[i] ?? '';
173
174
  let inSingleQuote = false;
174
175
  let inDoubleQuote = false;
175
- let inTemplate = false;
176
176
  for (let c = 0; c < line.length; c++) {
177
177
  const ch = line[c] ?? '';
178
178
  const next = line[c + 1] ?? '';
@@ -174,6 +174,7 @@ function extractCollapsedSignature(lines: readonly string[], startIndex: number,
174
174
  function findBraceBlockEnd(lines: readonly string[], startIndex: number, kind: FoldedSymbolKind): number {
175
175
  const isCallable = kind === 'function' || kind === 'method';
176
176
  let inBlockComment = false;
177
+ let inTemplate = false;
177
178
  let parenDepth = 0;
178
179
  let seenParamsOpen = false;
179
180
  let seenParamsClose = !isCallable;
@@ -186,7 +187,6 @@ function findBraceBlockEnd(lines: readonly string[], startIndex: number, kind: F
186
187
  const line = lines[i] ?? '';
187
188
  let inSingleQuote = false;
188
189
  let inDoubleQuote = false;
189
- let inTemplate = false;
190
190
 
191
191
  for (let c = 0; c < line.length; c++) {
192
192
  const ch = line[c] ?? '';
@@ -47,7 +47,7 @@ export function resolveRoute(config, kind) {
47
47
  reason: 'utility route set explicitly in config'
48
48
  };
49
49
  }
50
- const cheap = UTILITY_MODEL_BY_PROVIDER[provider];
50
+ const cheap = Object.hasOwn(UTILITY_MODEL_BY_PROVIDER, provider) ? UTILITY_MODEL_BY_PROVIDER[provider] : undefined;
51
51
  if (!cheap) {
52
52
  return { ...stay, reason: `no published utility tier for ${provider}; paying full rate` };
53
53
  }