@causyne/agent 1.20.122 → 1.20.124

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 (518) hide show
  1. package/bin/causyne.js +38 -15
  2. package/docs/SECURITY_REVIEW.md +42 -6
  3. package/package.json +5 -5
  4. package/src/acp/agentCatalog.js +74 -50
  5. package/src/acp/agentCatalog.ts +82 -49
  6. package/src/acp/client.js +309 -86
  7. package/src/acp/client.ts +291 -84
  8. package/src/acp/protocol.js +147 -3
  9. package/src/acp/protocol.ts +162 -3
  10. package/src/acp/server.js +138 -39
  11. package/src/acp/server.ts +122 -41
  12. package/src/agent/errorClassifier.js +42 -6
  13. package/src/agent/errorClassifier.ts +44 -5
  14. package/src/agent/providerFailure.js +1 -1
  15. package/src/agent/providerFailure.ts +7 -1
  16. package/src/agent/toolArgValidator.js +38 -4
  17. package/src/agent/toolArgValidator.ts +39 -4
  18. package/src/agent/toolTurnIntegrity.js +28 -7
  19. package/src/agent/toolTurnIntegrity.ts +25 -6
  20. package/src/agent/workspaceBoundary.js +30 -4
  21. package/src/agent/workspaceBoundary.ts +32 -4
  22. package/src/agentLoop.js +598 -217
  23. package/src/agentLoop.ts +621 -215
  24. package/src/approvalPolicy.js +28 -1
  25. package/src/approvalPolicy.ts +28 -1
  26. package/src/auditLog.js +641 -48
  27. package/src/auditLog.ts +661 -0
  28. package/src/autoUpdate.js +32 -5
  29. package/src/autoUpdate.ts +27 -5
  30. package/src/backgroundTasks.js +328 -0
  31. package/src/backgroundTasks.ts +339 -0
  32. package/src/benchmarks/codingEval.js +558 -0
  33. package/src/benchmarks/codingEval.ts +628 -0
  34. package/src/benchmarks/planCache.js +115 -134
  35. package/src/benchmarks/planCache.ts +163 -0
  36. package/src/browser/browserRuntime.js +52 -0
  37. package/src/browser/browserRuntime.ts +55 -0
  38. package/src/browser/causyneBrowser.js +884 -10
  39. package/src/browser/causyneBrowser.ts +1042 -32
  40. package/src/browser/searchProviders.js +94 -6
  41. package/src/browser/searchProviders.ts +89 -6
  42. package/src/browser/urlPolicy.js +8 -1
  43. package/src/browser/urlPolicy.ts +7 -1
  44. package/src/browser/workspacePathSafety.js +6 -4
  45. package/src/browser/workspacePathSafety.ts +7 -4
  46. package/src/capabilities.js +18 -17
  47. package/src/capabilities.ts +38 -0
  48. package/src/checkpoints.js +1241 -1127
  49. package/src/checkpoints.ts +1377 -0
  50. package/src/cliMode.js +707 -755
  51. package/src/cliMode.ts +780 -0
  52. package/src/codebase/repoMap.js +656 -0
  53. package/src/codebase/repoMap.ts +664 -0
  54. package/src/commands.js +3651 -2514
  55. package/src/commands.ts +3985 -0
  56. package/src/compiledSkills.js +8052 -8054
  57. package/src/compiledSkills.ts +8078 -0
  58. package/src/config.js +103 -1
  59. package/src/config.ts +110 -1
  60. package/src/configVault.js +29 -2
  61. package/src/configVault.ts +26 -2
  62. package/src/contextManager.js +473 -557
  63. package/src/contextManager.ts +599 -0
  64. package/src/continuum/adapters/antigravity.js +8 -3
  65. package/src/continuum/adapters/antigravity.ts +8 -3
  66. package/src/continuum/sanitizer.js +23 -1
  67. package/src/continuum/sanitizer.ts +23 -1
  68. package/src/continuum/ui/continuumPicker.js +0 -2
  69. package/src/continuum/ui/continuumPicker.ts +0 -2
  70. package/src/continuum/ui/continuumPickerView.js +0 -2
  71. package/src/continuum/ui/continuumPickerView.ts +4 -20
  72. package/src/core/contextCompactor.js +88 -7
  73. package/src/core/contextCompactor.ts +87 -8
  74. package/src/creative/liveBridge.js +3 -2
  75. package/src/creative/liveBridge.ts +4 -2
  76. package/src/creative/studioScripts.js +1 -1
  77. package/src/creative/studioScripts.ts +1 -1
  78. package/src/decideTools.js +7 -2
  79. package/src/decideTools.ts +7 -2
  80. package/src/decisionPolicy.js +10 -2
  81. package/src/decisionPolicy.ts +10 -2
  82. package/src/designPalettes.js +72 -84
  83. package/src/designPalettes.ts +111 -0
  84. package/src/devMode.js +2 -2
  85. package/src/devMode.ts +6 -0
  86. package/src/diffReview.js +370 -0
  87. package/src/diffReview.ts +407 -0
  88. package/src/dynamicCatalogue.js +311 -11
  89. package/src/dynamicCatalogue.ts +331 -11
  90. package/src/embodimentSession.js +143 -154
  91. package/src/embodimentSession.ts +173 -0
  92. package/src/engines/installer.js +60 -29
  93. package/src/engines/installer.ts +73 -22
  94. package/src/enterprisePolicy.js +660 -0
  95. package/src/enterprisePolicy.ts +728 -0
  96. package/src/entrypoint.js +514 -268
  97. package/src/entrypoint.ts +607 -0
  98. package/src/gitSnapshot.js +417 -312
  99. package/src/gitSnapshot.ts +500 -0
  100. package/src/headlessCli.js +324 -13
  101. package/src/headlessCli.ts +321 -12
  102. package/src/hooks.js +247 -26
  103. package/src/hooks.ts +236 -26
  104. package/src/ignoreRules.js +297 -0
  105. package/src/ignoreRules.ts +308 -0
  106. package/src/implementationPlan.js +7 -6
  107. package/src/implementationPlan.ts +8 -6
  108. package/src/infra/atomicWriter.js +92 -19
  109. package/src/infra/atomicWriter.ts +108 -19
  110. package/src/launchIntent.js +13 -2
  111. package/src/launchIntent.ts +13 -2
  112. package/src/licensing/entitlements.js +553 -237
  113. package/src/licensing/entitlements.ts +590 -0
  114. package/src/licensing/policy.js +17 -1
  115. package/src/licensing/policy.ts +31 -0
  116. package/src/lsp/lspCatalog.js +398 -0
  117. package/src/lsp/lspCatalog.ts +452 -0
  118. package/src/lsp/lspClient.js +699 -0
  119. package/src/lsp/lspClient.ts +799 -0
  120. package/src/lsp/lspProtocol.js +121 -0
  121. package/src/lsp/lspProtocol.ts +140 -0
  122. package/src/mcp/mcpClient.js +69 -8
  123. package/src/mcp/mcpClient.ts +66 -9
  124. package/src/mcp/mcpRegistry.js +180 -7
  125. package/src/mcp/mcpRegistry.ts +171 -7
  126. package/src/mcp/mcpSecurity.js +6 -7
  127. package/src/mcp/mcpSecurity.ts +7 -6
  128. package/src/memory/episodicStore.js +2 -5
  129. package/src/memory/episodicStore.ts +2 -5
  130. package/src/memory.js +80 -32
  131. package/src/memory.ts +111 -0
  132. package/src/memoryManager.js +151 -143
  133. package/src/memoryManager.ts +182 -0
  134. package/src/modelCatalogue.js +172 -195
  135. package/src/modelCatalogue.ts +201 -0
  136. package/src/modelIds.js +8 -27
  137. package/src/modelIds.ts +33 -0
  138. package/src/modelVariants.js +600 -0
  139. package/src/modelVariants.ts +663 -0
  140. package/src/observer/evidence.js +5 -1
  141. package/src/observer/evidence.ts +5 -1
  142. package/src/osKeychain.js +17 -9
  143. package/src/osKeychain.ts +14 -9
  144. package/src/outputStore.js +210 -156
  145. package/src/outputStore.ts +321 -0
  146. package/src/planCache.js +3 -6
  147. package/src/planCache.ts +3 -6
  148. package/src/plugins/pluginManager.js +689 -461
  149. package/src/plugins/pluginManager.ts +807 -0
  150. package/src/plugins/pluginRunner.js +82 -37
  151. package/src/plugins/pluginRunner.ts +98 -0
  152. package/src/plugins/pluginSkills.js +47 -9
  153. package/src/plugins/pluginSkills.ts +46 -8
  154. package/src/pluginsFactory/discovery.js +0 -1
  155. package/src/pluginsFactory/discovery.ts +0 -1
  156. package/src/pluginsFactory/templates.js +17 -4
  157. package/src/pluginsFactory/templates.ts +17 -4
  158. package/src/prWorkflow.js +337 -0
  159. package/src/prWorkflow.ts +376 -0
  160. package/src/procSignal.js +1 -2
  161. package/src/procSignal.ts +1 -3
  162. package/src/projectInstructions.js +319 -0
  163. package/src/projectInstructions.ts +361 -0
  164. package/src/providers/acp.js +234 -49
  165. package/src/providers/acp.ts +240 -50
  166. package/src/providers/anthropic.js +152 -47
  167. package/src/providers/anthropic.ts +152 -45
  168. package/src/providers/antigravity.js +565 -354
  169. package/src/providers/antigravity.ts +555 -355
  170. package/src/providers/base.js +9 -2
  171. package/src/providers/base.ts +10 -2
  172. package/src/providers/byokHttp.js +127 -17
  173. package/src/providers/byokHttp.ts +175 -18
  174. package/src/providers/byokStream.js +162 -36
  175. package/src/providers/byokStream.ts +162 -55
  176. package/src/providers/dashscope-byok.js +29 -3
  177. package/src/providers/dashscope-byok.ts +30 -2
  178. package/src/providers/deepseek.js +12 -3
  179. package/src/providers/deepseek.ts +12 -3
  180. package/src/providers/factory.js +41 -0
  181. package/src/providers/factory.ts +42 -0
  182. package/src/providers/gemini.js +74 -22
  183. package/src/providers/gemini.ts +78 -26
  184. package/src/providers/moonshot.js +36 -3
  185. package/src/providers/moonshot.ts +32 -3
  186. package/src/providers/ollama.js +267 -21
  187. package/src/providers/ollama.ts +302 -29
  188. package/src/providers/openai-compatible.js +67 -11
  189. package/src/providers/openai-compatible.ts +78 -17
  190. package/src/providers/openai.js +25 -2
  191. package/src/providers/openai.ts +24 -2
  192. package/src/providers/openrouter.js +233 -66
  193. package/src/providers/openrouter.ts +226 -70
  194. package/src/providers/qwen-byok.js +29 -3
  195. package/src/providers/qwen-byok.ts +30 -2
  196. package/src/providers/wireNormalizer.js +66 -0
  197. package/src/providers/wireNormalizer.ts +64 -0
  198. package/src/providers/xai.js +10 -3
  199. package/src/providers/xai.ts +9 -3
  200. package/src/provisioning/capabilityConsent.js +29 -11
  201. package/src/provisioning/capabilityConsent.ts +42 -0
  202. package/src/provisioning/capabilityProvisioner.js +309 -197
  203. package/src/provisioning/capabilityProvisioner.ts +413 -0
  204. package/src/provisioning/capabilityTools.js +31 -17
  205. package/src/provisioning/capabilityTools.ts +43 -0
  206. package/src/provisioning/npmInstall.js +33 -5
  207. package/src/provisioning/npmInstall.ts +33 -5
  208. package/src/reporting.js +328 -326
  209. package/src/reporting.ts +482 -0
  210. package/src/sandbox.js +37 -0
  211. package/src/sandbox.ts +38 -0
  212. package/src/sessionJournal.js +24 -3
  213. package/src/sessionJournal.ts +18 -3
  214. package/src/sessionStore.js +1 -2
  215. package/src/sessionStore.ts +2 -0
  216. package/src/slopDetector.js +202 -265
  217. package/src/slopDetector.ts +279 -0
  218. package/src/smartToolsUse.js +10 -4
  219. package/src/smartToolsUse.ts +10 -4
  220. package/src/stallGuard.js +10 -3
  221. package/src/stallGuard.ts +9 -3
  222. package/src/taskBuffer.js +91 -40
  223. package/src/taskBuffer.ts +94 -0
  224. package/src/tokenTracker.js +78 -11
  225. package/src/tokenTracker.ts +69 -11
  226. package/src/toolPacks.js +5 -0
  227. package/src/toolPacks.ts +5 -0
  228. package/src/tools/applyPatch.js +610 -0
  229. package/src/tools/applyPatch.ts +661 -0
  230. package/src/tools/archive.js +135 -21
  231. package/src/tools/archive.ts +136 -21
  232. package/src/tools/astryxOracle.js +77 -72
  233. package/src/tools/astryxOracle.ts +95 -0
  234. package/src/tools/axSnapshot.js +127 -147
  235. package/src/tools/axSnapshot.ts +174 -0
  236. package/src/tools/backgroundTask.js +86 -0
  237. package/src/tools/backgroundTask.ts +121 -0
  238. package/src/tools/blenderAutomator.js +434 -390
  239. package/src/tools/blenderAutomator.ts +623 -0
  240. package/src/tools/checkSystemSpecs.js +54 -61
  241. package/src/tools/checkSystemSpecs.ts +73 -0
  242. package/src/tools/clipboard.js +42 -31
  243. package/src/tools/clipboard.ts +61 -0
  244. package/src/tools/codeSearchAst.js +359 -91
  245. package/src/tools/codeSearchAst.ts +399 -0
  246. package/src/tools/codeSearcher.js +179 -37
  247. package/src/tools/codeSearcher.ts +188 -33
  248. package/src/tools/codeTools.js +208 -245
  249. package/src/tools/codeTools.ts +271 -0
  250. package/src/tools/codebaseSearch.js +5 -0
  251. package/src/tools/codebaseSearch.ts +5 -0
  252. package/src/tools/desktopAct.js +185 -197
  253. package/src/tools/desktopAct.ts +257 -0
  254. package/src/tools/dynamicLoader.js +4 -40
  255. package/src/tools/dynamicLoader.ts +13 -0
  256. package/src/tools/executeProceduralMedia.js +117 -86
  257. package/src/tools/executeProceduralMedia.ts +135 -0
  258. package/src/tools/fileTracker.js +74 -0
  259. package/src/tools/fileTracker.ts +94 -0
  260. package/src/tools/fsDelete.js +57 -47
  261. package/src/tools/fsDelete.ts +80 -0
  262. package/src/tools/fsEdit.js +192 -74
  263. package/src/tools/fsEdit.ts +201 -72
  264. package/src/tools/fsMove.js +79 -52
  265. package/src/tools/fsMove.ts +108 -0
  266. package/src/tools/fsRead.js +54 -15
  267. package/src/tools/fsRead.ts +55 -15
  268. package/src/tools/fsSearch.js +5 -0
  269. package/src/tools/fsSearch.ts +5 -0
  270. package/src/tools/fsWrite.js +14 -6
  271. package/src/tools/fsWrite.ts +14 -6
  272. package/src/tools/gameAiBehaviorTree.js +74 -91
  273. package/src/tools/gameAiBehaviorTree.ts +219 -0
  274. package/src/tools/gameAnimationRig.js +128 -147
  275. package/src/tools/gameAnimationRig.ts +215 -0
  276. package/src/tools/gameAssetFetcher.js +403 -441
  277. package/src/tools/gameAssetFetcher.ts +477 -0
  278. package/src/tools/gameAssetHarvester.js +171 -200
  279. package/src/tools/gameAssetHarvester.ts +261 -0
  280. package/src/tools/gameAudioSynth.js +223 -259
  281. package/src/tools/gameAudioSynth.ts +255 -0
  282. package/src/tools/gameBuilder.js +100 -91
  283. package/src/tools/gameBuilder.ts +913 -0
  284. package/src/tools/gameCanvasAudit.js +138 -96
  285. package/src/tools/gameCanvasAudit.ts +157 -0
  286. package/src/tools/gameCinematicSequencer.js +93 -111
  287. package/src/tools/gameCinematicSequencer.ts +165 -0
  288. package/src/tools/gameDataForge.js +115 -118
  289. package/src/tools/gameDataForge.ts +151 -0
  290. package/src/tools/gameDialogueTreeGen.js +125 -156
  291. package/src/tools/gameDialogueTreeGen.ts +159 -0
  292. package/src/tools/gameEconomyBalancer.js +150 -153
  293. package/src/tools/gameEconomyBalancer.ts +186 -0
  294. package/src/tools/gameEntitySpawner.js +91 -108
  295. package/src/tools/gameEntitySpawner.ts +209 -0
  296. package/src/tools/gameLoreForge.js +125 -147
  297. package/src/tools/gameLoreForge.ts +162 -0
  298. package/src/tools/gameQuestArcBuilder.js +105 -144
  299. package/src/tools/gameQuestArcBuilder.ts +147 -0
  300. package/src/tools/gameSceneBuilder.js +143 -149
  301. package/src/tools/gameSceneBuilder.ts +196 -0
  302. package/src/tools/gameShaderForge.js +83 -101
  303. package/src/tools/gameShaderForge.ts +181 -0
  304. package/src/tools/gameTilemapGenerator.js +99 -129
  305. package/src/tools/gameTilemapGenerator.ts +158 -0
  306. package/src/tools/gameUiHudBuilder.js +109 -129
  307. package/src/tools/gameUiHudBuilder.ts +300 -0
  308. package/src/tools/gameVfxEmitterGen.js +86 -89
  309. package/src/tools/gameVfxEmitterGen.ts +133 -0
  310. package/src/tools/gameWebRuntimeInspector.js +153 -86
  311. package/src/tools/gameWebRuntimeInspector.ts +167 -0
  312. package/src/tools/generateMediaViaApi.js +53 -12
  313. package/src/tools/generateMediaViaApi.ts +52 -12
  314. package/src/tools/gitExec.js +133 -86
  315. package/src/tools/gitExec.ts +146 -0
  316. package/src/tools/gitWorktree.js +115 -0
  317. package/src/tools/gitWorktree.ts +150 -0
  318. package/src/tools/godotAutomator.js +417 -394
  319. package/src/tools/godotAutomator.ts +530 -0
  320. package/src/tools/lspCodeIntel.js +217 -0
  321. package/src/tools/lspCodeIntel.ts +260 -0
  322. package/src/tools/manageLocalAiDependencies.js +242 -206
  323. package/src/tools/manageLocalAiDependencies.ts +288 -0
  324. package/src/tools/multiEdit.js +16 -76
  325. package/src/tools/multiEdit.ts +20 -77
  326. package/src/tools/osSandbox.js +152 -15
  327. package/src/tools/osSandbox.ts +148 -15
  328. package/src/tools/palmierAutomator.js +147 -95
  329. package/src/tools/palmierAutomator.ts +171 -0
  330. package/src/tools/pdfReader.js +95 -104
  331. package/src/tools/pdfReader.ts +125 -0
  332. package/src/tools/persistentShell.js +267 -144
  333. package/src/tools/persistentShell.ts +314 -0
  334. package/src/tools/pluginManager.js +84 -72
  335. package/src/tools/pluginManager.ts +109 -0
  336. package/src/tools/printer.js +278 -296
  337. package/src/tools/printer.ts +326 -0
  338. package/src/tools/procTerm.js +96 -83
  339. package/src/tools/procTerm.ts +127 -0
  340. package/src/tools/processList.js +45 -48
  341. package/src/tools/processList.ts +73 -0
  342. package/src/tools/registry.js +298 -286
  343. package/src/tools/registry.ts +486 -0
  344. package/src/tools/repoMap.js +46 -0
  345. package/src/tools/repoMap.ts +66 -0
  346. package/src/tools/subagentOrchestrator.js +404 -348
  347. package/src/tools/subagentOrchestrator.ts +457 -0
  348. package/src/tools/sysRun.js +83 -26
  349. package/src/tools/sysRun.ts +80 -26
  350. package/src/tools/toolForge.js +84 -67
  351. package/src/tools/toolForge.ts +102 -0
  352. package/src/tools/toolPathSafety.js +262 -0
  353. package/src/tools/toolPathSafety.ts +308 -0
  354. package/src/tools/toolScanner.js +28 -0
  355. package/src/tools/toolScanner.ts +29 -0
  356. package/src/tools/toolSelfRepair.js +21 -6
  357. package/src/tools/toolSelfRepair.ts +26 -6
  358. package/src/tools/walkerSafety.ts +1 -0
  359. package/src/tools/webFetch.js +5 -2
  360. package/src/tools/webFetch.ts +5 -2
  361. package/src/toolsList.js +5 -0
  362. package/src/toolsList.ts +5 -0
  363. package/src/tui/ask.js +159 -168
  364. package/src/tui/ask.ts +259 -0
  365. package/src/tui/block.js +0 -1
  366. package/src/tui/block.ts +0 -1
  367. package/src/tui/chatRenderer.js +1193 -1441
  368. package/src/tui/chatRenderer.ts +1336 -0
  369. package/src/tui/clipboardImage.js +36 -12
  370. package/src/tui/clipboardImage.ts +39 -13
  371. package/src/tui/clipboardSync.js +34 -9
  372. package/src/tui/clipboardSync.ts +38 -9
  373. package/src/tui/codeProgress.js +0 -1
  374. package/src/tui/codeProgress.ts +0 -1
  375. package/src/tui/completion.js +395 -371
  376. package/src/tui/completion.ts +574 -0
  377. package/src/tui/composerControls.js +113 -19
  378. package/src/tui/composerControls.ts +124 -19
  379. package/src/tui/consoleGuard.js +27 -7
  380. package/src/tui/consoleGuard.ts +29 -7
  381. package/src/tui/dialogs.js +864 -717
  382. package/src/tui/dialogs.ts +984 -0
  383. package/src/tui/diff.js +205 -195
  384. package/src/tui/diff.ts +336 -0
  385. package/src/tui/history.js +143 -108
  386. package/src/tui/history.ts +167 -0
  387. package/src/tui/home.js +165 -161
  388. package/src/tui/home.ts +251 -0
  389. package/src/tui/invocation.js +58 -65
  390. package/src/tui/invocation.ts +117 -0
  391. package/src/tui/keys.js +437 -420
  392. package/src/tui/keys.ts +597 -0
  393. package/src/tui/lineEditor.js +477 -432
  394. package/src/tui/lineEditor.ts +542 -0
  395. package/src/tui/messageActionPlacement.js +0 -1
  396. package/src/tui/messageActionPlacement.ts +0 -1
  397. package/src/tui/messageInteraction.js +0 -2
  398. package/src/tui/messageInteraction.ts +0 -2
  399. package/src/tui/modelPicker.js +0 -3
  400. package/src/tui/modelPicker.ts +3 -6
  401. package/src/tui/observerPicker.js +0 -2
  402. package/src/tui/observerPicker.ts +0 -2
  403. package/src/tui/overlay.js +0 -1
  404. package/src/tui/overlay.ts +0 -1
  405. package/src/tui/prompt.js +1816 -2151
  406. package/src/tui/prompt.ts +1870 -0
  407. package/src/tui/runningLight.js +0 -1
  408. package/src/tui/runningLight.ts +0 -1
  409. package/src/tui/selectList.js +365 -337
  410. package/src/tui/selectList.ts +441 -0
  411. package/src/tui/sessionPicker.js +0 -1
  412. package/src/tui/sessionPicker.ts +0 -1
  413. package/src/tui/sessionPickerView.js +0 -2
  414. package/src/tui/sessionPickerView.ts +4 -21
  415. package/src/tui/sessionSidebar.js +3 -1
  416. package/src/tui/sessionSidebar.ts +4 -1
  417. package/src/tui/setup.js +17 -5
  418. package/src/tui/setup.ts +19 -5
  419. package/src/tui/skillAuthoring.js +0 -2
  420. package/src/tui/skillAuthoring.ts +0 -3
  421. package/src/tui/stageSurface.js +829 -909
  422. package/src/tui/stageSurface.ts +1003 -0
  423. package/src/tui/statusLine.js +7 -4
  424. package/src/tui/statusLine.ts +7 -3
  425. package/src/tui/terminalInputFramer.js +82 -69
  426. package/src/tui/terminalInputFramer.ts +116 -0
  427. package/src/tui/text.js +25 -10
  428. package/src/tui/text.ts +24 -10
  429. package/src/tui/textLayout.js +0 -1
  430. package/src/tui/textLayout.ts +0 -1
  431. package/src/tui/theme.js +245 -250
  432. package/src/tui/theme.ts +441 -0
  433. package/src/tui/thinkingBox.js +0 -1
  434. package/src/tui/thinkingBox.ts +0 -1
  435. package/src/tui/transcript.js +239 -216
  436. package/src/tui/transcript.ts +324 -0
  437. package/src/tui/turnRail.js +53 -54
  438. package/src/tui/turnRail.ts +51 -49
  439. package/src/tui/usageCard.js +0 -2
  440. package/src/tui/usageCard.ts +0 -2
  441. package/src/tui/workspaceSwitch.js +4 -2
  442. package/src/tui/workspaceSwitch.ts +5 -2
  443. package/src/types/contracts.ts +4 -1
  444. package/src/utils/browserOpen.js +107 -0
  445. package/src/utils/browserOpen.ts +129 -0
  446. package/src/utils/cli_ui.js +0 -0
  447. package/src/utils/cli_ui.ts +158 -0
  448. package/src/utils/winSpawn.js +248 -0
  449. package/src/utils/winSpawn.ts +275 -0
  450. package/src/verification/boundedExplorer.js +138 -107
  451. package/src/verification/boundedExplorer.ts +154 -0
  452. package/src/verification/byokSmokeProbe.js +193 -0
  453. package/src/verification/byokSmokeProbe.ts +234 -0
  454. package/src/verification/cliProbe.js +144 -110
  455. package/src/verification/cliProbe.ts +170 -0
  456. package/src/verification/featureMap.js +105 -75
  457. package/src/verification/featureMap.ts +124 -0
  458. package/src/verification/interactivePty.js +195 -100
  459. package/src/verification/interactivePty.ts +333 -0
  460. package/src/verification/propertyProbe.js +109 -101
  461. package/src/verification/propertyProbe.ts +159 -0
  462. package/src/verification/ptyProbe.js +168 -73
  463. package/src/verification/ptyProbe.ts +254 -0
  464. package/src/verification/skillCatalog.js +25 -25
  465. package/src/verification/skillCatalog.ts +66 -0
  466. package/src/verification/statechart.js +140 -127
  467. package/src/verification/statechart.ts +196 -0
  468. package/src/verification/uiRuntime.js +80 -49
  469. package/src/verification/uiRuntime.ts +88 -0
  470. package/src/version.js +37 -32
  471. package/src/version.ts +45 -0
  472. package/src/web/guiLauncher.js +89 -0
  473. package/src/web/guiLauncher.ts +119 -0
  474. package/src/web/skybridgeBrowserBridge.js +256 -0
  475. package/src/web/skybridgeBrowserBridge.ts +285 -0
  476. package/src/web/skybridgeBrowserMcp.js +730 -0
  477. package/src/web/skybridgeBrowserMcp.ts +813 -0
  478. package/src/web/skybridgeClientScript.js +3951 -0
  479. package/src/web/skybridgeClientScript.ts +3952 -0
  480. package/src/web/skybridgeServer.js +2622 -0
  481. package/src/web/skybridgeServer.ts +2787 -0
  482. package/src/web/skybridgeStyles.js +827 -0
  483. package/src/web/skybridgeStyles.ts +828 -0
  484. package/src/web/skybridgeUi.js +472 -0
  485. package/src/web/skybridgeUi.ts +485 -0
  486. package/src/worktreeManager.js +511 -0
  487. package/src/worktreeManager.ts +546 -0
  488. package/src/zeroCostFailover.js +168 -0
  489. package/src/zeroCostFailover.ts +198 -0
  490. package/src/zeroCostRouting.js +391 -0
  491. package/src/zeroCostRouting.ts +437 -0
  492. package/src/agentLoop.d.ts +0 -65
  493. package/src/auditLog.d.ts +0 -3
  494. package/src/checkpoints.d.ts +0 -4
  495. package/src/compiledSkills.d.ts +0 -5
  496. package/src/contextManager.d.ts +0 -14
  497. package/src/designPalettes.d.ts +0 -2
  498. package/src/devMode.d.ts +0 -1
  499. package/src/embodimentSession.d.ts +0 -2
  500. package/src/licensing/entitlements.d.ts +0 -14
  501. package/src/memory.d.ts +0 -13
  502. package/src/memoryManager.d.ts +0 -1
  503. package/src/modelCatalogue.d.ts +0 -6
  504. package/src/modelIds.d.ts +0 -2
  505. package/src/outputStore.d.ts +0 -4
  506. package/src/plugins/pluginManager.d.ts +0 -7
  507. package/src/providers/antigravity.d.ts +0 -19
  508. package/src/provisioning/capabilityProvisioner.d.ts +0 -12
  509. package/src/slopDetector.d.ts +0 -3
  510. package/src/taskBuffer.d.ts +0 -1
  511. package/src/tools/desktopAct.d.ts +0 -10
  512. package/src/tools/registry.d.ts +0 -5
  513. package/src/tui/chatRenderer.d.ts +0 -27
  514. package/src/tui/diff.d.ts +0 -3
  515. package/src/utils/cli_ui.d.ts +0 -19
  516. package/src/utils/paths.d.ts +0 -3
  517. package/src/verification/skillCatalog.d.ts +0 -1
  518. package/src/version.d.ts +0 -1
