@causyne/agent 1.20.122 → 1.20.124

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (518) hide show
  1. package/bin/causyne.js +38 -15
  2. package/docs/SECURITY_REVIEW.md +42 -6
  3. package/package.json +5 -5
  4. package/src/acp/agentCatalog.js +74 -50
  5. package/src/acp/agentCatalog.ts +82 -49
  6. package/src/acp/client.js +309 -86
  7. package/src/acp/client.ts +291 -84
  8. package/src/acp/protocol.js +147 -3
  9. package/src/acp/protocol.ts +162 -3
  10. package/src/acp/server.js +138 -39
  11. package/src/acp/server.ts +122 -41
  12. package/src/agent/errorClassifier.js +42 -6
  13. package/src/agent/errorClassifier.ts +44 -5
  14. package/src/agent/providerFailure.js +1 -1
  15. package/src/agent/providerFailure.ts +7 -1
  16. package/src/agent/toolArgValidator.js +38 -4
  17. package/src/agent/toolArgValidator.ts +39 -4
  18. package/src/agent/toolTurnIntegrity.js +28 -7
  19. package/src/agent/toolTurnIntegrity.ts +25 -6
  20. package/src/agent/workspaceBoundary.js +30 -4
  21. package/src/agent/workspaceBoundary.ts +32 -4
  22. package/src/agentLoop.js +598 -217
  23. package/src/agentLoop.ts +621 -215
  24. package/src/approvalPolicy.js +28 -1
  25. package/src/approvalPolicy.ts +28 -1
  26. package/src/auditLog.js +641 -48
  27. package/src/auditLog.ts +661 -0
  28. package/src/autoUpdate.js +32 -5
  29. package/src/autoUpdate.ts +27 -5
  30. package/src/backgroundTasks.js +328 -0
  31. package/src/backgroundTasks.ts +339 -0
  32. package/src/benchmarks/codingEval.js +558 -0
  33. package/src/benchmarks/codingEval.ts +628 -0
  34. package/src/benchmarks/planCache.js +115 -134
  35. package/src/benchmarks/planCache.ts +163 -0
  36. package/src/browser/browserRuntime.js +52 -0
  37. package/src/browser/browserRuntime.ts +55 -0
  38. package/src/browser/causyneBrowser.js +884 -10
  39. package/src/browser/causyneBrowser.ts +1042 -32
  40. package/src/browser/searchProviders.js +94 -6
  41. package/src/browser/searchProviders.ts +89 -6
  42. package/src/browser/urlPolicy.js +8 -1
  43. package/src/browser/urlPolicy.ts +7 -1
  44. package/src/browser/workspacePathSafety.js +6 -4
  45. package/src/browser/workspacePathSafety.ts +7 -4
  46. package/src/capabilities.js +18 -17
  47. package/src/capabilities.ts +38 -0
  48. package/src/checkpoints.js +1241 -1127
  49. package/src/checkpoints.ts +1377 -0
  50. package/src/cliMode.js +707 -755
  51. package/src/cliMode.ts +780 -0
  52. package/src/codebase/repoMap.js +656 -0
  53. package/src/codebase/repoMap.ts +664 -0
  54. package/src/commands.js +3651 -2514
  55. package/src/commands.ts +3985 -0
  56. package/src/compiledSkills.js +8052 -8054
  57. package/src/compiledSkills.ts +8078 -0
  58. package/src/config.js +103 -1
  59. package/src/config.ts +110 -1
  60. package/src/configVault.js +29 -2
  61. package/src/configVault.ts +26 -2
  62. package/src/contextManager.js +473 -557
  63. package/src/contextManager.ts +599 -0
  64. package/src/continuum/adapters/antigravity.js +8 -3
  65. package/src/continuum/adapters/antigravity.ts +8 -3
  66. package/src/continuum/sanitizer.js +23 -1
  67. package/src/continuum/sanitizer.ts +23 -1
  68. package/src/continuum/ui/continuumPicker.js +0 -2
  69. package/src/continuum/ui/continuumPicker.ts +0 -2
  70. package/src/continuum/ui/continuumPickerView.js +0 -2
  71. package/src/continuum/ui/continuumPickerView.ts +4 -20
  72. package/src/core/contextCompactor.js +88 -7
  73. package/src/core/contextCompactor.ts +87 -8
  74. package/src/creative/liveBridge.js +3 -2
  75. package/src/creative/liveBridge.ts +4 -2
  76. package/src/creative/studioScripts.js +1 -1
  77. package/src/creative/studioScripts.ts +1 -1
  78. package/src/decideTools.js +7 -2
  79. package/src/decideTools.ts +7 -2
  80. package/src/decisionPolicy.js +10 -2
  81. package/src/decisionPolicy.ts +10 -2
  82. package/src/designPalettes.js +72 -84
  83. package/src/designPalettes.ts +111 -0
  84. package/src/devMode.js +2 -2
  85. package/src/devMode.ts +6 -0
  86. package/src/diffReview.js +370 -0
  87. package/src/diffReview.ts +407 -0
  88. package/src/dynamicCatalogue.js +311 -11
  89. package/src/dynamicCatalogue.ts +331 -11
  90. package/src/embodimentSession.js +143 -154
  91. package/src/embodimentSession.ts +173 -0
  92. package/src/engines/installer.js +60 -29
  93. package/src/engines/installer.ts +73 -22
  94. package/src/enterprisePolicy.js +660 -0
  95. package/src/enterprisePolicy.ts +728 -0
  96. package/src/entrypoint.js +514 -268
  97. package/src/entrypoint.ts +607 -0
  98. package/src/gitSnapshot.js +417 -312
  99. package/src/gitSnapshot.ts +500 -0
  100. package/src/headlessCli.js +324 -13
  101. package/src/headlessCli.ts +321 -12
  102. package/src/hooks.js +247 -26
  103. package/src/hooks.ts +236 -26
  104. package/src/ignoreRules.js +297 -0
  105. package/src/ignoreRules.ts +308 -0
  106. package/src/implementationPlan.js +7 -6
  107. package/src/implementationPlan.ts +8 -6
  108. package/src/infra/atomicWriter.js +92 -19
  109. package/src/infra/atomicWriter.ts +108 -19
  110. package/src/launchIntent.js +13 -2
  111. package/src/launchIntent.ts +13 -2
  112. package/src/licensing/entitlements.js +553 -237
  113. package/src/licensing/entitlements.ts +590 -0
  114. package/src/licensing/policy.js +17 -1
  115. package/src/licensing/policy.ts +31 -0
  116. package/src/lsp/lspCatalog.js +398 -0
  117. package/src/lsp/lspCatalog.ts +452 -0
  118. package/src/lsp/lspClient.js +699 -0
  119. package/src/lsp/lspClient.ts +799 -0
  120. package/src/lsp/lspProtocol.js +121 -0
  121. package/src/lsp/lspProtocol.ts +140 -0
  122. package/src/mcp/mcpClient.js +69 -8
  123. package/src/mcp/mcpClient.ts +66 -9
  124. package/src/mcp/mcpRegistry.js +180 -7
  125. package/src/mcp/mcpRegistry.ts +171 -7
  126. package/src/mcp/mcpSecurity.js +6 -7
  127. package/src/mcp/mcpSecurity.ts +7 -6
  128. package/src/memory/episodicStore.js +2 -5
  129. package/src/memory/episodicStore.ts +2 -5
  130. package/src/memory.js +80 -32
  131. package/src/memory.ts +111 -0
  132. package/src/memoryManager.js +151 -143
  133. package/src/memoryManager.ts +182 -0
  134. package/src/modelCatalogue.js +172 -195
  135. package/src/modelCatalogue.ts +201 -0
  136. package/src/modelIds.js +8 -27
  137. package/src/modelIds.ts +33 -0
  138. package/src/modelVariants.js +600 -0
  139. package/src/modelVariants.ts +663 -0
  140. package/src/observer/evidence.js +5 -1
  141. package/src/observer/evidence.ts +5 -1
  142. package/src/osKeychain.js +17 -9
  143. package/src/osKeychain.ts +14 -9
  144. package/src/outputStore.js +210 -156
  145. package/src/outputStore.ts +321 -0
  146. package/src/planCache.js +3 -6
  147. package/src/planCache.ts +3 -6
  148. package/src/plugins/pluginManager.js +689 -461
  149. package/src/plugins/pluginManager.ts +807 -0
  150. package/src/plugins/pluginRunner.js +82 -37
  151. package/src/plugins/pluginRunner.ts +98 -0
  152. package/src/plugins/pluginSkills.js +47 -9
  153. package/src/plugins/pluginSkills.ts +46 -8
  154. package/src/pluginsFactory/discovery.js +0 -1
  155. package/src/pluginsFactory/discovery.ts +0 -1
  156. package/src/pluginsFactory/templates.js +17 -4
  157. package/src/pluginsFactory/templates.ts +17 -4
  158. package/src/prWorkflow.js +337 -0
  159. package/src/prWorkflow.ts +376 -0
  160. package/src/procSignal.js +1 -2
  161. package/src/procSignal.ts +1 -3
  162. package/src/projectInstructions.js +319 -0
  163. package/src/projectInstructions.ts +361 -0
  164. package/src/providers/acp.js +234 -49
  165. package/src/providers/acp.ts +240 -50
  166. package/src/providers/anthropic.js +152 -47
  167. package/src/providers/anthropic.ts +152 -45
  168. package/src/providers/antigravity.js +565 -354
  169. package/src/providers/antigravity.ts +555 -355
  170. package/src/providers/base.js +9 -2
  171. package/src/providers/base.ts +10 -2
  172. package/src/providers/byokHttp.js +127 -17
  173. package/src/providers/byokHttp.ts +175 -18
  174. package/src/providers/byokStream.js +162 -36
  175. package/src/providers/byokStream.ts +162 -55
  176. package/src/providers/dashscope-byok.js +29 -3
  177. package/src/providers/dashscope-byok.ts +30 -2
  178. package/src/providers/deepseek.js +12 -3
  179. package/src/providers/deepseek.ts +12 -3
  180. package/src/providers/factory.js +41 -0
  181. package/src/providers/factory.ts +42 -0
  182. package/src/providers/gemini.js +74 -22
  183. package/src/providers/gemini.ts +78 -26
  184. package/src/providers/moonshot.js +36 -3
  185. package/src/providers/moonshot.ts +32 -3
  186. package/src/providers/ollama.js +267 -21
  187. package/src/providers/ollama.ts +302 -29
  188. package/src/providers/openai-compatible.js +67 -11
  189. package/src/providers/openai-compatible.ts +78 -17
  190. package/src/providers/openai.js +25 -2
  191. package/src/providers/openai.ts +24 -2
  192. package/src/providers/openrouter.js +233 -66
  193. package/src/providers/openrouter.ts +226 -70
  194. package/src/providers/qwen-byok.js +29 -3
  195. package/src/providers/qwen-byok.ts +30 -2
  196. package/src/providers/wireNormalizer.js +66 -0
  197. package/src/providers/wireNormalizer.ts +64 -0
  198. package/src/providers/xai.js +10 -3
  199. package/src/providers/xai.ts +9 -3
  200. package/src/provisioning/capabilityConsent.js +29 -11
  201. package/src/provisioning/capabilityConsent.ts +42 -0
  202. package/src/provisioning/capabilityProvisioner.js +309 -197
  203. package/src/provisioning/capabilityProvisioner.ts +413 -0
  204. package/src/provisioning/capabilityTools.js +31 -17
  205. package/src/provisioning/capabilityTools.ts +43 -0
  206. package/src/provisioning/npmInstall.js +33 -5
  207. package/src/provisioning/npmInstall.ts +33 -5
  208. package/src/reporting.js +328 -326
  209. package/src/reporting.ts +482 -0
  210. package/src/sandbox.js +37 -0
  211. package/src/sandbox.ts +38 -0
  212. package/src/sessionJournal.js +24 -3
  213. package/src/sessionJournal.ts +18 -3
  214. package/src/sessionStore.js +1 -2
  215. package/src/sessionStore.ts +2 -0
  216. package/src/slopDetector.js +202 -265
  217. package/src/slopDetector.ts +279 -0
  218. package/src/smartToolsUse.js +10 -4
  219. package/src/smartToolsUse.ts +10 -4
  220. package/src/stallGuard.js +10 -3
  221. package/src/stallGuard.ts +9 -3
  222. package/src/taskBuffer.js +91 -40
  223. package/src/taskBuffer.ts +94 -0
  224. package/src/tokenTracker.js +78 -11
  225. package/src/tokenTracker.ts +69 -11
  226. package/src/toolPacks.js +5 -0
  227. package/src/toolPacks.ts +5 -0
  228. package/src/tools/applyPatch.js +610 -0
  229. package/src/tools/applyPatch.ts +661 -0
  230. package/src/tools/archive.js +135 -21
  231. package/src/tools/archive.ts +136 -21
  232. package/src/tools/astryxOracle.js +77 -72
  233. package/src/tools/astryxOracle.ts +95 -0
  234. package/src/tools/axSnapshot.js +127 -147
  235. package/src/tools/axSnapshot.ts +174 -0
  236. package/src/tools/backgroundTask.js +86 -0
  237. package/src/tools/backgroundTask.ts +121 -0
  238. package/src/tools/blenderAutomator.js +434 -390
  239. package/src/tools/blenderAutomator.ts +623 -0
  240. package/src/tools/checkSystemSpecs.js +54 -61
  241. package/src/tools/checkSystemSpecs.ts +73 -0
  242. package/src/tools/clipboard.js +42 -31
  243. package/src/tools/clipboard.ts +61 -0
  244. package/src/tools/codeSearchAst.js +359 -91
  245. package/src/tools/codeSearchAst.ts +399 -0
  246. package/src/tools/codeSearcher.js +179 -37
  247. package/src/tools/codeSearcher.ts +188 -33
  248. package/src/tools/codeTools.js +208 -245
  249. package/src/tools/codeTools.ts +271 -0
  250. package/src/tools/codebaseSearch.js +5 -0
  251. package/src/tools/codebaseSearch.ts +5 -0
  252. package/src/tools/desktopAct.js +185 -197
  253. package/src/tools/desktopAct.ts +257 -0
  254. package/src/tools/dynamicLoader.js +4 -40
  255. package/src/tools/dynamicLoader.ts +13 -0
  256. package/src/tools/executeProceduralMedia.js +117 -86
  257. package/src/tools/executeProceduralMedia.ts +135 -0
  258. package/src/tools/fileTracker.js +74 -0
  259. package/src/tools/fileTracker.ts +94 -0
  260. package/src/tools/fsDelete.js +57 -47
  261. package/src/tools/fsDelete.ts +80 -0
  262. package/src/tools/fsEdit.js +192 -74
  263. package/src/tools/fsEdit.ts +201 -72
  264. package/src/tools/fsMove.js +79 -52
  265. package/src/tools/fsMove.ts +108 -0
  266. package/src/tools/fsRead.js +54 -15
  267. package/src/tools/fsRead.ts +55 -15
  268. package/src/tools/fsSearch.js +5 -0
  269. package/src/tools/fsSearch.ts +5 -0
  270. package/src/tools/fsWrite.js +14 -6
  271. package/src/tools/fsWrite.ts +14 -6
  272. package/src/tools/gameAiBehaviorTree.js +74 -91
  273. package/src/tools/gameAiBehaviorTree.ts +219 -0
  274. package/src/tools/gameAnimationRig.js +128 -147
  275. package/src/tools/gameAnimationRig.ts +215 -0
  276. package/src/tools/gameAssetFetcher.js +403 -441
  277. package/src/tools/gameAssetFetcher.ts +477 -0
  278. package/src/tools/gameAssetHarvester.js +171 -200
  279. package/src/tools/gameAssetHarvester.ts +261 -0
  280. package/src/tools/gameAudioSynth.js +223 -259
  281. package/src/tools/gameAudioSynth.ts +255 -0
  282. package/src/tools/gameBuilder.js +100 -91
  283. package/src/tools/gameBuilder.ts +913 -0
  284. package/src/tools/gameCanvasAudit.js +138 -96
  285. package/src/tools/gameCanvasAudit.ts +157 -0
  286. package/src/tools/gameCinematicSequencer.js +93 -111
  287. package/src/tools/gameCinematicSequencer.ts +165 -0
  288. package/src/tools/gameDataForge.js +115 -118
  289. package/src/tools/gameDataForge.ts +151 -0
  290. package/src/tools/gameDialogueTreeGen.js +125 -156
  291. package/src/tools/gameDialogueTreeGen.ts +159 -0
  292. package/src/tools/gameEconomyBalancer.js +150 -153
  293. package/src/tools/gameEconomyBalancer.ts +186 -0
  294. package/src/tools/gameEntitySpawner.js +91 -108
  295. package/src/tools/gameEntitySpawner.ts +209 -0
  296. package/src/tools/gameLoreForge.js +125 -147
  297. package/src/tools/gameLoreForge.ts +162 -0
  298. package/src/tools/gameQuestArcBuilder.js +105 -144
  299. package/src/tools/gameQuestArcBuilder.ts +147 -0
  300. package/src/tools/gameSceneBuilder.js +143 -149
  301. package/src/tools/gameSceneBuilder.ts +196 -0
  302. package/src/tools/gameShaderForge.js +83 -101
  303. package/src/tools/gameShaderForge.ts +181 -0
  304. package/src/tools/gameTilemapGenerator.js +99 -129
  305. package/src/tools/gameTilemapGenerator.ts +158 -0
  306. package/src/tools/gameUiHudBuilder.js +109 -129
  307. package/src/tools/gameUiHudBuilder.ts +300 -0
  308. package/src/tools/gameVfxEmitterGen.js +86 -89
  309. package/src/tools/gameVfxEmitterGen.ts +133 -0
  310. package/src/tools/gameWebRuntimeInspector.js +153 -86
  311. package/src/tools/gameWebRuntimeInspector.ts +167 -0
  312. package/src/tools/generateMediaViaApi.js +53 -12
  313. package/src/tools/generateMediaViaApi.ts +52 -12
  314. package/src/tools/gitExec.js +133 -86
  315. package/src/tools/gitExec.ts +146 -0
  316. package/src/tools/gitWorktree.js +115 -0
  317. package/src/tools/gitWorktree.ts +150 -0
  318. package/src/tools/godotAutomator.js +417 -394
  319. package/src/tools/godotAutomator.ts +530 -0
  320. package/src/tools/lspCodeIntel.js +217 -0
  321. package/src/tools/lspCodeIntel.ts +260 -0
  322. package/src/tools/manageLocalAiDependencies.js +242 -206
  323. package/src/tools/manageLocalAiDependencies.ts +288 -0
  324. package/src/tools/multiEdit.js +16 -76
  325. package/src/tools/multiEdit.ts +20 -77
  326. package/src/tools/osSandbox.js +152 -15
  327. package/src/tools/osSandbox.ts +148 -15
  328. package/src/tools/palmierAutomator.js +147 -95
  329. package/src/tools/palmierAutomator.ts +171 -0
  330. package/src/tools/pdfReader.js +95 -104
  331. package/src/tools/pdfReader.ts +125 -0
  332. package/src/tools/persistentShell.js +267 -144
  333. package/src/tools/persistentShell.ts +314 -0
  334. package/src/tools/pluginManager.js +84 -72
  335. package/src/tools/pluginManager.ts +109 -0
  336. package/src/tools/printer.js +278 -296
  337. package/src/tools/printer.ts +326 -0
  338. package/src/tools/procTerm.js +96 -83
  339. package/src/tools/procTerm.ts +127 -0
  340. package/src/tools/processList.js +45 -48
  341. package/src/tools/processList.ts +73 -0
  342. package/src/tools/registry.js +298 -286
  343. package/src/tools/registry.ts +486 -0
  344. package/src/tools/repoMap.js +46 -0
  345. package/src/tools/repoMap.ts +66 -0
  346. package/src/tools/subagentOrchestrator.js +404 -348
  347. package/src/tools/subagentOrchestrator.ts +457 -0
  348. package/src/tools/sysRun.js +83 -26
  349. package/src/tools/sysRun.ts +80 -26
  350. package/src/tools/toolForge.js +84 -67
  351. package/src/tools/toolForge.ts +102 -0
  352. package/src/tools/toolPathSafety.js +262 -0
  353. package/src/tools/toolPathSafety.ts +308 -0
  354. package/src/tools/toolScanner.js +28 -0
  355. package/src/tools/toolScanner.ts +29 -0
  356. package/src/tools/toolSelfRepair.js +21 -6
  357. package/src/tools/toolSelfRepair.ts +26 -6
  358. package/src/tools/walkerSafety.ts +1 -0
  359. package/src/tools/webFetch.js +5 -2
  360. package/src/tools/webFetch.ts +5 -2
  361. package/src/toolsList.js +5 -0
  362. package/src/toolsList.ts +5 -0
  363. package/src/tui/ask.js +159 -168
  364. package/src/tui/ask.ts +259 -0
  365. package/src/tui/block.js +0 -1
  366. package/src/tui/block.ts +0 -1
  367. package/src/tui/chatRenderer.js +1193 -1441
  368. package/src/tui/chatRenderer.ts +1336 -0
  369. package/src/tui/clipboardImage.js +36 -12
  370. package/src/tui/clipboardImage.ts +39 -13
  371. package/src/tui/clipboardSync.js +34 -9
  372. package/src/tui/clipboardSync.ts +38 -9
  373. package/src/tui/codeProgress.js +0 -1
  374. package/src/tui/codeProgress.ts +0 -1
  375. package/src/tui/completion.js +395 -371
  376. package/src/tui/completion.ts +574 -0
  377. package/src/tui/composerControls.js +113 -19
  378. package/src/tui/composerControls.ts +124 -19
  379. package/src/tui/consoleGuard.js +27 -7
  380. package/src/tui/consoleGuard.ts +29 -7
  381. package/src/tui/dialogs.js +864 -717
  382. package/src/tui/dialogs.ts +984 -0
  383. package/src/tui/diff.js +205 -195
  384. package/src/tui/diff.ts +336 -0
  385. package/src/tui/history.js +143 -108
  386. package/src/tui/history.ts +167 -0
  387. package/src/tui/home.js +165 -161
  388. package/src/tui/home.ts +251 -0
  389. package/src/tui/invocation.js +58 -65
  390. package/src/tui/invocation.ts +117 -0
  391. package/src/tui/keys.js +437 -420
  392. package/src/tui/keys.ts +597 -0
  393. package/src/tui/lineEditor.js +477 -432
  394. package/src/tui/lineEditor.ts +542 -0
  395. package/src/tui/messageActionPlacement.js +0 -1
  396. package/src/tui/messageActionPlacement.ts +0 -1
  397. package/src/tui/messageInteraction.js +0 -2
  398. package/src/tui/messageInteraction.ts +0 -2
  399. package/src/tui/modelPicker.js +0 -3
  400. package/src/tui/modelPicker.ts +3 -6
  401. package/src/tui/observerPicker.js +0 -2
  402. package/src/tui/observerPicker.ts +0 -2
  403. package/src/tui/overlay.js +0 -1
  404. package/src/tui/overlay.ts +0 -1
  405. package/src/tui/prompt.js +1816 -2151
  406. package/src/tui/prompt.ts +1870 -0
  407. package/src/tui/runningLight.js +0 -1
  408. package/src/tui/runningLight.ts +0 -1
  409. package/src/tui/selectList.js +365 -337
  410. package/src/tui/selectList.ts +441 -0
  411. package/src/tui/sessionPicker.js +0 -1
  412. package/src/tui/sessionPicker.ts +0 -1
  413. package/src/tui/sessionPickerView.js +0 -2
  414. package/src/tui/sessionPickerView.ts +4 -21
  415. package/src/tui/sessionSidebar.js +3 -1
  416. package/src/tui/sessionSidebar.ts +4 -1
  417. package/src/tui/setup.js +17 -5
  418. package/src/tui/setup.ts +19 -5
  419. package/src/tui/skillAuthoring.js +0 -2
  420. package/src/tui/skillAuthoring.ts +0 -3
  421. package/src/tui/stageSurface.js +829 -909
  422. package/src/tui/stageSurface.ts +1003 -0
  423. package/src/tui/statusLine.js +7 -4
  424. package/src/tui/statusLine.ts +7 -3
  425. package/src/tui/terminalInputFramer.js +82 -69
  426. package/src/tui/terminalInputFramer.ts +116 -0
  427. package/src/tui/text.js +25 -10
  428. package/src/tui/text.ts +24 -10
  429. package/src/tui/textLayout.js +0 -1
  430. package/src/tui/textLayout.ts +0 -1
  431. package/src/tui/theme.js +245 -250
  432. package/src/tui/theme.ts +441 -0
  433. package/src/tui/thinkingBox.js +0 -1
  434. package/src/tui/thinkingBox.ts +0 -1
  435. package/src/tui/transcript.js +239 -216
  436. package/src/tui/transcript.ts +324 -0
  437. package/src/tui/turnRail.js +53 -54
  438. package/src/tui/turnRail.ts +51 -49
  439. package/src/tui/usageCard.js +0 -2
  440. package/src/tui/usageCard.ts +0 -2
  441. package/src/tui/workspaceSwitch.js +4 -2
  442. package/src/tui/workspaceSwitch.ts +5 -2
  443. package/src/types/contracts.ts +4 -1
  444. package/src/utils/browserOpen.js +107 -0
  445. package/src/utils/browserOpen.ts +129 -0
  446. package/src/utils/cli_ui.js +0 -0
  447. package/src/utils/cli_ui.ts +158 -0
  448. package/src/utils/winSpawn.js +248 -0
  449. package/src/utils/winSpawn.ts +275 -0
  450. package/src/verification/boundedExplorer.js +138 -107
  451. package/src/verification/boundedExplorer.ts +154 -0
  452. package/src/verification/byokSmokeProbe.js +193 -0
  453. package/src/verification/byokSmokeProbe.ts +234 -0
  454. package/src/verification/cliProbe.js +144 -110
  455. package/src/verification/cliProbe.ts +170 -0
  456. package/src/verification/featureMap.js +105 -75
  457. package/src/verification/featureMap.ts +124 -0
  458. package/src/verification/interactivePty.js +195 -100
  459. package/src/verification/interactivePty.ts +333 -0
  460. package/src/verification/propertyProbe.js +109 -101
  461. package/src/verification/propertyProbe.ts +159 -0
  462. package/src/verification/ptyProbe.js +168 -73
  463. package/src/verification/ptyProbe.ts +254 -0
  464. package/src/verification/skillCatalog.js +25 -25
  465. package/src/verification/skillCatalog.ts +66 -0
  466. package/src/verification/statechart.js +140 -127
  467. package/src/verification/statechart.ts +196 -0
  468. package/src/verification/uiRuntime.js +80 -49
  469. package/src/verification/uiRuntime.ts +88 -0
  470. package/src/version.js +37 -32
  471. package/src/version.ts +45 -0
  472. package/src/web/guiLauncher.js +89 -0
  473. package/src/web/guiLauncher.ts +119 -0
  474. package/src/web/skybridgeBrowserBridge.js +256 -0
  475. package/src/web/skybridgeBrowserBridge.ts +285 -0
  476. package/src/web/skybridgeBrowserMcp.js +730 -0
  477. package/src/web/skybridgeBrowserMcp.ts +813 -0
  478. package/src/web/skybridgeClientScript.js +3951 -0
  479. package/src/web/skybridgeClientScript.ts +3952 -0
  480. package/src/web/skybridgeServer.js +2622 -0
  481. package/src/web/skybridgeServer.ts +2787 -0
  482. package/src/web/skybridgeStyles.js +827 -0
  483. package/src/web/skybridgeStyles.ts +828 -0
  484. package/src/web/skybridgeUi.js +472 -0
  485. package/src/web/skybridgeUi.ts +485 -0
  486. package/src/worktreeManager.js +511 -0
  487. package/src/worktreeManager.ts +546 -0
  488. package/src/zeroCostFailover.js +168 -0
  489. package/src/zeroCostFailover.ts +198 -0
  490. package/src/zeroCostRouting.js +391 -0
  491. package/src/zeroCostRouting.ts +437 -0
  492. package/src/agentLoop.d.ts +0 -65
  493. package/src/auditLog.d.ts +0 -3
  494. package/src/checkpoints.d.ts +0 -4
  495. package/src/compiledSkills.d.ts +0 -5
  496. package/src/contextManager.d.ts +0 -14
  497. package/src/designPalettes.d.ts +0 -2
  498. package/src/devMode.d.ts +0 -1
  499. package/src/embodimentSession.d.ts +0 -2
  500. package/src/licensing/entitlements.d.ts +0 -14
  501. package/src/memory.d.ts +0 -13
  502. package/src/memoryManager.d.ts +0 -1
  503. package/src/modelCatalogue.d.ts +0 -6
  504. package/src/modelIds.d.ts +0 -2
  505. package/src/outputStore.d.ts +0 -4
  506. package/src/plugins/pluginManager.d.ts +0 -7
  507. package/src/providers/antigravity.d.ts +0 -19
  508. package/src/provisioning/capabilityProvisioner.d.ts +0 -12
  509. package/src/slopDetector.d.ts +0 -3
  510. package/src/taskBuffer.d.ts +0 -1
  511. package/src/tools/desktopAct.d.ts +0 -10
  512. package/src/tools/registry.d.ts +0 -5
  513. package/src/tui/chatRenderer.d.ts +0 -27
  514. package/src/tui/diff.d.ts +0 -3
  515. package/src/utils/cli_ui.d.ts +0 -19
  516. package/src/utils/paths.d.ts +0 -3
  517. package/src/verification/skillCatalog.d.ts +0 -1
  518. package/src/version.d.ts +0 -1
@@ -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
+ }