@causyne/agent 1.20.121 → 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 (640) hide show
  1. package/README.md +3 -3
  2. package/bin/causyne.js +38 -15
  3. package/docs/SECURITY_REVIEW.md +42 -6
  4. package/package.json +5 -5
  5. package/src/acp/agentCatalog.js +141 -62
  6. package/src/acp/agentCatalog.ts +142 -65
  7. package/src/acp/client.js +489 -109
  8. package/src/acp/client.ts +465 -108
  9. package/src/acp/peerProfiles.js +55 -22
  10. package/src/acp/peerProfiles.ts +51 -22
  11. package/src/acp/protocol.js +181 -8
  12. package/src/acp/protocol.ts +189 -8
  13. package/src/acp/server.js +250 -53
  14. package/src/acp/server.ts +234 -53
  15. package/src/agent/errorClassifier.js +48 -8
  16. package/src/agent/errorClassifier.ts +50 -7
  17. package/src/agent/providerFailure.js +1 -1
  18. package/src/agent/providerFailure.ts +7 -1
  19. package/src/agent/toolArgValidator.js +38 -4
  20. package/src/agent/toolArgValidator.ts +39 -4
  21. package/src/agent/toolTurnIntegrity.js +28 -7
  22. package/src/agent/toolTurnIntegrity.ts +25 -6
  23. package/src/agent/workspaceBoundary.js +30 -4
  24. package/src/agent/workspaceBoundary.ts +32 -4
  25. package/src/agentLoop.js +609 -222
  26. package/src/agentLoop.ts +632 -220
  27. package/src/approvalGrants.js +19 -7
  28. package/src/approvalGrants.ts +20 -7
  29. package/src/approvalPolicy.js +76 -16
  30. package/src/approvalPolicy.ts +74 -16
  31. package/src/auditLog.js +641 -48
  32. package/src/auditLog.ts +661 -0
  33. package/src/autoUpdate.js +37 -7
  34. package/src/autoUpdate.ts +32 -7
  35. package/src/backgroundTasks.js +328 -0
  36. package/src/backgroundTasks.ts +339 -0
  37. package/src/benchmarks/codingEval.js +558 -0
  38. package/src/benchmarks/codingEval.ts +628 -0
  39. package/src/benchmarks/planCache.js +115 -134
  40. package/src/benchmarks/planCache.ts +163 -0
  41. package/src/browser/browserRuntime.js +52 -0
  42. package/src/browser/browserRuntime.ts +55 -0
  43. package/src/browser/causyneBrowser.js +887 -12
  44. package/src/browser/causyneBrowser.ts +1045 -34
  45. package/src/browser/searchProviders.js +95 -7
  46. package/src/browser/searchProviders.ts +90 -7
  47. package/src/browser/urlPolicy.js +8 -1
  48. package/src/browser/urlPolicy.ts +7 -1
  49. package/src/browser/workspacePathSafety.js +6 -4
  50. package/src/browser/workspacePathSafety.ts +7 -4
  51. package/src/capabilities.js +18 -17
  52. package/src/capabilities.ts +38 -0
  53. package/src/checkpoints.js +1241 -1127
  54. package/src/checkpoints.ts +1377 -0
  55. package/src/cliMode.js +707 -755
  56. package/src/cliMode.ts +780 -0
  57. package/src/codebase/repoMap.js +656 -0
  58. package/src/codebase/repoMap.ts +664 -0
  59. package/src/commands.js +3651 -2514
  60. package/src/commands.ts +3985 -0
  61. package/src/compiledSkills.js +8052 -8054
  62. package/src/compiledSkills.ts +8078 -0
  63. package/src/config.js +389 -250
  64. package/src/config.ts +451 -0
  65. package/src/configVault.js +113 -19
  66. package/src/configVault.ts +103 -19
  67. package/src/contextManager.js +473 -557
  68. package/src/contextManager.ts +599 -0
  69. package/src/continuum/adapters/antigravity.js +8 -3
  70. package/src/continuum/adapters/antigravity.ts +8 -3
  71. package/src/continuum/compactor.js +2 -1
  72. package/src/continuum/compactor.ts +2 -1
  73. package/src/continuum/sanitizer.js +33 -4
  74. package/src/continuum/sanitizer.ts +32 -4
  75. package/src/continuum/ui/continuumPicker.js +0 -2
  76. package/src/continuum/ui/continuumPicker.ts +0 -2
  77. package/src/continuum/ui/continuumPickerView.js +3 -4
  78. package/src/continuum/ui/continuumPickerView.ts +7 -22
  79. package/src/core/contextCompactor.js +88 -7
  80. package/src/core/contextCompactor.ts +87 -8
  81. package/src/cortex/vectorDb.js +26 -15
  82. package/src/cortex/vectorDb.ts +26 -16
  83. package/src/creative/liveBridge.js +10 -7
  84. package/src/creative/liveBridge.ts +11 -7
  85. package/src/creative/studioScripts.js +17 -6
  86. package/src/creative/studioScripts.ts +15 -6
  87. package/src/decideTools.js +7 -2
  88. package/src/decideTools.ts +7 -2
  89. package/src/decisionPolicy.js +26 -6
  90. package/src/decisionPolicy.ts +24 -6
  91. package/src/designPalettes.js +72 -84
  92. package/src/designPalettes.ts +111 -0
  93. package/src/devMode.js +2 -2
  94. package/src/devMode.ts +6 -0
  95. package/src/diffReview.js +370 -0
  96. package/src/diffReview.ts +407 -0
  97. package/src/documentEngine/antiSlopAuditor.js +10 -5
  98. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  99. package/src/documentEngine/documentForge.js +47 -15
  100. package/src/documentEngine/documentForge.ts +43 -14
  101. package/src/dynamicCatalogue.js +311 -11
  102. package/src/dynamicCatalogue.ts +331 -11
  103. package/src/embodimentSession.js +143 -154
  104. package/src/embodimentSession.ts +173 -0
  105. package/src/engines/design.js +2 -1
  106. package/src/engines/design.ts +2 -1
  107. package/src/engines/film.js +4 -4
  108. package/src/engines/film.ts +2 -2
  109. package/src/engines/installer.js +60 -29
  110. package/src/engines/installer.ts +73 -22
  111. package/src/engines/light.js +2 -1
  112. package/src/engines/light.ts +2 -1
  113. package/src/engines/registry.js +1 -1
  114. package/src/engines/registry.ts +1 -1
  115. package/src/engines/reverseHarness.js +4 -3
  116. package/src/engines/reverseHarness.ts +4 -3
  117. package/src/enterprisePolicy.js +660 -0
  118. package/src/enterprisePolicy.ts +728 -0
  119. package/src/entrypoint.js +514 -268
  120. package/src/entrypoint.ts +607 -0
  121. package/src/gitSnapshot.js +417 -312
  122. package/src/gitSnapshot.ts +500 -0
  123. package/src/headlessCli.js +326 -14
  124. package/src/headlessCli.ts +323 -13
  125. package/src/historyPruner.js +3 -2
  126. package/src/historyPruner.ts +3 -2
  127. package/src/hooks.js +250 -26
  128. package/src/hooks.ts +239 -26
  129. package/src/ignoreRules.js +297 -0
  130. package/src/ignoreRules.ts +308 -0
  131. package/src/implementationPlan.js +28 -17
  132. package/src/implementationPlan.ts +29 -17
  133. package/src/infra/atomicWriter.js +96 -20
  134. package/src/infra/atomicWriter.ts +112 -20
  135. package/src/launchIntent.js +14 -3
  136. package/src/launchIntent.ts +14 -3
  137. package/src/licensing/entitlements.js +553 -237
  138. package/src/licensing/entitlements.ts +590 -0
  139. package/src/licensing/policy.js +17 -1
  140. package/src/licensing/policy.ts +31 -0
  141. package/src/lsp/lspCatalog.js +398 -0
  142. package/src/lsp/lspCatalog.ts +452 -0
  143. package/src/lsp/lspClient.js +699 -0
  144. package/src/lsp/lspClient.ts +799 -0
  145. package/src/lsp/lspProtocol.js +121 -0
  146. package/src/lsp/lspProtocol.ts +140 -0
  147. package/src/mcp/mcpClient.js +69 -8
  148. package/src/mcp/mcpClient.ts +66 -9
  149. package/src/mcp/mcpRegistry.js +180 -7
  150. package/src/mcp/mcpRegistry.ts +171 -7
  151. package/src/mcp/mcpSecurity.js +6 -7
  152. package/src/mcp/mcpSecurity.ts +7 -6
  153. package/src/memory/episodicStore.js +2 -5
  154. package/src/memory/episodicStore.ts +2 -5
  155. package/src/memory/scopedFacts.js +1 -1
  156. package/src/memory/scopedFacts.ts +1 -1
  157. package/src/memory/symbolFolder.js +1 -1
  158. package/src/memory/symbolFolder.ts +1 -1
  159. package/src/memory.js +80 -32
  160. package/src/memory.ts +111 -0
  161. package/src/memoryManager.js +151 -143
  162. package/src/memoryManager.ts +182 -0
  163. package/src/modelCatalogue.js +172 -195
  164. package/src/modelCatalogue.ts +201 -0
  165. package/src/modelIds.js +8 -27
  166. package/src/modelIds.ts +33 -0
  167. package/src/modelRouter.js +1 -1
  168. package/src/modelRouter.ts +1 -1
  169. package/src/modelVariants.js +600 -0
  170. package/src/modelVariants.ts +663 -0
  171. package/src/observer/evidence.js +15 -5
  172. package/src/observer/evidence.ts +15 -5
  173. package/src/osKeychain.js +79 -17
  174. package/src/osKeychain.ts +64 -17
  175. package/src/outputStore.js +210 -156
  176. package/src/outputStore.ts +321 -0
  177. package/src/perception.js +3 -2
  178. package/src/perception.ts +3 -2
  179. package/src/planCache.js +5 -8
  180. package/src/planCache.ts +5 -8
  181. package/src/plugins/pluginManager.js +689 -461
  182. package/src/plugins/pluginManager.ts +807 -0
  183. package/src/plugins/pluginRunner.js +82 -37
  184. package/src/plugins/pluginRunner.ts +98 -0
  185. package/src/plugins/pluginSkills.js +47 -9
  186. package/src/plugins/pluginSkills.ts +46 -8
  187. package/src/pluginsFactory/discovery.js +0 -1
  188. package/src/pluginsFactory/discovery.ts +0 -1
  189. package/src/pluginsFactory/pluginsFactory.js +19 -11
  190. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  191. package/src/pluginsFactory/templates.js +17 -4
  192. package/src/pluginsFactory/templates.ts +17 -4
  193. package/src/prWorkflow.js +337 -0
  194. package/src/prWorkflow.ts +376 -0
  195. package/src/procSignal.js +1 -2
  196. package/src/procSignal.ts +1 -3
  197. package/src/projectInstructions.js +319 -0
  198. package/src/projectInstructions.ts +361 -0
  199. package/src/promptMentions.js +2 -2
  200. package/src/promptMentions.ts +2 -2
  201. package/src/providers/acp.js +235 -50
  202. package/src/providers/acp.ts +241 -51
  203. package/src/providers/anthropic.js +431 -400
  204. package/src/providers/anthropic.ts +493 -0
  205. package/src/providers/antigravity.js +575 -358
  206. package/src/providers/antigravity.ts +565 -359
  207. package/src/providers/base.js +229 -320
  208. package/src/providers/base.ts +348 -0
  209. package/src/providers/byokHttp.js +183 -30
  210. package/src/providers/byokHttp.ts +232 -32
  211. package/src/providers/byokStream.js +287 -70
  212. package/src/providers/byokStream.ts +282 -71
  213. package/src/providers/dashscope-byok.js +123 -89
  214. package/src/providers/dashscope-byok.ts +142 -0
  215. package/src/providers/deepseek.js +82 -72
  216. package/src/providers/deepseek.ts +108 -0
  217. package/src/providers/factory.js +76 -28
  218. package/src/providers/factory.ts +82 -0
  219. package/src/providers/gemini.js +279 -278
  220. package/src/providers/gemini.ts +313 -0
  221. package/src/providers/loopGuard.js +9 -5
  222. package/src/providers/loopGuard.ts +10 -5
  223. package/src/providers/moonshot.js +103 -72
  224. package/src/providers/moonshot.ts +122 -0
  225. package/src/providers/muse.js +82 -152
  226. package/src/providers/muse.ts +122 -0
  227. package/src/providers/ollama.js +360 -106
  228. package/src/providers/ollama.ts +408 -0
  229. package/src/providers/openai-compatible.js +168 -95
  230. package/src/providers/openai-compatible.ts +200 -0
  231. package/src/providers/openai.js +45 -15
  232. package/src/providers/openai.ts +52 -0
  233. package/src/providers/openrouter.js +342 -113
  234. package/src/providers/openrouter.ts +333 -116
  235. package/src/providers/pi.js +6 -0
  236. package/src/providers/pi.ts +6 -0
  237. package/src/providers/qwen-byok.js +122 -87
  238. package/src/providers/qwen-byok.ts +141 -0
  239. package/src/providers/toolContracts.js +40 -14
  240. package/src/providers/toolContracts.ts +35 -14
  241. package/src/providers/wireNormalizer.js +144 -11
  242. package/src/providers/wireNormalizer.ts +132 -12
  243. package/src/providers/xai.js +80 -72
  244. package/src/providers/xai.ts +103 -0
  245. package/src/provisioning/capabilityConsent.js +29 -11
  246. package/src/provisioning/capabilityConsent.ts +42 -0
  247. package/src/provisioning/capabilityProvisioner.js +309 -197
  248. package/src/provisioning/capabilityProvisioner.ts +413 -0
  249. package/src/provisioning/capabilityTools.js +31 -17
  250. package/src/provisioning/capabilityTools.ts +43 -0
  251. package/src/provisioning/npmInstall.js +33 -5
  252. package/src/provisioning/npmInstall.ts +33 -5
  253. package/src/reliability/assetEvidence.js +4 -2
  254. package/src/reliability/assetEvidence.ts +4 -2
  255. package/src/reporting.js +328 -326
  256. package/src/reporting.ts +482 -0
  257. package/src/sandbox.js +526 -554
  258. package/src/sandbox.ts +590 -0
  259. package/src/sandboxPolicy.js +95 -16
  260. package/src/sandboxPolicy.ts +97 -16
  261. package/src/sessionJournal.js +32 -6
  262. package/src/sessionJournal.ts +27 -6
  263. package/src/sessionStore.js +1 -2
  264. package/src/sessionStore.ts +2 -0
  265. package/src/skills/skillResourceSafety.js +19 -8
  266. package/src/skills/skillResourceSafety.ts +16 -7
  267. package/src/skillsManager.js +3 -3
  268. package/src/skillsManager.ts +3 -3
  269. package/src/slopDetector.js +202 -265
  270. package/src/slopDetector.ts +279 -0
  271. package/src/smartToolsUse.js +38 -8
  272. package/src/smartToolsUse.ts +39 -11
  273. package/src/stallGuard.js +53 -23
  274. package/src/stallGuard.ts +53 -23
  275. package/src/subagentJournal.js +6 -4
  276. package/src/subagentJournal.ts +6 -4
  277. package/src/taskBuffer.js +91 -40
  278. package/src/taskBuffer.ts +94 -0
  279. package/src/textDiff.js +6 -1
  280. package/src/textDiff.ts +6 -1
  281. package/src/timeMachine.js +7 -1
  282. package/src/timeMachine.ts +7 -1
  283. package/src/tokenTracker.js +120 -38
  284. package/src/tokenTracker.ts +110 -38
  285. package/src/toolPacks.js +8 -1
  286. package/src/toolPacks.ts +8 -1
  287. package/src/tools/applyPatch.js +610 -0
  288. package/src/tools/applyPatch.ts +661 -0
  289. package/src/tools/archive.js +372 -48
  290. package/src/tools/archive.ts +372 -48
  291. package/src/tools/astryxOracle.js +77 -72
  292. package/src/tools/astryxOracle.ts +95 -0
  293. package/src/tools/axSnapshot.js +127 -147
  294. package/src/tools/axSnapshot.ts +174 -0
  295. package/src/tools/backgroundTask.js +86 -0
  296. package/src/tools/backgroundTask.ts +121 -0
  297. package/src/tools/blenderAutomator.js +434 -390
  298. package/src/tools/blenderAutomator.ts +623 -0
  299. package/src/tools/checkSystemSpecs.js +54 -61
  300. package/src/tools/checkSystemSpecs.ts +73 -0
  301. package/src/tools/clipboard.js +42 -31
  302. package/src/tools/clipboard.ts +61 -0
  303. package/src/tools/codeSearchAst.js +359 -91
  304. package/src/tools/codeSearchAst.ts +399 -0
  305. package/src/tools/codeSearcher.js +179 -37
  306. package/src/tools/codeSearcher.ts +188 -33
  307. package/src/tools/codeTools.js +208 -245
  308. package/src/tools/codeTools.ts +271 -0
  309. package/src/tools/codebaseSearch.js +5 -0
  310. package/src/tools/codebaseSearch.ts +5 -0
  311. package/src/tools/computerUse.js +7 -3
  312. package/src/tools/computerUse.ts +7 -3
  313. package/src/tools/creativeApps.js +13 -8
  314. package/src/tools/creativeApps.ts +22 -9
  315. package/src/tools/deferredMcpSearch.js +26 -14
  316. package/src/tools/deferredMcpSearch.ts +26 -14
  317. package/src/tools/desktopAct.js +185 -197
  318. package/src/tools/desktopAct.ts +257 -0
  319. package/src/tools/desktopOpen.js +69 -10
  320. package/src/tools/desktopOpen.ts +70 -11
  321. package/src/tools/documentForge.js +167 -82
  322. package/src/tools/documentForge.ts +169 -84
  323. package/src/tools/dynamicLoader.js +4 -40
  324. package/src/tools/dynamicLoader.ts +13 -0
  325. package/src/tools/executeProceduralMedia.js +117 -86
  326. package/src/tools/executeProceduralMedia.ts +135 -0
  327. package/src/tools/fileTracker.js +74 -0
  328. package/src/tools/fileTracker.ts +94 -0
  329. package/src/tools/fsDelete.js +57 -47
  330. package/src/tools/fsDelete.ts +80 -0
  331. package/src/tools/fsEdit.js +250 -61
  332. package/src/tools/fsEdit.ts +265 -63
  333. package/src/tools/fsFind.js +8 -5
  334. package/src/tools/fsFind.ts +7 -4
  335. package/src/tools/fsMove.js +79 -52
  336. package/src/tools/fsMove.ts +108 -0
  337. package/src/tools/fsRead.js +163 -18
  338. package/src/tools/fsRead.ts +169 -18
  339. package/src/tools/fsSearch.js +5 -0
  340. package/src/tools/fsSearch.ts +5 -0
  341. package/src/tools/fsWrite.js +31 -11
  342. package/src/tools/fsWrite.ts +31 -13
  343. package/src/tools/gameAiBehaviorTree.js +74 -91
  344. package/src/tools/gameAiBehaviorTree.ts +219 -0
  345. package/src/tools/gameAnimationRig.js +128 -147
  346. package/src/tools/gameAnimationRig.ts +215 -0
  347. package/src/tools/gameAssetFetcher.js +403 -441
  348. package/src/tools/gameAssetFetcher.ts +477 -0
  349. package/src/tools/gameAssetHarvester.js +171 -200
  350. package/src/tools/gameAssetHarvester.ts +261 -0
  351. package/src/tools/gameAudioSynth.js +223 -259
  352. package/src/tools/gameAudioSynth.ts +255 -0
  353. package/src/tools/gameBuilder.js +100 -91
  354. package/src/tools/gameBuilder.ts +913 -0
  355. package/src/tools/gameCanvasAudit.js +138 -96
  356. package/src/tools/gameCanvasAudit.ts +157 -0
  357. package/src/tools/gameCinematicSequencer.js +93 -111
  358. package/src/tools/gameCinematicSequencer.ts +165 -0
  359. package/src/tools/gameDataForge.js +115 -118
  360. package/src/tools/gameDataForge.ts +151 -0
  361. package/src/tools/gameDialogueTreeGen.js +125 -156
  362. package/src/tools/gameDialogueTreeGen.ts +159 -0
  363. package/src/tools/gameEconomyBalancer.js +150 -153
  364. package/src/tools/gameEconomyBalancer.ts +186 -0
  365. package/src/tools/gameEntitySpawner.js +91 -108
  366. package/src/tools/gameEntitySpawner.ts +209 -0
  367. package/src/tools/gameLoreForge.js +125 -147
  368. package/src/tools/gameLoreForge.ts +162 -0
  369. package/src/tools/gameQuestArcBuilder.js +105 -144
  370. package/src/tools/gameQuestArcBuilder.ts +147 -0
  371. package/src/tools/gameSceneBuilder.js +143 -149
  372. package/src/tools/gameSceneBuilder.ts +196 -0
  373. package/src/tools/gameShaderForge.js +83 -101
  374. package/src/tools/gameShaderForge.ts +181 -0
  375. package/src/tools/gameTilemapGenerator.js +99 -129
  376. package/src/tools/gameTilemapGenerator.ts +158 -0
  377. package/src/tools/gameUiHudBuilder.js +109 -129
  378. package/src/tools/gameUiHudBuilder.ts +300 -0
  379. package/src/tools/gameVfxEmitterGen.js +86 -89
  380. package/src/tools/gameVfxEmitterGen.ts +133 -0
  381. package/src/tools/gameWebRuntimeInspector.js +153 -86
  382. package/src/tools/gameWebRuntimeInspector.ts +167 -0
  383. package/src/tools/generateMediaViaApi.js +126 -22
  384. package/src/tools/generateMediaViaApi.ts +123 -22
  385. package/src/tools/gitExec.js +133 -86
  386. package/src/tools/gitExec.ts +146 -0
  387. package/src/tools/gitWorktree.js +115 -0
  388. package/src/tools/gitWorktree.ts +150 -0
  389. package/src/tools/godotAutomator.js +417 -394
  390. package/src/tools/godotAutomator.ts +530 -0
  391. package/src/tools/lspCodeIntel.js +217 -0
  392. package/src/tools/lspCodeIntel.ts +260 -0
  393. package/src/tools/manageLocalAiDependencies.js +242 -206
  394. package/src/tools/manageLocalAiDependencies.ts +288 -0
  395. package/src/tools/memoryRecall.js +62 -11
  396. package/src/tools/memoryRecall.ts +70 -13
  397. package/src/tools/memoryWrite.js +27 -14
  398. package/src/tools/memoryWrite.ts +30 -14
  399. package/src/tools/multiEdit.js +73 -63
  400. package/src/tools/multiEdit.ts +80 -65
  401. package/src/tools/nativeEngine.js +33 -18
  402. package/src/tools/nativeEngine.ts +31 -18
  403. package/src/tools/openSourceToolProvisioner.js +49 -14
  404. package/src/tools/openSourceToolProvisioner.ts +54 -15
  405. package/src/tools/osSandbox.js +202 -25
  406. package/src/tools/osSandbox.ts +192 -25
  407. package/src/tools/palmierAutomator.js +147 -95
  408. package/src/tools/palmierAutomator.ts +171 -0
  409. package/src/tools/payloadSanitizer.js +40 -8
  410. package/src/tools/payloadSanitizer.ts +39 -8
  411. package/src/tools/pdfReader.js +95 -104
  412. package/src/tools/pdfReader.ts +125 -0
  413. package/src/tools/peerAgent.js +96 -34
  414. package/src/tools/peerAgent.ts +114 -37
  415. package/src/tools/persistentShell.js +267 -144
  416. package/src/tools/persistentShell.ts +314 -0
  417. package/src/tools/pluginManager.js +84 -72
  418. package/src/tools/pluginManager.ts +109 -0
  419. package/src/tools/pluginsFactory.js +38 -6
  420. package/src/tools/pluginsFactory.ts +42 -6
  421. package/src/tools/printer.js +278 -296
  422. package/src/tools/printer.ts +326 -0
  423. package/src/tools/procTerm.js +96 -83
  424. package/src/tools/procTerm.ts +127 -0
  425. package/src/tools/processList.js +45 -48
  426. package/src/tools/processList.ts +73 -0
  427. package/src/tools/readNativeSkill.js +10 -8
  428. package/src/tools/readNativeSkill.ts +10 -8
  429. package/src/tools/registry.js +298 -286
  430. package/src/tools/registry.ts +486 -0
  431. package/src/tools/repoMap.js +46 -0
  432. package/src/tools/repoMap.ts +66 -0
  433. package/src/tools/requestDecision.js +10 -3
  434. package/src/tools/requestDecision.ts +10 -3
  435. package/src/tools/resolveAutomator.js +91 -17
  436. package/src/tools/resolveAutomator.ts +102 -17
  437. package/src/tools/reverseEngineering.js +168 -41
  438. package/src/tools/reverseEngineering.ts +161 -41
  439. package/src/tools/subagentOrchestrator.js +404 -348
  440. package/src/tools/subagentOrchestrator.ts +457 -0
  441. package/src/tools/sysRun.js +148 -51
  442. package/src/tools/sysRun.ts +142 -46
  443. package/src/tools/toolDispatch.js +24 -1
  444. package/src/tools/toolDispatch.ts +21 -1
  445. package/src/tools/toolForge.js +84 -67
  446. package/src/tools/toolForge.ts +102 -0
  447. package/src/tools/toolOutputStore.js +62 -23
  448. package/src/tools/toolOutputStore.ts +56 -23
  449. package/src/tools/toolPathSafety.js +262 -0
  450. package/src/tools/toolPathSafety.ts +308 -0
  451. package/src/tools/toolScanner.js +41 -10
  452. package/src/tools/toolScanner.ts +42 -10
  453. package/src/tools/toolSelfRepair.js +115 -34
  454. package/src/tools/toolSelfRepair.ts +122 -34
  455. package/src/tools/uiForge.js +71 -6
  456. package/src/tools/uiForge.ts +74 -6
  457. package/src/tools/viewImage.js +62 -17
  458. package/src/tools/viewImage.ts +57 -12
  459. package/src/tools/visionInspector.js +15 -3
  460. package/src/tools/visionInspector.ts +15 -3
  461. package/src/tools/walkerSafety.js +2 -0
  462. package/src/tools/walkerSafety.ts +2 -0
  463. package/src/tools/webFetch.js +110 -12
  464. package/src/tools/webFetch.ts +110 -13
  465. package/src/toolsList.js +5 -0
  466. package/src/toolsList.ts +5 -0
  467. package/src/tui/ask.js +159 -168
  468. package/src/tui/ask.ts +259 -0
  469. package/src/tui/banner.js +3 -2
  470. package/src/tui/banner.ts +3 -2
  471. package/src/tui/block.js +0 -1
  472. package/src/tui/block.ts +0 -1
  473. package/src/tui/chatRenderer.js +1193 -1441
  474. package/src/tui/chatRenderer.ts +1336 -0
  475. package/src/tui/clipboardImage.js +36 -12
  476. package/src/tui/clipboardImage.ts +39 -13
  477. package/src/tui/clipboardSync.js +34 -9
  478. package/src/tui/clipboardSync.ts +38 -9
  479. package/src/tui/codeProgress.js +0 -1
  480. package/src/tui/codeProgress.ts +0 -1
  481. package/src/tui/completion.js +395 -371
  482. package/src/tui/completion.ts +574 -0
  483. package/src/tui/composerControls.js +113 -19
  484. package/src/tui/composerControls.ts +124 -19
  485. package/src/tui/consoleGuard.js +39 -11
  486. package/src/tui/consoleGuard.ts +38 -11
  487. package/src/tui/dialogs.js +864 -717
  488. package/src/tui/dialogs.ts +984 -0
  489. package/src/tui/diff.js +205 -195
  490. package/src/tui/diff.ts +336 -0
  491. package/src/tui/history.js +143 -108
  492. package/src/tui/history.ts +167 -0
  493. package/src/tui/home.js +165 -161
  494. package/src/tui/home.ts +251 -0
  495. package/src/tui/invocation.js +58 -65
  496. package/src/tui/invocation.ts +117 -0
  497. package/src/tui/keys.js +437 -420
  498. package/src/tui/keys.ts +597 -0
  499. package/src/tui/lineEditor.js +477 -432
  500. package/src/tui/lineEditor.ts +542 -0
  501. package/src/tui/messageActionPlacement.js +0 -1
  502. package/src/tui/messageActionPlacement.ts +0 -1
  503. package/src/tui/messageInteraction.js +2 -5
  504. package/src/tui/messageInteraction.ts +2 -5
  505. package/src/tui/modelPicker.js +1 -3
  506. package/src/tui/modelPicker.ts +4 -6
  507. package/src/tui/observerPicker.js +0 -2
  508. package/src/tui/observerPicker.ts +0 -2
  509. package/src/tui/overlay.js +3 -2
  510. package/src/tui/overlay.ts +3 -2
  511. package/src/tui/prompt.js +1816 -2151
  512. package/src/tui/prompt.ts +1870 -0
  513. package/src/tui/runningLight.js +0 -1
  514. package/src/tui/runningLight.ts +0 -1
  515. package/src/tui/selectList.js +365 -337
  516. package/src/tui/selectList.ts +441 -0
  517. package/src/tui/sessionPicker.js +3 -3
  518. package/src/tui/sessionPicker.ts +3 -3
  519. package/src/tui/sessionPickerView.js +7 -3
  520. package/src/tui/sessionPickerView.ts +10 -22
  521. package/src/tui/sessionSidebar.js +3 -1
  522. package/src/tui/sessionSidebar.ts +4 -1
  523. package/src/tui/setup.js +17 -5
  524. package/src/tui/setup.ts +19 -5
  525. package/src/tui/skillAuthoring.js +0 -2
  526. package/src/tui/skillAuthoring.ts +0 -3
  527. package/src/tui/stageSurface.js +829 -909
  528. package/src/tui/stageSurface.ts +1003 -0
  529. package/src/tui/statusLine.js +7 -4
  530. package/src/tui/statusLine.ts +7 -3
  531. package/src/tui/terminalInputFramer.js +82 -69
  532. package/src/tui/terminalInputFramer.ts +116 -0
  533. package/src/tui/text.js +25 -10
  534. package/src/tui/text.ts +24 -10
  535. package/src/tui/textLayout.js +0 -1
  536. package/src/tui/textLayout.ts +0 -1
  537. package/src/tui/theme.js +245 -250
  538. package/src/tui/theme.ts +441 -0
  539. package/src/tui/thinkingBox.js +0 -1
  540. package/src/tui/thinkingBox.ts +0 -1
  541. package/src/tui/toolOutputNormalizer.js +2 -3
  542. package/src/tui/toolOutputNormalizer.ts +4 -3
  543. package/src/tui/transcript.js +239 -216
  544. package/src/tui/transcript.ts +324 -0
  545. package/src/tui/turnRail.js +53 -54
  546. package/src/tui/turnRail.ts +51 -49
  547. package/src/tui/usageCard.js +0 -2
  548. package/src/tui/usageCard.ts +0 -2
  549. package/src/tui/viewport.js +4 -4
  550. package/src/tui/viewport.ts +5 -5
  551. package/src/tui/workspaceIdentity.js +2 -1
  552. package/src/tui/workspaceIdentity.ts +2 -1
  553. package/src/tui/workspaceSwitch.js +4 -2
  554. package/src/tui/workspaceSwitch.ts +5 -2
  555. package/src/types/contracts.ts +4 -1
  556. package/src/uncertainty.js +8 -3
  557. package/src/uncertainty.ts +8 -3
  558. package/src/utils/browserOpen.js +107 -0
  559. package/src/utils/browserOpen.ts +129 -0
  560. package/src/utils/cli_ui.js +0 -0
  561. package/src/utils/cli_ui.ts +158 -0
  562. package/src/utils/paths.js +8 -5
  563. package/src/utils/paths.ts +9 -7
  564. package/src/utils/winSpawn.js +248 -0
  565. package/src/utils/winSpawn.ts +275 -0
  566. package/src/verification/boundedExplorer.js +138 -107
  567. package/src/verification/boundedExplorer.ts +154 -0
  568. package/src/verification/byokSmokeProbe.js +193 -0
  569. package/src/verification/byokSmokeProbe.ts +234 -0
  570. package/src/verification/cliProbe.js +144 -110
  571. package/src/verification/cliProbe.ts +170 -0
  572. package/src/verification/featureMap.js +105 -75
  573. package/src/verification/featureMap.ts +124 -0
  574. package/src/verification/interactivePty.js +195 -100
  575. package/src/verification/interactivePty.ts +333 -0
  576. package/src/verification/propertyProbe.js +109 -101
  577. package/src/verification/propertyProbe.ts +159 -0
  578. package/src/verification/ptyProbe.js +168 -73
  579. package/src/verification/ptyProbe.ts +254 -0
  580. package/src/verification/skillCatalog.js +25 -25
  581. package/src/verification/skillCatalog.ts +66 -0
  582. package/src/verification/statechart.js +140 -127
  583. package/src/verification/statechart.ts +196 -0
  584. package/src/verification/uiRuntime.js +80 -49
  585. package/src/verification/uiRuntime.ts +88 -0
  586. package/src/version.js +37 -32
  587. package/src/version.ts +45 -0
  588. package/src/vfeTracker.js +9 -3
  589. package/src/vfeTracker.ts +9 -3
  590. package/src/web/guiLauncher.js +89 -0
  591. package/src/web/guiLauncher.ts +119 -0
  592. package/src/web/skybridgeBrowserBridge.js +256 -0
  593. package/src/web/skybridgeBrowserBridge.ts +285 -0
  594. package/src/web/skybridgeBrowserMcp.js +730 -0
  595. package/src/web/skybridgeBrowserMcp.ts +813 -0
  596. package/src/web/skybridgeClientScript.js +3951 -0
  597. package/src/web/skybridgeClientScript.ts +3952 -0
  598. package/src/web/skybridgeServer.js +2622 -0
  599. package/src/web/skybridgeServer.ts +2787 -0
  600. package/src/web/skybridgeStyles.js +827 -0
  601. package/src/web/skybridgeStyles.ts +828 -0
  602. package/src/web/skybridgeUi.js +472 -0
  603. package/src/web/skybridgeUi.ts +485 -0
  604. package/src/worktreeManager.js +511 -0
  605. package/src/worktreeManager.ts +546 -0
  606. package/src/zeroCostFailover.js +168 -0
  607. package/src/zeroCostFailover.ts +198 -0
  608. package/src/zeroCostRouting.js +391 -0
  609. package/src/zeroCostRouting.ts +437 -0
  610. package/src/agentLoop.d.ts +0 -65
  611. package/src/auditLog.d.ts +0 -3
  612. package/src/checkpoints.d.ts +0 -4
  613. package/src/compiledSkills.d.ts +0 -5
  614. package/src/config.d.ts +0 -2
  615. package/src/contextManager.d.ts +0 -14
  616. package/src/designPalettes.d.ts +0 -2
  617. package/src/devMode.d.ts +0 -1
  618. package/src/embodimentSession.d.ts +0 -2
  619. package/src/licensing/entitlements.d.ts +0 -14
  620. package/src/memory.d.ts +0 -13
  621. package/src/memoryManager.d.ts +0 -1
  622. package/src/modelCatalogue.d.ts +0 -6
  623. package/src/modelIds.d.ts +0 -2
  624. package/src/outputStore.d.ts +0 -4
  625. package/src/plugins/pluginManager.d.ts +0 -7
  626. package/src/providers/antigravity.d.ts +0 -19
  627. package/src/providers/base.d.ts +0 -94
  628. package/src/providers/factory.d.ts +0 -1
  629. package/src/provisioning/capabilityProvisioner.d.ts +0 -12
  630. package/src/sandbox.d.ts +0 -1
  631. package/src/slopDetector.d.ts +0 -3
  632. package/src/taskBuffer.d.ts +0 -1
  633. package/src/tools/desktopAct.d.ts +0 -10
  634. package/src/tools/registry.d.ts +0 -5
  635. package/src/tui/chatRenderer.d.ts +0 -27
  636. package/src/tui/diff.d.ts +0 -3
  637. package/src/utils/cli_ui.d.ts +0 -19
  638. package/src/utils/paths.d.ts +0 -3
  639. package/src/verification/skillCatalog.d.ts +0 -1
  640. package/src/version.d.ts +0 -1