@@ -5,9 +5,18 @@ import { spawn } from 'node:child_process';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { causyneHome } from '../utils/paths.js';
7
7
  import { parsePluginSkills } from './pluginSkills.js';
8
-
9
- const PLUGIN_ROOT = path.join(causyneHome(), 'plugins');
10
- const STATE_FILE = path.join(PLUGIN_ROOT, 'state.json');
8
+ import { isWithinPhysicalPath, physicalPath } from '../agent/workspaceBoundary.js';
9
+ import { isBlockedWorkspaceRoot } from '../sandboxPolicy.js';
10
+ import { redactProviderSecrets } from '../providers/byokHttp.js';
11
+ import { safeDisplay } from '../tui/text.js';
12
+ function pluginRoot() {
13
+ return path.join(causyneHome(), 'plugins');
14
+ }
15
+ function stateFile() {
16
+ return path.join(pluginRoot(), 'state.json');
17
+ }
18
+ const PLUGIN_ROOT = pluginRoot();
19
+ const STATE_FILE = stateFile();
11
20
  const RUNNER_FILE = fileURLToPath(new URL('./pluginRunner.js', import.meta.url));
12
21
  const PACKAGE_FILE = fileURLToPath(new URL('../../package.json', import.meta.url));
13
22
  const MAX_MANIFEST_BYTES = 64 * 1024;
