@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
@@ -9,7 +9,13 @@ import {
9
9
  ensureCapability,
10
10
  loadCapabilityPackage
11
11
  } from '../provisioning/capabilityProvisioner.js';
12
- import { resolveBrowserRuntime, type PreparedBrowserRuntime } from './browserRuntime.js';
12
+ import {
13
+ inspectAvailableBrowserRuntimes,
14
+ resolveBrowserRuntime,
15
+ resolveCamoufoxRuntime,
16
+ resolveChromiumRuntime,
17
+ type PreparedBrowserRuntime
18
+ } from './browserRuntime.js';
13
19
  import { assertPublicWebUrl, assertBrowserNavigableUrl, isLoopbackHost } from './urlPolicy.js';
14
20
  import { ensureSafeWorkspaceInputPath, ensureSafeWorkspaceOutputPath } from './workspacePathSafety.js';
15
21
  import { windowSnapshot, type SnapshotWindow } from './snapshotWindow.js';
@@ -217,8 +223,9 @@ export function extractDeterministic(options: {
217
223
  const check = validateExtractSchema(options.schema);
218
224
  if (!check.ok) throw new Error(check.error ?? 'Invalid extraction schema');
219
225
 
220
- const result: Record<string, unknown> = {};
226
+ const result = Object.create(null) as Record<string, unknown>;
221
227
  for (const [prop, def] of Object.entries(options.schema.properties)) {
228
+ if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') continue;
222
229
  const refId = def['x-ref'];
223
230
  let value: unknown = null;
224
231
  if (refId) {
@@ -233,7 +240,7 @@ export function extractDeterministic(options: {
233
240
  }
234
241
  result[prop] = value;
235
242
  }
236
- return result;
243
+ return { ...result };
237
244
  }
238
245
 
239
246
  export interface PageStructureField {
@@ -382,6 +389,7 @@ interface BrowserPage {
382
389
  route(pattern: string, handler: (route: BrowserRoute) => Promise<void>): Promise<void>;
383
390
  setDefaultTimeout(milliseconds: number): void;
384
391
  setViewportSize?(size: { width: number; height: number }): Promise<void>;
392
+ viewportSize?(): { width: number; height: number } | null;
385
393
  goBack(options?: Record<string, unknown>): Promise<unknown>;
386
394
  goForward(options?: Record<string, unknown>): Promise<unknown>;
387
395
  reload(options?: Record<string, unknown>): Promise<unknown>;
@@ -391,15 +399,145 @@ interface BrowserPage {
391
399
  keyboard: {
392
400
  press(key: string): Promise<void>;
393
401
  type?(text: string, options?: { delay?: number }): Promise<void>;
402
+ insertText?(text: string): Promise<void>;
394
403
  };
395
404
  mouse: {
396
405
  wheel(deltaX: number, deltaY: number): Promise<void>;
406
+ click?(x: number, y: number, options?: Record<string, unknown>): Promise<void>;
407
+ dblclick?(x: number, y: number, options?: Record<string, unknown>): Promise<void>;
397
408
  move?(x: number, y: number): Promise<void>;
398
- down?(): Promise<void>;
399
- up?(): Promise<void>;
409
+ down?(options?: { button?: 'left' | 'right' | 'middle' }): Promise<void>;
410
+ up?(options?: { button?: 'left' | 'right' | 'middle' }): Promise<void>;
400
411
  };
401
412
  }
402
413
 
414
+ export type BrowserEnginePreference = 'auto' | 'chromium' | 'camoufox';
415
+ export type BrowserStreamMode = 'cdp-screencast' | 'adaptive-frames' | 'idle';
416
+
417
+ export interface BrowserCookieRecord {
418
+ name: string;
419
+ value: string;
420
+ domain: string;
421
+ path?: string | undefined;
422
+ expires?: number | undefined;
423
+ httpOnly?: boolean | undefined;
424
+ secure?: boolean | undefined;
425
+ sameSite?: 'Strict' | 'Lax' | 'None' | undefined;
426
+ }
427
+
428
+ export interface LiveBrowserTabSummary {
429
+ tabId: string;
430
+ url: string;
431
+ title: string;
432
+ active: boolean;
433
+ }
434
+
435
+ export interface LiveBrowserAwarenessContext {
436
+ active: boolean;
437
+ visible: boolean;
438
+ engine: 'chromium' | 'camoufox' | null;
439
+ activeTabId: string | null;
440
+ url: string;
441
+ title: string;
442
+ viewport: { width: number; height: number };
443
+ tabs: LiveBrowserTabSummary[];
444
+ }
445
+
446
+ export interface LiveBrowserMediaInfo {
447
+ tag: 'video' | 'audio';
448
+ paused: boolean;
449
+ ended: boolean;
450
+ muted: boolean;
451
+ currentTime: number;
452
+ duration: number;
453
+ width: number;
454
+ height: number;
455
+ readyState: number;
456
+ error: string;
457
+ }
458
+
459
+ export interface AgentBrowserPageInspection {
460
+ tabId: string;
461
+ url: string;
462
+ title: string;
463
+ engine: 'chromium' | 'camoufox' | null;
464
+ visible: boolean;
465
+ viewport: { width: number; height: number };
466
+ refsCount: number;
467
+ snapshot: string;
468
+ visibleText: string;
469
+ media: LiveBrowserMediaInfo[];
470
+ runtimeErrors: string[];
471
+ tabs: LiveBrowserTabSummary[];
472
+ }
473
+
474
+ export interface AgentViewportCapture {
475
+ tabId: string;
476
+ url: string;
477
+ title: string;
478
+ width: number;
479
+ height: number;
480
+ mimeType: 'image/jpeg';
481
+ buffer: Buffer;
482
+ mediaTimeSeconds: number | null;
483
+ mediaPaused: boolean | null;
484
+ }
485
+
486
+ export interface LiveBrowserFrame {
487
+ active: boolean;
488
+ visible: boolean;
489
+ engine: 'chromium' | 'camoufox' | null;
490
+ enginePreference: BrowserEnginePreference;
491
+ streamMode: BrowserStreamMode;
492
+ enginesAvailable: { camoufox: boolean; chromium: boolean };
493
+ tabId: string | null;
494
+ url: string;
495
+ title: string;
496
+ width: number;
497
+ height: number;
498
+ tabs: LiveBrowserTabSummary[];
499
+ imageBase64: string | null;
500
+ mimeType: 'image/jpeg' | 'image/png';
501
+ }
502
+
503
+ export interface LiveStreamEvent {
504
+ type: 'frame' | 'meta' | 'closed';
505
+ active: boolean;
506
+ visible: boolean;
507
+ engine: 'chromium' | 'camoufox' | null;
508
+ enginePreference: BrowserEnginePreference;
509
+ streamMode: BrowserStreamMode;
510
+ enginesAvailable: { camoufox: boolean; chromium: boolean };
511
+ tabId: string | null;
512
+ url: string;
513
+ title: string;
514
+ width: number;
515
+ height: number;
516
+ tabs: LiveBrowserTabSummary[];
517
+ imageBase64?: string | null | undefined;
518
+ mimeType?: 'image/jpeg' | 'image/png' | undefined;
519
+ fps?: number | undefined;
520
+ }
521
+
522
+ export interface LiveBrowserInteraction {
523
+ kind: 'click' | 'dblclick' | 'contextmenu' | 'mousedown' | 'mousemove' | 'mouseup' | 'wheel' | 'type' | 'key' | 'paste';
524
+ x?: number | undefined;
525
+ y?: number | undefined;
526
+ deltaX?: number | undefined;
527
+ deltaY?: number | undefined;
528
+ text?: string | undefined;
529
+ key?: string | undefined;
530
+ button?: 'left' | 'right' | 'middle' | undefined;
531
+ skipFrame?: boolean | undefined;
532
+ }
533
+
534
+ interface BrowserCdpSession {
535
+ send(method: string, params?: Record<string, unknown>): Promise<unknown>;
536
+ on(event: string, listener: (payload: Record<string, unknown>) => void): void;
537
+ off?(event: string, listener: (payload: Record<string, unknown>) => void): void;
538
+ detach(): Promise<void>;
539
+ }
540
+
403
541
  interface BrowserSession {
404
542
  newPage(): Promise<BrowserPage>;
405
543
  pages(): BrowserPage[];
@@ -407,6 +545,9 @@ interface BrowserSession {
407
545
  isConnected?(): boolean;
408
546
  route?(pattern: string, handler: (route: BrowserRoute) => Promise<void>): Promise<void>;
409
547
  on?(event: 'page', handler: (page: BrowserPage) => void): void;
548
+ addCookies?(cookies: BrowserCookieRecord[]): Promise<void>;
549
+ cookies?(urls?: string | string[]): Promise<BrowserCookieRecord[]>;
550
+ newCDPSession?(page: BrowserPage): Promise<BrowserCdpSession>;
410
551
  }
411
552
 
412
553
  interface BrowserEngineModule {
@@ -793,12 +934,15 @@ const PAGE_STRUCTURE_EXTRACT_SCRIPT = `(() => {
793
934
  .map(c => trunc(c.textContent, MAX_CELL_CHARS));
794
935
  if (cells.length === 0 || cells.every(c => c === '')) continue;
795
936
  if (headers.length > 0 && headers.some(Boolean)) {
796
- const obj = {};
937
+ const obj = Object.create(null);
797
938
  cells.forEach((val, idx) => {
798
- const key = headers[idx] || ('col_' + (idx + 1));
939
+ const rawKey = headers[idx] || ('col_' + (idx + 1));
940
+ const key = (rawKey === '__proto__' || rawKey === 'constructor' || rawKey === 'prototype')
941
+ ? ('col_' + (idx + 1))
942
+ : rawKey;
799
943
  obj[key] = val;
800
944
  });
801
- rows.push(obj);
945
+ rows.push(Object.assign({}, obj));
802
946
  } else {
803
947
  rows.push(cells);
804
948
  }
@@ -952,10 +1096,13 @@ export class CausyneBrowser {
952
1096
  private readonly ensureBrowserCapability: NonNullable<RuntimeOptions['ensureBrowserCapability']>;
953
1097
  private readonly loadBrowserEngine: NonNullable<RuntimeOptions['loadBrowserEngine']>;
954
1098
  private readonly resolveRuntime: NonNullable<RuntimeOptions['resolveRuntime']>;
1099
+ private readonly customResolveRuntime: boolean;
955
1100
  private profileDirectory: string;
956
1101
  private readonly pinnedProfileDirectory: boolean;
957
1102
  private queuedOperations = 0;
958
- private readonly visible: boolean;
1103
+ private visible: boolean;
1104
+ private enginePreference: BrowserEnginePreference = 'auto';
1105
+ private activeEngine: 'chromium' | 'camoufox' | null = null;
959
1106
  private readonly validateUrl: (value: string) => Promise<URL>;
960
1107
  private session: BrowserSession | null = null;
961
1108
  private starting: Promise<void> | null = null;
@@ -970,11 +1117,26 @@ export class CausyneBrowser {
970
1117
  private approvedLoopbackOrigins = new Set<string>();
971
1118
  private pendingLocalNavigation: string | null = null;
972
1119
  private lastTarget: { kind: 'preview'; workspace: string; filePath: string } | { kind: 'url'; url: string } | null = null;
1120
+ private streamListeners = new Set<(event: LiveStreamEvent) => void>();
1121
+ private cdpSession: BrowserCdpSession | null = null;
1122
+ private cdpPage: BrowserPage | null = null;
1123
+ private cdpFrameHandler: ((payload: Record<string, unknown>) => void) | null = null;
1124
+ private streamMode: BrowserStreamMode = 'idle';
1125
+ private adaptiveTimer: NodeJS.Timeout | null = null;
1126
+ private metaSyncTimer: NodeJS.Timeout | null = null;
1127
+ private adaptiveInFlight = false;
1128
+ private recentFrameTimestamps: number[] = [];
1129
+ private cachedTabSummaries: LiveBrowserTabSummary[] = [];
1130
+ private cachedUrl = '';
1131
+ private cachedTitle = '';
1132
+ private cachedWidth = 1280;
1133
+ private cachedHeight = 800;
973
1134
 
974
1135
  constructor(options: RuntimeOptions = {}) {
975
1136
  this.workspace = path.resolve(options.workspace ?? process.cwd());
976
1137
  this.ensureBrowserCapability = options.ensureBrowserCapability ?? (() => ensureCapability('browser'));
977
1138
  this.loadBrowserEngine = options.loadBrowserEngine ?? (async () => await loadCapabilityPackage('camoufox-js') as BrowserEngineModule);
1139
+ this.customResolveRuntime = options.resolveRuntime !== undefined;
978
1140
  this.resolveRuntime = options.resolveRuntime ?? resolveBrowserRuntime;
979
1141
  this.pinnedProfileDirectory = options.profileDirectory !== undefined;
980
1142
  this.profileDirectory = path.resolve(options.profileDirectory ?? workspaceProfileDirectory(this.workspace));
@@ -1137,8 +1299,10 @@ export class CausyneBrowser {
1137
1299
  this.idleGeneration++;
1138
1300
  if (this.idleTimer) clearTimeout(this.idleTimer);
1139
1301
  this.idleTimer = null;
1302
+ await this.stopLiveStreamTransport(true);
1140
1303
  const session = this.session;
1141
1304
  this.session = null;
1305
+ this.activeEngine = null;
1142
1306
  this.starting = null;
1143
1307
  this.tabs.clear();
1144
1308
  this.workspacePreview.clear();
@@ -1148,9 +1312,811 @@ export class CausyneBrowser {
1148
1312
  this.pendingLocalNavigation = null;
1149
1313
  this.securedPages = new WeakSet<object>();
1150
1314
  this.pageStates = new WeakMap<object, TabState>();
1315
+ this.cachedTabSummaries = [];
1316
+ this.cachedUrl = '';
1317
+ this.cachedTitle = '';
1151
1318
  if (session) await session.close().catch(() => {});
1152
1319
  }
1153
1320
 
1321
+ isActive(): boolean {
1322
+ return this.isSessionHealthy();
1323
+ }
1324
+
1325
+ /**
1326
+ * Synchronous, zero-side-effect snapshot of the live shared browser state for
1327
+ * agent prompt awareness. Never launches the browser when idle.
1328
+ */
1329
+ getLiveAwarenessContext(): LiveBrowserAwarenessContext {
1330
+ if (!this.isSessionHealthy()) {
1331
+ return {
1332
+ active: false,
1333
+ visible: this.visible,
1334
+ engine: null,
1335
+ activeTabId: null,
1336
+ url: '',
1337
+ title: '',
1338
+ viewport: { width: this.cachedWidth, height: this.cachedHeight },
1339
+ tabs: []
1340
+ };
1341
+ }
1342
+ const cachedTitleById = new Map<string, string>();
1343
+ for (const item of this.cachedTabSummaries) {
1344
+ cachedTitleById.set(item.tabId, item.title);
1345
+ }
1346
+ const liveTabs: LiveBrowserTabSummary[] = [];
1347
+ let activeTab: TabState | undefined = this.activeTabId ? this.tabs.get(this.activeTabId) : undefined;
1348
+ if (activeTab && (activeTab.page.isClosed() || activeTab.crashed)) {
1349
+ activeTab = undefined;
1350
+ }
1351
+ for (const tab of this.tabs.values()) {
1352
+ if (tab.page.isClosed() || tab.crashed) continue;
1353
+ if (!activeTab) activeTab = tab;
1354
+ const liveUrl = tab.page.url();
1355
+ const title = cachedTitleById.get(tab.id) ?? (tab.id === activeTab.id ? this.cachedTitle : '');
1356
+ liveTabs.push({
1357
+ tabId: tab.id,
1358
+ url: liveUrl,
1359
+ title,
1360
+ active: tab.id === activeTab.id
1361
+ });
1362
+ }
1363
+ const activeUrl = activeTab ? activeTab.page.url() : this.cachedUrl;
1364
+ const activeTitle = activeTab
1365
+ ? (cachedTitleById.get(activeTab.id) || this.cachedTitle)
1366
+ : this.cachedTitle;
1367
+ const vp = activeTab && typeof activeTab.page.viewportSize === 'function'
1368
+ ? activeTab.page.viewportSize()
1369
+ : null;
1370
+ return {
1371
+ active: liveTabs.length > 0,
1372
+ visible: this.visible,
1373
+ engine: this.activeEngine,
1374
+ activeTabId: activeTab?.id ?? null,
1375
+ url: activeUrl,
1376
+ title: activeTitle,
1377
+ viewport: {
1378
+ width: vp?.width ?? this.cachedWidth,
1379
+ height: vp?.height ?? this.cachedHeight
1380
+ },
1381
+ tabs: liveTabs
1382
+ };
1383
+ }
1384
+
1385
+ /**
1386
+ * Rich structured page inspection for agent tool calls (`causyne-browser` MCP
1387
+ * and shared browser workflows): URL, title, media/video playback state,
1388
+ * visible page text, interactive accessibility tree, and runtime errors.
1389
+ */
1390
+ async inspectPageForAgent(options: {
1391
+ tabId?: string | undefined;
1392
+ maxChars?: number | undefined;
1393
+ includeSnapshot?: boolean | undefined;
1394
+ } = {}): Promise<AgentBrowserPageInspection> {
1395
+ return this.enqueueOperation(async () => {
1396
+ await this.start();
1397
+ let state: TabState;
1398
+ if (options.tabId) {
1399
+ const chosen = this.tabs.get(options.tabId);
1400
+ if (!chosen || chosen.page.isClosed() || chosen.crashed) {
1401
+ throw new Error(`Unknown or closed browser tab: ${options.tabId}`);
1402
+ }
1403
+ this.activeTabId = chosen.id;
1404
+ state = chosen;
1405
+ } else {
1406
+ state = await this.activeTab();
1407
+ }
1408
+ await this.restoreLastTargetIfBlank(state);
1409
+ const maxChars = Math.max(500, Math.min(24000, options.maxChars ?? 8000));
1410
+ const includeSnapshot = options.includeSnapshot !== false;
1411
+ if (includeSnapshot) {
1412
+ await this.captureSnapshotState(state);
1413
+ }
1414
+ await this.refreshCachedTabMetadata();
1415
+ const domInfo = await state.page.evaluate<{ visibleText: string; media: LiveBrowserMediaInfo[] }>(`(() => {
1416
+ const rawText = (document.body && (document.body.innerText || document.body.textContent)) || '';
1417
+ const visibleText = rawText.replace(/\\r/g, '').replace(/\\n{3,}/g, '\\n\\n').trim().slice(0, ${maxChars});
1418
+ const media = [];
1419
+ const nodes = document.querySelectorAll('video, audio');
1420
+ for (let i = 0; i < nodes.length && i < 6; i += 1) {
1421
+ const el = nodes[i];
1422
+ const tag = el.tagName.toLowerCase() === 'audio' ? 'audio' : 'video';
1423
+ const errMsg = el.error ? (el.error.message || ('MEDIA_ERR_' + el.error.code)) : '';
1424
+ media.push({
1425
+ tag,
1426
+ paused: Boolean(el.paused),
1427
+ ended: Boolean(el.ended),
1428
+ muted: Boolean(el.muted),
1429
+ currentTime: Number.isFinite(el.currentTime) ? Number(el.currentTime) : 0,
1430
+ duration: Number.isFinite(el.duration) ? Number(el.duration) : 0,
1431
+ width: Number(el.videoWidth || el.clientWidth || 0),
1432
+ height: Number(el.videoHeight || el.clientHeight || 0),
1433
+ readyState: Number(el.readyState || 0),
1434
+ error: String(errMsg || '')
1435
+ });
1436
+ }
1437
+ return { visibleText, media };
1438
+ })()`).catch(() => ({ visibleText: '', media: [] as LiveBrowserMediaInfo[] }));
1439
+ const vp = typeof state.page.viewportSize === 'function' ? state.page.viewportSize() : null;
1440
+ const snapWindow = includeSnapshot ? windowSnapshot(state.lastSnapshot, 0) : null;
1441
+ return {
1442
+ tabId: state.id,
1443
+ url: state.page.url(),
1444
+ title: await this.safePageTitle(state.page),
1445
+ engine: this.activeEngine,
1446
+ visible: this.visible,
1447
+ viewport: { width: vp?.width ?? this.cachedWidth, height: vp?.height ?? this.cachedHeight },
1448
+ refsCount: state.refs.size,
1449
+ snapshot: snapWindow ? snapWindow.text : '',
1450
+ visibleText: domInfo.visibleText,
1451
+ media: domInfo.media,
1452
+ runtimeErrors: [...state.runtimeErrors],
1453
+ tabs: [...this.cachedTabSummaries]
1454
+ };
1455
+ });
1456
+ }
1457
+
1458
+ /**
1459
+ * Capture a live viewport frame buffer plus active media playback timestamp
1460
+ * for vision-capable agents inspecting the shared browser.
1461
+ */
1462
+ async captureViewportBuffer(options: {
1463
+ tabId?: string | undefined;
1464
+ fullPage?: boolean | undefined;
1465
+ quality?: number | undefined;
1466
+ } = {}): Promise<AgentViewportCapture> {
1467
+ return this.enqueueOperation(async () => {
1468
+ await this.start();
1469
+ let state: TabState;
1470
+ if (options.tabId) {
1471
+ const chosen = this.tabs.get(options.tabId);
1472
+ if (!chosen || chosen.page.isClosed() || chosen.crashed) {
1473
+ throw new Error(`Unknown or closed browser tab: ${options.tabId}`);
1474
+ }
1475
+ this.activeTabId = chosen.id;
1476
+ state = chosen;
1477
+ } else {
1478
+ state = await this.activeTab();
1479
+ }
1480
+ await this.restoreLastTargetIfBlank(state);
1481
+ await this.refreshCachedTabMetadata();
1482
+ const quality = Math.max(40, Math.min(92, options.quality ?? 78));
1483
+ const buffer = await state.page.screenshot({
1484
+ type: 'jpeg',
1485
+ quality,
1486
+ ...(options.fullPage === true ? { fullPage: true } : {}),
1487
+ timeout: 8000
1488
+ });
1489
+ const mediaState = await state.page.evaluate<{ time: number | null; paused: boolean | null }>(`(() => {
1490
+ const v = document.querySelector('video');
1491
+ if (!v) return { time: null, paused: null };
1492
+ return {
1493
+ time: Number.isFinite(v.currentTime) ? Number(v.currentTime) : null,
1494
+ paused: Boolean(v.paused)
1495
+ };
1496
+ })()`).catch(() => ({ time: null, paused: null }));
1497
+ const vp = typeof state.page.viewportSize === 'function' ? state.page.viewportSize() : null;
1498
+ return {
1499
+ tabId: state.id,
1500
+ url: state.page.url(),
1501
+ title: await this.safePageTitle(state.page),
1502
+ width: vp?.width ?? this.cachedWidth,
1503
+ height: vp?.height ?? this.cachedHeight,
1504
+ mimeType: 'image/jpeg',
1505
+ buffer,
1506
+ mediaTimeSeconds: mediaState.time,
1507
+ mediaPaused: mediaState.paused
1508
+ };
1509
+ });
1510
+ }
1511
+
1512
+ getRuntimeStatus(): {
1513
+ active: boolean;
1514
+ visible: boolean;
1515
+ engine: 'chromium' | 'camoufox' | null;
1516
+ enginePreference: BrowserEnginePreference;
1517
+ streamMode: BrowserStreamMode;
1518
+ enginesAvailable: { camoufox: boolean; chromium: boolean };
1519
+ } {
1520
+ const avail = inspectAvailableBrowserRuntimes();
1521
+ return {
1522
+ active: this.isSessionHealthy(),
1523
+ visible: this.visible,
1524
+ engine: this.activeEngine,
1525
+ enginePreference: this.enginePreference,
1526
+ streamMode: this.streamMode,
1527
+ enginesAvailable: { camoufox: avail.camoufox, chromium: avail.chromium }
1528
+ };
1529
+ }
1530
+
1531
+ async setDisplayMode(options: {
1532
+ visible?: boolean | undefined;
1533
+ enginePreference?: BrowserEnginePreference | undefined;
1534
+ ensureStarted?: boolean | undefined;
1535
+ }): Promise<LiveBrowserFrame> {
1536
+ return this.enqueueOperation(async () => {
1537
+ const nextVisible = typeof options.visible === 'boolean' ? options.visible : this.visible;
1538
+ const nextEngine: BrowserEnginePreference = options.enginePreference === 'camoufox'
1539
+ || options.enginePreference === 'chromium'
1540
+ || options.enginePreference === 'auto'
1541
+ ? options.enginePreference
1542
+ : this.enginePreference;
1543
+ const wasActive = this.isSessionHealthy();
1544
+ const changed = nextVisible !== this.visible || nextEngine !== this.enginePreference;
1545
+
1546
+ const preservedUrls: string[] = [];
1547
+ let activeIdx = 0;
1548
+ if (wasActive && changed) {
1549
+ let idx = 0;
1550
+ for (const tab of this.tabs.values()) {
1551
+ if (tab.page.isClosed() || tab.crashed) continue;
1552
+ const u = tab.page.url();
1553
+ if (u && u !== 'about:blank') {
1554
+ if (tab.id === this.activeTabId) activeIdx = preservedUrls.length;
1555
+ preservedUrls.push(u);
1556
+ }
1557
+ idx += 1;
1558
+ }
1559
+ void idx;
1560
+ await this.close();
1561
+ }
1562
+
1563
+ this.visible = nextVisible;
1564
+ this.enginePreference = nextEngine;
1565
+
1566
+ if (wasActive || options.ensureStarted) {
1567
+ await this.start();
1568
+ if (preservedUrls.length > 0) {
1569
+ let activeState: TabState | null = null;
1570
+ for (let i = 0; i < preservedUrls.length; i += 1) {
1571
+ const targetUrl = preservedUrls[i]!;
1572
+ const tabState = i === 0 ? await this.activeTab() : await this.createTab();
1573
+ try {
1574
+ await this.navigate(tabState, targetUrl);
1575
+ } catch {
1576
+ // Keep best-effort restoration across mode switches.
1577
+ }
1578
+ if (i === activeIdx) activeState = tabState;
1579
+ }
1580
+ if (activeState) this.activeTabId = activeState.id;
1581
+ }
1582
+ if (this.streamListeners.size > 0) {
1583
+ void this.syncLiveStreamAttachment().catch(() => {});
1584
+ }
1585
+ }
1586
+ return this.captureLiveFrameUnlocked({ ensureStarted: Boolean(options.ensureStarted || wasActive) });
1587
+ });
1588
+ }
1589
+
1590
+ subscribeLiveStream(listener: (event: LiveStreamEvent) => void): () => void {
1591
+ this.streamListeners.add(listener);
1592
+ if (this.isSessionHealthy()) {
1593
+ void this.syncLiveStreamAttachment().catch(() => {});
1594
+ } else {
1595
+ const status = this.getRuntimeStatus();
1596
+ listener({
1597
+ type: 'meta',
1598
+ active: false,
1599
+ visible: status.visible,
1600
+ engine: status.engine,
1601
+ enginePreference: status.enginePreference,
1602
+ streamMode: 'idle',
1603
+ enginesAvailable: status.enginesAvailable,
1604
+ tabId: null,
1605
+ url: '',
1606
+ title: '',
1607
+ width: this.cachedWidth,
1608
+ height: this.cachedHeight,
1609
+ tabs: []
1610
+ });
1611
+ }
1612
+ return () => {
1613
+ this.streamListeners.delete(listener);
1614
+ if (this.streamListeners.size === 0) {
1615
+ void this.stopLiveStreamTransport(false).catch(() => {});
1616
+ }
1617
+ };
1618
+ }
1619
+
1620
+ private emitLiveStreamEvent(event: LiveStreamEvent): void {
1621
+ for (const listener of this.streamListeners) {
1622
+ try {
1623
+ listener(event);
1624
+ } catch {
1625
+ // Isolate subscriber errors.
1626
+ }
1627
+ }
1628
+ }
1629
+
1630
+ private computeLiveFps(): number {
1631
+ const now = Date.now();
1632
+ this.recentFrameTimestamps.push(now);
1633
+ while (this.recentFrameTimestamps.length > 0 && now - this.recentFrameTimestamps[0]! > 1000) {
1634
+ this.recentFrameTimestamps.shift();
1635
+ }
1636
+ return this.recentFrameTimestamps.length;
1637
+ }
1638
+
1639
+ private async stopLiveStreamTransport(notifyClosed: boolean): Promise<void> {
1640
+ if (this.adaptiveTimer) {
1641
+ clearInterval(this.adaptiveTimer);
1642
+ this.adaptiveTimer = null;
1643
+ }
1644
+ if (this.metaSyncTimer) {
1645
+ clearInterval(this.metaSyncTimer);
1646
+ this.metaSyncTimer = null;
1647
+ }
1648
+ this.adaptiveInFlight = false;
1649
+ this.recentFrameTimestamps = [];
1650
+ const cdp = this.cdpSession;
1651
+ const handler = this.cdpFrameHandler;
1652
+ this.cdpSession = null;
1653
+ this.cdpPage = null;
1654
+ this.cdpFrameHandler = null;
1655
+ this.streamMode = 'idle';
1656
+ if (cdp) {
1657
+ if (handler && typeof cdp.off === 'function') {
1658
+ try { cdp.off('Page.screencastFrame', handler); } catch { /* ignore */ }
1659
+ }
1660
+ await cdp.send('Page.stopScreencast').catch(() => {});
1661
+ await cdp.detach().catch(() => {});
1662
+ }
1663
+ if (notifyClosed && this.streamListeners.size > 0) {
1664
+ const status = this.getRuntimeStatus();
1665
+ this.emitLiveStreamEvent({
1666
+ type: 'closed',
1667
+ active: false,
1668
+ visible: status.visible,
1669
+ engine: null,
1670
+ enginePreference: status.enginePreference,
1671
+ streamMode: 'idle',
1672
+ enginesAvailable: status.enginesAvailable,
1673
+ tabId: null,
1674
+ url: '',
1675
+ title: '',
1676
+ width: this.cachedWidth,
1677
+ height: this.cachedHeight,
1678
+ tabs: []
1679
+ });
1680
+ }
1681
+ }
1682
+
1683
+ private async refreshCachedTabMetadata(): Promise<boolean> {
1684
+ if (!this.isSessionHealthy()) return false;
1685
+ const active = this.activeTabId ? this.tabs.get(this.activeTabId) : [...this.tabs.values()].find(t => !t.page.isClosed() && !t.crashed);
1686
+ if (!active || active.page.isClosed() || active.crashed) return false;
1687
+ const vp = typeof active.page.viewportSize === 'function' ? active.page.viewportSize() : null;
1688
+ const width = vp?.width ?? 1280;
1689
+ const height = vp?.height ?? 800;
1690
+ const tabs: LiveBrowserTabSummary[] = [];
1691
+ for (const tab of this.tabs.values()) {
1692
+ if (tab.page.isClosed() || tab.crashed) continue;
1693
+ tabs.push({
1694
+ tabId: tab.id,
1695
+ url: tab.page.url(),
1696
+ title: await this.safePageTitle(tab.page),
1697
+ active: tab.id === active.id
1698
+ });
1699
+ }
1700
+ const url = active.page.url();
1701
+ const title = await this.safePageTitle(active.page);
1702
+ const sigPrev = JSON.stringify([this.cachedUrl, this.cachedTitle, this.cachedWidth, this.cachedHeight, this.cachedTabSummaries]);
1703
+ const sigNext = JSON.stringify([url, title, width, height, tabs]);
1704
+ this.cachedUrl = url;
1705
+ this.cachedTitle = title;
1706
+ this.cachedWidth = width;
1707
+ this.cachedHeight = height;
1708
+ this.cachedTabSummaries = tabs;
1709
+ return sigPrev !== sigNext;
1710
+ }
1711
+
1712
+ private async pushSingleAdaptiveFrame(): Promise<void> {
1713
+ if (this.adaptiveInFlight || this.queuedOperations > 0 || !this.isSessionHealthy() || this.streamListeners.size === 0) {
1714
+ return;
1715
+ }
1716
+ const active = this.activeTabId ? this.tabs.get(this.activeTabId) : [...this.tabs.values()].find(t => !t.page.isClosed() && !t.crashed);
1717
+ if (!active || active.page.isClosed() || active.crashed) return;
1718
+ this.adaptiveInFlight = true;
1719
+ try {
1720
+ await this.refreshCachedTabMetadata();
1721
+ const buf = await active.page.screenshot({ type: 'jpeg', quality: 68, timeout: 3000 });
1722
+ const status = this.getRuntimeStatus();
1723
+ this.emitLiveStreamEvent({
1724
+ type: 'frame',
1725
+ active: true,
1726
+ visible: status.visible,
1727
+ engine: status.engine,
1728
+ enginePreference: status.enginePreference,
1729
+ streamMode: this.streamMode,
1730
+ enginesAvailable: status.enginesAvailable,
1731
+ tabId: active.id,
1732
+ url: this.cachedUrl,
1733
+ title: this.cachedTitle,
1734
+ width: this.cachedWidth,
1735
+ height: this.cachedHeight,
1736
+ tabs: this.cachedTabSummaries,
1737
+ imageBase64: buf.toString('base64'),
1738
+ mimeType: 'image/jpeg',
1739
+ fps: this.computeLiveFps()
1740
+ });
1741
+ } catch {
1742
+ // Skip transient frame capture errors while page navigates.
1743
+ } finally {
1744
+ this.adaptiveInFlight = false;
1745
+ }
1746
+ }
1747
+
1748
+ private async syncLiveStreamAttachment(): Promise<void> {
1749
+ if (this.streamListeners.size === 0 || !this.isSessionHealthy() || !this.session) {
1750
+ await this.stopLiveStreamTransport(false);
1751
+ return;
1752
+ }
1753
+ const active = this.activeTabId
1754
+ ? this.tabs.get(this.activeTabId)
1755
+ : [...this.tabs.values()].find(t => !t.page.isClosed() && !t.crashed);
1756
+ if (!active || active.page.isClosed() || active.crashed) return;
1757
+
1758
+ await this.refreshCachedTabMetadata();
1759
+
1760
+ if (!this.metaSyncTimer) {
1761
+ this.metaSyncTimer = setInterval(() => {
1762
+ if (this.streamListeners.size === 0 || !this.isSessionHealthy()) return;
1763
+ const cur = this.activeTabId ? this.tabs.get(this.activeTabId) : undefined;
1764
+ if (cur && this.cdpPage && cur.page !== this.cdpPage) {
1765
+ void this.syncLiveStreamAttachment().catch(() => {});
1766
+ return;
1767
+ }
1768
+ void this.refreshCachedTabMetadata().then((changed) => {
1769
+ if (!changed || this.streamListeners.size === 0) return;
1770
+ const status = this.getRuntimeStatus();
1771
+ this.emitLiveStreamEvent({
1772
+ type: 'meta',
1773
+ active: true,
1774
+ visible: status.visible,
1775
+ engine: status.engine,
1776
+ enginePreference: status.enginePreference,
1777
+ streamMode: this.streamMode,
1778
+ enginesAvailable: status.enginesAvailable,
1779
+ tabId: this.activeTabId,
1780
+ url: this.cachedUrl,
1781
+ title: this.cachedTitle,
1782
+ width: this.cachedWidth,
1783
+ height: this.cachedHeight,
1784
+ tabs: this.cachedTabSummaries
1785
+ });
1786
+ }).catch(() => {});
1787
+ }, 1200);
1788
+ this.metaSyncTimer.unref?.();
1789
+ }
1790
+
1791
+ if (typeof this.session.newCDPSession === 'function' && this.activeEngine === 'chromium') {
1792
+ if (this.cdpSession && this.cdpPage === active.page && this.streamMode === 'cdp-screencast') {
1793
+ return;
1794
+ }
1795
+ if (this.adaptiveTimer) {
1796
+ clearInterval(this.adaptiveTimer);
1797
+ this.adaptiveTimer = null;
1798
+ }
1799
+ if (this.cdpSession) {
1800
+ const prev = this.cdpSession;
1801
+ const prevHandler = this.cdpFrameHandler;
1802
+ this.cdpSession = null;
1803
+ this.cdpPage = null;
1804
+ this.cdpFrameHandler = null;
1805
+ if (prevHandler && typeof prev.off === 'function') {
1806
+ try { prev.off('Page.screencastFrame', prevHandler); } catch { /* ignore */ }
1807
+ }
1808
+ await prev.send('Page.stopScreencast').catch(() => {});
1809
+ await prev.detach().catch(() => {});
1810
+ }
1811
+ try {
1812
+ const cdp = await this.session.newCDPSession(active.page);
1813
+ const handler = (payload: Record<string, unknown>) => {
1814
+ const sessionId = payload.sessionId;
1815
+ if (typeof sessionId === 'number') {
1816
+ void cdp.send('Page.screencastFrameAck', { sessionId }).catch(() => {});
1817
+ }
1818
+ const data = typeof payload.data === 'string' ? payload.data : '';
1819
+ if (!data || this.streamListeners.size === 0) return;
1820
+ const meta = payload.metadata && typeof payload.metadata === 'object'
1821
+ ? (payload.metadata as { deviceWidth?: number; deviceHeight?: number })
1822
+ : null;
1823
+ if (typeof meta?.deviceWidth === 'number' && meta.deviceWidth > 0) this.cachedWidth = meta.deviceWidth;
1824
+ if (typeof meta?.deviceHeight === 'number' && meta.deviceHeight > 0) this.cachedHeight = meta.deviceHeight;
1825
+ const liveUrl = active.page.url();
1826
+ if (liveUrl && liveUrl !== this.cachedUrl) {
1827
+ this.cachedUrl = liveUrl;
1828
+ this.cachedTabSummaries = this.cachedTabSummaries.map((t) =>
1829
+ t.tabId === active.id ? { ...t, url: liveUrl } : t
1830
+ );
1831
+ void this.refreshCachedTabMetadata().catch(() => {});
1832
+ }
1833
+ const status = this.getRuntimeStatus();
1834
+ this.emitLiveStreamEvent({
1835
+ type: 'frame',
1836
+ active: true,
1837
+ visible: status.visible,
1838
+ engine: status.engine,
1839
+ enginePreference: status.enginePreference,
1840
+ streamMode: 'cdp-screencast',
1841
+ enginesAvailable: status.enginesAvailable,
1842
+ tabId: this.activeTabId,
1843
+ url: liveUrl || this.cachedUrl,
1844
+ title: this.cachedTitle,
1845
+ width: this.cachedWidth,
1846
+ height: this.cachedHeight,
1847
+ tabs: this.cachedTabSummaries,
1848
+ imageBase64: data,
1849
+ mimeType: 'image/jpeg',
1850
+ fps: this.computeLiveFps()
1851
+ });
1852
+ };
1853
+ cdp.on('Page.screencastFrame', handler);
1854
+ await cdp.send('Page.startScreencast', {
1855
+ format: 'jpeg',
1856
+ quality: 68,
1857
+ maxWidth: Math.min(1440, Math.max(320, this.cachedWidth)),
1858
+ maxHeight: Math.min(960, Math.max(240, this.cachedHeight)),
1859
+ everyNthFrame: 1
1860
+ });
1861
+ this.cdpSession = cdp;
1862
+ this.cdpPage = active.page;
1863
+ this.cdpFrameHandler = handler;
1864
+ this.streamMode = 'cdp-screencast';
1865
+ void this.pushSingleAdaptiveFrame().catch(() => {});
1866
+ return;
1867
+ } catch {
1868
+ // Fall through cleanly to adaptive frame streaming if CDP screencast is unavailable.
1869
+ }
1870
+ }
1871
+
1872
+ this.streamMode = 'adaptive-frames';
1873
+ if (!this.adaptiveTimer) {
1874
+ this.adaptiveTimer = setInterval(() => {
1875
+ void this.pushSingleAdaptiveFrame().catch(() => {});
1876
+ }, 240);
1877
+ this.adaptiveTimer.unref?.();
1878
+ }
1879
+ void this.pushSingleAdaptiveFrame().catch(() => {});
1880
+ }
1881
+
1882
+ async captureLiveFrame(options: { ensureStarted?: boolean | undefined } = {}): Promise<LiveBrowserFrame> {
1883
+ return this.enqueueOperation(() => this.captureLiveFrameUnlocked(options));
1884
+ }
1885
+
1886
+ private async captureLiveFrameUnlocked(options: { ensureStarted?: boolean | undefined } = {}): Promise<LiveBrowserFrame> {
1887
+ const status = this.getRuntimeStatus();
1888
+ if (!this.isSessionHealthy()) {
1889
+ if (!options.ensureStarted) {
1890
+ return {
1891
+ active: false,
1892
+ visible: status.visible,
1893
+ engine: status.engine,
1894
+ enginePreference: status.enginePreference,
1895
+ streamMode: this.streamMode,
1896
+ enginesAvailable: status.enginesAvailable,
1897
+ tabId: null,
1898
+ url: '',
1899
+ title: '',
1900
+ width: 1280,
1901
+ height: 800,
1902
+ tabs: [],
1903
+ imageBase64: null,
1904
+ mimeType: 'image/jpeg'
1905
+ };
1906
+ }
1907
+ await this.start();
1908
+ }
1909
+ const state = await this.activeTab();
1910
+ const vp = typeof state.page.viewportSize === 'function' ? state.page.viewportSize() : null;
1911
+ const width = vp?.width ?? 1280;
1912
+ const height = vp?.height ?? 800;
1913
+ const tabs: LiveBrowserTabSummary[] = [];
1914
+ for (const tab of this.tabs.values()) {
1915
+ if (tab.page.isClosed() || tab.crashed) continue;
1916
+ tabs.push({
1917
+ tabId: tab.id,
1918
+ url: tab.page.url(),
1919
+ title: await this.safePageTitle(tab.page),
1920
+ active: tab.id === state.id
1921
+ });
1922
+ }
1923
+ let imageBase64: string | null = null;
1924
+ let mimeType: 'image/jpeg' | 'image/png' = 'image/jpeg';
1925
+ try {
1926
+ const buf = await state.page.screenshot({ type: 'jpeg', quality: 72, timeout: 5000 });
1927
+ imageBase64 = buf.toString('base64');
1928
+ } catch {
1929
+ try {
1930
+ const buf = await state.page.screenshot({ type: 'png', timeout: 5000 });
1931
+ imageBase64 = buf.toString('base64');
1932
+ mimeType = 'image/png';
1933
+ } catch {
1934
+ imageBase64 = null;
1935
+ }
1936
+ }
1937
+ this.cachedUrl = state.page.url();
1938
+ this.cachedTitle = await this.safePageTitle(state.page);
1939
+ this.cachedWidth = width;
1940
+ this.cachedHeight = height;
1941
+ this.cachedTabSummaries = tabs;
1942
+ if (this.streamListeners.size > 0) {
1943
+ void this.syncLiveStreamAttachment().catch(() => {});
1944
+ const latestStatus = this.getRuntimeStatus();
1945
+ this.emitLiveStreamEvent({
1946
+ type: 'meta',
1947
+ active: true,
1948
+ visible: latestStatus.visible,
1949
+ engine: latestStatus.engine,
1950
+ enginePreference: latestStatus.enginePreference,
1951
+ streamMode: this.streamMode,
1952
+ enginesAvailable: latestStatus.enginesAvailable,
1953
+ tabId: state.id,
1954
+ url: this.cachedUrl,
1955
+ title: this.cachedTitle,
1956
+ width,
1957
+ height,
1958
+ tabs
1959
+ });
1960
+ }
1961
+ const updatedStatus = this.getRuntimeStatus();
1962
+ this.touch();
1963
+ return {
1964
+ active: true,
1965
+ visible: updatedStatus.visible,
1966
+ engine: updatedStatus.engine,
1967
+ enginePreference: updatedStatus.enginePreference,
1968
+ streamMode: this.streamMode,
1969
+ enginesAvailable: updatedStatus.enginesAvailable,
1970
+ tabId: state.id,
1971
+ url: this.cachedUrl,
1972
+ title: this.cachedTitle,
1973
+ width,
1974
+ height,
1975
+ tabs,
1976
+ imageBase64,
1977
+ mimeType
1978
+ };
1979
+ }
1980
+
1981
+ private async dispatchInputOnPage(state: TabState, input: LiveBrowserInteraction): Promise<void> {
1982
+ const vp = typeof state.page.viewportSize === 'function' ? state.page.viewportSize() : null;
1983
+ const maxW = vp?.width ?? 1280;
1984
+ const maxH = vp?.height ?? 800;
1985
+ const clamp = (val: unknown, lo: number, hi: number): number => {
1986
+ const n = typeof val === 'number' && Number.isFinite(val) ? val : 0;
1987
+ return Math.max(lo, Math.min(hi, Math.round(n)));
1988
+ };
1989
+ const btn: 'left' | 'right' | 'middle' = input.button === 'right' || input.button === 'middle' ? input.button : 'left';
1990
+
1991
+ if (input.kind === 'mousemove') {
1992
+ const x = clamp(input.x, 0, maxW);
1993
+ const y = clamp(input.y, 0, maxH);
1994
+ if (typeof state.page.mouse.move === 'function') {
1995
+ await state.page.mouse.move(x, y);
1996
+ }
1997
+ } else if (input.kind === 'mousedown') {
1998
+ const x = clamp(input.x, 0, maxW);
1999
+ const y = clamp(input.y, 0, maxH);
2000
+ if (typeof state.page.mouse.move === 'function') await state.page.mouse.move(x, y);
2001
+ if (typeof state.page.mouse.down === 'function') await state.page.mouse.down({ button: btn });
2002
+ } else if (input.kind === 'mouseup') {
2003
+ const x = clamp(input.x, 0, maxW);
2004
+ const y = clamp(input.y, 0, maxH);
2005
+ if (typeof state.page.mouse.move === 'function') await state.page.mouse.move(x, y);
2006
+ if (typeof state.page.mouse.up === 'function') await state.page.mouse.up({ button: btn });
2007
+ } else if (input.kind === 'click' || input.kind === 'dblclick' || input.kind === 'contextmenu') {
2008
+ const x = clamp(input.x, 0, maxW);
2009
+ const y = clamp(input.y, 0, maxH);
2010
+ const clickBtn = input.kind === 'contextmenu' ? 'right' : btn;
2011
+ if (input.kind === 'dblclick' && typeof state.page.mouse.dblclick === 'function') {
2012
+ await state.page.mouse.dblclick(x, y, { button: clickBtn });
2013
+ } else if (typeof state.page.mouse.click === 'function') {
2014
+ await state.page.mouse.click(x, y, { button: clickBtn });
2015
+ } else if (state.page.mouse.move && state.page.mouse.down && state.page.mouse.up) {
2016
+ await state.page.mouse.move(x, y);
2017
+ await state.page.mouse.down({ button: clickBtn });
2018
+ await state.page.mouse.up({ button: clickBtn });
2019
+ }
2020
+ if (!input.skipFrame) await state.page.waitForTimeout(140);
2021
+ } else if (input.kind === 'wheel') {
2022
+ const dx = clamp(input.deltaX, -1200, 1200);
2023
+ const dy = clamp(input.deltaY, -1600, 1600);
2024
+ await state.page.mouse.wheel(dx, dy);
2025
+ if (!input.skipFrame) await state.page.waitForTimeout(90);
2026
+ } else if (input.kind === 'type' || input.kind === 'paste') {
2027
+ const text = typeof input.text === 'string' ? input.text.slice(0, 4000) : '';
2028
+ if (text) {
2029
+ if (typeof state.page.keyboard.insertText === 'function') {
2030
+ await state.page.keyboard.insertText(text);
2031
+ } else if (typeof state.page.keyboard.type === 'function') {
2032
+ await state.page.keyboard.type(text, { delay: 10 });
2033
+ }
2034
+ if (!input.skipFrame) await state.page.waitForTimeout(80);
2035
+ }
2036
+ } else if (input.kind === 'key') {
2037
+ const key = normalizeBrowserKey(String(input.key || 'Enter'));
2038
+ await state.page.keyboard.press(key);
2039
+ if (!input.skipFrame) await state.page.waitForTimeout(100);
2040
+ }
2041
+ state.refs.clear();
2042
+ }
2043
+
2044
+ /** Ultra-low-latency direct input dispatch when real-time live stream is active. */
2045
+ async dispatchLiveInput(input: LiveBrowserInteraction): Promise<{ ok: boolean }> {
2046
+ if (!this.isSessionHealthy()) {
2047
+ await this.interactAt(input);
2048
+ return { ok: true };
2049
+ }
2050
+ const active = this.activeTabId
2051
+ ? this.tabs.get(this.activeTabId)
2052
+ : [...this.tabs.values()].find(t => !t.page.isClosed() && !t.crashed);
2053
+ if (!active || active.page.isClosed() || active.crashed) {
2054
+ return { ok: false };
2055
+ }
2056
+ await this.dispatchInputOnPage(active, { ...input, skipFrame: true });
2057
+ this.touch();
2058
+ if (this.streamMode === 'adaptive-frames') {
2059
+ void this.pushSingleAdaptiveFrame().catch(() => {});
2060
+ }
2061
+ return { ok: true };
2062
+ }
2063
+
2064
+ async interactAt(input: LiveBrowserInteraction): Promise<LiveBrowserFrame> {
2065
+ return this.enqueueOperation(async () => {
2066
+ await this.start();
2067
+ const state = await this.activeTab();
2068
+ await this.dispatchInputOnPage(state, input);
2069
+ return this.captureLiveFrameUnlocked({ ensureStarted: true });
2070
+ });
2071
+ }
2072
+
2073
+ async importCookies(cookies: BrowserCookieRecord[]): Promise<{ imported: number }> {
2074
+ return this.enqueueOperation(async () => {
2075
+ await this.start();
2076
+ if (!this.session || typeof this.session.addCookies !== 'function') {
2077
+ throw new Error('Active browser engine does not support cookie session import.');
2078
+ }
2079
+ const sanitized: BrowserCookieRecord[] = [];
2080
+ for (const item of cookies.slice(0, 200)) {
2081
+ if (!item || typeof item.name !== 'string' || typeof item.value !== 'string' || typeof item.domain !== 'string') {
2082
+ continue;
2083
+ }
2084
+ const name = item.name.trim();
2085
+ const domain = item.domain.trim();
2086
+ if (!name || !domain || domain.includes('\0') || name.includes('\0')) continue;
2087
+ const entry: BrowserCookieRecord = {
2088
+ name,
2089
+ value: item.value,
2090
+ domain,
2091
+ path: typeof item.path === 'string' && item.path.startsWith('/') ? item.path : '/'
2092
+ };
2093
+ if (typeof item.expires === 'number' && Number.isFinite(item.expires) && item.expires > 0) {
2094
+ entry.expires = item.expires;
2095
+ }
2096
+ if (typeof item.httpOnly === 'boolean') entry.httpOnly = item.httpOnly;
2097
+ if (typeof item.secure === 'boolean') entry.secure = item.secure;
2098
+ if (item.sameSite === 'Strict' || item.sameSite === 'Lax' || item.sameSite === 'None') {
2099
+ entry.sameSite = item.sameSite;
2100
+ }
2101
+ sanitized.push(entry);
2102
+ }
2103
+ if (sanitized.length > 0) {
2104
+ await this.session.addCookies(sanitized);
2105
+ }
2106
+ this.touch();
2107
+ return { imported: sanitized.length };
2108
+ });
2109
+ }
2110
+
2111
+ async exportSessionCookies(url?: string): Promise<BrowserCookieRecord[]> {
2112
+ return this.enqueueOperation(async () => {
2113
+ if (!this.isSessionHealthy() || !this.session || typeof this.session.cookies !== 'function') {
2114
+ return [];
2115
+ }
2116
+ return url ? this.session.cookies([url]) : this.session.cookies();
2117
+ });
2118
+ }
2119
+
1154
2120
  private isSessionHealthy(): boolean {
1155
2121
  if (!this.session) return false;
1156
2122
  if (typeof this.session.isConnected === 'function' && !this.session.isConnected()) {
@@ -1164,6 +2130,24 @@ export class CausyneBrowser {
1164
2130
  }
1165
2131
  }
1166
2132
 
2133
+ private resolvePreferredRuntime(): PreparedBrowserRuntime {
2134
+ if (this.customResolveRuntime || this.enginePreference === 'auto') {
2135
+ return this.resolveRuntime();
2136
+ }
2137
+ if (this.enginePreference === 'camoufox') {
2138
+ const cf = resolveCamoufoxRuntime();
2139
+ if (!cf) {
2140
+ throw new Error('Camoufox runtime is not installed locally. Install Camoufox and set CAMOUFOX_EXECUTABLE_PATH, or switch engine to Chromium.');
2141
+ }
2142
+ return cf;
2143
+ }
2144
+ const ch = resolveChromiumRuntime();
2145
+ if (!ch) {
2146
+ throw new Error('Chromium/Chrome runtime was not found locally. Switch engine to Auto or Camoufox.');
2147
+ }
2148
+ return ch;
2149
+ }
2150
+
1167
2151
  private async start(): Promise<void> {
1168
2152
  if (this.session) {
1169
2153
  if (this.isSessionHealthy()) return;
@@ -1173,42 +2157,64 @@ export class CausyneBrowser {
1173
2157
  this.starting = (async () => {
1174
2158
  const verdict = await this.ensureBrowserCapability();
1175
2159
  if (!verdict.ok) throw new BrowserCapabilityError(verdict.reason ?? 'Browser capability is unavailable', verdict.requiresConsent);
1176
- const runtime = this.resolveRuntime();
2160
+ const runtime = this.resolvePreferredRuntime();
1177
2161
  if (runtime.engine === 'chromium') {
2162
+ this.activeEngine = 'chromium';
1178
2163
  const engine = await loadCapabilityPackage('playwright-core') as { chromium: { launchPersistentContext(profile: string, options: Record<string, unknown>): Promise<BrowserSession> } };
1179
2164
  const profile = path.join(this.profileDirectory, 'chromium');
2165
+ const isSystemChrome = runtime.source === 'system'
2166
+ && typeof runtime.executablePath === 'string'
2167
+ && !/headless/i.test(path.basename(runtime.executablePath));
2168
+ const desktopUa = process.platform === 'darwin'
2169
+ ? 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
2170
+ : (process.platform === 'win32'
2171
+ ? 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
2172
+ : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36');
1180
2173
  const chromiumArgs = [
2174
+ ...(!this.visible && isSystemChrome ? ['--headless=new'] : []),
1181
2175
  '--enable-webgl',
1182
2176
  '--use-gl=angle',
1183
2177
  ...(process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=swiftshader']),
1184
2178
  '--ignore-gpu-blocklist',
1185
- '--enable-gpu-rasterization'
2179
+ '--enable-gpu-rasterization',
2180
+ '--autoplay-policy=no-user-gesture-required',
2181
+ '--disable-blink-features=AutomationControlled',
2182
+ ...(this.visible ? ['--window-size=1300,880'] : [])
1186
2183
  ];
1187
2184
  this.session = await engine.chromium.launchPersistentContext(profile, {
1188
- executablePath: runtime.executablePath, headless: !this.visible, serviceWorkers: 'block', chromiumSandbox: true,
2185
+ executablePath: runtime.executablePath,
2186
+ headless: !this.visible,
2187
+ viewport: { width: 1280, height: 800 },
2188
+ ...(!this.visible ? { userAgent: desktopUa } : {}),
2189
+ ignoreDefaultArgs: ['--enable-automation'],
2190
+ serviceWorkers: 'block',
2191
+ chromiumSandbox: true,
1189
2192
  args: chromiumArgs,
1190
- handleSIGTERM: false, handleSIGINT: false, handleSIGHUP: false
2193
+ handleSIGTERM: false,
2194
+ handleSIGINT: false,
2195
+ handleSIGHUP: false
1191
2196
  });
1192
2197
  } else {
1193
- process.env.CAMOUFOX_INSTALL_DIR = runtime.installDirectory;
1194
- await fs.mkdir(this.profileDirectory, { recursive: true, mode: 0o700 });
1195
- const module = await this.loadBrowserEngine();
1196
- if (!module || typeof module.Camoufox !== 'function') throw new Error('Causyne Browser has no usable launcher');
1197
- this.session = await module.Camoufox({
1198
- headless: !this.visible,
1199
- user_data_dir: this.profileDirectory,
1200
- humanize: 0.35,
1201
- block_webrtc: true,
1202
- geoip: false,
1203
- enable_cache: true,
1204
- ...(runtime.executablePath ? { executable_path: runtime.executablePath } : {}),
1205
- firefox_user_prefs: {
1206
- 'Security.OCSP.enabled': 0
1207
- },
1208
- handleSIGTERM: false,
1209
- handleSIGINT: false,
1210
- handleSIGHUP: false
1211
- });
2198
+ this.activeEngine = 'camoufox';
2199
+ process.env.CAMOUFOX_INSTALL_DIR = runtime.installDirectory;
2200
+ await fs.mkdir(this.profileDirectory, { recursive: true, mode: 0o700 });
2201
+ const module = await this.loadBrowserEngine();
2202
+ if (!module || typeof module.Camoufox !== 'function') throw new Error('Causyne Browser has no usable launcher');
2203
+ this.session = await module.Camoufox({
2204
+ headless: !this.visible,
2205
+ user_data_dir: this.profileDirectory,
2206
+ humanize: 0.35,
2207
+ block_webrtc: true,
2208
+ geoip: false,
2209
+ enable_cache: true,
2210
+ ...(runtime.executablePath ? { executable_path: runtime.executablePath } : {}),
2211
+ firefox_user_prefs: {
2212
+ 'Security.OCSP.enabled': 0
2213
+ },
2214
+ handleSIGTERM: false,
2215
+ handleSIGINT: false,
2216
+ handleSIGHUP: false
2217
+ });
1212
2218
  }
1213
2219
  if (typeof this.session.route === 'function') {
1214
2220
  await this.session.route('**/*', route => this.guardRoute(route));
@@ -1218,6 +2224,9 @@ export class CausyneBrowser {
1218
2224
  const existing = this.session.pages().find(page => !page.isClosed());
1219
2225
  if (existing) await this.registerPage(existing);
1220
2226
  else await this.createTab();
2227
+ if (this.streamListeners.size > 0) {
2228
+ void this.syncLiveStreamAttachment().catch(() => {});
2229
+ }
1221
2230
  })();
1222
2231
  try {
1223
2232
  await this.starting;
@@ -1472,6 +2481,7 @@ export class CausyneBrowser {
1472
2481
  state.lastSnapshot = '';
1473
2482
  state.lastStructure = null;
1474
2483
  this.lastTarget = { kind: 'url', url: state.page.url() };
2484
+ await this.refreshCachedTabMetadata().catch(() => {});
1475
2485
  }
1476
2486
 
1477
2487
  private async preview(state: TabState, filePath: string, workspace: string): Promise<void> {