@@ -0,0 +1,2787 @@
1
+ /**
2
+ * Causyne Local Skybridge Server (`causyne web`)
3
+ *
4
+ * Foreground, user-initiated, loopback-only (`127.0.0.1`) HTTP + NDJSON bridge
5
+ * connecting a local browser tab (or verified `https://causyne.com` origin) to
6
+ * the user's selected local workspace folder and full Causyne Agent runtime.
7
+ *
8
+ * Security invariants:
9
+ * 1. Binds strictly to `127.0.0.1` — never `0.0.0.0` or LAN interfaces.
10
+ * 2. Strict `Host` header validation (`127.0.0.1:<port>` / `localhost:<port>`)
11
+ * blocks DNS Rebinding attacks.
12
+ * 3. Strict `Origin` allowlist (`http://127.0.0.1:<port>`, `http://localhost:<port>`,
13
+ * `https://causyne.com`, `https://www.causyne.com`) + Chrome Private Network
14
+ * Access (PNA) preflight headers block CSRF & cross-site hijacking.
15
+ * 4. 256-bit cryptographic session nonce verified with `crypto.timingSafeEqual`
16
+ * on every `/api/*` endpoint via `Authorization: Bearer <token>`.
17
+ * 5. Every file read/list/write is strictly locked inside `workspaceRoot` via
18
+ * `isPhysicalPathAllowed()` + `atomicWriteFileSync()` + audit logging.
19
+ * 6. Zero persistent daemon, zero `postinstall`, zero outbound reverse tunnel.
20
+ */
21
+
22
+ import http from 'node:http';
23
+ import crypto from 'node:crypto';
24
+ import fs from 'node:fs';
25
+ import path from 'node:path';
26
+ import { execFileSync } from 'node:child_process';
27
+ import type { AddressInfo } from 'node:net';
28
+
29
+ import { AgentLoop } from '../agentLoop.js';
30
+ import { createApprovalScope } from '../approvalGrants.js';
31
+ import { isPhysicalPathAllowed, physicalPath } from '../agent/workspaceBoundary.js';
32
+ import { atomicWriteFileSync } from '../infra/atomicWriter.js';
33
+ import {
34
+ applyProviderOverrides,
35
+ loadConfig,
36
+ resolveProviderApiKey,
37
+ saveConfig
38
+ } from '../config.js';
39
+ import { detectZeroCostProviders } from '../zeroCostRouting.js';
40
+ import { DEFAULT_MODEL_BY_PROVIDER, MODEL_CATALOGUE } from '../modelCatalogue.js';
41
+ import {
42
+ getAvailableProvidersOverview,
43
+ resolveAvailableProvidersOverview
44
+ } from '../dynamicCatalogue.js';
45
+ import { buildModelPickerItems } from '../tui/modelPicker.js';
46
+ import { disconnectOpenRouter } from '../auth/openrouterAuth.js';
47
+ import {
48
+ createSession,
49
+ deleteSession,
50
+ getSession,
51
+ listSessions,
52
+ renameSession,
53
+ saveSessionMessages,
54
+ type SessionMessage
55
+ } from '../sessionJournal.js';
56
+ import { collectWorkingTreeDiff, parseUnifiedDiff } from '../diffReview.js';
57
+ import { auditLog } from '../auditLog.js';
58
+ import { getPackageVersion } from '../version.js';
59
+ import { formatRedactedProviderErrorReport, redactProviderSecrets } from '../providers/byokHttp.js';
60
+ import { isIgnoredByCausyneIgnore } from '../ignoreRules.js';
61
+ import { listCommands, parseCommand, runCommand } from '../commands.js';
62
+ import { formatByokProbeReport, runZeroSpendByokProbe } from '../verification/byokSmokeProbe.js';
63
+ import { listGroups } from '../checkpoints.js';
64
+ import { listCompiledSkills } from '../skillsManager.js';
65
+ import { serverStatus, closeAll as closeAllMcpServers } from '../mcp/mcpRegistry.js';
66
+ import { lspSessionManager } from '../lsp/lspClient.js';
67
+ import { listAllPeers } from '../acp/peerProfiles.js';
68
+ import { listWorktrees } from '../worktreeManager.js';
69
+ import { backgroundTaskManager } from '../backgroundTasks.js';
70
+ import {
71
+ causyneBrowser,
72
+ expandSearchMacro,
73
+ type BrowserEnginePreference,
74
+ type LiveBrowserInteraction
75
+ } from '../browser/causyneBrowser.js';
76
+ import {
77
+ discoverLocalCdpTabs,
78
+ importExplicitUserBrowserData,
79
+ syncLocalCdpTabToCausyne
80
+ } from './skybridgeBrowserBridge.js';
81
+ import {
82
+ CAUSYNE_BROWSER_MCP_NAME,
83
+ handleBrowserMcpRpc,
84
+ type JsonRpcMessage
85
+ } from './skybridgeBrowserMcp.js';
86
+ import type { McpServer } from '../acp/protocol.js';
87
+ import {
88
+ DAILY_LIMIT_SUPPORT_MESSAGE,
89
+ EntitlementAccessError,
90
+ EntitlementClient
91
+ } from '../licensing/entitlements.js';
92
+ import {
93
+ LICENSE_ENFORCEMENT_ENABLED,
94
+ isValidLicensePlan
95
+ } from '../licensing/policy.js';
96
+ import { renderSkybridgeHtml, getCausyneFaviconSvg } from './skybridgeUi.js';
97
+
98
+ const MAX_JSON_BODY_BYTES = 1024 * 1024;
99
+ const MAX_FILE_READ_BYTES = 512 * 1024;
100
+ const MAX_FILE_WRITE_BYTES = 2 * 1024 * 1024;
101
+ const MAX_ATTACHMENT_BYTES = 32 * 1024;
102
+ const MAX_ATTACHMENTS = 6;
103
+ const MAX_LIST_ENTRIES = 250;
104
+ const SKIPPED_DIRS = new Set(['.git', 'node_modules', '.next', 'dist', 'build', '.venv']);
105
+ const ALLOWED_REMOTE_ORIGINS = new Set(['https://causyne.com', 'https://www.causyne.com']);
106
+ const SAFE_SESSION_ID_RE = /^s_[a-zA-Z0-9_-]{3,80}$/;
107
+ const SAFE_PROVIDER_RE = /^[a-zA-Z0-9._/-]{1,64}$/;
108
+ const SAFE_MODEL_RE = /^[a-zA-Z0-9._/:()+ -]{1,128}$/;
109
+
110
+ const PROVIDER_KEY_FOR_CATALOG_LABEL: Record<string, string> = {
111
+ 'DeepSeek': 'deepseek',
112
+ 'Qwen': 'qwen',
113
+ 'Anthropic': 'anthropic',
114
+ 'OpenAI': 'openai',
115
+ 'Gemini': 'gemini',
116
+ 'Meta (Muse)': 'muse',
117
+ 'Ollama (Local)': 'ollama',
118
+ 'Alibaba (DashScope)': 'dashscope-byok',
119
+ 'Moonshot (Kimi)': 'moonshot',
120
+ 'xAI (Grok)': 'xai',
121
+ 'Google Antigravity': 'antigravity',
122
+ 'Pi (Local Peer)': 'pi',
123
+ 'ACP (Peer Agents)': 'acp',
124
+ 'OpenCode (ACP)': 'acp/opencode',
125
+ 'Claude Code (ACP)': 'acp/claude',
126
+ 'OpenRouter (Free)': 'openrouter',
127
+ 'Groq (Free Tier)': 'groq',
128
+ 'Cerebras (Free Tier)': 'cerebras',
129
+ 'Mistral (Free Tier)': 'mistral'
130
+ };
131
+
132
+ export interface SkybridgeDecisionAnswer {
133
+ optionId?: string | null | undefined;
134
+ label: string;
135
+ custom?: boolean | undefined;
136
+ }
137
+
138
+ export interface SkybridgeLoopLike {
139
+ run(): Promise<void>;
140
+ abort?(): void;
141
+ resolveApproval?(toolCallId: string, approved: boolean): void;
142
+ resolveDecision?(requestId: string, answer: SkybridgeDecisionAnswer | null): void;
143
+ grantAlways?(toolName: string): void;
144
+ }
145
+
146
+ export type SkybridgeLoopFactory = (
147
+ sink: { readyState: number; send(raw: string): void },
148
+ taskId: string,
149
+ prompt: string,
150
+ options: {
151
+ workspaceRoot: string;
152
+ mode: string;
153
+ sessionId?: string | undefined;
154
+ provider?: string | undefined;
155
+ model?: string | undefined;
156
+ }
157
+ ) => SkybridgeLoopLike;
158
+
159
+ export interface SkybridgeEntitlementClientLike {
160
+ status(): Promise<any>;
161
+ checkout(plan: string): Promise<any>;
162
+ recover(recoveryCode: string): Promise<any>;
163
+ portal(): Promise<any>;
164
+ }
165
+
166
+ export interface StartSkybridgeOptions {
167
+ workspaceRoot?: string | undefined;
168
+ port?: number | undefined;
169
+ token?: string | undefined;
170
+ allowedOrigins?: readonly string[] | undefined;
171
+ loopFactory?: SkybridgeLoopFactory | undefined;
172
+ entitlementClient?: SkybridgeEntitlementClientLike | undefined;
173
+ }
174
+
175
+ export interface SkybridgeHandle {
176
+ url: string;
177
+ origin: string;
178
+ port: number;
179
+ token: string;
180
+ workspaceRoot: string;
181
+ close(): Promise<void>;
182
+ }
183
+
184
+ export function isAllowedSkybridgeHost(hostHeader: string | undefined, port: number): boolean {
185
+ if (!hostHeader || typeof hostHeader !== 'string') return false;
186
+ const normalized = hostHeader.trim().toLowerCase();
187
+ return normalized === `127.0.0.1:${port}`
188
+ || normalized === `localhost:${port}`
189
+ || normalized === `[::1]:${port}`;
190
+ }
191
+
192
+ export function isAllowedSkybridgeOrigin(
193
+ originHeader: string | undefined,
194
+ port: number,
195
+ extraOrigins: readonly string[] = []
196
+ ): boolean {
197
+ if (!originHeader || typeof originHeader !== 'string') return true;
198
+ const trimmed = originHeader.trim();
199
+ if (!trimmed || trimmed === 'null') return false;
200
+ let parsed: URL;
201
+ try {
202
+ parsed = new URL(trimmed);
203
+ } catch {
204
+ return false;
205
+ }
206
+ const canonical = parsed.origin.toLowerCase();
207
+ if (canonical === `http://127.0.0.1:${port}` || canonical === `http://localhost:${port}`) {
208
+ return true;
209
+ }
210
+ if (ALLOWED_REMOTE_ORIGINS.has(canonical)) return true;
211
+ for (const extra of extraOrigins) {
212
+ try {
213
+ const parsedExtra = new URL(extra);
214
+ if (parsedExtra.protocol === 'https:' && parsedExtra.origin.toLowerCase() === canonical) {
215
+ return true;
216
+ }
217
+ } catch {
218
+ // ignore invalid extra origin
219
+ }
220
+ }
221
+ return false;
222
+ }
223
+
224
+ function timingSafeBearerMatch(authHeader: string | undefined, expectedToken: string): boolean {
225
+ if (!authHeader || typeof authHeader !== 'string') return false;
226
+ const prefix = 'Bearer ';
227
+ if (!authHeader.startsWith(prefix)) return false;
228
+ const supplied = authHeader.slice(prefix.length).trim();
229
+ const a = Buffer.from(supplied, 'utf8');
230
+ const b = Buffer.from(expectedToken, 'utf8');
231
+ if (a.length !== b.length || a.length === 0) return false;
232
+ return crypto.timingSafeEqual(a, b);
233
+ }
234
+
235
+ function applySecurityHeaders(
236
+ res: http.ServerResponse,
237
+ originHeader: string | undefined,
238
+ originAllowed: boolean
239
+ ): void {
240
+ res.setHeader('X-Content-Type-Options', 'nosniff');
241
+ res.setHeader('X-Frame-Options', 'DENY');
242
+ res.setHeader('Referrer-Policy', 'no-referrer');
243
+ res.setHeader('Cache-Control', 'no-store');
244
+ if (originHeader && originAllowed) {
245
+ res.setHeader('Access-Control-Allow-Origin', originHeader);
246
+ res.setHeader('Access-Control-Allow-Private-Network', 'true');
247
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS');
248
+ res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type');
249
+ res.setHeader('Vary', 'Origin, Access-Control-Request-Private-Network');
250
+ }
251
+ }
252
+
253
+ function sendJson(res: http.ServerResponse, status: number, payload: unknown): void {
254
+ const body = JSON.stringify(payload);
255
+ res.statusCode = status;
256
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
257
+ res.end(body);
258
+ }
259
+
260
+ async function readJsonBody(
261
+ req: http.IncomingMessage,
262
+ maxBytes = MAX_JSON_BODY_BYTES
263
+ ): Promise<Record<string, any>> {
264
+ const chunks: Buffer[] = [];
265
+ let total = 0;
266
+ for await (const chunk of req) {
267
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
268
+ total += buf.length;
269
+ if (total > maxBytes) {
270
+ throw new Error('Request body exceeded maximum allowed size.');
271
+ }
272
+ chunks.push(buf);
273
+ }
274
+ const text = Buffer.concat(chunks).toString('utf8').trim();
275
+ if (!text) return {};
276
+ const parsed = JSON.parse(text);
277
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
278
+ throw new Error('JSON request body must be an object.');
279
+ }
280
+ return parsed as Record<string, any>;
281
+ }
282
+
283
+ function resolveWorkspaceRelativePath(workspaceRoot: string, rawRel: string): string | null {
284
+ if (typeof rawRel !== 'string' || rawRel.includes('\0')) return null;
285
+ const cleaned = rawRel.trim();
286
+ if (!cleaned) return null;
287
+ if (path.isAbsolute(cleaned)) return null;
288
+ const candidate = path.resolve(workspaceRoot, cleaned);
289
+ if (!isPhysicalPathAllowed(candidate, [workspaceRoot], false)) return null;
290
+ return candidate;
291
+ }
292
+
293
+ function listWorkspaceEntries(
294
+ workspaceRoot: string,
295
+ relDir: string,
296
+ query = ''
297
+ ): Array<{ path: string; name: string; type: 'dir' | 'file'; size: number }> {
298
+ const targetDir = relDir ? resolveWorkspaceRelativePath(workspaceRoot, relDir) : workspaceRoot;
299
+ if (!targetDir) throw new Error('Requested directory is outside the locked workspace.');
300
+ const q = query.trim().toLowerCase();
301
+ const entries: Array<{ path: string; name: string; type: 'dir' | 'file'; size: number }> = [];
302
+
303
+ const scan = (dir: string, depth: number): void => {
304
+ if (entries.length >= MAX_LIST_ENTRIES) return;
305
+ let dirents: fs.Dirent[];
306
+ try {
307
+ dirents = fs.readdirSync(dir, { withFileTypes: true });
308
+ } catch {
309
+ return;
310
+ }
311
+ for (const d of dirents) {
312
+ if (entries.length >= MAX_LIST_ENTRIES) break;
313
+ if (d.isSymbolicLink()) continue;
314
+ if (d.isDirectory() && SKIPPED_DIRS.has(d.name)) continue;
315
+ const abs = path.join(dir, d.name);
316
+ if (!isPhysicalPathAllowed(abs, [workspaceRoot], false)) continue;
317
+ if (isIgnoredByCausyneIgnore(abs, workspaceRoot, d.isDirectory())) continue;
318
+ const rel = path.relative(workspaceRoot, abs).split(path.sep).join('/');
319
+ const isDir = d.isDirectory();
320
+ let size = 0;
321
+ if (!isDir) {
322
+ try { size = fs.statSync(abs).size; } catch { size = 0; }
323
+ }
324
+ if (!q || rel.toLowerCase().includes(q)) {
325
+ entries.push({ path: rel, name: d.name, type: isDir ? 'dir' : 'file', size });
326
+ }
327
+ if (q && isDir && depth < 3) {
328
+ scan(abs, depth + 1);
329
+ }
330
+ }
331
+ };
332
+
333
+ scan(targetDir, 0);
334
+ entries.sort((a, b) => (a.type === b.type ? a.path.localeCompare(b.path) : a.type === 'dir' ? -1 : 1));
335
+ return entries;
336
+ }
337
+
338
+ const MUTATING_FILE_TOOLS = new Set([
339
+ 'fs_write', 'fs_edit', 'multi_edit', 'apply_patch', 'fs_delete', 'fs_move',
340
+ 'write_file', 'edit_file', 'write', 'edit', 'multiedit', 'replace_file_content',
341
+ 'multi_replace_file_content', 'write_to_file', 'create_file', 'document_forge',
342
+ 'ui_forge', 'screenshot', 'generate_media_via_api', 'code_verify_syntax'
343
+ ]);
344
+
345
+ const SHELL_TOOLS = new Set(['sysrun', 'bash', 'shell', 'run_command', 'execute_command']);
346
+
347
+ export interface SessionFileEvidence {
348
+ path: string;
349
+ status: 'added' | 'modified' | 'deleted';
350
+ bytesWritten?: number | undefined;
351
+ additions: number;
352
+ deletions: number;
353
+ hunks: Array<{ header: string; lines: string[] }>;
354
+ }
355
+
356
+ function formatByteSize(bytes: number): string {
357
+ if (!Number.isFinite(bytes) || bytes < 0) return '0 B';
358
+ if (bytes < 1024) return `${Math.round(bytes)} B`;
359
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
360
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
361
+ }
362
+
363
+ function normalizeWorkspaceRelCandidate(
364
+ workspaceRoot: string,
365
+ raw: unknown,
366
+ baseDir?: string
367
+ ): string | null {
368
+ if (typeof raw !== 'string') return null;
369
+ let trimmed = raw.trim().replace(/^["'`]+|["'`]+$/g, '');
370
+ if (!trimmed || trimmed.includes('\0') || trimmed.length > 500) return null;
371
+ if (/^https?:\/\//i.test(trimmed)) return null;
372
+ if (trimmed.toLowerCase().startsWith('file://')) {
373
+ trimmed = trimmed.slice('file://'.length);
374
+ const hashIdx = trimmed.indexOf('#');
375
+ if (hashIdx >= 0) trimmed = trimmed.slice(0, hashIdx);
376
+ const queryIdx = trimmed.indexOf('?');
377
+ if (queryIdx >= 0) trimmed = trimmed.slice(0, queryIdx);
378
+ try {
379
+ trimmed = decodeURIComponent(trimmed);
380
+ } catch {
381
+ // Keep raw decoded string if percent encoding is malformed.
382
+ }
383
+ if (/^\/[A-Za-z]:[\\/]/.test(trimmed)) {
384
+ trimmed = trimmed.slice(1);
385
+ }
386
+ } else {
387
+ const lineAnchor = trimmed.match(/^(.+?\.[a-zA-Z0-9]{1,8})#L\d+(?:-L?\d+)?$/);
388
+ if (lineAnchor?.[1]) trimmed = lineAnchor[1];
389
+ }
390
+ const escNl = trimmed.indexOf('\\n');
391
+ if (escNl >= 0) trimmed = trimmed.slice(0, escNl);
392
+ trimmed = trimmed.replace(/[),.;:]+$/g, '').trim();
393
+ if (!trimmed || trimmed === '.' || trimmed === '/') return null;
394
+ let rel = trimmed;
395
+ if (path.isAbsolute(trimmed)) {
396
+ const absNorm = path.resolve(trimmed);
397
+ if (!isPhysicalPathAllowed(absNorm, [workspaceRoot], false)) return null;
398
+ rel = path.relative(workspaceRoot, absNorm);
399
+ } else if (baseDir && path.isAbsolute(baseDir)) {
400
+ const absNorm = path.resolve(baseDir, trimmed);
401
+ if (!isPhysicalPathAllowed(absNorm, [workspaceRoot], false)) return null;
402
+ rel = path.relative(workspaceRoot, absNorm);
403
+ }
404
+ const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
405
+ if (!abs) return null;
406
+ const normalized = path.relative(workspaceRoot, abs).split(path.sep).join('/');
407
+ return normalized && !normalized.startsWith('..') ? normalized : null;
408
+ }
409
+
410
+ function tokenizeSimpleShell(command: string): string[] {
411
+ const tokens: string[] = [];
412
+ let current = '';
413
+ let quote: '"' | "'" | null = null;
414
+ for (let i = 0; i < command.length; i += 1) {
415
+ const ch = command[i]!;
416
+ if (quote) {
417
+ if (ch === quote) {
418
+ quote = null;
419
+ } else {
420
+ current += ch;
421
+ }
422
+ continue;
423
+ }
424
+ if (ch === '"' || ch === "'") {
425
+ quote = ch;
426
+ continue;
427
+ }
428
+ if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
429
+ if (current) {
430
+ tokens.push(current);
431
+ current = '';
432
+ }
433
+ continue;
434
+ }
435
+ if (ch === ';' || ch === '|') {
436
+ if (current) {
437
+ tokens.push(current);
438
+ current = '';
439
+ }
440
+ tokens.push(ch);
441
+ continue;
442
+ }
443
+ if (ch === '&' && command[i + 1] === '&') {
444
+ if (current) {
445
+ tokens.push(current);
446
+ current = '';
447
+ }
448
+ tokens.push('&&');
449
+ i += 1;
450
+ continue;
451
+ }
452
+ current += ch;
453
+ }
454
+ if (current) tokens.push(current);
455
+ return tokens;
456
+ }
457
+
458
+ function extractShellWriteTargets(command: string, workspaceRoot: string, cwdArg?: unknown): string[] {
459
+ const found: string[] = [];
460
+ let curDir = workspaceRoot;
461
+ if (typeof cwdArg === 'string' && cwdArg.trim()) {
462
+ const resolvedCwd = path.isAbsolute(cwdArg.trim())
463
+ ? path.resolve(cwdArg.trim())
464
+ : path.resolve(workspaceRoot, cwdArg.trim());
465
+ if (isPhysicalPathAllowed(resolvedCwd, [workspaceRoot], false)) {
466
+ curDir = resolvedCwd;
467
+ }
468
+ }
469
+ const tokens = tokenizeSimpleShell(command);
470
+ for (let i = 0; i < tokens.length; i += 1) {
471
+ const tok = tokens[i]!;
472
+ if (tok === 'cd' && tokens[i + 1]) {
473
+ const nextDir = tokens[i + 1]!;
474
+ const resolved = path.isAbsolute(nextDir)
475
+ ? path.resolve(nextDir)
476
+ : path.resolve(curDir, nextDir);
477
+ if (isPhysicalPathAllowed(resolved, [workspaceRoot], false)) {
478
+ curDir = resolved;
479
+ }
480
+ i += 1;
481
+ continue;
482
+ }
483
+ if ((tok === '-o' || tok === '--output' || tok === '>' || tok === '>>' || tok === 'tee') && tokens[i + 1]) {
484
+ const target = tokens[i + 1]!;
485
+ if (target !== '/dev/null' && !target.startsWith('-')) {
486
+ const norm = normalizeWorkspaceRelCandidate(workspaceRoot, target, curDir);
487
+ if (norm) found.push(norm);
488
+ }
489
+ i += 1;
490
+ continue;
491
+ }
492
+ if (tok === 'screencapture') {
493
+ let j = i + 1;
494
+ while (j < tokens.length && tokens[j] !== ';' && tokens[j] !== '&&' && tokens[j] !== '|') {
495
+ const arg = tokens[j]!;
496
+ if (!arg.startsWith('-')) {
497
+ const norm = normalizeWorkspaceRelCandidate(workspaceRoot, arg, curDir);
498
+ if (norm) found.push(norm);
499
+ }
500
+ j += 1;
501
+ }
502
+ i = j - 1;
503
+ }
504
+ }
505
+ return found;
506
+ }
507
+
508
+ function extractPatchPathsFromText(patchText: string): string[] {
509
+ const found: string[] = [];
510
+ for (const line of patchText.split(/\r?\n/)) {
511
+ const m = line.match(/^\*\*\*\s+(?:Add|Update|Delete)\s+File:\s+(.+)$/);
512
+ if (m?.[1]) found.push(m[1].trim());
513
+ const diffM = line.match(/^(?:\+\+\+|---)\s+[ab]\/(.+)$/);
514
+ if (diffM?.[1]) found.push(diffM[1].trim());
515
+ }
516
+ return found;
517
+ }
518
+
519
+ function buildSynthesizedWriteHunk(content: string): { additions: number; hunks: Array<{ header: string; lines: string[] }> } {
520
+ const lines = content.split(/\r?\n/);
521
+ if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
522
+ const capped = lines.slice(0, 140).map((ln) => `+${ln}`);
523
+ if (lines.length > 140) capped.push(`+... (${lines.length - 140} more lines)`);
524
+ return {
525
+ additions: lines.length,
526
+ hunks: capped.length > 0
527
+ ? [{ header: `@@ -0,0 +1,${lines.length} @@`, lines: capped }]
528
+ : []
529
+ };
530
+ }
531
+
532
+ function buildSynthesizedEditHunk(oldStr: string, newStr: string): {
533
+ additions: number;
534
+ deletions: number;
535
+ hunks: Array<{ header: string; lines: string[] }>;
536
+ } {
537
+ const oldLines = oldStr ? oldStr.split(/\r?\n/) : [];
538
+ const newLines = newStr ? newStr.split(/\r?\n/) : [];
539
+ const diffLines: string[] = [];
540
+ for (const ln of oldLines.slice(0, 80)) diffLines.push(`-${ln}`);
541
+ for (const ln of newLines.slice(0, 80)) diffLines.push(`+${ln}`);
542
+ return {
543
+ additions: newLines.length,
544
+ deletions: oldLines.length,
545
+ hunks: diffLines.length > 0
546
+ ? [{ header: `@@ -1,${oldLines.length} +1,${newLines.length} @@`, lines: diffLines }]
547
+ : []
548
+ };
549
+ }
550
+
551
+ function hasFileExtension(relPath: string): boolean {
552
+ const base = path.posix.basename(relPath);
553
+ const dot = base.lastIndexOf('.');
554
+ return dot > 0 && dot < base.length - 1 && base.length - dot <= 10;
555
+ }
556
+
557
+ export function extractSessionFileEvidence(
558
+ messages: readonly SessionMessage[],
559
+ workspaceRoot: string
560
+ ): Map<string, SessionFileEvidence> {
561
+ const evidenceMap = new Map<string, SessionFileEvidence>();
562
+ const touchedDirs = new Set<string>();
563
+
564
+ const recordFile = (
565
+ raw: unknown,
566
+ opts: {
567
+ status?: 'added' | 'modified' | 'deleted' | undefined;
568
+ bytesWritten?: number | undefined;
569
+ additions?: number | undefined;
570
+ deletions?: number | undefined;
571
+ hunks?: Array<{ header: string; lines: string[] }> | undefined;
572
+ baseDir?: string | undefined;
573
+ } = {}
574
+ ): void => {
575
+ const norm = normalizeWorkspaceRelCandidate(workspaceRoot, raw, opts.baseDir);
576
+ if (!norm) return;
577
+ const dir = path.posix.dirname(norm);
578
+ if (dir && dir !== '.') touchedDirs.add(dir);
579
+ const existing = evidenceMap.get(norm);
580
+ if (!existing) {
581
+ evidenceMap.set(norm, {
582
+ path: norm,
583
+ status: opts.status ?? 'added',
584
+ bytesWritten: opts.bytesWritten,
585
+ additions: opts.additions ?? 0,
586
+ deletions: opts.deletions ?? 0,
587
+ hunks: opts.hunks ?? []
588
+ });
589
+ return;
590
+ }
591
+ if (opts.status === 'deleted') existing.status = 'deleted';
592
+ else if (opts.status === 'modified' && existing.status !== 'added') existing.status = 'modified';
593
+ if (typeof opts.bytesWritten === 'number' && opts.bytesWritten > 0) {
594
+ existing.bytesWritten = opts.bytesWritten;
595
+ }
596
+ if (opts.hunks && opts.hunks.length > 0) {
597
+ existing.hunks = opts.hunks;
598
+ existing.additions = opts.additions ?? existing.additions;
599
+ existing.deletions = opts.deletions ?? existing.deletions;
600
+ }
601
+ };
602
+
603
+ const assistantBacktickCandidates: string[] = [];
604
+
605
+ for (const msg of messages) {
606
+ const rec = msg as Record<string, unknown>;
607
+ const toolCalls = Array.isArray(rec.tool_calls)
608
+ ? (rec.tool_calls as Array<Record<string, unknown>>)
609
+ : [];
610
+ for (const tc of toolCalls) {
611
+ const fn = (tc.function && typeof tc.function === 'object' ? tc.function : tc) as Record<string, unknown>;
612
+ const name = typeof fn.name === 'string' ? fn.name.trim().toLowerCase() : '';
613
+ if (!name) continue;
614
+ let args: Record<string, unknown> | null = null;
615
+ if (typeof fn.arguments === 'string') {
616
+ try {
617
+ const parsed = JSON.parse(fn.arguments);
618
+ if (parsed && typeof parsed === 'object') args = parsed as Record<string, unknown>;
619
+ } catch {
620
+ args = null;
621
+ }
622
+ } else if (fn.arguments && typeof fn.arguments === 'object') {
623
+ args = fn.arguments as Record<string, unknown>;
624
+ }
625
+ if (!args) continue;
626
+
627
+ if (MUTATING_FILE_TOOLS.has(name)) {
628
+ const status: 'added' | 'modified' | 'deleted' = name === 'fs_delete'
629
+ ? 'deleted'
630
+ : name.includes('edit') || name.includes('patch') || name.includes('replace')
631
+ ? 'modified'
632
+ : 'added';
633
+ const synthWrite = typeof args.content === 'string' && args.content.length > 0
634
+ ? buildSynthesizedWriteHunk(args.content)
635
+ : null;
636
+ const synthEdit = (typeof args.old_string === 'string' || typeof args.new_string === 'string')
637
+ && (Boolean(args.old_string) || Boolean(args.new_string))
638
+ ? buildSynthesizedEditHunk(String(args.old_string || ''), String(args.new_string || ''))
639
+ : null;
640
+ const pathKeys = [
641
+ 'path', 'filePath', 'file_path', 'targetFile', 'target_path',
642
+ 'filename', 'file', 'destination', 'outputFile', 'output_path', 'outputPath'
643
+ ];
644
+ for (const key of pathKeys) {
645
+ recordFile(args[key], {
646
+ status,
647
+ additions: synthWrite?.additions ?? synthEdit?.additions ?? 0,
648
+ deletions: synthEdit?.deletions ?? 0,
649
+ hunks: synthWrite?.hunks ?? synthEdit?.hunks ?? []
650
+ });
651
+ }
652
+ if (typeof args.patch === 'string') {
653
+ for (const p of extractPatchPathsFromText(args.patch)) {
654
+ recordFile(p, { status: 'modified' });
655
+ }
656
+ }
657
+ if (Array.isArray(args.edits)) {
658
+ for (const ed of args.edits) {
659
+ if (ed && typeof ed === 'object') {
660
+ recordFile((ed as Record<string, unknown>).path, { status: 'modified' });
661
+ }
662
+ }
663
+ }
664
+ } else if (name === 'browser_act' && Array.isArray(args.actions)) {
665
+ for (const a of args.actions) {
666
+ if (a && typeof a === 'object') {
667
+ const actObj = a as Record<string, unknown>;
668
+ if (actObj.filePath) recordFile(actObj.filePath, { status: 'modified' });
669
+ if (actObj.outputPath) recordFile(actObj.outputPath, { status: 'added' });
670
+ }
671
+ }
672
+ } else if (SHELL_TOOLS.has(name) && typeof args.command === 'string') {
673
+ for (const p of extractShellWriteTargets(args.command, workspaceRoot, args.cwd)) {
674
+ recordFile(p, { status: 'added' });
675
+ }
676
+ }
677
+ }
678
+
679
+ const extActions = Array.isArray(rec.external_actions)
680
+ ? (rec.external_actions as Array<Record<string, unknown>>)
681
+ : [];
682
+ for (const act of extActions) {
683
+ const name = typeof act.name === 'string' ? act.name.trim().toLowerCase() : '';
684
+ if (!name) continue;
685
+ if (MUTATING_FILE_TOOLS.has(name)) {
686
+ recordFile(act.detail, { status: name.includes('edit') ? 'modified' : 'added' });
687
+ const params = act.parameters && typeof act.parameters === 'object'
688
+ ? (act.parameters as Record<string, unknown>)
689
+ : null;
690
+ if (params) {
691
+ for (const key of ['path', 'filePath', 'file_path', 'targetFile', 'filename', 'file', 'destination', 'outputPath']) {
692
+ recordFile(params[key], { status: name.includes('edit') ? 'modified' : 'added' });
693
+ }
694
+ }
695
+ } else if (SHELL_TOOLS.has(name) && typeof act.detail === 'string') {
696
+ for (const p of extractShellWriteTargets(act.detail, workspaceRoot)) {
697
+ recordFile(p, { status: 'added' });
698
+ }
699
+ }
700
+ }
701
+
702
+ const rawText = typeof msg.content === 'string' ? msg.content : '';
703
+ if (msg.role === 'tool' && rawText) {
704
+ let toolText = rawText;
705
+ try {
706
+ const parsed = JSON.parse(rawText) as Record<string, unknown>;
707
+ if (parsed && typeof parsed === 'object' && typeof parsed.output === 'string') {
708
+ toolText = parsed.output;
709
+ }
710
+ } catch {
711
+ // Keep raw plain text tool output.
712
+ }
713
+ for (const m of toolText.matchAll(/Atomically wrote (\d+) bytes to ([^\r\n"'}]+)/g)) {
714
+ recordFile(m[2], { status: 'added', bytesWritten: Number(m[1]) || undefined });
715
+ }
716
+ for (const m of toolText.matchAll(/Saved (\d+)-byte screenshot to ([^\r\n"'}]+)/g)) {
717
+ recordFile(m[2], { status: 'added', bytesWritten: Number(m[1]) || undefined });
718
+ }
719
+ for (const m of toolText.matchAll(/(?:Successfully edited|Successfully wrote|Created file|Patched)\s+([^\r\n"'}]+)/g)) {
720
+ recordFile(m[1], { status: 'modified' });
721
+ }
722
+ }
723
+
724
+ if (msg.role === 'assistant' && rawText) {
725
+ for (const m of rawText.matchAll(/file:\/\/[^\s)\]"'<>]+/g)) {
726
+ recordFile(m[0], { status: 'added' });
727
+ }
728
+ for (const m of rawText.matchAll(/`([^`\r\n]{3,240})`/g)) {
729
+ const candidate = m[1]!;
730
+ if (candidate.includes('/') && hasFileExtension(candidate) && !candidate.includes(' ')) {
731
+ assistantBacktickCandidates.push(candidate);
732
+ }
733
+ }
734
+ }
735
+ }
736
+
737
+ for (const cand of assistantBacktickCandidates) {
738
+ const norm = normalizeWorkspaceRelCandidate(workspaceRoot, cand);
739
+ if (!norm || evidenceMap.has(norm)) continue;
740
+ const dir = path.posix.dirname(norm);
741
+ const abs = resolveWorkspaceRelativePath(workspaceRoot, norm);
742
+ const inTouchedDir = Boolean(dir && dir !== '.' && touchedDirs.has(dir));
743
+ const existsUntrackedDotAsset = Boolean(abs && norm.startsWith('.') && fs.existsSync(abs));
744
+ if (inTouchedDir || existsUntrackedDotAsset) {
745
+ recordFile(norm, { status: 'added' });
746
+ }
747
+ }
748
+
749
+ // Drop bare parent directories when concrete child files in that directory are present.
750
+ const allPaths = [...evidenceMap.keys()];
751
+ for (const p of allPaths) {
752
+ if (!hasFileExtension(p)) {
753
+ const prefix = `${p}/`;
754
+ if (allPaths.some((other) => other.startsWith(prefix))) {
755
+ evidenceMap.delete(p);
756
+ }
757
+ }
758
+ }
759
+
760
+ return evidenceMap;
761
+ }
762
+
763
+ export function extractSessionTouchedFiles(
764
+ messages: readonly SessionMessage[],
765
+ workspaceRoot: string
766
+ ): string[] {
767
+ return [...extractSessionFileEvidence(messages, workspaceRoot).keys()].sort();
768
+ }
769
+
770
+ export interface SessionDisplayStep {
771
+ tool: string;
772
+ target: string;
773
+ status: 'done' | 'failed';
774
+ output?: string | undefined;
775
+ }
776
+
777
+ export type SessionDisplayBlock =
778
+ | { kind: 'reasoning'; content: string }
779
+ | { kind: 'steps'; steps: SessionDisplayStep[] }
780
+ | { kind: 'text'; content: string };
781
+
782
+ export interface SessionDisplayMessage {
783
+ role: 'user' | 'assistant';
784
+ content: string;
785
+ reasoning?: string | undefined;
786
+ steps?: SessionDisplayStep[] | undefined;
787
+ blocks?: SessionDisplayBlock[] | undefined;
788
+ }
789
+
790
+ function summarizeArgsTarget(args: Record<string, unknown> | null): string {
791
+ if (!args) return '';
792
+ for (const key of ['path', 'filePath', 'file_path', 'file', 'command', 'query', 'url', 'skill_id']) {
793
+ if (typeof args[key] === 'string' && String(args[key]).trim()) {
794
+ return String(args[key]).trim().slice(0, 100);
795
+ }
796
+ }
797
+ return '';
798
+ }
799
+
800
+ function extractSessionDisplayMessages(
801
+ messages: readonly SessionMessage[]
802
+ ): SessionDisplayMessage[] {
803
+ const toolOutputsById = new Map<string, { output: string; failed: boolean }>();
804
+ for (const msg of messages) {
805
+ if (msg.role !== 'tool') continue;
806
+ const rec = msg as Record<string, unknown>;
807
+ const id = typeof rec.tool_call_id === 'string' ? rec.tool_call_id : '';
808
+ if (!id) continue;
809
+ const raw = typeof msg.content === 'string' ? msg.content : '';
810
+ let failed = false;
811
+ let summary = raw.trim().slice(0, 360);
812
+ try {
813
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
814
+ if (parsed && typeof parsed === 'object') {
815
+ if (parsed.success === false || typeof parsed.error === 'string') failed = true;
816
+ if (typeof parsed.error === 'string') summary = parsed.error.slice(0, 360);
817
+ else if (typeof parsed.output === 'string') summary = parsed.output.slice(0, 360);
818
+ }
819
+ } catch {
820
+ // plain text tool output
821
+ }
822
+ toolOutputsById.set(id, { output: summary, failed });
823
+ }
824
+
825
+ const out: SessionDisplayMessage[] = [];
826
+ for (const msg of messages) {
827
+ if (msg.role !== 'user' && msg.role !== 'assistant') continue;
828
+ const rec = msg as Record<string, unknown>;
829
+ let text = '';
830
+ if (typeof msg.content === 'string') {
831
+ text = msg.content;
832
+ } else if (Array.isArray(msg.content)) {
833
+ const parts: string[] = [];
834
+ for (const block of msg.content) {
835
+ if (block && typeof block === 'object' && typeof (block as any).text === 'string') {
836
+ parts.push(String((block as any).text));
837
+ }
838
+ }
839
+ text = parts.join('\n');
840
+ }
841
+ const trimmed = text.trim();
842
+ if (msg.role === 'user') {
843
+ if (!trimmed) continue;
844
+ out.push({ role: 'user', content: trimmed });
845
+ continue;
846
+ }
847
+
848
+ const steps: SessionDisplayStep[] = [];
849
+ const extActions = Array.isArray(rec.external_actions)
850
+ ? (rec.external_actions as Array<Record<string, unknown>>)
851
+ : [];
852
+ for (const act of extActions) {
853
+ const rawName = typeof act.name === 'string' ? act.name.trim() : '';
854
+ const rawDetail = typeof act.detail === 'string' ? act.detail.trim() : '';
855
+ if (!rawName || rawName === 'true' || rawName === ':' || rawDetail === 'true' || rawDetail === ':') continue;
856
+ steps.push({
857
+ tool: rawName.replace(/^causyne[-_]browser[_:]/i, ''),
858
+ target: rawDetail.slice(0, 100),
859
+ status: act.status === 'failed' ? 'failed' : 'done'
860
+ });
861
+ }
862
+ const toolCalls = Array.isArray(rec.tool_calls)
863
+ ? (rec.tool_calls as Array<Record<string, unknown>>)
864
+ : [];
865
+ for (const tc of toolCalls) {
866
+ const fn = (tc.function && typeof tc.function === 'object' ? tc.function : tc) as Record<string, unknown>;
867
+ const name = typeof fn.name === 'string' ? fn.name.trim() : '';
868
+ if (!name || name === 'true' || name === ':') continue;
869
+ let args: Record<string, unknown> | null = null;
870
+ if (typeof fn.arguments === 'string') {
871
+ try {
872
+ const parsed = JSON.parse(fn.arguments);
873
+ if (parsed && typeof parsed === 'object') args = parsed as Record<string, unknown>;
874
+ } catch {
875
+ args = null;
876
+ }
877
+ } else if (fn.arguments && typeof fn.arguments === 'object') {
878
+ args = fn.arguments as Record<string, unknown>;
879
+ }
880
+ const tcId = typeof tc.id === 'string' ? tc.id : '';
881
+ const matchedOut = tcId ? toolOutputsById.get(tcId) : undefined;
882
+ steps.push({
883
+ tool: name,
884
+ target: summarizeArgsTarget(args),
885
+ status: matchedOut?.failed ? 'failed' : 'done',
886
+ ...(matchedOut?.output ? { output: matchedOut.output } : {})
887
+ });
888
+ }
889
+ const rawReasoning = typeof rec.reasoning_content === 'string' ? rec.reasoning_content.trim() : '';
890
+ const reasoning = rawReasoning ? rawReasoning.slice(0, 8000) : undefined;
891
+
892
+ if (!trimmed && steps.length === 0 && !reasoning) continue;
893
+ const msgBlocks: SessionDisplayBlock[] = [];
894
+ if (reasoning) msgBlocks.push({ kind: 'reasoning', content: reasoning });
895
+ if (steps.length > 0) msgBlocks.push({ kind: 'steps', steps });
896
+ if (trimmed) msgBlocks.push({ kind: 'text', content: trimmed });
897
+
898
+ // Merge consecutive assistant messages between user turns into one cohesive Claude-style turn
899
+ // while preserving exact chronological interleaved blocks (reasoning -> steps -> text -> steps -> text).
900
+ const prev = out.length > 0 ? out[out.length - 1] : null;
901
+ if (prev && prev.role === 'assistant') {
902
+ const prevBlocks = prev.blocks ? [...prev.blocks] : [];
903
+ for (const blk of msgBlocks) {
904
+ const lastBlk = prevBlocks.length > 0 ? prevBlocks[prevBlocks.length - 1] : null;
905
+ if (blk.kind === 'steps' && lastBlk && lastBlk.kind === 'steps') {
906
+ lastBlk.steps = [...lastBlk.steps, ...blk.steps];
907
+ } else if (blk.kind === 'reasoning' && lastBlk && lastBlk.kind === 'reasoning') {
908
+ lastBlk.content = `${lastBlk.content}\n\n${blk.content}`.slice(0, 8000);
909
+ } else {
910
+ prevBlocks.push(blk);
911
+ }
912
+ }
913
+ prev.blocks = prevBlocks;
914
+ if (steps.length > 0) prev.steps = [...(prev.steps || []), ...steps];
915
+ if (reasoning) prev.reasoning = prev.reasoning ? `${prev.reasoning}\n\n${reasoning}`.slice(0, 8000) : reasoning;
916
+ if (trimmed) prev.content = prev.content ? `${prev.content}\n\n${trimmed}` : trimmed;
917
+ continue;
918
+ }
919
+ out.push({
920
+ role: 'assistant',
921
+ content: trimmed,
922
+ ...(reasoning ? { reasoning } : {}),
923
+ ...(steps.length > 0 ? { steps } : {}),
924
+ blocks: msgBlocks
925
+ });
926
+ }
927
+ return out;
928
+ }
929
+
930
+ function buildWorkspacePromptWithAttachments(
931
+ workspaceRoot: string,
932
+ prompt: string,
933
+ rawAttachments: unknown
934
+ ): { effectivePrompt: string; attachedPaths: string[] } {
935
+ if (!Array.isArray(rawAttachments) || rawAttachments.length === 0) {
936
+ return { effectivePrompt: prompt, attachedPaths: [] };
937
+ }
938
+ const attachedPaths: string[] = [];
939
+ const sections: string[] = [];
940
+ for (const raw of rawAttachments.slice(0, MAX_ATTACHMENTS)) {
941
+ if (typeof raw !== 'string') continue;
942
+ const abs = resolveWorkspaceRelativePath(workspaceRoot, raw);
943
+ if (!abs) continue;
944
+ if (isIgnoredByCausyneIgnore(abs, workspaceRoot, false)) continue;
945
+ try {
946
+ const stat = fs.lstatSync(abs);
947
+ if (stat.isSymbolicLink() || !stat.isFile()) continue;
948
+ const buf = fs.readFileSync(abs);
949
+ if (buf.includes(0)) continue;
950
+ const sliced = buf.length > MAX_ATTACHMENT_BYTES ? buf.subarray(0, MAX_ATTACHMENT_BYTES) : buf;
951
+ const rel = path.relative(workspaceRoot, abs).split(path.sep).join('/');
952
+ const truncatedNote = buf.length > MAX_ATTACHMENT_BYTES ? '\n[truncated]' : '';
953
+ attachedPaths.push(rel);
954
+ sections.push(`--- Attached workspace file: ${rel} ---\n${sliced.toString('utf8')}${truncatedNote}`);
955
+ } catch {
956
+ // skip unreadable attachment
957
+ }
958
+ }
959
+ if (sections.length === 0) {
960
+ return { effectivePrompt: prompt, attachedPaths: [] };
961
+ }
962
+ return {
963
+ effectivePrompt: `${sections.join('\n\n')}\n\n${prompt}`,
964
+ attachedPaths
965
+ };
966
+ }
967
+
968
+ function workspaceMatchesSession(sessionWorkspace: string, workspaceRoot: string): boolean {
969
+ if (!sessionWorkspace) return false;
970
+ const resolvedSession = physicalPath(sessionWorkspace);
971
+ return resolvedSession === workspaceRoot || sessionWorkspace === workspaceRoot;
972
+ }
973
+
974
+ function parseSessionIdRoute(pathname: string): string | null {
975
+ const prefix = '/api/sessions/';
976
+ if (!pathname.startsWith(prefix)) return null;
977
+ const raw = pathname.slice(prefix.length);
978
+ if (!raw || raw.includes('/')) return null;
979
+ let decoded = '';
980
+ try {
981
+ decoded = decodeURIComponent(raw);
982
+ } catch {
983
+ return null;
984
+ }
985
+ return SAFE_SESSION_ID_RE.test(decoded) ? decoded : null;
986
+ }
987
+
988
+ function parseSessionStreamRoute(pathname: string): string | null {
989
+ const prefix = '/api/sessions/';
990
+ const suffix = '/stream';
991
+ if (!pathname.startsWith(prefix) || !pathname.endsWith(suffix)) return null;
992
+ const raw = pathname.slice(prefix.length, pathname.length - suffix.length);
993
+ if (!raw || raw.includes('/')) return null;
994
+ let decoded = '';
995
+ try {
996
+ decoded = decodeURIComponent(raw);
997
+ } catch {
998
+ return null;
999
+ }
1000
+ return SAFE_SESSION_ID_RE.test(decoded) ? decoded : null;
1001
+ }
1002
+
1003
+ interface SessionActiveRun {
1004
+ key: string;
1005
+ sessionId: string | null;
1006
+ taskId: string;
1007
+ prompt: string;
1008
+ startedAt: number;
1009
+ status: 'running' | 'awaiting_client' | 'completed' | 'stopped' | 'errored';
1010
+ userStopped: boolean;
1011
+ loop: SkybridgeLoopLike;
1012
+ frames: string[];
1013
+ bufferedBytes: number;
1014
+ subscribers: Set<(frame: string) => void>;
1015
+ doneSubscribers: Set<() => void>;
1016
+ }
1017
+
1018
+ const MAX_RUN_BUFFERED_FRAMES = 2400;
1019
+ const MAX_RUN_BUFFERED_BYTES = 2 * 1024 * 1024;
1020
+ const STREAM_HEARTBEAT_MS = 15_000;
1021
+
1022
+ function readLastGitCommitDiffForFile(
1023
+ workspaceRoot: string,
1024
+ relPath: string
1025
+ ): { additions: number; deletions: number; hunks: Array<{ header: string; lines: string[] }> } | null {
1026
+ if (!relPath || relPath.startsWith('-') || relPath.includes('\0')) return null;
1027
+ try {
1028
+ const raw = execFileSync(
1029
+ 'git',
1030
+ ['log', '-n', '1', '--format=', '--unified=3', '--no-color', '-p', '--', relPath],
1031
+ {
1032
+ cwd: workspaceRoot,
1033
+ encoding: 'utf8',
1034
+ stdio: ['ignore', 'pipe', 'ignore'],
1035
+ maxBuffer: 256 * 1024,
1036
+ timeout: 3000,
1037
+ windowsHide: true
1038
+ }
1039
+ );
1040
+ if (!raw || !raw.trim()) return null;
1041
+ const parsed = parseUnifiedDiff(raw);
1042
+ const first = parsed[0];
1043
+ if (!first || first.hunks.length === 0) return null;
1044
+ return {
1045
+ additions: first.additions,
1046
+ deletions: first.deletions,
1047
+ hunks: first.hunks.slice(0, 12).map((h) => ({
1048
+ header: h.header,
1049
+ lines: h.lines.slice(0, 140)
1050
+ }))
1051
+ };
1052
+ } catch {
1053
+ return null;
1054
+ }
1055
+ }
1056
+
1057
+ export async function startSkybridgeServer(options: StartSkybridgeOptions = {}): Promise<SkybridgeHandle> {
1058
+ const rawRoot = options.workspaceRoot || process.cwd();
1059
+ const resolvedRoot = physicalPath(rawRoot);
1060
+ if (!resolvedRoot || !fs.existsSync(resolvedRoot) || !fs.statSync(resolvedRoot).isDirectory()) {
1061
+ throw new Error(`Invalid Skybridge workspace directory: ${rawRoot}`);
1062
+ }
1063
+ const workspaceRoot = resolvedRoot;
1064
+ const token = options.token || crypto.randomBytes(32).toString('base64url');
1065
+ const requestedPort = typeof options.port === 'number'
1066
+ && Number.isInteger(options.port)
1067
+ && options.port >= 0
1068
+ && options.port <= 65535
1069
+ ? options.port
1070
+ : 0;
1071
+ const extraOrigins = options.allowedOrigins ?? [];
1072
+ const version = getPackageVersion();
1073
+ const hasCustomFactory = typeof options.loopFactory === 'function';
1074
+ let boundPort = requestedPort;
1075
+ const serverApprovalScope = createApprovalScope();
1076
+ const buildSharedBrowserPeerMcp = (): McpServer[] => {
1077
+ if (!boundPort) return [];
1078
+ return [{
1079
+ type: 'http',
1080
+ name: CAUSYNE_BROWSER_MCP_NAME,
1081
+ url: `http://127.0.0.1:${boundPort}/api/mcp/browser`,
1082
+ headers: [{ name: 'Authorization', value: `Bearer ${token}` }]
1083
+ }];
1084
+ };
1085
+ const loopFactory: SkybridgeLoopFactory = options.loopFactory ?? ((sink, taskId, prompt, opts) => {
1086
+ const loopOptions: {
1087
+ workspaceRoot: string;
1088
+ memorySessionId?: string | null;
1089
+ provider?: string;
1090
+ model?: string;
1091
+ approvalScope?: ReturnType<typeof createApprovalScope>;
1092
+ peerMcpServers?: McpServer[];
1093
+ } = {
1094
+ workspaceRoot: opts.workspaceRoot,
1095
+ approvalScope: serverApprovalScope,
1096
+ peerMcpServers: buildSharedBrowserPeerMcp()
1097
+ };
1098
+ if (opts.sessionId) loopOptions.memorySessionId = opts.sessionId;
1099
+ if (opts.provider) loopOptions.provider = opts.provider;
1100
+ if (opts.model) loopOptions.model = opts.model;
1101
+ const loop = new AgentLoop(sink, taskId, prompt, loopOptions);
1102
+ if (opts.mode === 'A' || opts.mode === 'B' || opts.mode === 'C') {
1103
+ try {
1104
+ loop.setAutonomyMode(opts.mode);
1105
+ } catch {
1106
+ // Fallback when custom mode normalization differs.
1107
+ }
1108
+ if (loop.sandbox) {
1109
+ loop.sandbox.autonomyMode = opts.mode;
1110
+ }
1111
+ }
1112
+ const pendingDecisions = new Map<string, (answer: SkybridgeDecisionAnswer | null) => void>();
1113
+ loop.waitForDecision = (request: any) => {
1114
+ const reqId = typeof request?.id === 'string' && request.id ? request.id : `dec_${Date.now()}`;
1115
+ return new Promise<SkybridgeDecisionAnswer | null>((resolve) => {
1116
+ pendingDecisions.set(reqId, resolve);
1117
+ });
1118
+ };
1119
+ return {
1120
+ run: () => loop.run(),
1121
+ abort: () => {
1122
+ for (const [, resolve] of pendingDecisions) {
1123
+ try { resolve(null); } catch { /* ignore */ }
1124
+ }
1125
+ pendingDecisions.clear();
1126
+ loop.abort();
1127
+ },
1128
+ resolveApproval: (toolCallId: string, approved: boolean) => {
1129
+ const resolver = loop.pendingApprovals.get(toolCallId);
1130
+ if (resolver) resolver(approved);
1131
+ },
1132
+ resolveDecision: (requestId: string, answer: SkybridgeDecisionAnswer | null) => {
1133
+ const resolver = pendingDecisions.get(requestId);
1134
+ if (resolver) {
1135
+ pendingDecisions.delete(requestId);
1136
+ resolver(answer);
1137
+ }
1138
+ },
1139
+ grantAlways: (toolName: string) => {
1140
+ serverApprovalScope.grantAlways(toolName);
1141
+ }
1142
+ };
1143
+ });
1144
+
1145
+ const activeRuns = new Map<string, SessionActiveRun>();
1146
+ let taskCounter = 0;
1147
+
1148
+ const findActiveRun = (sessionId?: string | null): SessionActiveRun | null => {
1149
+ if (sessionId && activeRuns.has(sessionId)) {
1150
+ return activeRuns.get(sessionId) ?? null;
1151
+ }
1152
+ if (!sessionId && activeRuns.size === 1) {
1153
+ return activeRuns.values().next().value ?? null;
1154
+ }
1155
+ return null;
1156
+ };
1157
+
1158
+ const pushRunFrame = (run: SessionActiveRun, raw: string): void => {
1159
+ const clean = raw.replace(/\r?\n/g, ' ');
1160
+ const frameBytes = Buffer.byteLength(clean, 'utf8');
1161
+ if (run.frames.length < MAX_RUN_BUFFERED_FRAMES && run.bufferedBytes + frameBytes <= MAX_RUN_BUFFERED_BYTES) {
1162
+ run.frames.push(clean);
1163
+ run.bufferedBytes += frameBytes;
1164
+ }
1165
+ for (const send of run.subscribers) {
1166
+ try {
1167
+ send(clean);
1168
+ } catch {
1169
+ // Isolate subscriber write failures so detached runs continue uninterrupted.
1170
+ }
1171
+ }
1172
+ };
1173
+
1174
+ const attachRunStream = (
1175
+ req: http.IncomingMessage,
1176
+ res: http.ServerResponse,
1177
+ run: SessionActiveRun,
1178
+ replayBuffered: boolean
1179
+ ): void => {
1180
+ req.setTimeout(0);
1181
+ res.setTimeout(0);
1182
+ try { req.socket?.setKeepAlive(true, STREAM_HEARTBEAT_MS); } catch { /* ignore */ }
1183
+ res.statusCode = 200;
1184
+ res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
1185
+ res.setHeader('Transfer-Encoding', 'chunked');
1186
+ res.setHeader('Cache-Control', 'no-store');
1187
+ res.setHeader('X-Accel-Buffering', 'no');
1188
+ res.flushHeaders?.();
1189
+
1190
+ const writeLine = (cleanFrame: string): void => {
1191
+ if (res.writableEnded || res.destroyed) return;
1192
+ res.write(`${cleanFrame}\n`);
1193
+ };
1194
+
1195
+ const heartbeatTimer = setInterval(() => {
1196
+ if (res.writableEnded || res.destroyed) return;
1197
+ writeLine(JSON.stringify({ type: 'heartbeat', ts: Date.now() }));
1198
+ }, STREAM_HEARTBEAT_MS);
1199
+ heartbeatTimer.unref?.();
1200
+
1201
+ let detached = false;
1202
+ const detach = (): void => {
1203
+ if (detached) return;
1204
+ detached = true;
1205
+ clearInterval(heartbeatTimer);
1206
+ run.subscribers.delete(writeLine);
1207
+ run.doneSubscribers.delete(finishResponse);
1208
+ };
1209
+
1210
+ const finishResponse = (): void => {
1211
+ detach();
1212
+ if (!res.writableEnded && !res.destroyed) res.end();
1213
+ };
1214
+
1215
+ // Disconnecting a browser tab or switching chats ONLY unsubscribes this HTTP response.
1216
+ // It NEVER aborts the detached AgentLoop; only explicit POST /api/stop cancels it.
1217
+ res.on('close', detach);
1218
+
1219
+ if (replayBuffered) {
1220
+ for (const frame of run.frames) {
1221
+ writeLine(frame);
1222
+ }
1223
+ }
1224
+
1225
+ if (run.status === 'running' || run.status === 'awaiting_client') {
1226
+ run.subscribers.add(writeLine);
1227
+ run.doneSubscribers.add(finishResponse);
1228
+ } else {
1229
+ finishResponse();
1230
+ }
1231
+ };
1232
+ const sessionTouchedFilesMap = new Map<string, Set<string>>();
1233
+ const recordSessionTouchedFile = (sessionId: string | null | undefined, rawPath: unknown): void => {
1234
+ if (!sessionId || !SAFE_SESSION_ID_RE.test(sessionId)) return;
1235
+ const norm = normalizeWorkspaceRelCandidate(workspaceRoot, rawPath);
1236
+ if (!norm) return;
1237
+ let set = sessionTouchedFilesMap.get(sessionId);
1238
+ if (!set) {
1239
+ set = new Set<string>();
1240
+ sessionTouchedFilesMap.set(sessionId, set);
1241
+ }
1242
+ set.add(norm);
1243
+ };
1244
+ let browserControlOwner: 'human' | 'agent' = 'human';
1245
+ let browserAgentActivity: { active: boolean; tool: string; detail: string; updatedAt: number } = {
1246
+ active: false,
1247
+ tool: '',
1248
+ detail: '',
1249
+ updatedAt: 0
1250
+ };
1251
+ const browserStreamClients = new Set<(payload: Record<string, unknown>) => void>();
1252
+ const broadcastBrowserNotice = (payload: Record<string, unknown>): void => {
1253
+ for (const send of browserStreamClients) {
1254
+ try {
1255
+ send(payload);
1256
+ } catch {
1257
+ // Isolate individual stream clients.
1258
+ }
1259
+ }
1260
+ };
1261
+
1262
+ const server = http.createServer(async (req, res) => {
1263
+ const hostHeader = req.headers.host;
1264
+ if (!isAllowedSkybridgeHost(hostHeader, boundPort)) {
1265
+ res.statusCode = 403;
1266
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
1267
+ res.end(JSON.stringify({ error: 'Forbidden Host header (DNS rebinding protection).' }));
1268
+ return;
1269
+ }
1270
+
1271
+ const originHeader = typeof req.headers.origin === 'string' ? req.headers.origin : undefined;
1272
+ const originAllowed = isAllowedSkybridgeOrigin(originHeader, boundPort, extraOrigins);
1273
+ applySecurityHeaders(res, originHeader, originAllowed);
1274
+
1275
+ if (originHeader && !originAllowed) {
1276
+ sendJson(res, 403, { error: 'Origin not permitted by Causyne Skybridge.' });
1277
+ return;
1278
+ }
1279
+
1280
+ if (req.method === 'OPTIONS') {
1281
+ res.statusCode = 204;
1282
+ res.end();
1283
+ return;
1284
+ }
1285
+
1286
+ const parsedUrl = new URL(req.url || '/', `http://127.0.0.1:${boundPort}`);
1287
+ const pathname = parsedUrl.pathname;
1288
+
1289
+ if (req.method === 'GET' && pathname === '/favicon.svg') {
1290
+ res.statusCode = 200;
1291
+ res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
1292
+ res.setHeader('Cache-Control', 'public, max-age=3600');
1293
+ res.end(getCausyneFaviconSvg());
1294
+ return;
1295
+ }
1296
+
1297
+ if (req.method === 'GET' && pathname === '/favicon.ico') {
1298
+ res.statusCode = 204;
1299
+ res.end();
1300
+ return;
1301
+ }
1302
+
1303
+ if (req.method === 'GET' && pathname === '/') {
1304
+ const cspNonce = crypto.randomBytes(16).toString('base64url');
1305
+ res.statusCode = 200;
1306
+ res.setHeader(
1307
+ 'Content-Security-Policy',
1308
+ `default-src 'self'; script-src 'self' 'nonce-${cspNonce}'; `
1309
+ + `style-src 'self' 'unsafe-inline'; img-src 'self' data:; `
1310
+ + `frame-src http://127.0.0.1:* http://localhost:*; `
1311
+ + `connect-src 'self'; frame-ancestors 'none'`
1312
+ );
1313
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
1314
+ res.end(renderSkybridgeHtml({
1315
+ cspNonce,
1316
+ workspaceName: path.basename(workspaceRoot),
1317
+ version
1318
+ }));
1319
+ return;
1320
+ }
1321
+
1322
+ if (!pathname.startsWith('/api/')) {
1323
+ sendJson(res, 404, { error: 'Not found.' });
1324
+ return;
1325
+ }
1326
+
1327
+ if (!timingSafeBearerMatch(req.headers.authorization, token)) {
1328
+ sendJson(res, 401, { error: 'Unauthorized. Valid Skybridge Bearer token required.' });
1329
+ return;
1330
+ }
1331
+
1332
+ try {
1333
+ if (req.method === 'GET' && pathname === '/api/health') {
1334
+ const config = loadConfig();
1335
+ const zeroCost = await detectZeroCostProviders({ config, probeOllama: false });
1336
+ const readyZeroCost = zeroCost.filter((z) => z.readiness === 'ready');
1337
+ sendJson(res, 200, {
1338
+ ok: true,
1339
+ version,
1340
+ workspaceRoot,
1341
+ workspaceName: path.basename(workspaceRoot),
1342
+ provider: config.provider || 'unconfigured',
1343
+ model: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || 'default',
1344
+ zeroCostReadyCount: readyZeroCost.length,
1345
+ zeroCostRoutes: readyZeroCost.map((z) => ({
1346
+ id: z.id,
1347
+ provider: z.provider,
1348
+ model: z.model,
1349
+ label: z.label,
1350
+ costTier: z.costTier
1351
+ })),
1352
+ busy: activeRuns.size > 0
1353
+ });
1354
+ return;
1355
+ }
1356
+
1357
+ if (req.method === 'GET' && pathname === '/api/models') {
1358
+ const config = loadConfig();
1359
+ const forceRefresh = parsedUrl.searchParams.get('refresh') === '1';
1360
+ const allowLive = forceRefresh || parsedUrl.searchParams.get('live') === '1';
1361
+ const overview = allowLive
1362
+ ? await resolveAvailableProvidersOverview(config, { forceRefresh })
1363
+ : getAvailableProvidersOverview(config);
1364
+ const activeProviderRaw = String(config.provider || '').toLowerCase().trim();
1365
+ const initialTab: 'acp' | 'byok' | 'free' = activeProviderRaw === 'openrouter'
1366
+ ? 'free'
1367
+ : (activeProviderRaw === 'antigravity'
1368
+ || activeProviderRaw === 'agy'
1369
+ || activeProviderRaw === 'pi'
1370
+ || activeProviderRaw === 'acp'
1371
+ || activeProviderRaw.startsWith('acp/')
1372
+ ? 'acp'
1373
+ : 'byok');
1374
+ const tabs = {
1375
+ acp: buildModelPickerItems(config, overview, { tab: 'acp', maxAcpPerPeer: Infinity }),
1376
+ byok: buildModelPickerItems(config, overview, { tab: 'byok', maxAcpPerPeer: Infinity }),
1377
+ free: buildModelPickerItems(config, overview, { tab: 'free', maxAcpPerPeer: Infinity })
1378
+ };
1379
+ const zeroCost = await detectZeroCostProviders({ config, probeOllama: false });
1380
+ const readySet = new Set(zeroCost.filter((z) => z.readiness === 'ready').map((z) => z.provider));
1381
+ const groups = Object.entries(MODEL_CATALOGUE).map(([label, models]) => {
1382
+ const providerId = PROVIDER_KEY_FOR_CATALOG_LABEL[label] || label.toLowerCase();
1383
+ const hasKey = Boolean(resolveProviderApiKey(config, providerId));
1384
+ const isZeroCostReady = readySet.has(providerId);
1385
+ return {
1386
+ label,
1387
+ provider: providerId,
1388
+ configured: hasKey || isZeroCostReady,
1389
+ zeroCostReady: isZeroCostReady,
1390
+ defaultModel: DEFAULT_MODEL_BY_PROVIDER[providerId] || models[0] || '',
1391
+ models
1392
+ };
1393
+ });
1394
+ sendJson(res, 200, {
1395
+ ok: true,
1396
+ activeProvider: config.provider || 'unconfigured',
1397
+ activeModel: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || '',
1398
+ initialTab,
1399
+ tabs,
1400
+ overview,
1401
+ zeroCost: zeroCost.map((z) => ({
1402
+ id: z.id,
1403
+ provider: z.provider,
1404
+ model: z.model,
1405
+ label: z.label,
1406
+ costTier: z.costTier,
1407
+ readiness: z.readiness
1408
+ })),
1409
+ groups
1410
+ });
1411
+ return;
1412
+ }
1413
+
1414
+ if (req.method === 'POST' && pathname === '/api/model') {
1415
+ const body = await readJsonBody(req);
1416
+ const action = typeof body.action === 'string' ? body.action.trim() : '';
1417
+ const provider = typeof body.provider === 'string' ? body.provider.trim() : '';
1418
+ const model = typeof body.model === 'string' ? body.model.trim() : '';
1419
+ if (action === 'disconnect' && provider === 'openrouter') {
1420
+ disconnectOpenRouter();
1421
+ const updated = loadConfig();
1422
+ auditLog.log({ event: 'skybridge_openrouter_disconnect' });
1423
+ sendJson(res, 200, {
1424
+ ok: true,
1425
+ disconnected: true,
1426
+ provider: updated.provider || 'unconfigured',
1427
+ model: updated.model || DEFAULT_MODEL_BY_PROVIDER[String(updated.provider || '')] || 'default'
1428
+ });
1429
+ return;
1430
+ }
1431
+ if (!provider || !SAFE_PROVIDER_RE.test(provider)) {
1432
+ sendJson(res, 400, { error: 'Valid provider identifier is required.' });
1433
+ return;
1434
+ }
1435
+ if (model && !SAFE_MODEL_RE.test(model)) {
1436
+ sendJson(res, 400, { error: 'Invalid model identifier.' });
1437
+ return;
1438
+ }
1439
+ const config = loadConfig();
1440
+ const resolvedModel = model || DEFAULT_MODEL_BY_PROVIDER[provider] || '';
1441
+ applyProviderOverrides(config, provider, resolvedModel);
1442
+ saveConfig(config);
1443
+ auditLog.log({
1444
+ event: 'skybridge_model_switch',
1445
+ provider: config.provider,
1446
+ model: config.model
1447
+ });
1448
+ sendJson(res, 200, {
1449
+ ok: true,
1450
+ provider: config.provider,
1451
+ model: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || 'default'
1452
+ });
1453
+ return;
1454
+ }
1455
+
1456
+ if (req.method === 'GET' && pathname === '/api/sessions') {
1457
+ const all = listSessions();
1458
+ const scoped = all.filter((row) => workspaceMatchesSession(row.workspace, workspaceRoot));
1459
+ sendJson(res, 200, {
1460
+ ok: true,
1461
+ sessions: scoped.slice(0, 50).map((row) => {
1462
+ const run = activeRuns.get(row.id);
1463
+ const isRunning = Boolean(run && (run.status === 'running' || run.status === 'awaiting_client'));
1464
+ return {
1465
+ id: row.id,
1466
+ title: row.title,
1467
+ createdAt: row.createdAt,
1468
+ updatedAt: row.updatedAt,
1469
+ messageCount: row.messageCount,
1470
+ running: isRunning,
1471
+ awaitingClient: Boolean(run && run.status === 'awaiting_client')
1472
+ };
1473
+ })
1474
+ });
1475
+ return;
1476
+ }
1477
+
1478
+ const sessionStreamId = parseSessionStreamRoute(pathname);
1479
+ if (req.method === 'GET' && sessionStreamId) {
1480
+ const run = activeRuns.get(sessionStreamId);
1481
+ if (!run || (run.status !== 'running' && run.status !== 'awaiting_client')) {
1482
+ res.statusCode = 200;
1483
+ res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
1484
+ res.setHeader('Cache-Control', 'no-store');
1485
+ res.end(`${JSON.stringify({ type: 'idle', sessionId: sessionStreamId })}\n`);
1486
+ return;
1487
+ }
1488
+ attachRunStream(req, res, run, true);
1489
+ return;
1490
+ }
1491
+
1492
+ if (req.method === 'POST' && pathname === '/api/sessions') {
1493
+ const body = await readJsonBody(req);
1494
+ const rawTitle = typeof body.title === 'string' ? body.title.trim().slice(0, 80) : '';
1495
+ const created = createSession(workspaceRoot, rawTitle || 'Untitled', false);
1496
+ sendJson(res, 201, {
1497
+ ok: true,
1498
+ session: {
1499
+ id: created.id,
1500
+ title: created.title,
1501
+ createdAt: created.createdAt,
1502
+ updatedAt: created.updatedAt,
1503
+ messageCount: 0,
1504
+ messages: []
1505
+ }
1506
+ });
1507
+ return;
1508
+ }
1509
+
1510
+ const sessionIdParam = parseSessionIdRoute(pathname);
1511
+ if (sessionIdParam) {
1512
+ const existing = getSession(sessionIdParam);
1513
+ if (!existing || !workspaceMatchesSession(existing.workspace, workspaceRoot)) {
1514
+ sendJson(res, 404, { error: 'Session not found in this workspace.' });
1515
+ return;
1516
+ }
1517
+ if (req.method === 'GET') {
1518
+ const persistedTouched = extractSessionTouchedFiles(existing.messages, workspaceRoot);
1519
+ const liveTouched = [...(sessionTouchedFilesMap.get(existing.id) ?? [])];
1520
+ const touchedFiles = [...new Set([...persistedTouched, ...liveTouched])].sort();
1521
+ const activeRun = activeRuns.get(existing.id);
1522
+ const isRunning = Boolean(activeRun && (activeRun.status === 'running' || activeRun.status === 'awaiting_client'));
1523
+ sendJson(res, 200, {
1524
+ ok: true,
1525
+ session: {
1526
+ id: existing.id,
1527
+ title: existing.title,
1528
+ createdAt: existing.createdAt,
1529
+ updatedAt: existing.updatedAt,
1530
+ messageCount: existing.messages.length,
1531
+ messages: extractSessionDisplayMessages(existing.messages),
1532
+ touchedFiles,
1533
+ running: isRunning,
1534
+ awaitingClient: Boolean(activeRun && activeRun.status === 'awaiting_client'),
1535
+ activeRun: isRunning && activeRun ? {
1536
+ taskId: activeRun.taskId,
1537
+ status: activeRun.status,
1538
+ prompt: activeRun.prompt,
1539
+ startedAt: activeRun.startedAt
1540
+ } : null
1541
+ }
1542
+ });
1543
+ return;
1544
+ }
1545
+ if (req.method === 'PATCH') {
1546
+ const body = await readJsonBody(req);
1547
+ const nextTitle = typeof body.title === 'string' ? body.title.trim().slice(0, 80) : '';
1548
+ if (!nextTitle) {
1549
+ sendJson(res, 400, { error: 'A non-empty session title is required.' });
1550
+ return;
1551
+ }
1552
+ const updated = renameSession(existing.id, nextTitle);
1553
+ if (!updated) {
1554
+ sendJson(res, 400, { error: 'Could not rename session.' });
1555
+ return;
1556
+ }
1557
+ sendJson(res, 200, { ok: true, id: existing.id, title: nextTitle });
1558
+ return;
1559
+ }
1560
+ if (req.method === 'DELETE') {
1561
+ const removed = deleteSession(existing.id);
1562
+ sendJson(res, removed ? 200 : 404, { ok: removed, id: existing.id });
1563
+ return;
1564
+ }
1565
+ }
1566
+
1567
+ if (req.method === 'GET' && pathname === '/api/files') {
1568
+ const dir = parsedUrl.searchParams.get('dir') || '';
1569
+ const q = parsedUrl.searchParams.get('q') || '';
1570
+ const entries = listWorkspaceEntries(workspaceRoot, dir, q);
1571
+ const parentDir = dir ? path.posix.dirname(dir.replace(/\\/g, '/')) : '';
1572
+ sendJson(res, 200, {
1573
+ ok: true,
1574
+ dir,
1575
+ parentDir: parentDir === '.' ? '' : parentDir,
1576
+ entries
1577
+ });
1578
+ return;
1579
+ }
1580
+
1581
+ if (req.method === 'GET' && pathname === '/api/file') {
1582
+ const rel = parsedUrl.searchParams.get('path') || '';
1583
+ const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
1584
+ if (!abs) {
1585
+ sendJson(res, 403, { error: 'Path is outside the locked workspace boundary.' });
1586
+ return;
1587
+ }
1588
+ const stat = fs.lstatSync(abs);
1589
+ if (stat.isSymbolicLink() || !stat.isFile()) {
1590
+ sendJson(res, 403, { error: 'Only regular workspace files can be read.' });
1591
+ return;
1592
+ }
1593
+ if (stat.size > MAX_FILE_READ_BYTES) {
1594
+ sendJson(res, 413, { error: `File exceeds ${MAX_FILE_READ_BYTES} byte preview limit.` });
1595
+ return;
1596
+ }
1597
+ const content = fs.readFileSync(abs, 'utf8');
1598
+ sendJson(res, 200, {
1599
+ ok: true,
1600
+ path: path.relative(workspaceRoot, abs).split(path.sep).join('/'),
1601
+ size: stat.size,
1602
+ content
1603
+ });
1604
+ return;
1605
+ }
1606
+
1607
+ if (req.method === 'POST' && pathname === '/api/file') {
1608
+ const body = await readJsonBody(req, MAX_FILE_WRITE_BYTES);
1609
+ const rel = typeof body.path === 'string' ? body.path : '';
1610
+ const content = typeof body.content === 'string' ? body.content : null;
1611
+ if (!rel || content === null) {
1612
+ sendJson(res, 400, { error: 'Both `path` and string `content` are required.' });
1613
+ return;
1614
+ }
1615
+ const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
1616
+ if (!abs) {
1617
+ sendJson(res, 403, { error: 'Refusing write outside locked workspace boundary.' });
1618
+ return;
1619
+ }
1620
+ const relNormalized = path.relative(workspaceRoot, abs).split(path.sep).join('/');
1621
+ if (isIgnoredByCausyneIgnore(abs, workspaceRoot, false)) {
1622
+ sendJson(res, 403, { error: 'File path is blocked by .causyneignore.' });
1623
+ return;
1624
+ }
1625
+ const byteCount = Buffer.byteLength(content, 'utf8');
1626
+ if (byteCount > MAX_FILE_WRITE_BYTES) {
1627
+ sendJson(res, 413, { error: 'File content exceeds maximum write limit.' });
1628
+ return;
1629
+ }
1630
+ atomicWriteFileSync(abs, content);
1631
+ if (typeof body.sessionId === 'string') {
1632
+ recordSessionTouchedFile(body.sessionId.trim(), relNormalized);
1633
+ }
1634
+ auditLog.log({ event: 'skybridge_file_write', path: relNormalized, bytes: byteCount });
1635
+ sendJson(res, 200, { ok: true, path: relNormalized, bytes: byteCount });
1636
+ return;
1637
+ }
1638
+
1639
+ if (req.method === 'GET' && pathname === '/api/diff') {
1640
+ const staged = parsedUrl.searchParams.get('staged') === '1';
1641
+ const rawSessionId = (parsedUrl.searchParams.get('sessionId') || '').trim();
1642
+ const sessionId = SAFE_SESSION_ID_RE.test(rawSessionId) ? rawSessionId : '';
1643
+ const rawScope = (parsedUrl.searchParams.get('scope') || '').trim().toLowerCase();
1644
+ const scope: 'session' | 'workspace' = rawScope === 'session' && sessionId ? 'session' : 'workspace';
1645
+
1646
+ const sessionEvidenceMap = new Map<string, SessionFileEvidence>();
1647
+ if (sessionId) {
1648
+ const sess = getSession(sessionId);
1649
+ if (sess && workspaceMatchesSession(sess.workspace, workspaceRoot)) {
1650
+ for (const [p, ev] of extractSessionFileEvidence(sess.messages, workspaceRoot)) {
1651
+ sessionEvidenceMap.set(p, ev);
1652
+ }
1653
+ }
1654
+ for (const p of sessionTouchedFilesMap.get(sessionId) ?? []) {
1655
+ if (!sessionEvidenceMap.has(p)) {
1656
+ sessionEvidenceMap.set(p, {
1657
+ path: p,
1658
+ status: 'modified',
1659
+ additions: 0,
1660
+ deletions: 0,
1661
+ hunks: []
1662
+ });
1663
+ }
1664
+ }
1665
+ }
1666
+
1667
+ const buildNonGitSessionEntry = (rel: string, ev: SessionFileEvidence | undefined, isGit: boolean) => {
1668
+ const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
1669
+ let existsOnDisk = false;
1670
+ let diskSize = 0;
1671
+ let diskHunks: Array<{ header: string; lines: string[] }> = [];
1672
+ let diskAdditions = 0;
1673
+ let diskDeletions = 0;
1674
+ let fromLastCommit = false;
1675
+ if (abs) {
1676
+ try {
1677
+ const st = fs.lstatSync(abs);
1678
+ if (!st.isSymbolicLink() && st.isFile()) {
1679
+ existsOnDisk = true;
1680
+ diskSize = st.size;
1681
+ if (isGit && (!ev || ev.hunks.length === 0)) {
1682
+ const commitDiff = readLastGitCommitDiffForFile(workspaceRoot, rel);
1683
+ if (commitDiff) {
1684
+ diskHunks = commitDiff.hunks;
1685
+ diskAdditions = commitDiff.additions;
1686
+ diskDeletions = commitDiff.deletions;
1687
+ fromLastCommit = true;
1688
+ }
1689
+ }
1690
+ if (diskHunks.length === 0 && st.size > 0 && st.size <= 48 * 1024 && (!ev || ev.hunks.length === 0)) {
1691
+ const buf = fs.readFileSync(abs);
1692
+ if (!buf.includes(0)) {
1693
+ const synth = buildSynthesizedWriteHunk(buf.toString('utf8'));
1694
+ diskHunks = synth.hunks;
1695
+ diskAdditions = synth.additions;
1696
+ }
1697
+ }
1698
+ }
1699
+ } catch {
1700
+ existsOnDisk = false;
1701
+ }
1702
+ }
1703
+ const hunks = ev && ev.hunks.length > 0 ? ev.hunks : diskHunks;
1704
+ const additions = ev && ev.additions > 0 ? ev.additions : diskAdditions;
1705
+ const deletions = ev && ev.deletions > 0 ? ev.deletions : diskDeletions;
1706
+ const status = fromLastCommit && diskDeletions > 0
1707
+ ? 'modified'
1708
+ : (ev?.status ?? (existsOnDisk ? 'modified' : 'added'));
1709
+ let note: string | undefined;
1710
+ if (existsOnDisk) {
1711
+ if (fromLastCommit) {
1712
+ note = 'Latest committed diff on disk';
1713
+ } else if (hunks.length === 0) {
1714
+ note = diskSize > 0
1715
+ ? `On disk (${formatByteSize(diskSize)}) · ${isGit ? 'committed or binary asset' : 'workspace file'}`
1716
+ : (isGit ? 'Clean on disk' : 'Touched in this conversation');
1717
+ }
1718
+ } else {
1719
+ const sizeLabel = ev?.bytesWritten ? ` (${formatByteSize(ev.bytesWritten)})` : '';
1720
+ note = `Written in this chat${sizeLabel} · no longer on disk`;
1721
+ }
1722
+ return {
1723
+ path: rel,
1724
+ status,
1725
+ additions,
1726
+ deletions,
1727
+ inGitDiff: false,
1728
+ existsOnDisk,
1729
+ note,
1730
+ hunks
1731
+ };
1732
+ };
1733
+
1734
+ try {
1735
+ const report = collectWorkingTreeDiff(workspaceRoot, { staged });
1736
+ const mappedWorkspaceFiles = report.files.slice(0, 60).map((f) => {
1737
+ const abs = resolveWorkspaceRelativePath(workspaceRoot, f.displayPath);
1738
+ let existsOnDisk = f.status !== 'deleted';
1739
+ let note: string | undefined;
1740
+ if (abs && f.hunks.length === 0 && f.status !== 'deleted') {
1741
+ try {
1742
+ const st = fs.lstatSync(abs);
1743
+ existsOnDisk = st.isFile();
1744
+ if (existsOnDisk) note = `Binary or large asset (${formatByteSize(st.size)})`;
1745
+ } catch {
1746
+ existsOnDisk = false;
1747
+ }
1748
+ }
1749
+ return {
1750
+ path: f.displayPath,
1751
+ status: f.status,
1752
+ additions: f.additions,
1753
+ deletions: f.deletions,
1754
+ inGitDiff: true,
1755
+ existsOnDisk,
1756
+ note,
1757
+ hunks: f.hunks.slice(0, 20).map((h) => ({
1758
+ header: h.header,
1759
+ lines: h.lines.slice(0, 200)
1760
+ }))
1761
+ };
1762
+ });
1763
+ const matchedSessionGitFiles = mappedWorkspaceFiles.filter((f) => sessionEvidenceMap.has(f.path));
1764
+ const matchedPaths = new Set(matchedSessionGitFiles.map((f) => f.path));
1765
+ const extraSessionFiles = [...sessionEvidenceMap.keys()]
1766
+ .sort()
1767
+ .filter((rel) => !matchedPaths.has(rel))
1768
+ .map((rel) => buildNonGitSessionEntry(rel, sessionEvidenceMap.get(rel), true));
1769
+ const sessionFiles = [...matchedSessionGitFiles, ...extraSessionFiles];
1770
+ const returnedFiles = scope === 'session' ? sessionFiles : mappedWorkspaceFiles;
1771
+ const totalAdditions = scope === 'session'
1772
+ ? returnedFiles.reduce((sum, f) => sum + f.additions, 0)
1773
+ : report.totalAdditions;
1774
+ const totalDeletions = scope === 'session'
1775
+ ? returnedFiles.reduce((sum, f) => sum + f.deletions, 0)
1776
+ : report.totalDeletions;
1777
+ sendJson(res, 200, {
1778
+ ok: true,
1779
+ isGitRepo: true,
1780
+ scope,
1781
+ sessionId: sessionId || null,
1782
+ staged: report.staged,
1783
+ workspaceFileCount: mappedWorkspaceFiles.length,
1784
+ sessionFileCount: sessionFiles.length,
1785
+ totalAdditions,
1786
+ totalDeletions,
1787
+ truncated: report.truncated,
1788
+ files: returnedFiles
1789
+ });
1790
+ } catch {
1791
+ const fallbackSessionFiles = [...sessionEvidenceMap.keys()]
1792
+ .sort()
1793
+ .map((rel) => buildNonGitSessionEntry(rel, sessionEvidenceMap.get(rel), false));
1794
+ sendJson(res, 200, {
1795
+ ok: true,
1796
+ isGitRepo: false,
1797
+ scope,
1798
+ sessionId: sessionId || null,
1799
+ staged,
1800
+ workspaceFileCount: 0,
1801
+ sessionFileCount: fallbackSessionFiles.length,
1802
+ totalAdditions: fallbackSessionFiles.reduce((sum, f) => sum + f.additions, 0),
1803
+ totalDeletions: fallbackSessionFiles.reduce((sum, f) => sum + f.deletions, 0),
1804
+ truncated: false,
1805
+ files: scope === 'session' ? fallbackSessionFiles : []
1806
+ });
1807
+ }
1808
+ return;
1809
+ }
1810
+
1811
+ if (req.method === 'GET' && pathname === '/api/doctor/report') {
1812
+ const config = loadConfig();
1813
+ sendJson(res, 200, {
1814
+ ok: true,
1815
+ report: formatRedactedProviderErrorReport({
1816
+ provider: config.provider,
1817
+ model: config.model,
1818
+ causyneVersion: version
1819
+ })
1820
+ });
1821
+ return;
1822
+ }
1823
+
1824
+ if (req.method === 'GET' && pathname === '/api/license/status') {
1825
+ const liveRequested = parsedUrl.searchParams.get('live') === '1';
1826
+ const hasCustomClient = Boolean(options.entitlementClient);
1827
+ if (!LICENSE_ENFORCEMENT_ENABLED && !hasCustomClient && !liveRequested) {
1828
+ sendJson(res, 200, {
1829
+ ok: true,
1830
+ enforcementEnabled: false,
1831
+ entitlement: 'free',
1832
+ plan: 'free',
1833
+ paidUntil: null,
1834
+ dailySeconds: 21_600,
1835
+ remainingSeconds: 21_600,
1836
+ resetsAt: null,
1837
+ recoveryCode: null,
1838
+ supportMessage: DAILY_LIMIT_SUPPORT_MESSAGE
1839
+ });
1840
+ return;
1841
+ }
1842
+ try {
1843
+ const client = options.entitlementClient ?? new EntitlementClient();
1844
+ const data = await client.status();
1845
+ sendJson(res, 200, {
1846
+ ok: true,
1847
+ enforcementEnabled: LICENSE_ENFORCEMENT_ENABLED,
1848
+ entitlement: typeof data?.entitlement === 'string' ? data.entitlement : 'free',
1849
+ plan: typeof data?.plan === 'string' ? data.plan : 'free',
1850
+ status: typeof data?.status === 'string' ? data.status : 'free',
1851
+ paidUntil: typeof data?.paidUntil === 'string' ? data.paidUntil : null,
1852
+ dailySeconds: typeof data?.dailySeconds === 'number' ? data.dailySeconds : null,
1853
+ remainingSeconds: typeof data?.remainingSeconds === 'number' ? data.remainingSeconds : null,
1854
+ resetsAt: typeof data?.resetsAt === 'string' ? data.resetsAt : null,
1855
+ recoveryCode: typeof data?.recoveryCode === 'string' ? data.recoveryCode : null,
1856
+ supportMessage: typeof data?.upgradeMessage === 'string' ? data.upgradeMessage : DAILY_LIMIT_SUPPORT_MESSAGE
1857
+ });
1858
+ } catch (err: unknown) {
1859
+ const msg = err instanceof EntitlementAccessError
1860
+ ? err.message
1861
+ : 'Unable to reach licensing service right now.';
1862
+ sendJson(res, 503, { ok: false, error: msg, enforcementEnabled: LICENSE_ENFORCEMENT_ENABLED });
1863
+ }
1864
+ return;
1865
+ }
1866
+
1867
+ if (req.method === 'POST' && pathname === '/api/license/checkout') {
1868
+ const body = await readJsonBody(req);
1869
+ const plan = typeof body.plan === 'string' ? body.plan.trim() : '';
1870
+ if (!isValidLicensePlan(plan)) {
1871
+ sendJson(res, 400, { error: 'Unknown Causyne plan.' });
1872
+ return;
1873
+ }
1874
+ try {
1875
+ const client = options.entitlementClient ?? new EntitlementClient();
1876
+ const result = await client.checkout(plan);
1877
+ auditLog.log({ event: 'skybridge_license_checkout', plan });
1878
+ sendJson(res, 200, { ok: true, plan, url: result.url });
1879
+ } catch (err: unknown) {
1880
+ const msg = err instanceof EntitlementAccessError
1881
+ ? err.message
1882
+ : 'Unable to start Paddle checkout right now. Visit https://causyne.com/pricing.html.';
1883
+ sendJson(res, 502, { ok: false, error: msg });
1884
+ }
1885
+ return;
1886
+ }
1887
+
1888
+ if (req.method === 'POST' && pathname === '/api/license/recover') {
1889
+ const body = await readJsonBody(req);
1890
+ const code = typeof body.recoveryCode === 'string' ? body.recoveryCode.trim() : '';
1891
+ try {
1892
+ const client = options.entitlementClient ?? new EntitlementClient();
1893
+ const result = await client.recover(code);
1894
+ auditLog.log({ event: 'skybridge_license_recover', ok: true });
1895
+ sendJson(res, 200, {
1896
+ ok: true,
1897
+ entitlement: result?.entitlement ?? 'pro',
1898
+ plan: result?.plan ?? 'monthly',
1899
+ paidUntil: result?.paidUntil ?? null
1900
+ });
1901
+ } catch (err: unknown) {
1902
+ const status = err instanceof EntitlementAccessError && err.code === 'INVALID_RECOVERY_CODE' ? 400 : 404;
1903
+ const msg = err instanceof EntitlementAccessError ? err.message : 'Could not link recovery code.';
1904
+ sendJson(res, status, { ok: false, error: msg });
1905
+ }
1906
+ return;
1907
+ }
1908
+
1909
+ if (req.method === 'POST' && pathname === '/api/license/portal') {
1910
+ try {
1911
+ const client = options.entitlementClient ?? new EntitlementClient();
1912
+ const result = await client.portal();
1913
+ sendJson(res, 200, { ok: true, url: result.url });
1914
+ } catch (err: unknown) {
1915
+ const msg = err instanceof EntitlementAccessError ? err.message : 'Billing portal unavailable.';
1916
+ sendJson(res, 502, { ok: false, error: msg });
1917
+ }
1918
+ return;
1919
+ }
1920
+
1921
+ if (req.method === 'POST' && pathname === '/api/doctor/probe') {
1922
+ const report = await runZeroSpendByokProbe();
1923
+ sendJson(res, 200, {
1924
+ ok: true,
1925
+ report: formatByokProbeReport(report),
1926
+ summary: {
1927
+ testedCount: report.testedCount,
1928
+ passedCount: report.passedCount,
1929
+ failedCount: report.failedCount,
1930
+ skippedCount: report.skippedCount
1931
+ }
1932
+ });
1933
+ return;
1934
+ }
1935
+
1936
+ if (req.method === 'POST' && pathname === '/api/config/key') {
1937
+ const body = await readJsonBody(req);
1938
+ const provider = typeof body.provider === 'string' ? body.provider.trim().toLowerCase() : '';
1939
+ const apiKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : '';
1940
+ const forbidden = new Set(['__proto__', 'constructor', 'prototype']);
1941
+ if (!provider || forbidden.has(provider) || !SAFE_PROVIDER_RE.test(provider)) {
1942
+ sendJson(res, 400, { error: 'Valid provider identifier is required.' });
1943
+ return;
1944
+ }
1945
+ if (!apiKey || apiKey.length < 4 || apiKey.length > 512) {
1946
+ sendJson(res, 400, { error: 'API key must be between 4 and 512 characters.' });
1947
+ return;
1948
+ }
1949
+ const config = loadConfig();
1950
+ const existingKeys = config.providerKeys && typeof config.providerKeys === 'object' && !Array.isArray(config.providerKeys)
1951
+ ? { ...(config.providerKeys as Record<string, string>) }
1952
+ : {};
1953
+ existingKeys[provider] = apiKey;
1954
+ config.providerKeys = existingKeys;
1955
+ if (String(config.provider || '').trim().toLowerCase() === provider || body.activate === true) {
1956
+ applyProviderOverrides(config, provider, typeof body.model === 'string' ? body.model.trim() : undefined);
1957
+ }
1958
+ saveConfig(config);
1959
+ auditLog.log({ event: 'skybridge_vault_key_saved', provider });
1960
+ sendJson(res, 200, {
1961
+ ok: true,
1962
+ provider,
1963
+ configured: true,
1964
+ activeProvider: config.provider || 'unconfigured',
1965
+ activeModel: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || 'default'
1966
+ });
1967
+ return;
1968
+ }
1969
+
1970
+ if (req.method === 'GET' && pathname === '/api/commands') {
1971
+ const commands = listCommands('terminal').map((cmd) => ({
1972
+ name: cmd.name,
1973
+ aliases: cmd.aliases ?? [],
1974
+ usage: cmd.usage,
1975
+ description: cmd.description
1976
+ }));
1977
+ sendJson(res, 200, { ok: true, commands });
1978
+ return;
1979
+ }
1980
+
1981
+ if (req.method === 'POST' && pathname === '/api/command') {
1982
+ const body = await readJsonBody(req);
1983
+ let cmdName = '';
1984
+ let cmdArgv: string[] = [];
1985
+ if (typeof body.input === 'string' && body.input.trim()) {
1986
+ const rawLine = body.input.trim().startsWith('/') ? body.input.trim() : `/${body.input.trim()}`;
1987
+ const parsed = parseCommand(rawLine);
1988
+ if (!parsed) {
1989
+ sendJson(res, 400, { error: 'Invalid CLI slash command syntax.' });
1990
+ return;
1991
+ }
1992
+ cmdName = parsed.name;
1993
+ cmdArgv = parsed.argv;
1994
+ } else if (typeof body.name === 'string' && body.name.trim()) {
1995
+ cmdName = body.name.trim().toLowerCase();
1996
+ cmdArgv = Array.isArray(body.argv) ? body.argv.map((x: unknown) => String(x ?? '')) : [];
1997
+ } else {
1998
+ sendJson(res, 400, { error: 'Command input or name is required.' });
1999
+ return;
2000
+ }
2001
+ if (cmdName === 'exit' || cmdName === 'quit') {
2002
+ sendJson(res, 200, {
2003
+ ok: true,
2004
+ command: cmdName,
2005
+ title: 'Exit',
2006
+ output: 'Press Ctrl+C in the terminal running `causyne web` to stop the local Skybridge server cleanly.'
2007
+ });
2008
+ return;
2009
+ }
2010
+ const prevCwd = process.cwd();
2011
+ let result: Awaited<ReturnType<typeof runCommand>>;
2012
+ try {
2013
+ if (prevCwd !== workspaceRoot) process.chdir(workspaceRoot);
2014
+ result = await runCommand(cmdName, cmdArgv, {
2015
+ surface: 'terminal',
2016
+ workspaceRoot,
2017
+ cwd: workspaceRoot
2018
+ });
2019
+ } finally {
2020
+ try { if (process.cwd() !== prevCwd) process.chdir(prevCwd); } catch { /* ignore */ }
2021
+ }
2022
+ auditLog.log({ event: 'skybridge_cli_command', command: cmdName, ok: Boolean(result.ok) });
2023
+ sendJson(res, 200, {
2024
+ ok: Boolean(result.ok),
2025
+ command: cmdName,
2026
+ title: typeof result.title === 'string' ? result.title : `/${cmdName}`,
2027
+ effect: typeof result.effect === 'string' ? result.effect : null,
2028
+ output: redactProviderSecrets(String(result.output || ''))
2029
+ });
2030
+ return;
2031
+ }
2032
+
2033
+ if (req.method === 'GET' && pathname === '/api/cli/overview') {
2034
+ const checkpoints = listGroups(12).map((g) => ({
2035
+ id: g.taskId,
2036
+ createdAt: g.ts,
2037
+ label: g.prompt || g.taskId,
2038
+ fileCount: Array.isArray(g.fileEntries) ? g.fileEntries.length : 0
2039
+ }));
2040
+ const skills = listCompiledSkills();
2041
+ const mcpServers = serverStatus().map((s) => ({
2042
+ name: s.name,
2043
+ connected: Boolean((s as any).connected),
2044
+ granted: Boolean((s as any).granted),
2045
+ toolsCount: typeof (s as any).toolsCount === 'number' ? (s as any).toolsCount : 0
2046
+ }));
2047
+ const peers = listAllPeers().map((p) => ({
2048
+ name: p.id,
2049
+ label: p.label,
2050
+ command: p.command
2051
+ }));
2052
+ const tasks = backgroundTaskManager.list().slice(0, 20).map((t) => ({
2053
+ id: t.taskId,
2054
+ label: t.label,
2055
+ command: t.command,
2056
+ status: t.status,
2057
+ startedAt: t.startedAt
2058
+ }));
2059
+ let worktrees: Array<{ path: string; branch: string; managed: boolean }> = [];
2060
+ try {
2061
+ worktrees = listWorktrees(workspaceRoot).map((w) => ({
2062
+ path: w.path,
2063
+ branch: w.branch || 'detached',
2064
+ managed: Boolean(w.managed)
2065
+ }));
2066
+ } catch {
2067
+ worktrees = [];
2068
+ }
2069
+ sendJson(res, 200, {
2070
+ ok: true,
2071
+ commandsCount: listCommands('terminal').length,
2072
+ skillsCount: skills.length,
2073
+ checkpoints,
2074
+ mcpServers,
2075
+ peers,
2076
+ tasks,
2077
+ worktrees,
2078
+ browserActive: causyneBrowser({ workspace: workspaceRoot }).isActive(),
2079
+ browserControlOwner
2080
+ });
2081
+ return;
2082
+ }
2083
+
2084
+ if (req.method === 'GET' && pathname === '/api/mcp/browser') {
2085
+ res.statusCode = 405;
2086
+ res.setHeader('Allow', 'POST');
2087
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
2088
+ res.end(JSON.stringify({ error: 'Use POST for Streamable HTTP MCP JSON-RPC requests.' }));
2089
+ return;
2090
+ }
2091
+
2092
+ if (req.method === 'POST' && pathname === '/api/mcp/browser') {
2093
+ const body = await readJsonBody(req) as JsonRpcMessage;
2094
+ const reply = await handleBrowserMcpRpc(body, {
2095
+ workspaceRoot,
2096
+ version,
2097
+ onActivity: (activity) => {
2098
+ if (activity.phase === 'start') {
2099
+ browserControlOwner = 'agent';
2100
+ browserAgentActivity = {
2101
+ active: true,
2102
+ tool: activity.tool,
2103
+ detail: activity.detail,
2104
+ updatedAt: Date.now()
2105
+ };
2106
+ } else {
2107
+ browserAgentActivity = { active: false, tool: '', detail: '', updatedAt: Date.now() };
2108
+ }
2109
+ broadcastBrowserNotice({
2110
+ type: 'agent_activity',
2111
+ controlOwner: browserControlOwner,
2112
+ agentActivity: browserAgentActivity
2113
+ });
2114
+ }
2115
+ });
2116
+ if (reply === null) {
2117
+ res.statusCode = 202;
2118
+ res.end();
2119
+ return;
2120
+ }
2121
+ sendJson(res, 200, reply);
2122
+ return;
2123
+ }
2124
+
2125
+ if (req.method === 'GET' && pathname === '/api/browser/state') {
2126
+ const ensure = parsedUrl.searchParams.get('ensure') === '1';
2127
+ const browser = causyneBrowser({ workspace: workspaceRoot });
2128
+ const frame = await browser.captureLiveFrame({ ensureStarted: ensure });
2129
+ sendJson(res, 200, {
2130
+ ok: true,
2131
+ controlOwner: browserControlOwner,
2132
+ agentActivity: browserAgentActivity,
2133
+ computerUsePolicy: 'tiered-approval',
2134
+ ...frame
2135
+ });
2136
+ return;
2137
+ }
2138
+
2139
+ if (req.method === 'GET' && pathname === '/api/browser/stream') {
2140
+ const browser = causyneBrowser({ workspace: workspaceRoot });
2141
+ res.statusCode = 200;
2142
+ res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
2143
+ res.setHeader('Transfer-Encoding', 'chunked');
2144
+ res.setHeader('X-Accel-Buffering', 'no');
2145
+ const writeStreamLine = (payload: Record<string, unknown>): void => {
2146
+ if (res.writableEnded || res.destroyed) return;
2147
+ try {
2148
+ res.write(`${JSON.stringify(payload)}\n`);
2149
+ } catch {
2150
+ // Stream closed mid-write.
2151
+ }
2152
+ };
2153
+ const unsub = browser.subscribeLiveStream((ev) => {
2154
+ writeStreamLine({
2155
+ ...ev,
2156
+ controlOwner: browserControlOwner,
2157
+ agentActivity: browserAgentActivity,
2158
+ computerUsePolicy: 'tiered-approval'
2159
+ });
2160
+ });
2161
+ browserStreamClients.add(writeStreamLine);
2162
+ writeStreamLine({
2163
+ type: 'agent_activity',
2164
+ controlOwner: browserControlOwner,
2165
+ agentActivity: browserAgentActivity,
2166
+ computerUsePolicy: 'tiered-approval'
2167
+ });
2168
+ const keepAlive = setInterval(() => {
2169
+ writeStreamLine({ type: 'ping', ts: Date.now() });
2170
+ }, 15_000);
2171
+ keepAlive.unref?.();
2172
+ const cleanup = (): void => {
2173
+ clearInterval(keepAlive);
2174
+ browserStreamClients.delete(writeStreamLine);
2175
+ unsub();
2176
+ };
2177
+ req.on('close', cleanup);
2178
+ res.on('close', cleanup);
2179
+ return;
2180
+ }
2181
+
2182
+ if (req.method === 'POST' && pathname === '/api/browser/input') {
2183
+ const body = await readJsonBody(req);
2184
+ const kind = typeof body.kind === 'string' ? body.kind.trim() : '';
2185
+ const allowedKinds = new Set([
2186
+ 'click', 'dblclick', 'contextmenu', 'mousedown', 'mousemove', 'mouseup', 'wheel', 'type', 'key', 'paste'
2187
+ ]);
2188
+ if (!allowedKinds.has(kind)) {
2189
+ sendJson(res, 400, { error: 'Unsupported live browser input kind.' });
2190
+ return;
2191
+ }
2192
+ browserControlOwner = 'human';
2193
+ const browser = causyneBrowser({ workspace: workspaceRoot });
2194
+ const result = await browser.dispatchLiveInput({
2195
+ kind: kind as LiveBrowserInteraction['kind'],
2196
+ x: typeof body.x === 'number' ? body.x : undefined,
2197
+ y: typeof body.y === 'number' ? body.y : undefined,
2198
+ deltaX: typeof body.deltaX === 'number' ? body.deltaX : undefined,
2199
+ deltaY: typeof body.deltaY === 'number' ? body.deltaY : undefined,
2200
+ text: typeof body.text === 'string' ? body.text : undefined,
2201
+ key: typeof body.key === 'string' ? body.key : undefined,
2202
+ button: body.button === 'right' || body.button === 'middle' ? body.button : 'left',
2203
+ skipFrame: true
2204
+ });
2205
+ sendJson(res, 200, { ok: result.ok, controlOwner: browserControlOwner });
2206
+ return;
2207
+ }
2208
+
2209
+ if (req.method === 'POST' && pathname === '/api/browser/action') {
2210
+ const body = await readJsonBody(req);
2211
+ const action = typeof body.action === 'string' ? body.action.trim() : '';
2212
+ const browser = causyneBrowser({ workspace: workspaceRoot });
2213
+
2214
+ if (action === 'setMode') {
2215
+ browserControlOwner = 'human';
2216
+ const rawPref = typeof body.enginePreference === 'string' ? body.enginePreference.trim() : '';
2217
+ const enginePreference: BrowserEnginePreference | undefined = rawPref === 'camoufox'
2218
+ || rawPref === 'chromium'
2219
+ || rawPref === 'auto'
2220
+ ? rawPref
2221
+ : undefined;
2222
+ const frame = await browser.setDisplayMode({
2223
+ visible: typeof body.visible === 'boolean' ? body.visible : undefined,
2224
+ enginePreference,
2225
+ ensureStarted: body.ensureStarted === true
2226
+ });
2227
+ auditLog.log({
2228
+ event: 'skybridge_browser_mode_switch',
2229
+ visible: frame.visible,
2230
+ engine: frame.engine,
2231
+ enginePreference: frame.enginePreference
2232
+ });
2233
+ broadcastBrowserNotice({
2234
+ type: 'meta',
2235
+ controlOwner: browserControlOwner,
2236
+ agentActivity: browserAgentActivity,
2237
+ ...frame
2238
+ });
2239
+ sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, agentActivity: browserAgentActivity, ...frame });
2240
+ return;
2241
+ }
2242
+ if (action === 'takeControl') {
2243
+ browserControlOwner = 'human';
2244
+ browserAgentActivity = { active: false, tool: '', detail: '', updatedAt: Date.now() };
2245
+ const frame = await browser.captureLiveFrame({ ensureStarted: false });
2246
+ broadcastBrowserNotice({ type: 'agent_activity', controlOwner: browserControlOwner, agentActivity: browserAgentActivity });
2247
+ sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, agentActivity: browserAgentActivity, ...frame });
2248
+ return;
2249
+ }
2250
+ if (action === 'handToAgent') {
2251
+ browserControlOwner = 'agent';
2252
+ const frame = await browser.captureLiveFrame({ ensureStarted: false });
2253
+ broadcastBrowserNotice({ type: 'agent_activity', controlOwner: browserControlOwner, agentActivity: browserAgentActivity });
2254
+ sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, agentActivity: browserAgentActivity, ...frame });
2255
+ return;
2256
+ }
2257
+ if (action === 'start') {
2258
+ browserControlOwner = 'human';
2259
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
2260
+ sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
2261
+ return;
2262
+ }
2263
+ if (action === 'close') {
2264
+ await browser.close();
2265
+ const frame = await browser.captureLiveFrame({ ensureStarted: false });
2266
+ sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
2267
+ return;
2268
+ }
2269
+ if (action === 'goto' || action === 'newTab') {
2270
+ browserControlOwner = 'human';
2271
+ let rawUrl = typeof body.url === 'string' ? body.url.trim() : '';
2272
+ if (rawUrl.startsWith('@')) {
2273
+ const idx = rawUrl.indexOf(' ');
2274
+ const macro = idx === -1 ? rawUrl : rawUrl.slice(0, idx);
2275
+ const q = idx === -1 ? '' : rawUrl.slice(idx + 1).trim();
2276
+ const expanded = expandSearchMacro(macro, q);
2277
+ if (!expanded) {
2278
+ sendJson(res, 400, { error: 'Unsupported browser search macro.' });
2279
+ return;
2280
+ }
2281
+ rawUrl = expanded;
2282
+ } else if (rawUrl && !/^https?:\/\//i.test(rawUrl)) {
2283
+ rawUrl = rawUrl.includes('.') || rawUrl.startsWith('localhost')
2284
+ ? `https://${rawUrl}`
2285
+ : (expandSearchMacro('@duckduckgo_search', rawUrl) || `https://duckduckgo.com/?q=${encodeURIComponent(rawUrl)}`);
2286
+ }
2287
+ await browser.run(
2288
+ [action === 'newTab' ? { type: 'newTab', ...(rawUrl ? { url: rawUrl } : {}) } : { type: 'goto', url: rawUrl || 'about:blank' }],
2289
+ { workspace: workspaceRoot }
2290
+ );
2291
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
2292
+ sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
2293
+ return;
2294
+ }
2295
+ if (action === 'back' || action === 'forward' || action === 'reload') {
2296
+ browserControlOwner = 'human';
2297
+ await browser.run([{ type: action }], { workspace: workspaceRoot });
2298
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
2299
+ sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
2300
+ return;
2301
+ }
2302
+ if ((action === 'switchTab' || action === 'closeTab') && typeof body.tabId === 'string' && body.tabId.trim()) {
2303
+ browserControlOwner = 'human';
2304
+ await browser.run([{ type: action, tabId: body.tabId.trim() }], { workspace: workspaceRoot });
2305
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
2306
+ sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
2307
+ return;
2308
+ }
2309
+ if (action === 'viewport') {
2310
+ const width = Math.max(320, Math.min(1920, Number(body.width) || 1280));
2311
+ const height = Math.max(480, Math.min(1200, Number(body.height) || 800));
2312
+ await browser.run([{ type: 'viewport', width, height }], { workspace: workspaceRoot });
2313
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
2314
+ sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
2315
+ return;
2316
+ }
2317
+ if (action === 'snapshot') {
2318
+ const snap = await browser.snapshot(0);
2319
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
2320
+ sendJson(res, 200, {
2321
+ ok: true,
2322
+ controlOwner: browserControlOwner,
2323
+ snapshot: snap.text,
2324
+ refsCount: snap.refsCount,
2325
+ ...frame
2326
+ });
2327
+ return;
2328
+ }
2329
+ if (
2330
+ action === 'click'
2331
+ || action === 'dblclick'
2332
+ || action === 'contextmenu'
2333
+ || action === 'mousedown'
2334
+ || action === 'mousemove'
2335
+ || action === 'mouseup'
2336
+ || action === 'wheel'
2337
+ || action === 'type'
2338
+ || action === 'key'
2339
+ || action === 'paste'
2340
+ ) {
2341
+ browserControlOwner = 'human';
2342
+ const frame = await browser.interactAt({
2343
+ kind: action,
2344
+ x: typeof body.x === 'number' ? body.x : undefined,
2345
+ y: typeof body.y === 'number' ? body.y : undefined,
2346
+ deltaX: typeof body.deltaX === 'number' ? body.deltaX : undefined,
2347
+ deltaY: typeof body.deltaY === 'number' ? body.deltaY : undefined,
2348
+ text: typeof body.text === 'string' ? body.text : undefined,
2349
+ key: typeof body.key === 'string' ? body.key : undefined,
2350
+ button: body.button === 'right' || body.button === 'middle' ? body.button : 'left'
2351
+ });
2352
+ sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, agentActivity: browserAgentActivity, ...frame });
2353
+ return;
2354
+ }
2355
+ sendJson(res, 400, { error: 'Unsupported shared browser action.' });
2356
+ return;
2357
+ }
2358
+
2359
+ if (req.method === 'GET' && pathname === '/api/browser/cdp/tabs') {
2360
+ const portParam = parsedUrl.searchParams.get('port') || '9222';
2361
+ const discovered = await discoverLocalCdpTabs(portParam);
2362
+ sendJson(res, 200, {
2363
+ ok: true,
2364
+ port: discovered.port,
2365
+ tabs: discovered.tabs.map((t) => ({ id: t.id, title: t.title, url: t.url }))
2366
+ });
2367
+ return;
2368
+ }
2369
+
2370
+ if (req.method === 'POST' && pathname === '/api/browser/cdp/sync') {
2371
+ const body = await readJsonBody(req);
2372
+ const targetId = typeof body.targetId === 'string' ? body.targetId.trim() : '';
2373
+ if (!targetId) {
2374
+ sendJson(res, 400, { error: 'targetId is required to sync a local browser tab.' });
2375
+ return;
2376
+ }
2377
+ const synced = await syncLocalCdpTabToCausyne({
2378
+ workspaceRoot,
2379
+ port: body.port ?? 9222,
2380
+ targetId,
2381
+ includeCookies: body.includeCookies === true
2382
+ });
2383
+ browserControlOwner = 'human';
2384
+ auditLog.log({
2385
+ event: 'skybridge_browser_cdp_sync',
2386
+ importedCookies: synced.importedCookies
2387
+ });
2388
+ sendJson(res, 200, {
2389
+ ok: true,
2390
+ controlOwner: browserControlOwner,
2391
+ syncedUrl: synced.syncedUrl,
2392
+ importedCookies: synced.importedCookies,
2393
+ ...synced.frame
2394
+ });
2395
+ return;
2396
+ }
2397
+
2398
+ if (req.method === 'POST' && pathname === '/api/browser/import') {
2399
+ const body = await readJsonBody(req);
2400
+ const rawText = typeof body.rawText === 'string' ? body.rawText : '';
2401
+ const summary = await importExplicitUserBrowserData({
2402
+ workspaceRoot,
2403
+ rawText,
2404
+ openFirstUrl: body.openFirstUrl !== false
2405
+ });
2406
+ const frame = await causyneBrowser({ workspace: workspaceRoot }).captureLiveFrame({ ensureStarted: false });
2407
+ auditLog.log({
2408
+ event: 'skybridge_browser_import',
2409
+ importedCookies: summary.importedCookies,
2410
+ urlsCount: summary.importedUrls.length
2411
+ });
2412
+ sendJson(res, 200, {
2413
+ ok: true,
2414
+ controlOwner: browserControlOwner,
2415
+ ...summary,
2416
+ ...frame
2417
+ });
2418
+ return;
2419
+ }
2420
+
2421
+ if (req.method === 'POST' && pathname === '/api/approve') {
2422
+ const body = await readJsonBody(req);
2423
+ const toolCallId = typeof body.toolCallId === 'string' ? body.toolCallId.trim() : '';
2424
+ const sessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
2425
+ ? body.sessionId.trim()
2426
+ : '';
2427
+ const approved = body.approved === true;
2428
+ const remember = body.remember === true;
2429
+ const toolName = typeof body.tool === 'string' ? body.tool.trim().slice(0, 80) : '';
2430
+ const targetRun = findActiveRun(sessionId || null);
2431
+ if (!toolCallId || !targetRun?.loop.resolveApproval) {
2432
+ sendJson(res, 400, { error: 'No active pending approval matches that toolCallId.' });
2433
+ return;
2434
+ }
2435
+ if (approved && remember && toolName && targetRun.loop.grantAlways) {
2436
+ targetRun.loop.grantAlways(toolName);
2437
+ auditLog.log({ event: 'skybridge_approval_grant_always', tool: toolName });
2438
+ }
2439
+ targetRun.status = 'running';
2440
+ targetRun.loop.resolveApproval(toolCallId, approved);
2441
+ sendJson(res, 200, { ok: true, toolCallId, approved, remembered: Boolean(approved && remember && toolName) });
2442
+ return;
2443
+ }
2444
+
2445
+ if (req.method === 'POST' && pathname === '/api/decision') {
2446
+ const body = await readJsonBody(req);
2447
+ const requestId = typeof body.requestId === 'string' ? body.requestId.trim() : '';
2448
+ const sessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
2449
+ ? body.sessionId.trim()
2450
+ : '';
2451
+ const label = typeof body.label === 'string' ? body.label.trim().slice(0, 400) : '';
2452
+ const optionId = typeof body.optionId === 'string' ? body.optionId.trim().slice(0, 120) : null;
2453
+ const custom = body.custom === true;
2454
+ const targetRun = findActiveRun(sessionId || null);
2455
+ if (!requestId || !targetRun?.loop.resolveDecision) {
2456
+ sendJson(res, 400, { error: 'No active pending decision matches that requestId.' });
2457
+ return;
2458
+ }
2459
+ targetRun.status = 'running';
2460
+ targetRun.loop.resolveDecision(requestId, label ? { optionId, label, custom } : null);
2461
+ sendJson(res, 200, { ok: true, requestId, label });
2462
+ return;
2463
+ }
2464
+
2465
+ if (req.method === 'POST' && pathname === '/api/stop') {
2466
+ let stopSessionId = '';
2467
+ try {
2468
+ const body = await readJsonBody(req);
2469
+ if (typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())) {
2470
+ stopSessionId = body.sessionId.trim();
2471
+ }
2472
+ } catch {
2473
+ // Empty body is valid for /api/stop.
2474
+ }
2475
+ if (stopSessionId) {
2476
+ const run = activeRuns.get(stopSessionId);
2477
+ if (run) {
2478
+ run.userStopped = true;
2479
+ run.loop.abort?.();
2480
+ }
2481
+ } else {
2482
+ for (const run of activeRuns.values()) {
2483
+ run.userStopped = true;
2484
+ run.loop.abort?.();
2485
+ }
2486
+ }
2487
+ sendJson(res, 200, { ok: true });
2488
+ return;
2489
+ }
2490
+
2491
+ if (req.method === 'POST' && pathname === '/api/chat') {
2492
+ const body = await readJsonBody(req);
2493
+ const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';
2494
+ const rawMode = typeof body.mode === 'string' ? body.mode.trim().toUpperCase() : 'B';
2495
+ const mode = rawMode === 'A' || rawMode === 'B' || rawMode === 'C' ? rawMode : 'B';
2496
+ const requestedSessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
2497
+ ? body.sessionId.trim()
2498
+ : '';
2499
+ const providerOverride = typeof body.provider === 'string' && SAFE_PROVIDER_RE.test(body.provider.trim())
2500
+ ? body.provider.trim()
2501
+ : undefined;
2502
+ const modelOverride = typeof body.model === 'string' && SAFE_MODEL_RE.test(body.model.trim())
2503
+ ? body.model.trim()
2504
+ : undefined;
2505
+ if (!prompt) {
2506
+ sendJson(res, 400, { error: 'Prompt text is required.' });
2507
+ return;
2508
+ }
2509
+
2510
+ let boundSession = requestedSessionId ? getSession(requestedSessionId) : null;
2511
+ if (boundSession && !workspaceMatchesSession(boundSession.workspace, workspaceRoot)) {
2512
+ boundSession = null;
2513
+ }
2514
+ if (!boundSession && !hasCustomFactory) {
2515
+ boundSession = createSession(workspaceRoot, prompt.slice(0, 60), false);
2516
+ }
2517
+
2518
+ const runKey = boundSession?.id || '__ephemeral__';
2519
+ const existingRun = activeRuns.get(runKey);
2520
+ if (existingRun && (existingRun.status === 'running' || existingRun.status === 'awaiting_client')) {
2521
+ sendJson(res, 409, {
2522
+ error: 'This conversation already has a task running. Stop it or wait for completion.'
2523
+ });
2524
+ return;
2525
+ }
2526
+
2527
+ const { effectivePrompt, attachedPaths } = buildWorkspacePromptWithAttachments(
2528
+ workspaceRoot,
2529
+ prompt,
2530
+ body.attachments
2531
+ );
2532
+
2533
+ const taskId = `web-${++taskCounter}-${Date.now()}`;
2534
+ let collectedAssistantText = '';
2535
+ let runRef: SessionActiveRun | null = null;
2536
+
2537
+ const emitFrame = (raw: string): void => {
2538
+ const clean = raw.replace(/\r?\n/g, ' ');
2539
+ try {
2540
+ const parsed = JSON.parse(clean) as {
2541
+ type?: string;
2542
+ delta?: string;
2543
+ content?: string;
2544
+ tool?: string;
2545
+ actionName?: string;
2546
+ detail?: string;
2547
+ path?: string;
2548
+ args?: Record<string, unknown>;
2549
+ };
2550
+ if (parsed.type === 'agent_chunk' && typeof parsed.delta === 'string') {
2551
+ collectedAssistantText += parsed.delta;
2552
+ } else if (parsed.type === 'agent_message' && typeof parsed.content === 'string' && !collectedAssistantText) {
2553
+ collectedAssistantText = parsed.content;
2554
+ }
2555
+ if (runRef && (parsed.type === 'approval_request' || parsed.type === 'decision_request')) {
2556
+ runRef.status = 'awaiting_client';
2557
+ }
2558
+ const toolLower = typeof parsed.tool === 'string' ? parsed.tool.toLowerCase() : '';
2559
+ const actionLower = typeof parsed.actionName === 'string' ? parsed.actionName.toLowerCase() : '';
2560
+ if (boundSession?.id) {
2561
+ if (parsed.type === 'code_progress' && typeof parsed.path === 'string') {
2562
+ recordSessionTouchedFile(boundSession.id, parsed.path);
2563
+ } else if (
2564
+ (parsed.type === 'step_complete' || parsed.type === 'tool_result')
2565
+ && MUTATING_FILE_TOOLS.has(toolLower)
2566
+ && parsed.args
2567
+ ) {
2568
+ for (const key of ['path', 'filePath', 'file_path', 'targetFile', 'filename', 'file', 'destination']) {
2569
+ recordSessionTouchedFile(boundSession.id, parsed.args[key]);
2570
+ }
2571
+ } else if (parsed.type === 'notice' && MUTATING_FILE_TOOLS.has(actionLower) && parsed.detail) {
2572
+ recordSessionTouchedFile(boundSession.id, parsed.detail);
2573
+ }
2574
+ }
2575
+ const isBrowserTool = toolLower.includes('browser');
2576
+ const isComputerTool = toolLower.includes('computer_use') || toolLower.includes('desktop_act');
2577
+ if ((parsed.type === 'step_start' || parsed.type === 'tool_start') && (isBrowserTool || isComputerTool)) {
2578
+ if (isBrowserTool) browserControlOwner = 'agent';
2579
+ const detail = isBrowserTool && Array.isArray(parsed.args?.actions) && parsed.args.actions[0]
2580
+ ? String((parsed.args.actions[0] as Record<string, unknown>).type || 'browser.act')
2581
+ : String(parsed.args?.action || parsed.tool || '');
2582
+ browserAgentActivity = {
2583
+ active: true,
2584
+ tool: parsed.tool || 'browser.act',
2585
+ detail: detail.slice(0, 80),
2586
+ updatedAt: Date.now()
2587
+ };
2588
+ broadcastBrowserNotice({
2589
+ type: 'agent_activity',
2590
+ controlOwner: browserControlOwner,
2591
+ agentActivity: browserAgentActivity
2592
+ });
2593
+ } else if ((parsed.type === 'step_complete' || parsed.type === 'step_error' || parsed.type === 'tool_complete')
2594
+ && (isBrowserTool || isComputerTool)) {
2595
+ browserAgentActivity = { active: false, tool: '', detail: '', updatedAt: Date.now() };
2596
+ broadcastBrowserNotice({
2597
+ type: 'agent_activity',
2598
+ controlOwner: browserControlOwner,
2599
+ agentActivity: browserAgentActivity
2600
+ });
2601
+ }
2602
+ } catch {
2603
+ // pass raw frame through untouched
2604
+ }
2605
+ if (runRef) pushRunFrame(runRef, clean);
2606
+ };
2607
+
2608
+ const wrappedSink = { readyState: 1, send: emitFrame };
2609
+ const loop = loopFactory(wrappedSink, taskId, effectivePrompt, {
2610
+ workspaceRoot,
2611
+ mode,
2612
+ sessionId: boundSession?.id,
2613
+ provider: providerOverride,
2614
+ model: modelOverride
2615
+ });
2616
+
2617
+ const run: SessionActiveRun = {
2618
+ key: runKey,
2619
+ sessionId: boundSession?.id || null,
2620
+ taskId,
2621
+ prompt,
2622
+ startedAt: Date.now(),
2623
+ status: 'running',
2624
+ userStopped: false,
2625
+ loop,
2626
+ frames: [],
2627
+ bufferedBytes: 0,
2628
+ subscribers: new Set(),
2629
+ doneSubscribers: new Set()
2630
+ };
2631
+ runRef = run;
2632
+ activeRuns.set(runKey, run);
2633
+
2634
+ if (boundSession) {
2635
+ pushRunFrame(run, JSON.stringify({
2636
+ type: 'session_bound',
2637
+ sessionId: boundSession.id,
2638
+ title: boundSession.title,
2639
+ attachments: attachedPaths
2640
+ }));
2641
+ }
2642
+
2643
+ // Attach current HTTP response BEFORE starting loop; detaching later never aborts loop.
2644
+ attachRunStream(req, res, run, true);
2645
+
2646
+ void (async () => {
2647
+ try {
2648
+ await loop.run();
2649
+ if (boundSession && hasCustomFactory && collectedAssistantText.trim()) {
2650
+ const latest = getSession(boundSession.id);
2651
+ if (latest) {
2652
+ const nextMessages: SessionMessage[] = [
2653
+ ...latest.messages,
2654
+ { role: 'user', content: prompt },
2655
+ { role: 'assistant', content: collectedAssistantText.trim() }
2656
+ ];
2657
+ saveSessionMessages(boundSession.id, nextMessages);
2658
+ }
2659
+ }
2660
+ const refreshed = boundSession ? getSession(boundSession.id) : null;
2661
+ if (run.userStopped) {
2662
+ run.status = 'stopped';
2663
+ pushRunFrame(run, JSON.stringify({
2664
+ type: 'stopped',
2665
+ taskId,
2666
+ sessionId: boundSession?.id || null,
2667
+ title: refreshed?.title || boundSession?.title || null,
2668
+ userStopped: true
2669
+ }));
2670
+ } else {
2671
+ run.status = 'completed';
2672
+ pushRunFrame(run, JSON.stringify({
2673
+ type: 'done',
2674
+ taskId,
2675
+ sessionId: boundSession?.id || null,
2676
+ title: refreshed?.title || boundSession?.title || null
2677
+ }));
2678
+ }
2679
+ } catch (err: unknown) {
2680
+ run.status = run.userStopped ? 'stopped' : 'errored';
2681
+ if (run.userStopped) {
2682
+ pushRunFrame(run, JSON.stringify({
2683
+ type: 'stopped',
2684
+ taskId,
2685
+ sessionId: boundSession?.id || null,
2686
+ userStopped: true
2687
+ }));
2688
+ } else if (err instanceof EntitlementAccessError && err.code === 'DAILY_LIMIT_REACHED') {
2689
+ pushRunFrame(run, JSON.stringify({
2690
+ type: 'error',
2691
+ code: 'DAILY_LIMIT_REACHED',
2692
+ message: err.message || DAILY_LIMIT_SUPPORT_MESSAGE
2693
+ }));
2694
+ } else {
2695
+ auditLog.log({
2696
+ event: 'skybridge_chat_error',
2697
+ taskId,
2698
+ detail: redactProviderSecrets(err instanceof Error ? err.message : String(err)).slice(0, 300)
2699
+ });
2700
+ pushRunFrame(run, JSON.stringify({
2701
+ type: 'error',
2702
+ message: 'Task failed. Inspect local audit log or run `/doctor --report` for sanitized details.'
2703
+ }));
2704
+ }
2705
+ } finally {
2706
+ for (const doneCb of [...run.doneSubscribers]) {
2707
+ try { doneCb(); } catch { /* ignore */ }
2708
+ }
2709
+ run.subscribers.clear();
2710
+ run.doneSubscribers.clear();
2711
+ if (activeRuns.get(runKey) === run) {
2712
+ activeRuns.delete(runKey);
2713
+ }
2714
+ }
2715
+ })();
2716
+ return;
2717
+ }
2718
+
2719
+ sendJson(res, 404, { error: 'Unknown Skybridge API endpoint.' });
2720
+ } catch (err: unknown) {
2721
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String((err as any).code) : '';
2722
+ const status = code === 'ENOENT' ? 404 : 400;
2723
+ auditLog.log({
2724
+ event: 'skybridge_request_error',
2725
+ path: pathname,
2726
+ status,
2727
+ detail: redactProviderSecrets(err instanceof Error ? err.message : String(err)).slice(0, 300)
2728
+ });
2729
+ const safeError = status === 404
2730
+ ? 'Requested workspace resource was not found.'
2731
+ : 'Skybridge request could not be processed.';
2732
+ if (!res.headersSent) sendJson(res, status, { error: safeError });
2733
+ else if (!res.writableEnded) res.end();
2734
+ }
2735
+ });
2736
+
2737
+ // Disable Node's default 5-minute requestTimeout so long AgentLoop runs never drop mid-stream.
2738
+ server.requestTimeout = 0;
2739
+ server.timeout = 0;
2740
+ server.headersTimeout = 60_000;
2741
+ server.keepAliveTimeout = 65_000;
2742
+
2743
+ await new Promise<void>((resolve, reject) => {
2744
+ server.once('error', reject);
2745
+ server.listen(requestedPort, '127.0.0.1', () => {
2746
+ server.off('error', reject);
2747
+ const addr = server.address() as AddressInfo | null;
2748
+ boundPort = addr?.port ?? requestedPort;
2749
+ resolve();
2750
+ });
2751
+ });
2752
+
2753
+ const origin = `http://127.0.0.1:${boundPort}`;
2754
+ const url = `${origin}/#token=${token}`;
2755
+ auditLog.log({ event: 'skybridge_started', port: boundPort, workspaceRoot });
2756
+
2757
+ return {
2758
+ url,
2759
+ origin,
2760
+ port: boundPort,
2761
+ token,
2762
+ workspaceRoot,
2763
+ close: async () => {
2764
+ for (const run of activeRuns.values()) {
2765
+ run.userStopped = true;
2766
+ run.loop.abort?.();
2767
+ for (const doneCb of [...run.doneSubscribers]) {
2768
+ try { doneCb(); } catch { /* ignore */ }
2769
+ }
2770
+ }
2771
+ activeRuns.clear();
2772
+ await Promise.race([
2773
+ Promise.allSettled([
2774
+ Promise.resolve().then(() => closeAllMcpServers()),
2775
+ Promise.resolve().then(() => lspSessionManager.shutdownAll()),
2776
+ Promise.resolve().then(() => backgroundTaskManager.stopAll())
2777
+ ]),
2778
+ new Promise<void>((resolve) => {
2779
+ const timer = setTimeout(resolve, 2500);
2780
+ timer.unref?.();
2781
+ })
2782
+ ]);
2783
+ server.closeAllConnections?.();
2784
+ await new Promise<void>((resolve) => server.close(() => resolve()));
2785
+ }
2786
+ };
2787
+ }