@@ -19,516 +28,735 @@ const MAX_RESULT_BYTES = 1024 * 1024;
19
28
  const DEFAULT_TIMEOUT_MS = 30_000;
20
29
  const NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
21
30
  const TOOL_NAME = /^[a-z][a-z0-9_-]{0,63}$/;
31
+ const EXPORT_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/;
22
32
  const VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
23
33
  const CAPABILITIES = new Set([
24
- 'workspace:read',
25
- 'workspace:write',
26
- 'network',
27
- 'subprocess'
34
+ 'workspace:read',
35
+ 'workspace:write',
36
+ 'network',
37
+ 'subprocess'
28
38
  ]);
29
-
30
39
  function ensureRoot() {
31
- if (!fs.existsSync(PLUGIN_ROOT)) fs.mkdirSync(PLUGIN_ROOT, { recursive: true, mode: 0o700 });
40
+ const root = pluginRoot();
41
+ if (!fs.existsSync(root)) {
42
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
43
+ }
44
+ else {
45
+ const stat = fs.lstatSync(root);
46
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
47
+ throw new Error('Refusing symlink or non-directory plugin root');
48
+ }
49
+ }
50
+ if (process.platform !== 'win32') {
51
+ try {
52
+ fs.chmodSync(root, 0o700);
53
+ }
54
+ catch { /* ignore */ }
55
+ }
32
56
  }
33
-
34
57
  function safeObject(value) {
35
- return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
58
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
36
59
  }
37
-
60
+ const MAX_STATE_BYTES = 1024 * 1024;
61
+ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
38
62
  function readState() {
39
- try {
40
- if (!fs.existsSync(STATE_FILE)) return { version: 1, plugins: {} };
41
- const parsed = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
42
- return { version: 1, plugins: safeObject(parsed.plugins) };
43
- } catch (error) {
44
- return { version: 1, plugins: {} };
45
- }
63
+ try {
64
+ const sf = stateFile();
65
+ const stat = fs.lstatSync(sf);
66
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > MAX_STATE_BYTES) {
67
+ return { version: 1, plugins: Object.create(null) };
68
+ }
69
+ const parsed = JSON.parse(fs.readFileSync(sf, 'utf8'));
70
+ const rawPlugins = safeObject(parsed?.plugins);
71
+ const clean = Object.create(null);
72
+ for (const [key, val] of Object.entries(rawPlugins)) {
73
+ if (!NAME.test(key) || FORBIDDEN_KEYS.has(key))
74
+ continue;
75
+ if (val && typeof val === 'object' && !Array.isArray(val)) {
76
+ clean[key] = val;
77
+ }
78
+ }
79
+ return { version: 1, plugins: clean };
80
+ }
81
+ catch {
82
+ return { version: 1, plugins: Object.create(null) };
83
+ }
46
84
  }
47
-
48
85
  function writeState(state) {
49
- ensureRoot();
50
- const temporary = `${STATE_FILE}.tmp_${process.pid}`;
51
- fs.writeFileSync(temporary, JSON.stringify(state, null, 2), { mode: 0o600 });
52
- fs.renameSync(temporary, STATE_FILE);
86
+ ensureRoot();
87
+ const sf = stateFile();
88
+ try {
89
+ const existing = fs.lstatSync(sf);
90
+ if (existing.isSymbolicLink() || !existing.isFile()) {
91
+ throw new Error('Refusing to overwrite symlink or non-regular plugin state file');
92
+ }
93
+ }
94
+ catch (err) {
95
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
96
+ if (code !== 'ENOENT')
97
+ throw err;
98
+ }
99
+ const temporary = `${sf}.tmp_${process.pid}_${crypto.randomBytes(6).toString('hex')}`;
100
+ const payload = Buffer.from(JSON.stringify(state, null, 2), 'utf8');
101
+ try {
102
+ const fd = fs.openSync(temporary, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
103
+ try {
104
+ fs.writeSync(fd, payload, 0, payload.length);
105
+ fs.fsyncSync(fd);
106
+ }
107
+ finally {
108
+ fs.closeSync(fd);
109
+ }
110
+ fs.renameSync(temporary, sf);
111
+ if (process.platform !== 'win32') {
112
+ try {
113
+ fs.chmodSync(sf, 0o600);
114
+ }
115
+ catch { /* ignore */ }
116
+ }
117
+ }
118
+ catch (err) {
119
+ try {
120
+ if (fs.existsSync(temporary))
121
+ fs.unlinkSync(temporary);
122
+ }
123
+ catch { /* ignore */ }
124
+ throw err;
125
+ }
53
126
  }
54
-
55
127
  function resolveInside(root, relativePath) {
56
- const resolvedRoot = path.resolve(root);
57
- const resolved = path.resolve(root, String(relativePath || ''));
58
- if (resolved === resolvedRoot || !resolved.startsWith(resolvedRoot + path.sep)) {
59
- throw new Error(`Path escapes plugin root: ${relativePath}`);
60
- }
61
- return resolved;
128
+ if (typeof relativePath !== 'string' || !relativePath || relativePath.includes('\0') || path.isAbsolute(relativePath)) {
129
+ throw new Error(`Invalid plugin relative path: ${String(relativePath)}`);
130
+ }
131
+ const resolvedRoot = path.resolve(root);
132
+ const resolved = path.resolve(root, relativePath);
133
+ if (resolved === resolvedRoot || !resolved.startsWith(resolvedRoot + path.sep)) {
134
+ throw new Error(`Path escapes plugin root: ${relativePath}`);
135
+ }
136
+ const realRoot = physicalPath(resolvedRoot);
137
+ const realTarget = physicalPath(resolved);
138
+ if (!realRoot || !realTarget || realTarget === realRoot || !isWithinPhysicalPath(realTarget, realRoot)) {
139
+ throw new Error(`Path escapes plugin root physically: ${relativePath}`);
140
+ }
141
+ return resolved;
62
142
  }
63
-
64
143
  function regularFile(file, maxBytes) {
65
- const stat = fs.lstatSync(file);
66
- if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`${file} must be a regular file`);
67
- if (stat.size > maxBytes) throw new Error(`${file} exceeds ${Math.round(maxBytes / 1024)} KB`);
68
- return stat;
144
+ const stat = fs.lstatSync(file);
145
+ if (!stat.isFile() || stat.isSymbolicLink())
146
+ throw new Error(`${file} must be a regular file`);
147
+ if (stat.nlink > 1)
148
+ throw new Error(`${file} must not be a hardlink`);
149
+ if (stat.size > maxBytes)
150
+ throw new Error(`${file} exceeds ${Math.round(maxBytes / 1024)} KB`);
151
+ return stat;
69
152
  }
70
-
153
+ const MAX_PLUGIN_DEPTH = 16;
71
154
  function digestPluginDirectory(directory) {
72
- const files = [];
73
- const visit = (current) => {
74
- const entries = fs.readdirSync(current, { withFileTypes: true })
75
- .sort((left, right) => left.name.localeCompare(right.name));
76
- for (const entry of entries) {
77
- const absolute = path.join(current, entry.name);
78
- const stat = fs.lstatSync(absolute);
79
- if (stat.isSymbolicLink()) throw new Error(`Plugin content must not be a symlink: ${entry.name}`);
80
- if (stat.isDirectory()) {
81
- visit(absolute);
82
- continue;
83
- }
84
- if (!stat.isFile()) throw new Error(`Plugin content must be a regular file: ${entry.name}`);
85
- files.push({ absolute, relative: path.relative(directory, absolute), size: stat.size });
86
- if (files.length > MAX_PLUGIN_FILES) throw new Error(`Plugin exceeds ${MAX_PLUGIN_FILES} files`);
87
- }
88
- };
89
- visit(directory);
90
- const totalBytes = files.reduce((sum, file) => sum + file.size, 0);
91
- if (totalBytes > MAX_PLUGIN_BYTES) throw new Error('Plugin exceeds 2 MB');
92
-
93
- const digest = crypto.createHash('sha256');
94
- for (const file of files) {
95
- digest.update(file.relative);
96
- digest.update('\0');
97
- digest.update(fs.readFileSync(file.absolute));
98
- digest.update('\0');
99
- }
100
- return digest.digest('hex');
155
+ const files = [];
156
+ let totalBytes = 0;
157
+ const visit = (current, depth) => {
158
+ if (depth > MAX_PLUGIN_DEPTH)
159
+ throw new Error(`Plugin directory nesting exceeds ${MAX_PLUGIN_DEPTH}`);
160
+ const entries = fs.readdirSync(current, { withFileTypes: true })
161
+ .sort((left, right) => left.name.localeCompare(right.name));
162
+ for (const entry of entries) {
163
+ const absolute = path.join(current, entry.name);
164
+ const stat = fs.lstatSync(absolute);
165
+ if (stat.isSymbolicLink())
166
+ throw new Error(`Plugin content must not be a symlink: ${entry.name}`);
167
+ if (stat.isDirectory()) {
168
+ visit(absolute, depth + 1);
169
+ continue;
170
+ }
171
+ if (!stat.isFile())
172
+ throw new Error(`Plugin content must be a regular file: ${entry.name}`);
173
+ if (stat.nlink > 1)
174
+ throw new Error(`Plugin content must not be a hardlink: ${entry.name}`);
175
+ totalBytes += stat.size;
176
+ if (totalBytes > MAX_PLUGIN_BYTES)
177
+ throw new Error('Plugin exceeds 2 MB');
178
+ files.push({ absolute, relative: path.relative(directory, absolute), size: stat.size });
179
+ if (files.length > MAX_PLUGIN_FILES)
180
+ throw new Error(`Plugin exceeds ${MAX_PLUGIN_FILES} files`);
181
+ }
182
+ };
183
+ visit(directory, 0);
184
+ const digest = crypto.createHash('sha256');
185
+ for (const file of files) {
186
+ digest.update(file.relative);
187
+ digest.update('\0');
188
+ digest.update(fs.readFileSync(file.absolute));
189
+ digest.update('\0');
190
+ }
191
+ return digest.digest('hex');
101
192
  }
102
-
103
193
  function validateCapabilities(values, label) {
104
- if (values == null) return [];
105
- if (!Array.isArray(values)) throw new Error(`${label} capabilities must be an array`);
106
- const unique = [];
107
- for (const value of values) {
108
- if (!CAPABILITIES.has(value)) throw new Error(`${label} requests unknown capability ${JSON.stringify(value)}`);
109
- if (!unique.includes(value)) unique.push(value);
110
- }
111
- if (unique.includes('workspace:write') && !unique.includes('workspace:read')) unique.unshift('workspace:read');
112
- return unique;
194
+ if (values == null)
195
+ return [];
196
+ if (!Array.isArray(values))
197
+ throw new Error(`${label} capabilities must be an array`);
198
+ const unique = [];
199
+ for (const value of values) {
200
+ if (typeof value !== 'string' || !CAPABILITIES.has(value)) {
201
+ throw new Error(`${label} requests unknown capability ${JSON.stringify(value)}`);
202
+ }
203
+ if (!unique.includes(value))
204
+ unique.push(value);
205
+ }
206
+ if (unique.includes('workspace:write') && !unique.includes('workspace:read'))
207
+ unique.unshift('workspace:read');
208
+ return unique;
113
209
  }
114
-
115
210
  function readPlugin(directory) {
116
- const directoryStat = fs.lstatSync(directory);
117
- if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) {
118
- throw new Error('Plugin directory must not be a symlink');
119
- }
120
-
121
- const manifestFile = path.join(directory, 'plugin.json');
122
- regularFile(manifestFile, MAX_MANIFEST_BYTES);
123
- const raw = fs.readFileSync(manifestFile, 'utf8');
124
- const manifest = JSON.parse(raw);
125
- const folderName = path.basename(directory);
126
-
127
- if (manifest.schemaVersion !== 1) throw new Error('schemaVersion must be 1');
128
- if (!NAME.test(manifest.name || '') || manifest.name !== folderName) {
129
- throw new Error('Plugin name must match its lowercase folder name');
130
- }
131
- if (!VERSION.test(manifest.version || '')) throw new Error('Plugin version must use SemVer');
132
- if (typeof manifest.description !== 'string' || !manifest.description.trim()) {
133
- throw new Error('Plugin description is required');
134
- }
135
- const manifestTools = manifest.tools ?? [];
136
- if (!Array.isArray(manifestTools)) throw new Error('Plugin tools must be an array');
137
- if (manifestTools.length > MAX_TOOLS_PER_PLUGIN) {
138
- throw new Error(`Plugin exceeds ${MAX_TOOLS_PER_PLUGIN} tools`);
139
- }
140
-
141
- const pluginCapabilities = validateCapabilities(manifest.capabilities, manifest.name);
142
- const names = new Set();
143
- const tools = manifestTools.map((tool) => {
144
- if (!TOOL_NAME.test(tool?.name || '')) throw new Error(`Invalid tool name ${JSON.stringify(tool?.name)}`);
145
- if (names.has(tool.name)) throw new Error(`Duplicate tool name ${tool.name}`);
146
- names.add(tool.name);
147
- if (typeof tool.description !== 'string' || !tool.description.trim()) {
148
- throw new Error(`Tool ${tool.name} needs a description`);
149
- }
150
- if (!tool.parameters || tool.parameters.type !== 'object') {
151
- throw new Error(`Tool ${tool.name} parameters must be an object JSON schema`);
152
- }
153
- const entry = resolveInside(directory, tool.entry);
154
- regularFile(entry, MAX_ENTRY_BYTES);
155
- const capabilities = validateCapabilities(tool.capabilities ?? pluginCapabilities, `${manifest.name}/${tool.name}`);
211
+ const directoryStat = fs.lstatSync(directory);
212
+ if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) {
213
+ throw new Error('Plugin directory must not be a symlink');
214
+ }
215
+ const manifestFile = path.join(directory, 'plugin.json');
216
+ regularFile(manifestFile, MAX_MANIFEST_BYTES);
217
+ const raw = fs.readFileSync(manifestFile, 'utf8');
218
+ const parsedManifest = JSON.parse(raw);
219
+ if (!parsedManifest || typeof parsedManifest !== 'object' || Array.isArray(parsedManifest)) {
220
+ throw new Error('Plugin manifest must be a JSON object');
221
+ }
222
+ const manifest = parsedManifest;
223
+ const folderName = path.basename(directory);
224
+ if (manifest.schemaVersion !== 1)
225
+ throw new Error('schemaVersion must be 1');
226
+ if (typeof manifest.name !== 'string' || !NAME.test(manifest.name) || manifest.name !== folderName) {
227
+ throw new Error('Plugin name must match its lowercase folder name');
228
+ }
229
+ if (typeof manifest.version !== 'string' || !VERSION.test(manifest.version)) {
230
+ throw new Error('Plugin version must use SemVer');
231
+ }
232
+ if (typeof manifest.description !== 'string' || !manifest.description.trim() || manifest.description.length > 2000) {
233
+ throw new Error('Plugin description is required (max 2000 chars)');
234
+ }
235
+ const manifestTools = manifest.tools ?? [];
236
+ if (!Array.isArray(manifestTools))
237
+ throw new Error('Plugin tools must be an array');
238
+ if (manifestTools.length > MAX_TOOLS_PER_PLUGIN) {
239
+ throw new Error(`Plugin exceeds ${MAX_TOOLS_PER_PLUGIN} tools`);
240
+ }
241
+ const pluginCapabilities = validateCapabilities(manifest.capabilities, manifest.name);
242
+ const names = new Set();
243
+ const tools = manifestTools.map((tool) => {
244
+ if (!tool || typeof tool !== 'object' || Array.isArray(tool)) {
245
+ throw new Error('Plugin tool entry must be an object');
246
+ }
247
+ if (typeof tool.name !== 'string' || !TOOL_NAME.test(tool.name)) {
248
+ throw new Error(`Invalid tool name ${JSON.stringify(tool.name)}`);
249
+ }
250
+ if (names.has(tool.name))
251
+ throw new Error(`Duplicate tool name ${tool.name}`);
252
+ names.add(tool.name);
253
+ if (typeof tool.description !== 'string' || !tool.description.trim()) {
254
+ throw new Error(`Tool ${tool.name} needs a description`);
255
+ }
256
+ if (!tool.parameters || typeof tool.parameters !== 'object' || Array.isArray(tool.parameters) || tool.parameters.type !== 'object') {
257
+ throw new Error(`Tool ${tool.name} parameters must be an object JSON schema`);
258
+ }
259
+ const entry = resolveInside(directory, tool.entry);
260
+ regularFile(entry, MAX_ENTRY_BYTES);
261
+ const exportName = tool.export === undefined ? 'execute' : tool.export;
262
+ if (typeof exportName !== 'string' || !EXPORT_IDENT.test(exportName) || FORBIDDEN_KEYS.has(exportName)) {
263
+ throw new Error(`Tool ${tool.name} has invalid export name ${JSON.stringify(exportName)}`);
264
+ }
265
+ const capabilities = validateCapabilities(tool.capabilities ?? pluginCapabilities, `${manifest.name}/${tool.name}`);
266
+ return {
267
+ localName: tool.name,
268
+ name: `plugin__${manifest.name.replace(/-/g, '_')}__${tool.name}`,
269
+ description: tool.description.trim().slice(0, 1000),
270
+ parameters: tool.parameters,
271
+ entry,
272
+ exportName,
273
+ capabilities,
274
+ timeoutMs: Number.isInteger(tool.timeoutMs)
275
+ ? Math.max(1000, Math.min(tool.timeoutMs, 120_000))
276
+ : DEFAULT_TIMEOUT_MS
277
+ };
278
+ });
279
+ const skills = parsePluginSkills(directory, manifest.name, manifest.skills);
280
+ if (tools.length === 0 && skills.length === 0) {
281
+ throw new Error('Plugin must contribute at least one tool or skill');
282
+ }
156
283
  return {
157
- localName: tool.name,
158
- name: `plugin__${manifest.name.replace(/-/g, '_')}__${tool.name}`,
159
- description: tool.description.trim().slice(0, 1000),
160
- parameters: tool.parameters,
161
- entry,
162
- exportName: typeof tool.export === 'string' && tool.export ? tool.export : 'execute',
163
- capabilities,
164
- timeoutMs: Number.isInteger(tool.timeoutMs)
165
- ? Math.max(1000, Math.min(tool.timeoutMs, 120_000))
166
- : DEFAULT_TIMEOUT_MS
284
+ directory,
285
+ manifestFile,
286
+ // Pin every byte the plugin subprocess may read, not only the manifest.
287
+ // Otherwise an entry/helper could be replaced after review without
288
+ // changing plugin.json and would inherit stale trust.
289
+ digest: digestPluginDirectory(directory),
290
+ manifest: { ...manifest, capabilities: pluginCapabilities },
291
+ tools,
292
+ skills
167
293
  };
168
- });
169
- const skills = parsePluginSkills(directory, manifest.name, manifest.skills);
170
- if (tools.length === 0 && skills.length === 0) {
171
- throw new Error('Plugin must contribute at least one tool or skill');
172
- }
173
-
174
- return {
175
- directory,
176
- manifestFile,
177
- // Pin every byte the plugin subprocess may read, not only the manifest.
178
- // Otherwise an entry/helper could be replaced after review without
179
- // changing plugin.json and would inherit stale trust.
180
- digest: digestPluginDirectory(directory),
181
- manifest: { ...manifest, capabilities: pluginCapabilities },
182
- tools,
183
- skills
184
- };
185
294
  }
186
-
187
295
  function pluginDirectories() {
188
- ensureRoot();
189
- return fs.readdirSync(PLUGIN_ROOT, { withFileTypes: true })
190
- .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
191
- .map((entry) => path.join(PLUGIN_ROOT, entry.name))
192
- .sort();
296
+ try {
297
+ ensureRoot();
298
+ const root = pluginRoot();
299
+ return fs.readdirSync(root, { withFileTypes: true })
300
+ .filter((entry) => !entry.isSymbolicLink() && entry.isDirectory() && !entry.name.startsWith('.'))
301
+ .map((entry) => path.join(root, entry.name))
302
+ .sort();
303
+ }
304
+ catch {
305
+ return [];
306
+ }
193
307
  }
194
-
195
308
  export function listPlugins() {
196
- const state = readState();
197
- const rows = [];
198
- for (const directory of pluginDirectories()) {
199
- try {
200
- const plugin = readPlugin(directory);
201
- const trust = safeObject(state.plugins[plugin.manifest.name]);
202
- const modified = Boolean(trust.enabled && trust.digest !== plugin.digest);
203
- rows.push({
204
- name: plugin.manifest.name,
205
- version: plugin.manifest.version,
206
- description: plugin.manifest.description,
207
- enabled: Boolean(trust.enabled && !modified),
208
- modified,
209
- digest: plugin.digest,
210
- capabilities: plugin.manifest.capabilities,
211
- tools: plugin.tools.map((tool) => tool.name),
212
- skills: plugin.skills.map((skill) => `${skill.domain}/${skill.id}`),
213
- path: plugin.directory
214
- });
215
- } catch (error) {
216
- rows.push({ name: path.basename(directory), enabled: false, invalid: true, error: error.message, path: directory });
217
- }
218
- }
219
- return rows;
309
+ const state = readState();
310
+ const rows = [];
311
+ for (const directory of pluginDirectories()) {
312
+ try {
313
+ const plugin = readPlugin(directory);
314
+ const trust = Object.hasOwn(state.plugins, plugin.manifest.name) ? safeObject(state.plugins[plugin.manifest.name]) : {};
315
+ const modified = Boolean(trust.enabled && trust.digest !== plugin.digest);
316
+ rows.push({
317
+ name: plugin.manifest.name,
318
+ version: plugin.manifest.version,
319
+ description: plugin.manifest.description,
320
+ enabled: Boolean(trust.enabled && !modified),
321
+ modified,
322
+ digest: plugin.digest,
323
+ capabilities: plugin.manifest.capabilities,
324
+ tools: plugin.tools.map((tool) => tool.name),
325
+ skills: plugin.skills.map((skill) => `${skill.domain}/${skill.id}`),
326
+ path: plugin.directory
327
+ });
328
+ }
329
+ catch (error) {
330
+ rows.push({
331
+ name: path.basename(directory),
332
+ enabled: false,
333
+ invalid: true,
334
+ error: error instanceof Error ? error.message : String(error),
335
+ path: directory
336
+ });
337
+ }
338
+ }
339
+ return rows;
220
340
  }
221
-
222
341
  export function enablePlugin(name) {
223
- if (!NAME.test(name || '')) return { ok: false, error: 'Invalid plugin name' };
224
- try {
225
- const plugin = readPlugin(resolveInside(PLUGIN_ROOT, name));
226
- const state = readState();
227
- state.plugins[name] = { enabled: true, digest: plugin.digest, enabledAt: Date.now() };
228
- writeState(state);
229
- return {
230
- ok: true,
231
- name,
232
- digest: plugin.digest,
233
- capabilities: plugin.manifest.capabilities,
234
- tools: plugin.tools.map((tool) => tool.name),
235
- skills: plugin.skills.map((skill) => `${skill.domain}/${skill.id}`)
236
- };
237
- } catch (error) {
238
- return { ok: false, error: error.message };
239
- }
342
+ if (typeof name !== 'string' || !NAME.test(name))
343
+ return { ok: false, error: 'Invalid plugin name' };
344
+ try {
345
+ const plugin = readPlugin(resolveInside(pluginRoot(), name));
346
+ const state = readState();
347
+ state.plugins[name] = { enabled: true, digest: plugin.digest, enabledAt: Date.now() };
348
+ writeState(state);
349
+ return {
350
+ ok: true,
351
+ name,
352
+ digest: plugin.digest,
353
+ capabilities: plugin.manifest.capabilities,
354
+ tools: plugin.tools.map((tool) => tool.name),
355
+ skills: plugin.skills.map((skill) => `${skill.domain}/${skill.id}`)
356
+ };
357
+ }
358
+ catch (error) {
359
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
360
+ }
240
361
  }
241
-
242
362
  export function disablePlugin(name) {
243
- const state = readState();
244
- const current = safeObject(state.plugins[name]);
245
- state.plugins[name] = { ...current, enabled: false, disabledAt: Date.now() };
246
- writeState(state);
247
- return { ok: true, name };
363
+ if (typeof name !== 'string' || !NAME.test(name) || FORBIDDEN_KEYS.has(name)) {
364
+ return { ok: false, error: 'Invalid plugin name' };
365
+ }
366
+ const state = readState();
367
+ const current = Object.hasOwn(state.plugins, name) ? safeObject(state.plugins[name]) : {};
368
+ state.plugins[name] = { ...current, enabled: false, disabledAt: Date.now() };
369
+ writeState(state);
370
+ return { ok: true, name };
248
371
  }
249
-
250
- export function createPlugin({ name, description, toolName, toolDescription, parameters, code, capabilities = [] }) {
251
- if (!NAME.test(name || '')) return { ok: false, error: 'Plugin name must use lowercase letters, digits, and hyphens' };
252
- if (!TOOL_NAME.test(toolName || '')) return { ok: false, error: 'Tool name must start with a lowercase letter and use letters, digits, _ or -' };
253
- if (typeof description !== 'string' || !description.trim()) return { ok: false, error: 'Plugin description is required' };
254
- if (typeof toolDescription !== 'string' || !toolDescription.trim()) return { ok: false, error: 'Tool description is required' };
255
- if (!parameters || parameters.type !== 'object') return { ok: false, error: 'Tool parameters must be an object JSON schema' };
256
- if (typeof code !== 'string' || !code.trim()) return { ok: false, error: 'Plugin code is required' };
257
-
258
- let safeCapabilities;
259
- try {
260
- safeCapabilities = validateCapabilities(capabilities, name);
261
- } catch (error) {
262
- return { ok: false, error: error.message };
263
- }
264
-
265
- ensureRoot();
266
- const directory = path.join(PLUGIN_ROOT, name);
267
- if (fs.existsSync(directory)) return { ok: false, error: `Plugin ${name} already exists` };
268
-
269
- const entryName = `${toolName}.js`;
270
- const manifest = {
271
- schemaVersion: 1,
272
- name,
273
- version: '0.1.0',
274
- description: description.trim(),
275
- capabilities: safeCapabilities,
276
- tools: [{
277
- name: toolName,
278
- description: toolDescription.trim(),
279
- parameters,
280
- entry: entryName,
281
- export: 'execute'
282
- }]
283
- };
284
- const trimmedCode = code.trim();
285
- const source = trimmedCode.startsWith('export ')
286
- ? trimmedCode
287
- : trimmedCode.startsWith('async ') || trimmedCode.startsWith('(async ')
288
- ? `export const execute = ${trimmedCode};\n`
289
- : `export async function execute(args, context) {\n${trimmedCode}\n}\n`;
290
-
291
- try {
292
- fs.mkdirSync(directory, { recursive: false, mode: 0o700 });
293
- fs.writeFileSync(path.join(directory, 'plugin.json'), `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600 });
294
- fs.writeFileSync(path.join(directory, entryName), source, { mode: 0o600 });
295
- return {
296
- ok: true,
297
- name,
298
- path: directory,
299
- enabled: false,
300
- message: 'Plugin created disabled. Review its manifest and source, then enable it explicitly.'
372
+ export function createPlugin(input) {
373
+ const safeInput = input && typeof input === 'object' ? input : {};
374
+ const { name, description, toolName, toolDescription, parameters, code, capabilities = [] } = safeInput;
375
+ if (typeof name !== 'string' || !NAME.test(name) || FORBIDDEN_KEYS.has(name)) {
376
+ return { ok: false, error: 'Plugin name must use lowercase letters, digits, and hyphens' };
377
+ }
378
+ if (typeof toolName !== 'string' || !TOOL_NAME.test(toolName)) {
379
+ return { ok: false, error: 'Tool name must start with a lowercase letter and use letters, digits, _ or -' };
380
+ }
381
+ if (typeof description !== 'string' || !description.trim() || description.length > 2000) {
382
+ return { ok: false, error: 'Plugin description is required (max 2000 chars)' };
383
+ }
384
+ if (typeof toolDescription !== 'string' || !toolDescription.trim() || toolDescription.length > 1000) {
385
+ return { ok: false, error: 'Tool description is required (max 1000 chars)' };
386
+ }
387
+ if (!parameters || typeof parameters !== 'object' || Array.isArray(parameters) || parameters.type !== 'object') {
388
+ return { ok: false, error: 'Tool parameters must be an object JSON schema' };
389
+ }
390
+ if (typeof code !== 'string' || !code.trim() || Buffer.byteLength(code, 'utf8') > MAX_ENTRY_BYTES) {
391
+ return { ok: false, error: 'Plugin code is required and must be at most 512 KB' };
392
+ }
393
+ let safeCapabilities;
394
+ try {
395
+ safeCapabilities = validateCapabilities(capabilities, name);
396
+ }
397
+ catch (error) {
398
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
399
+ }
400
+ ensureRoot();
401
+ const directory = path.join(pluginRoot(), name);
402
+ if (fs.existsSync(directory))
403
+ return { ok: false, error: `Plugin ${name} already exists` };
404
+ const entryName = `${toolName}.js`;
405
+ const manifest = {
406
+ schemaVersion: 1,
407
+ name,
408
+ version: '0.1.0',
409
+ description: description.trim(),
410
+ capabilities: safeCapabilities,
411
+ tools: [{
412
+ name: toolName,
413
+ description: toolDescription.trim(),
414
+ parameters,
415
+ entry: entryName,
416
+ export: 'execute'
417
+ }]
301
418
  };
302
- } catch (error) {
303
- return { ok: false, error: error.message };
304
- }
419
+ const trimmedCode = code.trim();
420
+ const source = trimmedCode.startsWith('export ')
421
+ ? trimmedCode
422
+ : trimmedCode.startsWith('async ') || trimmedCode.startsWith('(async ')
423
+ ? `export const execute = ${trimmedCode};\n`
424
+ : `export async function execute(args, context) {\n${trimmedCode}\n}\n`;
425
+ let created = false;
426
+ try {
427
+ fs.mkdirSync(directory, { recursive: false, mode: 0o700 });
428
+ created = true;
429
+ fs.writeFileSync(path.join(directory, 'plugin.json'), `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
430
+ fs.writeFileSync(path.join(directory, entryName), source, { mode: 0o600, flag: 'wx' });
431
+ readPlugin(directory);
432
+ return {
433
+ ok: true,
434
+ name,
435
+ path: directory,
436
+ enabled: false,
437
+ message: 'Plugin created disabled. Review its manifest and source, then enable it explicitly.'
438
+ };
439
+ }
440
+ catch (error) {
441
+ if (created) {
442
+ try {
443
+ fs.rmSync(directory, { recursive: true, force: true });
444
+ }
445
+ catch { /* ignore */ }
446
+ }
447
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
448
+ }
305
449
  }
306
-
307
-
308
- export function createSkillPlugin({
309
- name, description, skillId, skillName, skillDescription, skillContent, licenseText
310
- } = {}) {
311
- if (!NAME.test(name || '')) return { ok: false, error: 'Invalid plugin name' };
312
- if (!NAME.test(skillId || '')) return { ok: false, error: 'Invalid skill id' };
313
- if (typeof description !== 'string' || !description.trim() || description.length > 1000) {
314
- return { ok: false, error: 'Plugin description must be 1..1000 characters' };
315
- }
316
- if (typeof skillName !== 'string' || !skillName.trim() || skillName.length > 120) {
317
- return { ok: false, error: 'Skill name must be 1..120 characters' };
318
- }
319
- if (typeof skillDescription !== 'string' || !skillDescription.trim()
320
- || skillDescription.length > 400) {
321
- return { ok: false, error: 'Skill description must be 1..400 characters' };
322
- }
323
- if (typeof skillContent !== 'string' || !skillContent.trim()
324
- || Buffer.byteLength(skillContent, 'utf8') > 32 * 1024) {
325
- return { ok: false, error: 'Skill content must be nonempty and at most 32 KB' };
326
- }
327
- if (typeof licenseText !== 'string' || licenseText.length > 32 * 1024) {
328
- return { ok: false, error: 'Full third-party license text is required' };
329
- }
330
-
331
- const isMit = /^MIT License\s*$/mi.test(licenseText)
332
- && /Permission is hereby granted, free of charge/i.test(licenseText)
333
- && /above copyright notice/i.test(licenseText);
334
- const isApache = /Apache License\s*Version 2\.0/i.test(licenseText)
335
- && /TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION/i.test(licenseText);
336
- if (!isMit && !isApache) {
337
- return { ok: false, error: 'Only reviewed MIT or Apache-2.0 license text is accepted' };
338
- }
339
-
340
- const manifest = {
341
- schemaVersion: 1, name, version: '0.1.0', description: description.trim(),
342
- capabilities: [], tools: [],
343
- skills: [{
344
- id: skillId, name: skillName.trim(),
345
- description: skillDescription.trim(), file: 'SKILL.md'
346
- }]
347
- };
348
- ensureRoot();
349
- const directory = path.join(PLUGIN_ROOT, name);
350
- if (fs.existsSync(directory)) return { ok: false, error: 'Plugin already exists' };
351
- let created = false;
352
- try {
353
- fs.mkdirSync(directory, { mode: 0o700 });
354
- created = true;
355
- fs.writeFileSync(path.join(directory, 'SKILL.md'), skillContent, {
356
- mode: 0o600, flag: 'wx'
357
- });
358
- fs.writeFileSync(path.join(directory, 'LICENSE'), licenseText, {
359
- mode: 0o600, flag: 'wx'
360
- });
361
- fs.writeFileSync(path.join(directory, 'plugin.json'),
362
- JSON.stringify(manifest, null, 2) + '\n', {
363
- mode: 0o600, flag: 'wx'
364
- });
365
- const reviewed = readPlugin(directory);
366
- return {
367
- ok: true, name, enabled: false, tools: [],
368
- skills: reviewed.skills.map(entry => entry.domain + '/' + entry.id),
369
- license: isMit ? 'MIT' : 'Apache-2.0',
370
- digest: reviewed.digest, path: directory,
371
- message: 'Skill packaged disabled. Review its instructions and license before explicit enablement.'
450
+ export function createSkillPlugin(input) {
451
+ const safeInput = input && typeof input === 'object' ? input : {};
452
+ const { name, description, skillId, skillName, skillDescription, skillContent, licenseText } = safeInput;
453
+ if (typeof name !== 'string' || !NAME.test(name) || FORBIDDEN_KEYS.has(name)) {
454
+ return { ok: false, error: 'Invalid plugin name' };
455
+ }
456
+ if (typeof skillId !== 'string' || !NAME.test(skillId))
457
+ return { ok: false, error: 'Invalid skill id' };
458
+ if (typeof description !== 'string' || !description.trim() || description.length > 1000) {
459
+ return { ok: false, error: 'Plugin description must be 1..1000 characters' };
460
+ }
461
+ if (typeof skillName !== 'string' || !skillName.trim() || skillName.length > 120) {
462
+ return { ok: false, error: 'Skill name must be 1..120 characters' };
463
+ }
464
+ if (typeof skillDescription !== 'string' || !skillDescription.trim()
465
+ || skillDescription.length > 400) {
466
+ return { ok: false, error: 'Skill description must be 1..400 characters' };
467
+ }
468
+ if (typeof skillContent !== 'string' || !skillContent.trim() || skillContent.includes('\0')
469
+ || Buffer.byteLength(skillContent, 'utf8') > 32 * 1024) {
470
+ return { ok: false, error: 'Skill content must be nonempty and at most 32 KB' };
471
+ }
472
+ if (typeof licenseText !== 'string' || licenseText.includes('\0') || licenseText.length > 32 * 1024) {
473
+ return { ok: false, error: 'Full third-party license text is required' };
474
+ }
475
+ const isMit = /^MIT License\s*$/mi.test(licenseText)
476
+ && /Permission is hereby granted, free of charge/i.test(licenseText)
477
+ && /above copyright notice/i.test(licenseText);
478
+ const isApache = /Apache License\s*Version 2\.0/i.test(licenseText)
479
+ && /TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION/i.test(licenseText);
480
+ if (!isMit && !isApache) {
481
+ return { ok: false, error: 'Only reviewed MIT or Apache-2.0 license text is accepted' };
482
+ }
483
+ const manifest = {
484
+ schemaVersion: 1, name, version: '0.1.0', description: description.trim(),
485
+ capabilities: [], tools: [],
486
+ skills: [{
487
+ id: skillId, name: skillName.trim(),
488
+ description: skillDescription.trim(), file: 'SKILL.md'
489
+ }]
372
490
  };
373
- } catch (error) {
374
- if (created) {
375
- try { fs.rmSync(directory, { recursive: true, force: true }); } catch {}
491
+ ensureRoot();
492
+ const directory = path.join(pluginRoot(), name);
493
+ if (fs.existsSync(directory))
494
+ return { ok: false, error: 'Plugin already exists' };
495
+ let created = false;
496
+ try {
497
+ fs.mkdirSync(directory, { mode: 0o700 });
498
+ created = true;
499
+ fs.writeFileSync(path.join(directory, 'SKILL.md'), skillContent, {
500
+ mode: 0o600, flag: 'wx'
501
+ });
502
+ fs.writeFileSync(path.join(directory, 'LICENSE'), licenseText, {
503
+ mode: 0o600, flag: 'wx'
504
+ });
505
+ fs.writeFileSync(path.join(directory, 'plugin.json'), JSON.stringify(manifest, null, 2) + '\n', {
506
+ mode: 0o600, flag: 'wx'
507
+ });
508
+ const reviewed = readPlugin(directory);
509
+ return {
510
+ ok: true, name, enabled: false, tools: [],
511
+ skills: reviewed.skills.map(entry => entry.domain + '/' + entry.id),
512
+ license: isMit ? 'MIT' : 'Apache-2.0',
513
+ digest: reviewed.digest, path: directory,
514
+ message: 'Skill packaged disabled. Review its instructions and license before explicit enablement.'
515
+ };
516
+ }
517
+ catch (error) {
518
+ if (created) {
519
+ try {
520
+ fs.rmSync(directory, { recursive: true, force: true });
521
+ }
522
+ catch { /* ignore */ }
523
+ }
524
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
376
525
  }
377
- return { ok: false, error: error instanceof Error ? error.message : String(error) };
378
- }
379
526
  }
380
-
381
527
  function enabledTools() {
382
- const state = readState();
383
- const tools = [];
384
- for (const directory of pluginDirectories()) {
385
- try {
386
- const plugin = readPlugin(directory);
387
- const trust = safeObject(state.plugins[plugin.manifest.name]);
388
- if (!trust.enabled || trust.digest !== plugin.digest) continue;
389
- for (const tool of plugin.tools) tools.push({ ...tool, plugin: plugin.manifest.name, pluginDirectory: directory });
390
- } catch (error) {
391
- // Invalid plugins are visible through listPlugins(), never through the model.
392
- }
393
- }
394
- return tools;
528
+ const state = readState();
529
+ const tools = [];
530
+ for (const directory of pluginDirectories()) {
531
+ try {
532
+ const plugin = readPlugin(directory);
533
+ const trust = Object.hasOwn(state.plugins, plugin.manifest.name) ? safeObject(state.plugins[plugin.manifest.name]) : {};
534
+ if (!trust.enabled || trust.digest !== plugin.digest)
535
+ continue;
536
+ for (const tool of plugin.tools)
537
+ tools.push({ ...tool, plugin: plugin.manifest.name, pluginDirectory: directory });
538
+ }
539
+ catch {
540
+ // Invalid plugins are visible through listPlugins(), never through the model.
541
+ }
542
+ }
543
+ return tools;
395
544
  }
396
-
397
545
  export function getPluginToolDefinitions() {
398
- return enabledTools().map((tool) => ({
399
- name: tool.name,
400
- description: tool.description,
401
- parameters: tool.parameters,
402
- xCausyneDeferred: true
403
- }));
546
+ return enabledTools().map((tool) => ({
547
+ name: tool.name,
548
+ description: tool.description,
549
+ parameters: tool.parameters,
550
+ xCausyneDeferred: true
551
+ }));
404
552
  }
405
-
406
553
  /**
407
554
  * Reviewed, enabled plugins may contribute prompt-only skills. Discovery has
408
555
  * already parsed these as inert UTF-8 data; no plugin module is imported.
409
556
  */
410
557
  export function getPluginSkills() {
411
- const state = readState();
412
- const skills = [];
413
- for (const directory of pluginDirectories()) {
414
- try {
415
- const plugin = readPlugin(directory);
416
- const trust = safeObject(state.plugins[plugin.manifest.name]);
417
- if (!trust.enabled || trust.digest !== plugin.digest) continue;
418
- skills.push(...plugin.skills);
419
- } catch (error) {
420
- // Invalid or modified plugins contribute nothing to the prompt.
421
- }
422
- }
423
- return skills;
558
+ const state = readState();
559
+ const skills = [];
560
+ for (const directory of pluginDirectories()) {
561
+ try {
562
+ const plugin = readPlugin(directory);
563
+ const trust = Object.hasOwn(state.plugins, plugin.manifest.name) ? safeObject(state.plugins[plugin.manifest.name]) : {};
564
+ if (!trust.enabled || trust.digest !== plugin.digest)
565
+ continue;
566
+ skills.push(...plugin.skills);
567
+ }
568
+ catch {
569
+ // Invalid or modified plugins contribute nothing to the prompt.
570
+ }
571
+ }
572
+ return skills;
424
573
  }
425
-
426
- function permissionArgs(tool, workspaceRoot) {
427
- // Node resolves `.js` module type by walking to package.json. Grant that one
428
- // metadata file explicitly; granting the repository root would let an
429
- // extension read Causyne's entire source tree for no functional reason.
430
- const readable = [path.dirname(RUNNER_FILE), PACKAGE_FILE, tool.pluginDirectory];
431
- const writable = [];
432
- if (tool.capabilities.includes('workspace:read') || tool.capabilities.includes('workspace:write')) {
433
- readable.push(workspaceRoot);
434
- }
435
- if (tool.capabilities.includes('workspace:write')) writable.push(workspaceRoot);
436
-
437
- // Repeat the flag. Comma-joining paths is parsed as one literal path by
438
- // Node's permission model on current releases.
439
- const args = ['--permission', ...readable.map((entry) => `--allow-fs-read=${entry}`)];
440
- if (writable.length > 0) {
441
- args.push(...writable.map((entry) => `--allow-fs-write=${entry}`));
442
- }
443
- if (tool.capabilities.includes('network')) args.push('--allow-net');
444
- if (tool.capabilities.includes('subprocess')) args.push('--allow-child-process');
445
- return args;
574
+ function permissionArgs(tool, workspaceRoots) {
575
+ // Node resolves `.js` module type by walking to package.json. Grant that one
576
+ // metadata file explicitly; granting the repository root would let an
577
+ // extension read Causyne's entire source tree for no functional reason.
578
+ const readable = [path.dirname(RUNNER_FILE), PACKAGE_FILE, tool.pluginDirectory];
579
+ const writable = [];
580
+ if (tool.capabilities.includes('workspace:read') || tool.capabilities.includes('workspace:write')) {
581
+ for (const root of workspaceRoots) {
582
+ if (!readable.includes(root))
583
+ readable.push(root);
584
+ }
585
+ }
586
+ if (tool.capabilities.includes('workspace:write')) {
587
+ for (const root of workspaceRoots) {
588
+ if (!writable.includes(root))
589
+ writable.push(root);
590
+ }
591
+ }
592
+ // Repeat the flag. Comma-joining paths is parsed as one literal path by
593
+ // Node's permission model on current releases.
594
+ const args = ['--permission', ...readable.map((entry) => `--allow-fs-read=${entry}`)];
595
+ if (writable.length > 0) {
596
+ args.push(...writable.map((entry) => `--allow-fs-write=${entry}`));
597
+ }
598
+ if (tool.capabilities.includes('network'))
599
+ args.push('--allow-net');
600
+ if (tool.capabilities.includes('subprocess'))
601
+ args.push('--allow-child-process');
602
+ return args;
446
603
  }
447
-
448
604
  async function runPluginTool(tool, args, context) {
449
- const workspaceRoot = path.resolve(context?.workspaceRoot || context?.workspacePaths?.[0] || process.cwd());
450
- // Resolve filesystem aliases before handing paths to Node's permission
451
- // model. On macOS, /var and /tmp are symlinks into /private; authorizing the
452
- // alias while the module loader opens the canonical target causes a false
453
- // denial even though both names identify the same reviewed plugin file.
454
- const runtimeTool = {
455
- ...tool,
456
- entry: fs.realpathSync(tool.entry),
457
- pluginDirectory: fs.realpathSync(tool.pluginDirectory)
458
- };
459
- const childArgs = [
460
- ...permissionArgs(runtimeTool, workspaceRoot),
461
- RUNNER_FILE,
462
- runtimeTool.entry,
463
- runtimeTool.exportName
464
- ];
465
- const payload = JSON.stringify({
466
- args: safeObject(args),
467
- context: {
468
- workspaceRoot,
469
- pluginRoot: runtimeTool.pluginDirectory,
470
- capabilities: runtimeTool.capabilities
471
- }
472
- });
473
-
474
- return new Promise((resolve) => {
475
- const child = spawn(process.execPath, childArgs, {
476
- stdio: ['pipe', 'pipe', 'pipe'],
477
- env: {
478
- PATH: process.env.PATH || '',
479
- LANG: process.env.LANG || 'C.UTF-8',
480
- TMPDIR: process.env.TMPDIR || ''
481
- }
482
- });
483
- let stdout = '';
484
- let stderr = '';
485
- let settled = false;
486
- const finish = (value) => {
487
- if (settled) return;
488
- settled = true;
489
- clearTimeout(timer);
490
- resolve(value);
605
+ // Re-verify trust and whole-directory digest immediately before spawning to
606
+ // close TOCTOU tampering between tool resolution and execution.
607
+ try {
608
+ const state = readState();
609
+ const trust = Object.hasOwn(state.plugins, tool.plugin) ? safeObject(state.plugins[tool.plugin]) : {};
610
+ const fresh = readPlugin(tool.pluginDirectory);
611
+ if (!trust.enabled || trust.digest !== fresh.digest) {
612
+ return { success: false, error: 'Plugin trust revoked or modified before execution' };
613
+ }
614
+ }
615
+ catch (verifyErr) {
616
+ return {
617
+ success: false,
618
+ error: `Plugin integrity check failed: ${verifyErr instanceof Error ? verifyErr.message : String(verifyErr)}`
619
+ };
620
+ }
621
+ const rawWorkspace = context?.workspaceRoot || context?.workspacePaths?.[0] || process.cwd();
622
+ if (typeof rawWorkspace !== 'string' || !rawWorkspace.trim() || rawWorkspace.includes('\0')) {
623
+ return { success: false, error: 'Invalid workspace root for plugin execution' };
624
+ }
625
+ const workspaceRoot = path.resolve(rawWorkspace);
626
+ if (isBlockedWorkspaceRoot(workspaceRoot)) {
627
+ return { success: false, error: 'Refusing plugin execution on a blocked system root' };
628
+ }
629
+ const realWorkspaceRoot = physicalPath(workspaceRoot) || workspaceRoot;
630
+ const workspacePermissionRoots = realWorkspaceRoot === workspaceRoot
631
+ ? [workspaceRoot]
632
+ : [workspaceRoot, realWorkspaceRoot];
633
+ // Resolve filesystem aliases before handing paths to Node's permission
634
+ // model. On macOS, /var and /tmp are symlinks into /private; authorizing the
635
+ // alias while the module loader opens the canonical target causes a false
636
+ // denial even though both names identify the same reviewed plugin file.
637
+ const runtimeTool = {
638
+ ...tool,
639
+ entry: fs.realpathSync(tool.entry),
640
+ pluginDirectory: fs.realpathSync(tool.pluginDirectory)
491
641
  };
492
- const timer = setTimeout(() => {
493
- child.kill('SIGTERM');
494
- finish({ success: false, error: `Plugin timed out after ${runtimeTool.timeoutMs} ms` });
495
- }, runtimeTool.timeoutMs);
496
- if (timer.unref) timer.unref();
497
-
498
- child.stdout.on('data', (chunk) => {
499
- stdout += chunk;
500
- if (Buffer.byteLength(stdout, 'utf8') > MAX_RESULT_BYTES) {
501
- child.kill('SIGTERM');
502
- finish({ success: false, error: 'Plugin result exceeded 1 MB' });
503
- }
504
- });
505
- child.stderr.on('data', (chunk) => {
506
- stderr = (stderr + chunk).slice(-16_000);
642
+ if (runtimeTool.entry === runtimeTool.pluginDirectory || !isWithinPhysicalPath(runtimeTool.entry, runtimeTool.pluginDirectory)) {
643
+ return { success: false, error: 'Refusing plugin entry outside its canonical plugin directory' };
644
+ }
645
+ const childArgs = [
646
+ ...permissionArgs(runtimeTool, workspacePermissionRoots),
647
+ RUNNER_FILE,
648
+ runtimeTool.entry,
649
+ runtimeTool.exportName
650
+ ];
651
+ const payload = JSON.stringify({
652
+ args: safeObject(args),
653
+ context: {
654
+ workspaceRoot,
655
+ pluginRoot: runtimeTool.pluginDirectory,
656
+ capabilities: runtimeTool.capabilities
657
+ }
507
658
  });
508
- child.on('error', (error) => finish({ success: false, error: error.message }));
509
- child.on('close', () => {
510
- const line = stdout.split(/\r?\n/).find((value) => value.startsWith('CAUSYNE_PLUGIN_RESULT:'));
511
- if (!line) {
512
- finish({ success: false, error: stderr.trim() || 'Plugin returned no structured result' });
513
- return;
514
- }
515
- try {
516
- finish(JSON.parse(line.slice('CAUSYNE_PLUGIN_RESULT:'.length)));
517
- } catch (error) {
518
- finish({ success: false, error: `Plugin returned invalid JSON: ${error.message}` });
519
- }
659
+ const runToken = crypto.randomBytes(16).toString('hex');
660
+ const resultMarker = `CAUSYNE_PLUGIN_RESULT:${runToken}:`;
661
+ return new Promise((resolve) => {
662
+ const childEnv = {
663
+ PATH: process.env.PATH || process.env.Path || '',
664
+ LANG: process.env.LANG || 'C.UTF-8',
665
+ TMPDIR: process.env.TMPDIR || '',
666
+ CAUSYNE_PLUGIN_TOKEN: runToken
667
+ };
668
+ if (process.platform === 'win32') {
669
+ if (process.env.SystemRoot)
670
+ childEnv.SystemRoot = process.env.SystemRoot;
671
+ if (process.env.TEMP)
672
+ childEnv.TEMP = process.env.TEMP;
673
+ if (process.env.TMP)
674
+ childEnv.TMP = process.env.TMP;
675
+ if (process.env.PATHEXT)
676
+ childEnv.PATHEXT = process.env.PATHEXT;
677
+ }
678
+ const child = spawn(process.execPath, childArgs, {
679
+ stdio: ['pipe', 'pipe', 'pipe'],
680
+ windowsHide: true,
681
+ env: childEnv
682
+ });
683
+ let stdout = '';
684
+ let stderr = '';
685
+ let settled = false;
686
+ const finish = (value) => {
687
+ if (settled)
688
+ return;
689
+ settled = true;
690
+ clearTimeout(timer);
691
+ resolve(value);
692
+ };
693
+ const terminateChild = () => {
694
+ try {
695
+ child.kill('SIGTERM');
696
+ }
697
+ catch { /* ignore */ }
698
+ const killTimer = setTimeout(() => {
699
+ try {
700
+ child.kill('SIGKILL');
701
+ }
702
+ catch { /* ignore */ }
703
+ }, 1500);
704
+ killTimer.unref?.();
705
+ };
706
+ const timer = setTimeout(() => {
707
+ terminateChild();
708
+ finish({ success: false, error: `Plugin timed out after ${runtimeTool.timeoutMs} ms` });
709
+ }, runtimeTool.timeoutMs);
710
+ if (timer.unref)
711
+ timer.unref();
712
+ child.stdout.on('data', (chunk) => {
713
+ stdout += String(chunk);
714
+ if (Buffer.byteLength(stdout, 'utf8') > MAX_RESULT_BYTES) {
715
+ terminateChild();
716
+ finish({ success: false, error: 'Plugin result exceeded 1 MB' });
717
+ }
718
+ });
719
+ child.stderr.on('data', (chunk) => {
720
+ stderr = (stderr + String(chunk)).slice(-16_000);
721
+ });
722
+ child.on('error', (error) => finish({
723
+ success: false,
724
+ error: safeDisplay(redactProviderSecrets(error.message))
725
+ }));
726
+ child.on('close', () => {
727
+ const lines = stdout.split(/\r?\n/);
728
+ let line;
729
+ for (let i = lines.length - 1; i >= 0; i--) {
730
+ if (lines[i]?.startsWith(resultMarker)) {
731
+ line = lines[i];
732
+ break;
733
+ }
734
+ }
735
+ if (!line) {
736
+ const cleanErr = safeDisplay(redactProviderSecrets(stderr.trim()));
737
+ finish({ success: false, error: cleanErr || 'Plugin returned no structured result' });
738
+ return;
739
+ }
740
+ try {
741
+ finish(JSON.parse(line.slice(resultMarker.length)));
742
+ }
743
+ catch (error) {
744
+ finish({ success: false, error: `Plugin returned invalid JSON: ${error instanceof Error ? error.message : String(error)}` });
745
+ }
746
+ });
747
+ child.stdin.on('error', () => { });
748
+ child.stdin.end(payload);
520
749
  });
521
- child.stdin.end(payload);
522
- });
523
750
  }
524
-
525
751
  export function resolvePluginTool(name) {
526
- const tool = enabledTools().find((candidate) => candidate.name === name);
527
- if (!tool) return null;
528
- return {
529
- schema: { name: tool.name, description: tool.description, parameters: tool.parameters },
530
- execute: (args, context = {}) => runPluginTool(tool, args, context)
531
- };
752
+ if (typeof name !== 'string' || !name || name.length > 160 || /[\r\n\0]/.test(name))
753
+ return null;
754
+ const tool = enabledTools().find((candidate) => candidate.name === name);
755
+ if (!tool)
756
+ return null;
757
+ return {
758
+ schema: { name: tool.name, description: tool.description, parameters: tool.parameters },
759
+ execute: (args, context = {}) => runPluginTool(tool, args, context)
760
+ };
532
761
  }
533
-
534
762
  export { PLUGIN_ROOT, STATE_FILE, CAPABILITIES };