superbased 1.6.3 → 2.0.0

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 (423) hide show
  1. package/README.md +169 -36
  2. package/SUPERBASED_SKILL.md +1196 -22
  3. package/dist/electron/core/input-injection/index.d.ts +6 -0
  4. package/dist/electron/core/input-injection/index.d.ts.map +1 -0
  5. package/dist/electron/core/input-injection/index.js +31 -0
  6. package/dist/electron/core/input-injection/index.js.map +1 -0
  7. package/dist/electron/core/input-injection/macos.d.ts +3 -0
  8. package/dist/electron/core/input-injection/macos.d.ts.map +1 -0
  9. package/dist/electron/core/input-injection/macos.js +14 -0
  10. package/dist/electron/core/input-injection/macos.js.map +1 -0
  11. package/dist/electron/core/input-injection/windows.d.ts +3 -0
  12. package/dist/electron/core/input-injection/windows.d.ts.map +1 -0
  13. package/dist/electron/core/input-injection/windows.js +119 -0
  14. package/dist/electron/core/input-injection/windows.js.map +1 -0
  15. package/dist/electron/core/json-store.d.ts +22 -0
  16. package/dist/electron/core/json-store.d.ts.map +1 -1
  17. package/dist/electron/core/json-store.js +61 -47
  18. package/dist/electron/core/json-store.js.map +1 -1
  19. package/dist/electron/core/platform.d.ts +1 -0
  20. package/dist/electron/core/platform.d.ts.map +1 -1
  21. package/dist/electron/core/serialize-schema.d.ts +35 -0
  22. package/dist/electron/core/serialize-schema.d.ts.map +1 -0
  23. package/dist/electron/core/serialize-schema.js +89 -0
  24. package/dist/electron/core/serialize-schema.js.map +1 -0
  25. package/dist/electron/core/settings-schema.d.ts +81 -0
  26. package/dist/electron/core/settings-schema.d.ts.map +1 -0
  27. package/dist/electron/core/settings-schema.js +1357 -0
  28. package/dist/electron/core/settings-schema.js.map +1 -0
  29. package/dist/electron/logger.d.ts.map +1 -1
  30. package/dist/electron/logger.js +22 -8
  31. package/dist/electron/logger.js.map +1 -1
  32. package/dist/electron/main.js +417 -133
  33. package/dist/electron/modules/accessibility/macos-provider.d.ts +8 -0
  34. package/dist/electron/modules/accessibility/macos-provider.d.ts.map +1 -0
  35. package/dist/electron/modules/accessibility/macos-provider.js +94 -0
  36. package/dist/electron/modules/accessibility/macos-provider.js.map +1 -0
  37. package/dist/electron/modules/accessibility/provider.d.ts +12 -0
  38. package/dist/electron/modules/accessibility/provider.d.ts.map +1 -0
  39. package/dist/electron/modules/accessibility/provider.js +52 -0
  40. package/dist/electron/modules/accessibility/provider.js.map +1 -0
  41. package/dist/electron/modules/accessibility/types.d.ts +63 -0
  42. package/dist/electron/modules/accessibility/types.d.ts.map +1 -0
  43. package/dist/electron/modules/accessibility/types.js +6 -0
  44. package/dist/electron/modules/accessibility/types.js.map +1 -0
  45. package/dist/electron/modules/accessibility/windows-provider.d.ts +8 -0
  46. package/dist/electron/modules/accessibility/windows-provider.d.ts.map +1 -0
  47. package/dist/electron/modules/accessibility/windows-provider.js +85 -0
  48. package/dist/electron/modules/accessibility/windows-provider.js.map +1 -0
  49. package/dist/electron/modules/api-server.d.ts +4 -1
  50. package/dist/electron/modules/api-server.d.ts.map +1 -1
  51. package/dist/electron/modules/api-server.js +1414 -218
  52. package/dist/electron/modules/api-server.js.map +1 -1
  53. package/dist/electron/modules/auth.d.ts +14 -0
  54. package/dist/electron/modules/auth.d.ts.map +1 -1
  55. package/dist/electron/modules/auth.js +43 -0
  56. package/dist/electron/modules/auth.js.map +1 -1
  57. package/dist/electron/modules/azure-speech-realtime.d.ts.map +1 -1
  58. package/dist/electron/modules/azure-speech-realtime.js +56 -0
  59. package/dist/electron/modules/azure-speech-realtime.js.map +1 -1
  60. package/dist/electron/modules/capture.d.ts +8 -0
  61. package/dist/electron/modules/capture.d.ts.map +1 -1
  62. package/dist/electron/modules/capture.js +33 -0
  63. package/dist/electron/modules/capture.js.map +1 -1
  64. package/dist/electron/modules/compose-screenshots.d.ts +8 -0
  65. package/dist/electron/modules/compose-screenshots.d.ts.map +1 -0
  66. package/dist/electron/modules/compose-screenshots.js +86 -0
  67. package/dist/electron/modules/compose-screenshots.js.map +1 -0
  68. package/dist/electron/modules/context-menu-detect.d.ts +47 -0
  69. package/dist/electron/modules/context-menu-detect.d.ts.map +1 -0
  70. package/dist/electron/modules/context-menu-detect.js +272 -0
  71. package/dist/electron/modules/context-menu-detect.js.map +1 -0
  72. package/dist/electron/modules/dictation.d.ts.map +1 -1
  73. package/dist/electron/modules/dictation.js +12 -7
  74. package/dist/electron/modules/dictation.js.map +1 -1
  75. package/dist/electron/modules/gif-util.d.ts +9 -0
  76. package/dist/electron/modules/gif-util.d.ts.map +1 -0
  77. package/dist/electron/modules/gif-util.js +63 -0
  78. package/dist/electron/modules/gif-util.js.map +1 -0
  79. package/dist/electron/modules/gui-automation-errors.d.ts +11 -0
  80. package/dist/electron/modules/gui-automation-errors.d.ts.map +1 -0
  81. package/dist/electron/modules/gui-automation-errors.js +79 -0
  82. package/dist/electron/modules/gui-automation-errors.js.map +1 -0
  83. package/dist/electron/modules/gui-automation-telemetry.d.ts +38 -0
  84. package/dist/electron/modules/gui-automation-telemetry.d.ts.map +1 -0
  85. package/dist/electron/modules/gui-automation-telemetry.js +200 -0
  86. package/dist/electron/modules/gui-automation-telemetry.js.map +1 -0
  87. package/dist/electron/modules/gui-automation.d.ts +1143 -0
  88. package/dist/electron/modules/gui-automation.d.ts.map +1 -0
  89. package/dist/electron/modules/gui-automation.js +8769 -0
  90. package/dist/electron/modules/gui-automation.js.map +1 -0
  91. package/dist/electron/modules/hotkeys.d.ts +2 -1
  92. package/dist/electron/modules/hotkeys.d.ts.map +1 -1
  93. package/dist/electron/modules/hotkeys.js +25 -1
  94. package/dist/electron/modules/hotkeys.js.map +1 -1
  95. package/dist/electron/modules/human-input/index.d.ts +35 -0
  96. package/dist/electron/modules/human-input/index.d.ts.map +1 -0
  97. package/dist/electron/modules/human-input/index.js +163 -0
  98. package/dist/electron/modules/human-input/index.js.map +1 -0
  99. package/dist/electron/modules/human-input/keyboard/timing.d.ts +38 -0
  100. package/dist/electron/modules/human-input/keyboard/timing.d.ts.map +1 -0
  101. package/dist/electron/modules/human-input/keyboard/timing.js +57 -0
  102. package/dist/electron/modules/human-input/keyboard/timing.js.map +1 -0
  103. package/dist/electron/modules/human-input/mouse/path.d.ts +24 -0
  104. package/dist/electron/modules/human-input/mouse/path.d.ts.map +1 -0
  105. package/dist/electron/modules/human-input/mouse/path.js +80 -0
  106. package/dist/electron/modules/human-input/mouse/path.js.map +1 -0
  107. package/dist/electron/modules/human-input/mouse/velocity.d.ts +48 -0
  108. package/dist/electron/modules/human-input/mouse/velocity.d.ts.map +1 -0
  109. package/dist/electron/modules/human-input/mouse/velocity.js +93 -0
  110. package/dist/electron/modules/human-input/mouse/velocity.js.map +1 -0
  111. package/dist/electron/modules/human-input/profiles.d.ts +90 -0
  112. package/dist/electron/modules/human-input/profiles.d.ts.map +1 -0
  113. package/dist/electron/modules/human-input/profiles.js +124 -0
  114. package/dist/electron/modules/human-input/profiles.js.map +1 -0
  115. package/dist/electron/modules/human-input/rng.d.ts +16 -0
  116. package/dist/electron/modules/human-input/rng.d.ts.map +1 -0
  117. package/dist/electron/modules/human-input/rng.js +101 -0
  118. package/dist/electron/modules/human-input/rng.js.map +1 -0
  119. package/dist/electron/modules/human-input/salt.d.ts +15 -0
  120. package/dist/electron/modules/human-input/salt.d.ts.map +1 -0
  121. package/dist/electron/modules/human-input/salt.js +48 -0
  122. package/dist/electron/modules/human-input/salt.js.map +1 -0
  123. package/dist/electron/modules/image-utils.d.ts +20 -0
  124. package/dist/electron/modules/image-utils.d.ts.map +1 -0
  125. package/dist/electron/modules/image-utils.js +80 -0
  126. package/dist/electron/modules/image-utils.js.map +1 -0
  127. package/dist/electron/modules/ollama/capability.d.ts +32 -0
  128. package/dist/electron/modules/ollama/capability.d.ts.map +1 -0
  129. package/dist/electron/modules/ollama/capability.js +117 -0
  130. package/dist/electron/modules/ollama/capability.js.map +1 -0
  131. package/dist/electron/modules/ollama/client.d.ts +14 -0
  132. package/dist/electron/modules/ollama/client.d.ts.map +1 -0
  133. package/dist/electron/modules/ollama/client.js +134 -0
  134. package/dist/electron/modules/ollama/client.js.map +1 -0
  135. package/dist/electron/modules/ollama/detector.d.ts +29 -0
  136. package/dist/electron/modules/ollama/detector.d.ts.map +1 -0
  137. package/dist/electron/modules/ollama/detector.js +177 -0
  138. package/dist/electron/modules/ollama/detector.js.map +1 -0
  139. package/dist/electron/modules/ollama/dispatcher.d.ts +36 -0
  140. package/dist/electron/modules/ollama/dispatcher.d.ts.map +1 -0
  141. package/dist/electron/modules/ollama/dispatcher.js +97 -0
  142. package/dist/electron/modules/ollama/dispatcher.js.map +1 -0
  143. package/dist/electron/modules/ollama/router.d.ts +51 -0
  144. package/dist/electron/modules/ollama/router.d.ts.map +1 -0
  145. package/dist/electron/modules/ollama/router.js +201 -0
  146. package/dist/electron/modules/ollama/router.js.map +1 -0
  147. package/dist/electron/modules/pin-window.d.ts.map +1 -1
  148. package/dist/electron/modules/pin-window.js +2 -1
  149. package/dist/electron/modules/pin-window.js.map +1 -1
  150. package/dist/electron/modules/platform/dpi.d.ts +2 -0
  151. package/dist/electron/modules/platform/dpi.d.ts.map +1 -0
  152. package/dist/electron/modules/platform/dpi.js +48 -0
  153. package/dist/electron/modules/platform/dpi.js.map +1 -0
  154. package/dist/electron/modules/platform/errors.d.ts +13 -0
  155. package/dist/electron/modules/platform/errors.d.ts.map +1 -0
  156. package/dist/electron/modules/platform/errors.js +36 -0
  157. package/dist/electron/modules/platform/errors.js.map +1 -0
  158. package/dist/electron/modules/platform/index.d.ts +24 -0
  159. package/dist/electron/modules/platform/index.d.ts.map +1 -0
  160. package/dist/electron/modules/platform/index.js +133 -0
  161. package/dist/electron/modules/platform/index.js.map +1 -0
  162. package/dist/electron/modules/platform/interfaces.d.ts +140 -0
  163. package/dist/electron/modules/platform/interfaces.d.ts.map +1 -0
  164. package/dist/electron/modules/platform/interfaces.js +14 -0
  165. package/dist/electron/modules/platform/interfaces.js.map +1 -0
  166. package/dist/electron/modules/platform/macos/ax.d.ts +15 -0
  167. package/dist/electron/modules/platform/macos/ax.d.ts.map +1 -0
  168. package/dist/electron/modules/platform/macos/ax.js +222 -0
  169. package/dist/electron/modules/platform/macos/ax.js.map +1 -0
  170. package/dist/electron/modules/platform/macos/capture.d.ts +14 -0
  171. package/dist/electron/modules/platform/macos/capture.d.ts.map +1 -0
  172. package/dist/electron/modules/platform/macos/capture.js +106 -0
  173. package/dist/electron/modules/platform/macos/capture.js.map +1 -0
  174. package/dist/electron/modules/platform/macos/input.d.ts +16 -0
  175. package/dist/electron/modules/platform/macos/input.d.ts.map +1 -0
  176. package/dist/electron/modules/platform/macos/input.js +342 -0
  177. package/dist/electron/modules/platform/macos/input.js.map +1 -0
  178. package/dist/electron/modules/platform/macos/launch.d.ts +10 -0
  179. package/dist/electron/modules/platform/macos/launch.d.ts.map +1 -0
  180. package/dist/electron/modules/platform/macos/launch.js +114 -0
  181. package/dist/electron/modules/platform/macos/launch.js.map +1 -0
  182. package/dist/electron/modules/platform/macos/session.d.ts +8 -0
  183. package/dist/electron/modules/platform/macos/session.d.ts.map +1 -0
  184. package/dist/electron/modules/platform/macos/session.js +17 -0
  185. package/dist/electron/modules/platform/macos/session.js.map +1 -0
  186. package/dist/electron/modules/platform/macos/window.d.ts +31 -0
  187. package/dist/electron/modules/platform/macos/window.d.ts.map +1 -0
  188. package/dist/electron/modules/platform/macos/window.js +271 -0
  189. package/dist/electron/modules/platform/macos/window.js.map +1 -0
  190. package/dist/electron/modules/platform/shared.d.ts +10 -0
  191. package/dist/electron/modules/platform/shared.d.ts.map +1 -0
  192. package/dist/electron/modules/platform/shared.js +201 -0
  193. package/dist/electron/modules/platform/shared.js.map +1 -0
  194. package/dist/electron/modules/platform/types.d.ts +182 -0
  195. package/dist/electron/modules/platform/types.d.ts.map +1 -0
  196. package/dist/electron/modules/platform/types.js +24 -0
  197. package/dist/electron/modules/platform/types.js.map +1 -0
  198. package/dist/electron/modules/platform/windows/ax.d.ts +15 -0
  199. package/dist/electron/modules/platform/windows/ax.d.ts.map +1 -0
  200. package/dist/electron/modules/platform/windows/ax.js +277 -0
  201. package/dist/electron/modules/platform/windows/ax.js.map +1 -0
  202. package/dist/electron/modules/platform/windows/capture.d.ts +14 -0
  203. package/dist/electron/modules/platform/windows/capture.d.ts.map +1 -0
  204. package/dist/electron/modules/platform/windows/capture.js +115 -0
  205. package/dist/electron/modules/platform/windows/capture.js.map +1 -0
  206. package/dist/electron/modules/platform/windows/input.d.ts +17 -0
  207. package/dist/electron/modules/platform/windows/input.d.ts.map +1 -0
  208. package/dist/electron/modules/platform/windows/input.js +422 -0
  209. package/dist/electron/modules/platform/windows/input.js.map +1 -0
  210. package/dist/electron/modules/platform/windows/launch.d.ts +10 -0
  211. package/dist/electron/modules/platform/windows/launch.d.ts.map +1 -0
  212. package/dist/electron/modules/platform/windows/launch.js +185 -0
  213. package/dist/electron/modules/platform/windows/launch.js.map +1 -0
  214. package/dist/electron/modules/platform/windows/session.d.ts +8 -0
  215. package/dist/electron/modules/platform/windows/session.d.ts.map +1 -0
  216. package/dist/electron/modules/platform/windows/session.js +87 -0
  217. package/dist/electron/modules/platform/windows/session.js.map +1 -0
  218. package/dist/electron/modules/platform/windows/tray.d.ts +13 -0
  219. package/dist/electron/modules/platform/windows/tray.d.ts.map +1 -0
  220. package/dist/electron/modules/platform/windows/tray.js +390 -0
  221. package/dist/electron/modules/platform/windows/tray.js.map +1 -0
  222. package/dist/electron/modules/platform/windows/window.d.ts +30 -0
  223. package/dist/electron/modules/platform/windows/window.d.ts.map +1 -0
  224. package/dist/electron/modules/platform/windows/window.js +444 -0
  225. package/dist/electron/modules/platform/windows/window.js.map +1 -0
  226. package/dist/electron/modules/recording/providers/change-detect-shared-wrapper.d.ts +15 -0
  227. package/dist/electron/modules/recording/providers/change-detect-shared-wrapper.d.ts.map +1 -0
  228. package/dist/electron/modules/recording/providers/change-detect-shared-wrapper.js +62 -0
  229. package/dist/electron/modules/recording/providers/change-detect-shared-wrapper.js.map +1 -0
  230. package/dist/electron/modules/recording/providers/provider-factory.d.ts.map +1 -1
  231. package/dist/electron/modules/recording/providers/provider-factory.js +13 -7
  232. package/dist/electron/modules/recording/providers/provider-factory.js.map +1 -1
  233. package/dist/electron/modules/scroll-calibration.d.ts +152 -0
  234. package/dist/electron/modules/scroll-calibration.d.ts.map +1 -0
  235. package/dist/electron/modules/scroll-calibration.js +271 -0
  236. package/dist/electron/modules/scroll-calibration.js.map +1 -0
  237. package/dist/electron/modules/scroll-capture.d.ts +3 -1
  238. package/dist/electron/modules/scroll-capture.d.ts.map +1 -1
  239. package/dist/electron/modules/scroll-capture.js +21 -72
  240. package/dist/electron/modules/scroll-capture.js.map +1 -1
  241. package/dist/electron/modules/sequence-locate.d.ts +126 -0
  242. package/dist/electron/modules/sequence-locate.d.ts.map +1 -0
  243. package/dist/electron/modules/sequence-locate.js +356 -0
  244. package/dist/electron/modules/sequence-locate.js.map +1 -0
  245. package/dist/electron/modules/store.d.ts +15 -56
  246. package/dist/electron/modules/store.d.ts.map +1 -1
  247. package/dist/electron/modules/store.js +84 -58
  248. package/dist/electron/modules/store.js.map +1 -1
  249. package/dist/electron/modules/stt/capability-probe.d.ts +67 -0
  250. package/dist/electron/modules/stt/capability-probe.d.ts.map +1 -0
  251. package/dist/electron/modules/stt/capability-probe.js +331 -0
  252. package/dist/electron/modules/stt/capability-probe.js.map +1 -0
  253. package/dist/electron/modules/stt/macos-engine.d.ts +20 -0
  254. package/dist/electron/modules/stt/macos-engine.d.ts.map +1 -0
  255. package/dist/electron/modules/stt/macos-engine.js +231 -0
  256. package/dist/electron/modules/stt/macos-engine.js.map +1 -0
  257. package/dist/electron/modules/stt/model-manager.d.ts +87 -0
  258. package/dist/electron/modules/stt/model-manager.d.ts.map +1 -0
  259. package/dist/electron/modules/stt/model-manager.js +321 -0
  260. package/dist/electron/modules/stt/model-manager.js.map +1 -0
  261. package/dist/electron/modules/stt/router.d.ts +35 -0
  262. package/dist/electron/modules/stt/router.d.ts.map +1 -0
  263. package/dist/electron/modules/stt/router.js +232 -0
  264. package/dist/electron/modules/stt/router.js.map +1 -0
  265. package/dist/electron/modules/stt/sherpa-engine.d.ts +43 -0
  266. package/dist/electron/modules/stt/sherpa-engine.d.ts.map +1 -0
  267. package/dist/electron/modules/stt/sherpa-engine.js +521 -0
  268. package/dist/electron/modules/stt/sherpa-engine.js.map +1 -0
  269. package/dist/electron/modules/stt/types.d.ts +72 -0
  270. package/dist/electron/modules/stt/types.d.ts.map +1 -0
  271. package/dist/electron/modules/stt/types.js +16 -0
  272. package/dist/electron/modules/stt/types.js.map +1 -0
  273. package/dist/electron/modules/stt/winrt-engine.d.ts +20 -0
  274. package/dist/electron/modules/stt/winrt-engine.d.ts.map +1 -0
  275. package/dist/electron/modules/stt/winrt-engine.js +238 -0
  276. package/dist/electron/modules/stt/winrt-engine.js.map +1 -0
  277. package/dist/electron/modules/template-match.d.ts +62 -0
  278. package/dist/electron/modules/template-match.d.ts.map +1 -0
  279. package/dist/electron/modules/template-match.js +205 -0
  280. package/dist/electron/modules/template-match.js.map +1 -0
  281. package/dist/electron/modules/tray.d.ts +2 -0
  282. package/dist/electron/modules/tray.d.ts.map +1 -1
  283. package/dist/electron/modules/tray.js +136 -8
  284. package/dist/electron/modules/tray.js.map +1 -1
  285. package/dist/electron/modules/undo-stack.d.ts +22 -0
  286. package/dist/electron/modules/undo-stack.d.ts.map +1 -0
  287. package/dist/electron/modules/undo-stack.js +41 -0
  288. package/dist/electron/modules/undo-stack.js.map +1 -0
  289. package/dist/electron/modules/watchers/active-window-watcher.d.ts +5 -0
  290. package/dist/electron/modules/watchers/active-window-watcher.d.ts.map +1 -0
  291. package/dist/electron/modules/watchers/active-window-watcher.js +152 -0
  292. package/dist/electron/modules/watchers/active-window-watcher.js.map +1 -0
  293. package/dist/electron/modules/watchers/clipboard-watcher.d.ts +5 -0
  294. package/dist/electron/modules/watchers/clipboard-watcher.d.ts.map +1 -0
  295. package/dist/electron/modules/watchers/clipboard-watcher.js +90 -0
  296. package/dist/electron/modules/watchers/clipboard-watcher.js.map +1 -0
  297. package/dist/electron/modules/watchers/file-watcher.d.ts +5 -0
  298. package/dist/electron/modules/watchers/file-watcher.d.ts.map +1 -0
  299. package/dist/electron/modules/watchers/file-watcher.js +91 -0
  300. package/dist/electron/modules/watchers/file-watcher.js.map +1 -0
  301. package/dist/electron/modules/watchers/registry.d.ts +34 -0
  302. package/dist/electron/modules/watchers/registry.d.ts.map +1 -0
  303. package/dist/electron/modules/watchers/registry.js +108 -0
  304. package/dist/electron/modules/watchers/registry.js.map +1 -0
  305. package/dist/electron/modules/watchers/screen-region-service.d.ts +18 -0
  306. package/dist/electron/modules/watchers/screen-region-service.d.ts.map +1 -0
  307. package/dist/electron/modules/watchers/screen-region-service.js +126 -0
  308. package/dist/electron/modules/watchers/screen-region-service.js.map +1 -0
  309. package/dist/electron/modules/watchers/screen-region-watcher.d.ts +6 -0
  310. package/dist/electron/modules/watchers/screen-region-watcher.d.ts.map +1 -0
  311. package/dist/electron/modules/watchers/screen-region-watcher.js +70 -0
  312. package/dist/electron/modules/watchers/screen-region-watcher.js.map +1 -0
  313. package/dist/electron/modules/window-activate.d.ts +103 -0
  314. package/dist/electron/modules/window-activate.d.ts.map +1 -0
  315. package/dist/electron/modules/window-activate.js +630 -0
  316. package/dist/electron/modules/window-activate.js.map +1 -0
  317. package/dist/electron/modules/window-input.d.ts +43 -0
  318. package/dist/electron/modules/window-input.d.ts.map +1 -0
  319. package/dist/electron/modules/window-input.js +623 -0
  320. package/dist/electron/modules/window-input.js.map +1 -0
  321. package/dist/electron/modules/window-resolver.d.ts +35 -0
  322. package/dist/electron/modules/window-resolver.d.ts.map +1 -0
  323. package/dist/electron/modules/window-resolver.js +210 -0
  324. package/dist/electron/modules/window-resolver.js.map +1 -0
  325. package/dist/headless/electron/core/input-injection/index.js +30 -0
  326. package/dist/headless/electron/core/input-injection/macos.js +13 -0
  327. package/dist/headless/electron/core/input-injection/windows.js +118 -0
  328. package/dist/headless/electron/core/json-store.js +61 -47
  329. package/dist/headless/electron/core/serialize-schema.js +88 -0
  330. package/dist/headless/electron/core/settings-schema.js +1356 -0
  331. package/dist/headless/electron/logger.js +22 -8
  332. package/dist/headless/electron/modules/accessibility/macos-provider.js +93 -0
  333. package/dist/headless/electron/modules/accessibility/provider.js +51 -0
  334. package/dist/headless/electron/modules/accessibility/types.js +5 -0
  335. package/dist/headless/electron/modules/accessibility/windows-provider.js +84 -0
  336. package/dist/headless/electron/modules/api-server.js +1414 -218
  337. package/dist/headless/electron/modules/auth.js +43 -0
  338. package/dist/headless/electron/modules/azure-speech-realtime.js +56 -0
  339. package/dist/headless/electron/modules/capture.js +33 -0
  340. package/dist/headless/electron/modules/context-menu-detect.js +271 -0
  341. package/dist/headless/electron/modules/dictation.js +12 -7
  342. package/dist/headless/electron/modules/gui-automation-errors.js +78 -0
  343. package/dist/headless/electron/modules/gui-automation-telemetry.js +199 -0
  344. package/dist/headless/electron/modules/gui-automation.js +8768 -0
  345. package/dist/headless/electron/modules/human-input/keyboard/timing.js +56 -0
  346. package/dist/headless/electron/modules/human-input/mouse/path.js +79 -0
  347. package/dist/headless/electron/modules/human-input/mouse/velocity.js +92 -0
  348. package/dist/headless/electron/modules/human-input/profiles.js +123 -0
  349. package/dist/headless/electron/modules/human-input/rng.js +100 -0
  350. package/dist/headless/electron/modules/human-input/salt.js +47 -0
  351. package/dist/headless/electron/modules/image-utils.js +79 -0
  352. package/dist/headless/electron/modules/ollama/capability.js +116 -0
  353. package/dist/headless/electron/modules/ollama/client.js +133 -0
  354. package/dist/headless/electron/modules/ollama/detector.js +176 -0
  355. package/dist/headless/electron/modules/ollama/dispatcher.js +96 -0
  356. package/dist/headless/electron/modules/ollama/router.js +200 -0
  357. package/dist/headless/electron/modules/platform/dpi.js +47 -0
  358. package/dist/headless/electron/modules/platform/errors.js +35 -0
  359. package/dist/headless/electron/modules/platform/index.js +132 -0
  360. package/dist/headless/electron/modules/platform/interfaces.js +13 -0
  361. package/dist/headless/electron/modules/platform/macos/ax.js +221 -0
  362. package/dist/headless/electron/modules/platform/macos/capture.js +105 -0
  363. package/dist/headless/electron/modules/platform/macos/input.js +341 -0
  364. package/dist/headless/electron/modules/platform/macos/launch.js +113 -0
  365. package/dist/headless/electron/modules/platform/macos/session.js +16 -0
  366. package/dist/headless/electron/modules/platform/macos/window.js +270 -0
  367. package/dist/headless/electron/modules/platform/shared.js +200 -0
  368. package/dist/headless/electron/modules/platform/types.js +23 -0
  369. package/dist/headless/electron/modules/platform/windows/ax.js +276 -0
  370. package/dist/headless/electron/modules/platform/windows/capture.js +114 -0
  371. package/dist/headless/electron/modules/platform/windows/input.js +421 -0
  372. package/dist/headless/electron/modules/platform/windows/launch.js +184 -0
  373. package/dist/headless/electron/modules/platform/windows/session.js +86 -0
  374. package/dist/headless/electron/modules/platform/windows/tray.js +389 -0
  375. package/dist/headless/electron/modules/platform/windows/window.js +443 -0
  376. package/dist/headless/electron/modules/recording/providers/change-detect-shared-wrapper.js +61 -0
  377. package/dist/headless/electron/modules/recording/providers/provider-factory.js +13 -7
  378. package/dist/headless/electron/modules/scroll-calibration.js +270 -0
  379. package/dist/headless/electron/modules/sequence-locate.js +355 -0
  380. package/dist/headless/electron/modules/store.js +84 -58
  381. package/dist/headless/electron/modules/stt/capability-probe.js +330 -0
  382. package/dist/headless/electron/modules/stt/macos-engine.js +230 -0
  383. package/dist/headless/electron/modules/stt/model-manager.js +320 -0
  384. package/dist/headless/electron/modules/stt/router.js +231 -0
  385. package/dist/headless/electron/modules/stt/sherpa-engine.js +520 -0
  386. package/dist/headless/electron/modules/stt/types.js +15 -0
  387. package/dist/headless/electron/modules/stt/winrt-engine.js +237 -0
  388. package/dist/headless/electron/modules/template-match.js +204 -0
  389. package/dist/headless/electron/modules/undo-stack.js +40 -0
  390. package/dist/headless/electron/modules/watchers/active-window-watcher.js +151 -0
  391. package/dist/headless/electron/modules/watchers/clipboard-watcher.js +89 -0
  392. package/dist/headless/electron/modules/watchers/file-watcher.js +90 -0
  393. package/dist/headless/electron/modules/watchers/registry.js +107 -0
  394. package/dist/headless/electron/modules/watchers/screen-region-service.js +125 -0
  395. package/dist/headless/electron/modules/watchers/screen-region-watcher.js +69 -0
  396. package/dist/headless/electron/modules/window-activate.js +629 -0
  397. package/dist/headless/electron/modules/window-input.js +622 -0
  398. package/dist/headless/electron/modules/window-resolver.js +209 -0
  399. package/dist/headless/headless/cli.js +60 -7
  400. package/dist/headless/headless/config-cmd.js +306 -0
  401. package/dist/headless/headless/doctor.js +599 -0
  402. package/dist/headless/headless/ollama-cmd.js +211 -0
  403. package/dist/headless/headless/platform-headless.js +13 -1
  404. package/dist/headless/headless/server.js +38 -2
  405. package/dist/headless/headless/stt-cmd.js +213 -0
  406. package/dist/headless/headless/tui/index.mjs +7 -0
  407. package/dist/headless/headless/tui/plain-dump.js +41 -0
  408. package/dist/headless/headless/tui/settings-app.mjs +744 -0
  409. package/dist/headless/headless/tui/setup-wizard.mjs +257 -0
  410. package/dist/headless/headless/tui-bridge.js +80 -0
  411. package/dist/headless/shared/constants.js +3 -1
  412. package/dist/shared/constants.d.ts +2 -0
  413. package/dist/shared/constants.d.ts.map +1 -1
  414. package/dist/shared/constants.js +3 -1
  415. package/dist/shared/constants.js.map +1 -1
  416. package/dist/shared/types.d.ts +8 -0
  417. package/dist/shared/types.d.ts.map +1 -1
  418. package/mcp-server/dist/api-client.js +257 -6
  419. package/mcp-server/dist/index.js +1660 -61
  420. package/mcp-server/dist/project-sense.js +161 -0
  421. package/mcp-server/dist/tool-categories.js +161 -0
  422. package/mcp-server/package.json +8 -2
  423. package/package.json +33 -5
@@ -40,6 +40,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
40
40
  };
41
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
42
  exports.registerRecordingRoutesOnServer = registerRecordingRoutesOnServer;
43
+ exports.getApiPort = getApiPort;
43
44
  exports.startApiServer = startApiServer;
44
45
  exports.stopApiServer = stopApiServer;
45
46
  exports.getApiAuthToken = getApiAuthToken;
@@ -73,6 +74,7 @@ const ocr_1 = require("./ocr");
73
74
  const redact_1 = require("./redact");
74
75
  const database_1 = require("../db/database");
75
76
  const constants_1 = require("../../shared/constants");
77
+ const image_utils_1 = require("./image-utils");
76
78
  const API_PORT = 47592;
77
79
  const API_HOST = '127.0.0.1';
78
80
  let server = null;
@@ -105,6 +107,26 @@ function isValidProjectDir(dir) {
105
107
  return false;
106
108
  return fs.existsSync(dir) && fs.statSync(dir).isDirectory();
107
109
  }
110
+ function isValidScreenshotPath(filePath) {
111
+ if (!filePath || !path.isAbsolute(filePath))
112
+ return false;
113
+ const resolved = path.resolve(filePath);
114
+ if (resolved.includes('..'))
115
+ return false;
116
+ // Allow captures dir, data dir, temp dir, and project .superbased/captures dirs
117
+ const capturesDir = getCapturesDir();
118
+ const dataDir = (0, platform_1.getPlatform)().getDataDir();
119
+ const tmpDir = require('os').tmpdir();
120
+ if (resolved.startsWith(capturesDir) || resolved.startsWith(dataDir) || resolved.startsWith(tmpDir)) {
121
+ return true;
122
+ }
123
+ // Allow project-specific captures: {projectDir}/.superbased/captures/
124
+ const sep = path.sep;
125
+ const marker = `${sep}.superbased${sep}captures${sep}`;
126
+ if (resolved.includes(marker))
127
+ return true;
128
+ return false;
129
+ }
108
130
  function sanitizeSettings(settings) {
109
131
  const sanitized = { ...settings };
110
132
  for (const key of BLOCKED_SETTINGS_KEYS) {
@@ -116,28 +138,6 @@ function generateAuthToken() {
116
138
  const { randomUUID } = require('crypto');
117
139
  return randomUUID();
118
140
  }
119
- async function resizeImageForAI(imageBuffer) {
120
- try {
121
- const sharp = require('sharp');
122
- const meta = await sharp(imageBuffer).metadata();
123
- const maxDim = Math.max(meta.width || 0, meta.height || 0);
124
- if (maxDim > 1568) {
125
- const resized = await sharp(imageBuffer)
126
- .resize({
127
- width: maxDim === meta.width ? 1568 : undefined,
128
- height: maxDim === meta.height ? 1568 : undefined,
129
- fit: 'inside',
130
- })
131
- .png()
132
- .toBuffer();
133
- return resized.toString('base64');
134
- }
135
- return imageBuffer.toString('base64');
136
- }
137
- catch {
138
- return imageBuffer.toString('base64');
139
- }
140
- }
141
141
  /** Resize a capture buffer to a target resolution for token efficiency. */
142
142
  async function resizeCapture(buffer, resolution, maxWidth, maxHeight) {
143
143
  const sharp = require('sharp');
@@ -174,6 +174,37 @@ async function resizeCapture(buffer, resolution, maxWidth, maxHeight) {
174
174
  function registerHealthRoutes(server) {
175
175
  server.get('/api/health', async (_req, reply) => {
176
176
  const version = (0, config_1.getVersion)();
177
+ // Capability manifest (Phase 2a.5) — agents self-check before invoking
178
+ // optional features (GUI automation, watchers, etc.). Lazy-load so the
179
+ // health endpoint stays cheap when the module is missing.
180
+ let guiCaps;
181
+ try {
182
+ const { getCapabilityManifest } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
183
+ guiCaps = getCapabilityManifest();
184
+ }
185
+ catch { /* gui-automation may be unavailable; omit from manifest */ }
186
+ // Ollama detection (Phase 6.1) — short form for /api/health. Full detail
187
+ // at /api/ollama/status. Respects `ollama.detection.enabled`.
188
+ let ollamaShort;
189
+ try {
190
+ const { probeOllama, toHealthShort } = await Promise.resolve().then(() => __importStar(require('./ollama/detector')));
191
+ const status = await probeOllama();
192
+ ollamaShort = toHealthShort(status);
193
+ }
194
+ catch { /* detector unavailable; omit */ }
195
+ // §6.11 — gui-automation telemetry. Opt-in only (guiAutomation.telemetryOptIn).
196
+ // When opt-in is OFF, the key is omitted entirely so /api/health response
197
+ // shape doesn't hint at the feature to unprivileged callers.
198
+ let guiTelemetry;
199
+ try {
200
+ const { getSettings } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
201
+ const settings = getSettings();
202
+ if (settings.telemetryOptIn) {
203
+ const { snapshot } = await Promise.resolve().then(() => __importStar(require('./gui-automation-telemetry')));
204
+ guiTelemetry = snapshot();
205
+ }
206
+ }
207
+ catch { /* telemetry module optional */ }
177
208
  return reply.code(200).send({
178
209
  status: 'ok',
179
210
  version,
@@ -188,7 +219,694 @@ function registerHealthRoutes(server) {
188
219
  ocr: true,
189
220
  recording: !!(0, store_1.getSetting)('recordingFeatureEnabled'),
190
221
  },
222
+ capabilities: {
223
+ ...(guiCaps || {}),
224
+ },
225
+ ollama: ollamaShort,
226
+ ...(guiTelemetry ? { telemetry: guiTelemetry } : {}),
227
+ });
228
+ });
229
+ }
230
+ // ── Accessibility Routes (Phase 8.1 — native AX / UIA tree dump) ──
231
+ function registerAccessibilityRoutes(s) {
232
+ s.get('/api/accessibility/status', async (_request, reply) => {
233
+ const { getProviderStatus } = await Promise.resolve().then(() => __importStar(require('./accessibility/provider')));
234
+ return reply.code(200).send(getProviderStatus());
235
+ });
236
+ s.get('/api/accessibility/tree', async (request, reply) => {
237
+ const { getProvider } = await Promise.resolve().then(() => __importStar(require('./accessibility/provider')));
238
+ const provider = getProvider();
239
+ if (!provider) {
240
+ return reply.code(501).send({
241
+ ok: false,
242
+ error: 'no_provider',
243
+ message: 'No accessibility provider is available on this platform.',
244
+ });
245
+ }
246
+ const q = request.query || {};
247
+ const pid = q.pid !== undefined ? Number(q.pid) : undefined;
248
+ const hwnd = q.hwnd !== undefined ? Number(q.hwnd) : undefined;
249
+ const maxDepth = q.maxDepth !== undefined ? Number(q.maxDepth) : undefined;
250
+ const includeAttributes = q.includeAttributes === '1' || q.includeAttributes === 'true';
251
+ try {
252
+ const tree = await provider.getTree({ pid, hwnd, maxDepth, includeAttributes });
253
+ return reply.code(200).send({ ok: true, tree });
254
+ }
255
+ catch (err) {
256
+ const e = err;
257
+ const code = e.code ?? 'tree_failed';
258
+ const httpCode = code === 'accessibility_not_trusted' ? 403
259
+ : code === 'pid_required' || code === 'no_application_for_pid' ? 400
260
+ : code === 'binding_unavailable' ? 501
261
+ : 500;
262
+ return reply.code(httpCode).send({
263
+ ok: false,
264
+ error: code,
265
+ message: e.message ?? String(err),
266
+ });
267
+ }
268
+ });
269
+ s.get('/api/accessibility/focused', async (_request, reply) => {
270
+ const { getProvider } = await Promise.resolve().then(() => __importStar(require('./accessibility/provider')));
271
+ const provider = getProvider();
272
+ if (!provider) {
273
+ return reply.code(501).send({
274
+ ok: false,
275
+ error: 'no_provider',
276
+ message: 'No accessibility provider is available on this platform.',
277
+ });
278
+ }
279
+ try {
280
+ const node = await provider.getFocusedElement();
281
+ return reply.code(200).send({ ok: true, node });
282
+ }
283
+ catch (err) {
284
+ const e = err;
285
+ const code = e.code ?? 'focused_failed';
286
+ const httpCode = code === 'accessibility_not_trusted' ? 403 : 500;
287
+ return reply.code(httpCode).send({
288
+ ok: false,
289
+ error: code,
290
+ message: e.message ?? String(err),
291
+ });
292
+ }
293
+ });
294
+ s.post('/api/accessibility/prompt-permission', async (_request, reply) => {
295
+ const { getProvider } = await Promise.resolve().then(() => __importStar(require('./accessibility/provider')));
296
+ const provider = getProvider();
297
+ if (!provider) {
298
+ return reply.code(501).send({
299
+ ok: false,
300
+ error: 'no_provider',
301
+ });
302
+ }
303
+ const state = await provider.promptForPermission();
304
+ return reply.code(200).send({ ok: true, permission: state });
305
+ });
306
+ }
307
+ // ── Ollama Routes (Phase 6.1 — detection only; routing ships in 6.2) ──
308
+ function registerOllamaRoutes(s) {
309
+ s.get('/api/ollama/status', async (request, reply) => {
310
+ const { probeOllama } = await Promise.resolve().then(() => __importStar(require('./ollama/detector')));
311
+ const q = request.query || {};
312
+ const force = q.force === '1' || q.force === 'true' || q.force === true;
313
+ const status = await probeOllama({ force });
314
+ return reply.code(200).send(status);
315
+ });
316
+ // POST /api/ollama/test-connection — for the first-opt-in UX flow (Phase 6.2).
317
+ // Body: { host?: string, model?: string }. When `host` is provided, probes
318
+ // that host without writing it to settings — lets users validate before
319
+ // committing. When `model` is provided, checks that model is present in the
320
+ // daemon's catalog.
321
+ s.post('/api/ollama/test-connection', async (request, reply) => {
322
+ const body = (request.body ?? {});
323
+ const { probeOllama, getConfiguredHost } = await Promise.resolve().then(() => __importStar(require('./ollama/detector')));
324
+ const hostOverride = typeof body.host === 'string' && body.host.trim().length > 0
325
+ ? body.host.trim()
326
+ : undefined;
327
+ const effectiveHost = hostOverride ?? getConfiguredHost();
328
+ const status = await probeOllama({ force: true, hostOverride });
329
+ const result = {
330
+ ok: status.detected,
331
+ host: effectiveHost,
332
+ detected: status.detected,
333
+ version: status.version,
334
+ modelCount: status.models.length,
335
+ error: status.detected ? undefined : (status.probeError || 'Ollama did not respond'),
336
+ };
337
+ if (typeof body.model === 'string' && body.model.trim().length > 0 && status.detected) {
338
+ const wanted = body.model.trim();
339
+ // Exact match first; then tag-stripped prefix (e.g. 'llama3.1' matches 'llama3.1:8b').
340
+ const matches = status.models
341
+ .map((m) => m.name)
342
+ .filter((n) => n === wanted || n.startsWith(`${wanted}:`) || n.startsWith(`${wanted.split(':')[0]}:`));
343
+ const exact = status.models.some((m) => m.name === wanted);
344
+ result.modelCheck = {
345
+ requested: wanted,
346
+ found: exact,
347
+ matches: matches.length > 0 ? matches.slice(0, 10) : undefined,
348
+ };
349
+ if (!exact) {
350
+ result.ok = false;
351
+ result.error = matches.length > 0
352
+ ? `Model ${wanted} not installed. Similar models present: ${matches.slice(0, 5).join(', ')}. Pull with: ollama pull ${wanted}`
353
+ : `Model ${wanted} not installed. Pull with: ollama pull ${wanted}`;
354
+ }
355
+ }
356
+ return reply.code(200).send(result);
357
+ });
358
+ }
359
+ function registerAutomationRoutes(server) {
360
+ // GUI automation endpoints (Phase 2a). All actions enforce the master toggle
361
+ // + per-action toggle + protected-apps blocklist via gui-automation.ts gates.
362
+ // The handlers themselves are thin — safety logic lives in the module.
363
+ server.post('/api/automation/click', async (req, reply) => {
364
+ // 0.10 adds label / automationId / role+name / caseSensitive fields.
365
+ // 2.1 adds clickCount + modifiers.
366
+ const body = req.body || {};
367
+ const { clickAt } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
368
+ const result = await clickAt({ ...body, caller: 'http' });
369
+ if (result.ok) {
370
+ const { pushUndo } = await Promise.resolve().then(() => __importStar(require('./undo-stack')));
371
+ pushUndo({ action: 'click', details: { x: body.x, y: body.y, window: body.window, processName: body.processName } });
372
+ }
373
+ return reply.code(result.ok ? 200 : 403).send(result);
374
+ });
375
+ server.post('/api/automation/type', async (req, reply) => {
376
+ // 0.10 adds label / automationId / role+name / caseSensitive — when set,
377
+ // the tool clicks the matched field first then types.
378
+ // 2.6 adds clearFirst (select-all + delete) and delayMs (inter-key pacing).
379
+ // 5.3 adds ime (JKC Unicode path via VK_PACKET / CGEventKeyboardSetUnicodeString).
380
+ const body = req.body || {};
381
+ const { typeText: typeAction } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
382
+ const result = await typeAction({
383
+ text: body.text || '',
384
+ confirm: body.confirm,
385
+ window: body.window,
386
+ processName: body.processName,
387
+ hwnd: body.hwnd,
388
+ restoreFocus: body.restoreFocus,
389
+ returnObservation: body.returnObservation,
390
+ label: body.label,
391
+ automationId: body.automationId,
392
+ role: body.role,
393
+ name: body.name,
394
+ caseSensitive: body.caseSensitive,
395
+ clearFirst: body.clearFirst,
396
+ delayMs: body.delayMs,
397
+ ime: body.ime,
398
+ humanize: body.humanize,
399
+ caller: 'http',
400
+ });
401
+ if (result.ok && body.text) {
402
+ const { pushUndo } = await Promise.resolve().then(() => __importStar(require('./undo-stack')));
403
+ pushUndo({ action: 'type', details: { text: body.text, window: body.window, processName: body.processName } });
404
+ }
405
+ return reply.code(result.ok ? 200 : 403).send(result);
406
+ });
407
+ server.post('/api/automation/hotkey', async (req, reply) => {
408
+ const body = req.body || {};
409
+ const { hotkey } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
410
+ const result = await hotkey({ combo: body.combo || '', confirm: body.confirm, window: body.window, processName: body.processName, hwnd: body.hwnd, restoreFocus: body.restoreFocus, returnObservation: body.returnObservation, method: body.method, caller: 'http' });
411
+ if (result.ok) {
412
+ const { pushUndo } = await Promise.resolve().then(() => __importStar(require('./undo-stack')));
413
+ pushUndo({ action: 'hotkey', details: { combo: body.combo, window: body.window, processName: body.processName } });
414
+ }
415
+ return reply.code(result.ok ? 200 : 403).send(result);
416
+ });
417
+ server.post('/api/automation/scroll', async (req, reply) => {
418
+ // 2.5 adds axis?: 'y' | 'x' for horizontal scroll.
419
+ const body = req.body || {};
420
+ const { scroll } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
421
+ const result = await scroll({ amount: typeof body.amount === 'number' ? body.amount : 0, confirm: body.confirm, window: body.window, processName: body.processName, hwnd: body.hwnd, restoreFocus: body.restoreFocus, method: body.method, returnObservation: body.returnObservation, unit: body.unit, axis: body.axis, anchorX: body.anchorX, anchorY: body.anchorY, recalibrate: body.recalibrate, caller: 'http' });
422
+ if (result.ok) {
423
+ const { pushUndo } = await Promise.resolve().then(() => __importStar(require('./undo-stack')));
424
+ pushUndo({ action: 'scroll', details: { amount: body.amount, window: body.window, processName: body.processName } });
425
+ }
426
+ return reply.code(result.ok ? 200 : 403).send(result);
427
+ });
428
+ // Multi-scroll multi-capture in ONE call. Calibrate → scroll one page →
429
+ // capture → repeat up to maxPages, stopping when no-movement detected.
430
+ // Returns all frames inline as a single response. Replaces N separate
431
+ // scroll+screenshot approvals with 1.
432
+ server.post('/api/automation/scroll-capture', async (req, reply) => {
433
+ const body = req.body || {};
434
+ const { runScrollCapture } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
435
+ const result = await runScrollCapture({
436
+ anchorX: typeof body.anchorX === 'number' ? body.anchorX : NaN,
437
+ anchorY: typeof body.anchorY === 'number' ? body.anchorY : NaN,
438
+ window: body.window, processName: body.processName, hwnd: body.hwnd,
439
+ direction: body.direction,
440
+ maxPages: body.maxPages,
441
+ confirm: body.confirm,
442
+ restoreFocus: body.restoreFocus,
443
+ recalibrate: body.recalibrate,
444
+ stopOnAtEnd: body.stopOnAtEnd,
445
+ settleMs: body.settleMs,
446
+ caller: 'http',
447
+ });
448
+ return reply.code(result.ok ? 200 : 403).send(result);
449
+ });
450
+ // Semantic scroll-until-found: loops ui_dump → search → scroll 1 page →
451
+ // retry under ONE activation window. Single approval covers the whole
452
+ // flow. Returns { found, pagesScrolled, atEnd?, match?, matches?, observation }.
453
+ server.post('/api/automation/scroll-to', async (req, reply) => {
454
+ const body = req.body || {};
455
+ const { runScrollTo } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
456
+ const result = await runScrollTo({
457
+ targetText: body.targetText || '',
458
+ direction: body.direction,
459
+ maxPages: body.maxPages,
460
+ matchMode: body.matchMode,
461
+ caseSensitive: body.caseSensitive,
462
+ confirm: body.confirm,
463
+ window: body.window, processName: body.processName, hwnd: body.hwnd,
464
+ restoreFocus: body.restoreFocus,
465
+ returnObservation: body.returnObservation,
466
+ ocrScaleFactor: body.ocrScaleFactor,
467
+ caller: 'http',
468
+ });
469
+ return reply.code(result.ok ? 200 : 403).send(result);
470
+ });
471
+ // 1.4 superbased_context_menu_select — right-click + popup detect + item click in one approval.
472
+ server.post('/api/automation/context-menu-select', async (req, reply) => {
473
+ const body = req.body || {};
474
+ const { contextMenuSelect } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
475
+ const result = await contextMenuSelect({
476
+ x: body.x ?? NaN, y: body.y ?? NaN, menuItemText: body.menuItemText ?? '',
477
+ caseSensitive: body.caseSensitive, timeoutMs: body.timeoutMs, confirm: body.confirm,
478
+ window: body.window, processName: body.processName, hwnd: body.hwnd,
479
+ restoreFocus: body.restoreFocus, returnObservation: body.returnObservation,
480
+ caller: 'http',
481
+ });
482
+ return reply.code(result.ok ? 200 : 403).send(result);
483
+ });
484
+ // 2.4 superbased_pixel_color — read the RGBA at (x, y). Pure screen-read, no input.
485
+ server.post('/api/automation/pixel-color', async (req, reply) => {
486
+ const body = req.body || {};
487
+ const { pixelColor } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
488
+ const result = await pixelColor({ x: body.x ?? NaN, y: body.y ?? NaN, expected: body.expected, tolerance: body.tolerance, confirm: body.confirm, caller: 'http' });
489
+ return reply.code(result.ok ? 200 : 403).send(result);
490
+ });
491
+ // 2.2 superbased_hover — move cursor + dwell. Reveals tooltips / hover-only UI.
492
+ server.post('/api/automation/hover', async (req, reply) => {
493
+ const body = req.body || {};
494
+ const { hoverAt } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
495
+ const result = await hoverAt({ ...body, caller: 'http' });
496
+ return reply.code(result.ok ? 200 : 403).send(result);
497
+ });
498
+ // 1.3 superbased_drag — press / interpolate / release. HTML5 DnD + native drag both supported.
499
+ // 3.3 — path[] with optional atMs; fromX/Y/toX/Y optional when path has ≥2 waypoints.
500
+ server.post('/api/automation/drag', async (req, reply) => {
501
+ const body = req.body || {};
502
+ const { dragAt } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
503
+ const result = await dragAt({
504
+ fromX: body.fromX, fromY: body.fromY, toX: body.toX, toY: body.toY,
505
+ path: body.path, durationMs: body.durationMs, steps: body.steps,
506
+ button: body.button, modifiers: body.modifiers, confirm: body.confirm,
507
+ window: body.window, processName: body.processName, hwnd: body.hwnd,
508
+ restoreFocus: body.restoreFocus, returnObservation: body.returnObservation,
509
+ humanize: body.humanize,
510
+ caller: 'http',
511
+ });
512
+ return reply.code(result.ok ? 200 : 403).send(result);
513
+ });
514
+ // 1.2 superbased_resize_window — presets (iphone/ipad/desktop/fullscreen) + custom.
515
+ server.post('/api/automation/resize-window', async (req, reply) => {
516
+ const body = req.body || {};
517
+ const { resizeWindow } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
518
+ const result = await resizeWindow({ ...body, caller: 'http' });
519
+ // resize_window is a state-changing action but not trivially reversible
520
+ // (needs stored original rect + display). Per Phase 5.4 judgment call L1,
521
+ // omit from undo-stack; agent/user restores manually if needed.
522
+ return reply.code(result.ok ? 200 : 403).send(result);
523
+ });
524
+ // 3.1 superbased_window_state — minimize/maximize/restore/close/always-on-top/move-to-display.
525
+ server.post('/api/automation/window-state', async (req, reply) => {
526
+ const body = req.body || {};
527
+ const { setWindowState } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
528
+ if (!body.action) {
529
+ return reply.code(400).send({ ok: false, error: 'window_state requires `action`', errorCode: 'INVALID_ARGS' });
530
+ }
531
+ const result = await setWindowState({ ...body, action: body.action, caller: 'http' });
532
+ // Like resize_window, window_state is state-changing but not in the undo
533
+ // stack (restoring close/move would need captured prior rect + display).
534
+ return reply.code(result.ok ? 200 : 403).send(result);
535
+ });
536
+ // superbased_window_bounds — read-only rect + state for a single window.
537
+ // Pure query — no gate. Resolves the target via the standard window /
538
+ // processName / hwnd pyramid then calls PlatformWindowAdapter.getBounds.
539
+ server.post('/api/automation/window-bounds', async (req, reply) => {
540
+ const body = req.body || {};
541
+ const { windowBounds } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
542
+ const result = await windowBounds({ ...body, caller: 'http' });
543
+ return reply.code(result.ok ? 200 : 403).send(result);
544
+ });
545
+ // superbased_find_title_bar_drag_region — pure query that runs ui_dump
546
+ // internally, walks the AX tree, and returns a safe pickup coord for
547
+ // title-bar drag. No gate. Same targeting as window_bounds.
548
+ server.post('/api/automation/find-title-bar-drag-region', async (req, reply) => {
549
+ const body = req.body || {};
550
+ const { findTitleBarDragRegion } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
551
+ const result = await findTitleBarDragRegion({ ...body, caller: 'http' });
552
+ return reply.code(result.ok ? 200 : 403).send(result);
553
+ });
554
+ // 3.6 superbased_display_list — enumerate displays with virtual-screen bounds + scale + primary flag + color space.
555
+ // Pure read — no gate. Thin wrapper around PlatformCaptureAdapter.enumerateDisplays().
556
+ server.get('/api/automation/display-list', async (_req, reply) => {
557
+ try {
558
+ const { platform } = await Promise.resolve().then(() => __importStar(require('./platform')));
559
+ const displays = await platform.capture.enumerateDisplays();
560
+ return reply.code(200).send({ ok: true, displays });
561
+ }
562
+ catch (err) {
563
+ return reply.code(500).send({ ok: false, error: err instanceof Error ? err.message : String(err), errorCode: 'TARGET_HOSTILE' });
564
+ }
565
+ });
566
+ // 3.5 superbased_find_image — sharp/NCC template match on downsampled buffers.
567
+ server.post('/api/automation/find-image', async (req, reply) => {
568
+ const body = req.body || {};
569
+ const { findImage } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
570
+ const result = await findImage({ ...body, caller: 'http' });
571
+ return reply.code(result.ok ? 200 : 403).send(result);
572
+ });
573
+ // 3.5 superbased_capture_template — snapshot a region + write metadata sidecar.
574
+ server.post('/api/automation/capture-template', async (req, reply) => {
575
+ const body = req.body || {};
576
+ const { captureTemplate } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
577
+ if (!body.region) {
578
+ return reply.code(400).send({ ok: false, error: 'capture_template requires `region`', errorCode: 'INVALID_ARGS' });
579
+ }
580
+ const result = await captureTemplate({ ...body, region: body.region, caller: 'http' });
581
+ return reply.code(result.ok ? 200 : 403).send(result);
582
+ });
583
+ // 6.7 superbased_dry_run — wrapper tool; returns errorCode: 'DRYRUN' with
584
+ // the named tool + args echoed back. Does not dispatch.
585
+ server.post('/api/automation/dry-run', async (req, reply) => {
586
+ const body = req.body || {};
587
+ const { dryRun } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
588
+ if (typeof body.tool !== 'string') {
589
+ return reply.code(400).send({ ok: false, error: 'dry_run requires `tool: string`', errorCode: 'INVALID_ARGS' });
590
+ }
591
+ const result = await dryRun({ tool: body.tool, args: body.args, caller: 'http' });
592
+ return reply.code(200).send(result);
593
+ });
594
+ // 6.8 superbased_replay — reconstructs a sequence from the audit log and
595
+ // dispatches via runSequence(). Default-safe: dryRun:true unless
596
+ // explicitly dryRun:false + confirm:true.
597
+ server.post('/api/automation/replay', async (req, reply) => {
598
+ const body = req.body || {};
599
+ const { replay } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
600
+ const result = await replay({ ...body, caller: 'http' });
601
+ return reply.code(result.ok ? 200 : 403).send(result);
602
+ });
603
+ // 6.9 superbased_doctor_gui_automation — hermetic probe against a canned
604
+ // target (Notepad / TextEdit). Bypasses launchAllowlist via direct adapter
605
+ // call; reports per-primitive pass/fail + TCC status (macOS).
606
+ server.post('/api/automation/doctor-gui-automation', async (req, reply) => {
607
+ const body = req.body || {};
608
+ const { doctorGuiAutomation } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
609
+ const result = await doctorGuiAutomation({ ...body, caller: 'http' });
610
+ return reply.code(result.ok ? 200 : 403).send(result);
611
+ });
612
+ // 4.7 superbased_open_url — ShellExecute (or Start-Process <browser>) with optional waitForLoad.
613
+ server.post('/api/automation/open-url', async (req, reply) => {
614
+ const body = req.body || {};
615
+ const { openUrl } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
616
+ if (typeof body.url !== 'string') {
617
+ return reply.code(400).send({ ok: false, error: 'open_url requires `url: string`', errorCode: 'INVALID_ARGS' });
618
+ }
619
+ const result = await openUrl({ ...body, url: body.url, caller: 'http' });
620
+ return reply.code(result.ok ? 200 : 403).send(result);
621
+ });
622
+ // 5.1 superbased_drag_file — scaffold only; returns UNSUPPORTED_YET pending
623
+ // the native OLE helper (IDataObject + DoDragDrop). API shape is stable.
624
+ server.post('/api/automation/drag-file', async (req, reply) => {
625
+ const body = req.body || {};
626
+ const { dragFile } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
627
+ if (typeof body.filePath !== 'string') {
628
+ return reply.code(400).send({ ok: false, error: 'drag_file requires `filePath: string`', errorCode: 'INVALID_ARGS' });
629
+ }
630
+ if (typeof body.toX !== 'number' || typeof body.toY !== 'number') {
631
+ return reply.code(400).send({ ok: false, error: 'drag_file requires `toX: number` and `toY: number`', errorCode: 'INVALID_ARGS' });
632
+ }
633
+ const result = await dragFile({ ...body, filePath: body.filePath, toX: body.toX, toY: body.toY, caller: 'http' });
634
+ return reply.code(result.ok ? 200 : 403).send(result);
635
+ });
636
+ // 5.6 superbased_virtual_desktop — Win+Ctrl+Left/Right (Windows), Ctrl+Left/Right (macOS Spaces).
637
+ server.post('/api/automation/virtual-desktop', async (req, reply) => {
638
+ const body = req.body || {};
639
+ const { virtualDesktop } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
640
+ if (body.direction !== 'left' && body.direction !== 'right') {
641
+ return reply.code(400).send({ ok: false, error: 'virtual_desktop requires direction: "left" | "right"', errorCode: 'INVALID_ARGS' });
642
+ }
643
+ const result = await virtualDesktop({ ...body, direction: body.direction, caller: 'http' });
644
+ return reply.code(result.ok ? 200 : 403).send(result);
645
+ });
646
+ // 5.2 superbased_tray_click — enumerate Windows tray, tooltip-match, click at resolved coords.
647
+ server.post('/api/automation/tray-click', async (req, reply) => {
648
+ const body = req.body || {};
649
+ const { clickTrayIcon } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
650
+ if (typeof body.tooltipMatch !== 'string') {
651
+ return reply.code(400).send({ ok: false, error: 'tray_click requires `tooltipMatch: string`', errorCode: 'INVALID_ARGS' });
652
+ }
653
+ const result = await clickTrayIcon({ ...body, tooltipMatch: body.tooltipMatch, caller: 'http' });
654
+ return reply.code(result.ok ? 200 : 403).send(result);
655
+ });
656
+ // 4.6 superbased_tab_management — browser hotkey wrappers (new/close/next/prev/switch_to).
657
+ server.post('/api/automation/tab-management', async (req, reply) => {
658
+ const body = req.body || {};
659
+ const { tabManagement } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
660
+ if (!body.tabAction) {
661
+ return reply.code(400).send({ ok: false, error: 'tab_management requires `tabAction`', errorCode: 'INVALID_ARGS' });
662
+ }
663
+ const result = await tabManagement({ ...body, tabAction: body.tabAction, caller: 'http' });
664
+ return reply.code(result.ok ? 200 : 403).send(result);
665
+ });
666
+ // 4.5 superbased_find_in_page — browser-hotkey wrapper: Ctrl+F → type → Enter.
667
+ server.post('/api/automation/find-in-page', async (req, reply) => {
668
+ const body = req.body || {};
669
+ const { findInPage } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
670
+ if (typeof body.query !== 'string') {
671
+ return reply.code(400).send({ ok: false, error: 'find_in_page requires `query: string`', errorCode: 'INVALID_ARGS' });
672
+ }
673
+ const result = await findInPage({ ...body, query: body.query, caller: 'http' });
674
+ return reply.code(result.ok ? 200 : 403).send(result);
675
+ });
676
+ // 4.3 superbased_dialog_handle — confirm/dismiss/fill_path against a modal dialog.
677
+ server.post('/api/automation/dialog-handle', async (req, reply) => {
678
+ const body = req.body || {};
679
+ const { dialogHandle } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
680
+ if (!body.dialogAction) {
681
+ return reply.code(400).send({ ok: false, error: 'dialog_handle requires `dialogAction`', errorCode: 'INVALID_ARGS' });
682
+ }
683
+ const result = await dialogHandle({ ...body, dialogAction: body.dialogAction, caller: 'http' });
684
+ return reply.code(result.ok ? 200 : 403).send(result);
685
+ });
686
+ // 4.2 superbased_form_fill — macro: ax-resolve + ValuePattern (or click+clearFirst+type) + Tab + optional Submit.
687
+ server.post('/api/automation/form-fill', async (req, reply) => {
688
+ const body = req.body || {};
689
+ const { formFill } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
690
+ if (!Array.isArray(body.fields)) {
691
+ return reply.code(400).send({ ok: false, error: 'form_fill requires `fields: [...]`', errorCode: 'INVALID_ARGS' });
692
+ }
693
+ // Assert each field has the shape formFill expects — route to the
694
+ // orchestrator which validates fully (value type, locator presence).
695
+ const result = await formFill({
696
+ ...body,
697
+ fields: body.fields,
698
+ caller: 'http',
699
+ });
700
+ return reply.code(result.ok ? 200 : 403).send(result);
701
+ });
702
+ // 4.1 superbased_ax_invoke — UIA pattern invocation (Invoke/Toggle/Select/SetValue/Expand/Collapse).
703
+ server.post('/api/automation/ax-invoke', async (req, reply) => {
704
+ const body = req.body || {};
705
+ const { axInvoke } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
706
+ if (!body.pattern) {
707
+ return reply.code(400).send({ ok: false, error: 'ax_invoke requires `pattern`', errorCode: 'INVALID_ARGS' });
708
+ }
709
+ const result = await axInvoke({ ...body, pattern: body.pattern, caller: 'http' });
710
+ return reply.code(result.ok ? 200 : 403).send(result);
711
+ });
712
+ // 3.2 superbased_launch_app — Start-Process-backed launch gated by the allowlist.
713
+ server.post('/api/automation/launch-app', async (req, reply) => {
714
+ const body = req.body || {};
715
+ const { launchApp } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
716
+ const result = await launchApp({ ...body, caller: 'http' });
717
+ return reply.code(result.ok ? 200 : 403).send(result);
718
+ });
719
+ // UI dump — one-call "read the page": screenshot + OCR elements + AX tree
720
+ // in a single MCP turn. Read-only; no activation, no safety gate beyond
721
+ // the master toggle (if the caller can screenshot, they can ui_dump).
722
+ server.post('/api/automation/ui-dump', async (req, reply) => {
723
+ const body = req.body || {};
724
+ const { runUiDump } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
725
+ const result = await runUiDump({ ...body, caller: 'http' });
726
+ return reply.code(result.ok ? 200 : 500).send(result);
727
+ });
728
+ // Batched sequence — ONE approval, ONE activation window, N steps.
729
+ // Fixes the 20+-permission-prompt flood for any multi-step GUI task.
730
+ server.post('/api/automation/sequence', async (req, reply) => {
731
+ const body = req.body || {};
732
+ const { runSequence } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
733
+ const result = await runSequence({
734
+ steps: Array.isArray(body.steps) ? body.steps : [],
735
+ window: body.window, processName: body.processName, hwnd: body.hwnd,
736
+ restoreFocus: body.restoreFocus, confirm: body.confirm, stopOnError: body.stopOnError,
737
+ caller: 'http',
738
+ });
739
+ // Push each successful input-producing step to the undo stack. Screenshot,
740
+ // wait, and move are read-only / ephemeral — not recorded.
741
+ if (result.results && result.results.length > 0) {
742
+ const { pushUndo } = await Promise.resolve().then(() => __importStar(require('./undo-stack')));
743
+ for (let i = 0; i < result.results.length; i++) {
744
+ const r = result.results[i];
745
+ if (!r.ok)
746
+ continue;
747
+ const step = Array.isArray(body.steps) ? body.steps[i] : undefined;
748
+ if (!step)
749
+ continue;
750
+ if (step.action === 'click')
751
+ pushUndo({ action: 'click', details: { x: step.x, y: step.y, window: body.window, processName: body.processName } });
752
+ else if (step.action === 'type')
753
+ pushUndo({ action: 'type', details: { text: step.text, window: body.window, processName: body.processName } });
754
+ else if (step.action === 'hotkey')
755
+ pushUndo({ action: 'hotkey', details: { combo: step.combo, window: body.window, processName: body.processName } });
756
+ else if (step.action === 'scroll')
757
+ pushUndo({ action: 'scroll', details: { amount: step.amount, window: body.window, processName: body.processName } });
758
+ }
759
+ }
760
+ return reply.code(result.ok ? 200 : 403).send(result);
761
+ });
762
+ // Phase 5.4 — pop the top of the per-session undo stack and attempt to
763
+ // reverse the recorded action. type → press Backspace N times (N = length
764
+ // of the typed text). Everything else is recorded but not reversible;
765
+ // returns ok:false with a clear reason rather than pretending. Matches
766
+ // the "honest > clever" guidance from judgment call L1.
767
+ server.post('/api/automation/undo-last', async (_req, reply) => {
768
+ const { popUndo, undoDepth } = await Promise.resolve().then(() => __importStar(require('./undo-stack')));
769
+ const entry = popUndo();
770
+ if (!entry) {
771
+ return reply.code(200).send({ ok: false, error: 'stack_empty', message: 'No GUI automation actions to undo in this session.' });
772
+ }
773
+ if (entry.action === 'type') {
774
+ const text = entry.details.text ?? '';
775
+ const charCount = text.length;
776
+ if (charCount === 0) {
777
+ return reply.code(200).send({ ok: false, error: 'nothing_to_undo', action: entry.action, message: 'Typed empty string; nothing to reverse.' });
778
+ }
779
+ try {
780
+ const { hotkey } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
781
+ let deleted = 0;
782
+ for (let i = 0; i < charCount; i++) {
783
+ const r = await hotkey({ combo: 'Backspace', confirm: true, window: entry.details.window, processName: entry.details.processName, caller: 'http' });
784
+ if (!r.ok) {
785
+ // Partial undo — stop and report. Don't re-push; the backspaces
786
+ // already sent won't reverse themselves either.
787
+ return reply.code(200).send({
788
+ ok: false,
789
+ error: 'partial_undo',
790
+ action: entry.action,
791
+ charsDeleted: deleted,
792
+ charsTotal: charCount,
793
+ stackDepth: undoDepth(),
794
+ message: `Deleted ${deleted}/${charCount} characters before backspace failed.`,
795
+ reason: r.error ?? 'unknown',
796
+ });
797
+ }
798
+ deleted++;
799
+ }
800
+ return reply.code(200).send({
801
+ ok: true,
802
+ action: entry.action,
803
+ charsDeleted: deleted,
804
+ stackDepth: undoDepth(),
805
+ message: `Undid type action: deleted ${deleted} characters.`,
806
+ });
807
+ }
808
+ catch (err) {
809
+ return reply.code(200).send({
810
+ ok: false,
811
+ error: 'undo_failed',
812
+ action: entry.action,
813
+ message: err instanceof Error ? err.message : String(err),
814
+ });
815
+ }
816
+ }
817
+ // click / hotkey / scroll / focus-window — record only, not reversible.
818
+ return reply.code(200).send({
819
+ ok: false,
820
+ error: 'not_reversible',
821
+ action: entry.action,
822
+ details: entry.details,
823
+ stackDepth: undoDepth(),
824
+ message: `${entry.action} actions are not reversible. The entry has been popped from the stack; run undo_last again to reverse the next-most-recent entry.`,
825
+ });
826
+ });
827
+ server.post('/api/automation/focus-window', async (req, reply) => {
828
+ const body = req.body || {};
829
+ if (!body.window && !body.processName && !body.hwnd) {
830
+ return reply.code(400).send({ ok: false, error: 'window, processName, or hwnd is required' });
831
+ }
832
+ try {
833
+ const { resolveWindow } = await Promise.resolve().then(() => __importStar(require('./window-resolver')));
834
+ const matchResult = await resolveWindow({ window: body.window, processName: body.processName, hwnd: body.hwnd });
835
+ if (!matchResult.ok || !matchResult.best) {
836
+ return reply.code(404).send({
837
+ ok: false,
838
+ error: matchResult.error,
839
+ reason: matchResult.reason,
840
+ alternatives: matchResult.alternatives?.map((c) => ({
841
+ title: c.name, processName: c.processName, hwnd: c.hwnd, score: c.score, scoreReason: c.scoreReason,
842
+ })),
843
+ });
844
+ }
845
+ const match = matchResult.best;
846
+ const { activateWindow } = await Promise.resolve().then(() => __importStar(require('./window-activate')));
847
+ const diag = await activateWindow(match);
848
+ await new Promise((r) => setTimeout(r, 200));
849
+ return reply.code(200).send({
850
+ ok: true,
851
+ method: 'window',
852
+ matchedWindow: {
853
+ title: match.name, processName: match.processName, hwnd: match.hwnd,
854
+ score: match.score, scoreReason: match.scoreReason,
855
+ },
856
+ alternatives: matchResult.alternatives && matchResult.alternatives.length > 0
857
+ ? matchResult.alternatives.map((c) => ({ title: c.name, processName: c.processName, hwnd: c.hwnd, score: c.score, scoreReason: c.scoreReason }))
858
+ : undefined,
859
+ previousWindow: diag.previous || undefined,
860
+ verified: diag.verified,
861
+ attempted: diag.attempted,
862
+ postForeground: diag.postForeground,
863
+ warning: diag.verified === false
864
+ ? `OS reports foreground is still ${diag.postForeground} (not target hwnd ${match.hwnd}). Subsequent input tools will refuse to type into the wrong window. Try clicking the target window once.`
865
+ : undefined,
866
+ });
867
+ }
868
+ catch (err) {
869
+ return reply.code(500).send({ ok: false, error: err.message || String(err) });
870
+ }
871
+ });
872
+ server.get('/api/automation/mouse-position', async (_req, reply) => {
873
+ const { getMousePosition } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
874
+ const result = await getMousePosition();
875
+ return reply.code(result.ok ? 200 : 500).send(result);
876
+ });
877
+ server.post('/api/automation/wait', async (req, reply) => {
878
+ const body = req.body || {};
879
+ const { waitMs } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
880
+ const result = await waitMs({ ms: typeof body.ms === 'number' ? body.ms : 0, caller: 'http' });
881
+ return reply.code(result.ok ? 200 : 400).send(result);
882
+ });
883
+ server.post('/api/automation/locate', async (req, reply) => {
884
+ const body = req.body || {};
885
+ if (!body.label)
886
+ return reply.code(400).send({ ok: false, error: 'label is required' });
887
+ const { locate } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
888
+ const result = await locate({ label: body.label, caseSensitive: body.caseSensitive, caller: 'http' });
889
+ return reply.code(result.ok ? 200 : 404).send(result);
890
+ });
891
+ // 0.9 wait_for — poll a condition until it holds or timeoutMs elapses.
892
+ // Read-only; no actions.* gate. Conditions: text, window, idle, pixelColor
893
+ // (pixelColor resolver arrives in S2 / 2.4).
894
+ server.post('/api/automation/wait-for', async (req, reply) => {
895
+ const body = req.body || {};
896
+ if (!body.condition || typeof body.condition !== 'object') {
897
+ return reply.code(400).send({ ok: false, error: 'condition is required', hint: 'Pass { condition: { type: "text"|"window"|"idle"|"pixelColor", ... }, timeoutMs }' });
898
+ }
899
+ if (typeof body.timeoutMs !== 'number' || body.timeoutMs <= 0) {
900
+ return reply.code(400).send({ ok: false, error: 'timeoutMs is required and must be > 0' });
901
+ }
902
+ const { runWaitFor } = await Promise.resolve().then(() => __importStar(require('./gui-automation')));
903
+ const result = await runWaitFor({
904
+ condition: body.condition,
905
+ timeoutMs: body.timeoutMs,
906
+ intervalMs: body.intervalMs,
907
+ caller: 'http',
191
908
  });
909
+ return reply.code(result.ok ? 200 : 408).send(result);
192
910
  });
193
911
  }
194
912
  function registerCaptureRoutes(server) {
@@ -311,7 +1029,10 @@ function registerCaptureRoutes(server) {
311
1029
  if (body.imageBase64) {
312
1030
  imageBuffer = Buffer.from(body.imageBase64, 'base64');
313
1031
  }
314
- else if (body.screenshotPath && fs.existsSync(body.screenshotPath)) {
1032
+ else if (body.screenshotPath) {
1033
+ if (!isValidScreenshotPath(body.screenshotPath) || !fs.existsSync(body.screenshotPath)) {
1034
+ return reply.code(400).send({ error: 'Invalid or inaccessible screenshotPath' });
1035
+ }
315
1036
  imageBuffer = fs.readFileSync(body.screenshotPath);
316
1037
  }
317
1038
  else {
@@ -337,10 +1058,10 @@ function registerAIRoutes(server) {
337
1058
  if (body.projectDir && !isValidProjectDir(body.projectDir)) {
338
1059
  return reply.code(400).send({ error: 'Invalid projectDir' });
339
1060
  }
340
- // Require authentication for AI features
341
- if (!(0, auth_1.isAuthenticated)()) {
342
- return reply.code(401).send({ error: 'Please sign in to use AI features.' });
343
- }
1061
+ // Auth gate is deferred to the provider router (Phase 6.3). When the
1062
+ // resolver picks cloud, it enforces sign-in via structured error; when
1063
+ // it picks Ollama, signed-out users with Ollama configured succeed.
1064
+ // The !isAuthenticated() early return is deliberately removed here.
344
1065
  // Get image(s)
345
1066
  const imagesBase64 = [];
346
1067
  let captureSourceApp = null;
@@ -352,7 +1073,7 @@ function registerAIRoutes(server) {
352
1073
  }
353
1074
  if (fs.existsSync(capture.screenshot_path)) {
354
1075
  const buf = fs.readFileSync(capture.screenshot_path);
355
- imagesBase64.push(await resizeImageForAI(buf));
1076
+ imagesBase64.push(await (0, image_utils_1.resizeImageForAI)(buf));
356
1077
  captureSourceApp = capture.source_app || null;
357
1078
  captureWindowTitle = capture.window_title || null;
358
1079
  }
@@ -360,9 +1081,12 @@ function registerAIRoutes(server) {
360
1081
  else if (body.imageBase64) {
361
1082
  imagesBase64.push(body.imageBase64);
362
1083
  }
363
- else if (body.screenshotPath && fs.existsSync(body.screenshotPath)) {
1084
+ else if (body.screenshotPath) {
1085
+ if (!isValidScreenshotPath(body.screenshotPath) || !fs.existsSync(body.screenshotPath)) {
1086
+ return reply.code(400).send({ error: 'Invalid or inaccessible screenshotPath' });
1087
+ }
364
1088
  const buf = fs.readFileSync(body.screenshotPath);
365
- imagesBase64.push(await resizeImageForAI(buf));
1089
+ imagesBase64.push(await (0, image_utils_1.resizeImageForAI)(buf));
366
1090
  }
367
1091
  else {
368
1092
  // No image — capture fullscreen automatically
@@ -384,7 +1108,7 @@ function registerAIRoutes(server) {
384
1108
  sourceApp: 'API',
385
1109
  windowTitle: 'Auto Capture for AI',
386
1110
  });
387
- imagesBase64.push(await resizeImageForAI(buffer));
1111
+ imagesBase64.push(await (0, image_utils_1.resizeImageForAI)(buffer));
388
1112
  }
389
1113
  // Parse instruction and build prompt
390
1114
  const { instruction } = (0, instruction_parser_1.parseInstruction)(body.instruction);
@@ -396,13 +1120,47 @@ function registerAIRoutes(server) {
396
1120
  regionIndex: i,
397
1121
  }));
398
1122
  const fullPrompt = (systemPrompt ? systemPrompt + '\n\n' : '') + (0, context_builder_1.buildPrompt)(instruction, contexts);
399
- // Stream AI via backend proxy and buffer complete response
1123
+ // Dispatch through the provider router (Phase 6.3). For vision-bearing
1124
+ // requests the pre-check runs before any streaming work; errors surface
1125
+ // with structured remediation hints. Task is 'vision' when images
1126
+ // accompany the request; otherwise 'chat' — mirrors how the user
1127
+ // perceives the call (superbased_ai with /extract on a screenshot is
1128
+ // a vision call from the routing perspective).
400
1129
  let fullResponse = '';
401
- for await (const chunk of (0, ai_client_1.streamAIFromBackend)({
402
- imagesBase64,
403
- instruction: fullPrompt,
404
- })) {
405
- fullResponse += chunk;
1130
+ let aiProvider = 'cloud';
1131
+ let aiModel;
1132
+ try {
1133
+ const { dispatchAI, DispatcherError } = await Promise.resolve().then(() => __importStar(require('./ollama/dispatcher')));
1134
+ const dispatch = await dispatchAI({
1135
+ task: imagesBase64.length > 0 ? 'vision' : 'chat',
1136
+ provider: body.provider,
1137
+ model: body.model,
1138
+ forceVision: body.forceVision,
1139
+ instruction: fullPrompt,
1140
+ imagesBase64,
1141
+ });
1142
+ aiProvider = dispatch.resolution.provider;
1143
+ aiModel = dispatch.resolution.model;
1144
+ for await (const chunk of dispatch.stream) {
1145
+ fullResponse += chunk;
1146
+ }
1147
+ void DispatcherError; // keep type in scope for catch block below
1148
+ }
1149
+ catch (err) {
1150
+ // Structured dispatcher error — surface code + hint in the body.
1151
+ if (err && typeof err === 'object' && 'code' in err) {
1152
+ const de = err;
1153
+ const httpCode = de.code === 'not_signed_in' ? 401 : 400;
1154
+ return reply.code(httpCode).send({
1155
+ error: de.message,
1156
+ code: de.code,
1157
+ hint: de.hint,
1158
+ provider: de.provider,
1159
+ });
1160
+ }
1161
+ // Non-structured (network / upstream) error — use 502 so callers can
1162
+ // distinguish from validation problems.
1163
+ return reply.code(502).send({ error: err instanceof Error ? err.message : String(err) });
406
1164
  }
407
1165
  // Save AI response to capture if captureId provided
408
1166
  if (body.captureId) {
@@ -413,6 +1171,8 @@ function registerAIRoutes(server) {
413
1171
  }
414
1172
  return reply.code(200).send({
415
1173
  response: fullResponse,
1174
+ provider: aiProvider,
1175
+ model: aiModel,
416
1176
  });
417
1177
  }
418
1178
  catch (err) {
@@ -508,6 +1268,15 @@ function registerSettingsRoutes(server) {
508
1268
  return reply.code(403).send({ error: `Setting '${body.key}' cannot be modified via API` });
509
1269
  }
510
1270
  (0, store_1.setSetting)(body.key, body.value);
1271
+ // Flush ollama detection cache when any ollama.* key changes so the next
1272
+ // probe sees the new enabled state / future 6.2+ host override immediately.
1273
+ if (typeof body.key === 'string' && body.key.startsWith('ollama.')) {
1274
+ try {
1275
+ const { flushOllamaCache } = await Promise.resolve().then(() => __importStar(require('./ollama/detector')));
1276
+ flushOllamaCache();
1277
+ }
1278
+ catch { /* detector unavailable; settings write still succeeded */ }
1279
+ }
511
1280
  return reply.code(200).send({ success: true });
512
1281
  });
513
1282
  // GET /api/settings/provider
@@ -616,6 +1385,253 @@ function registerCompressRoutes(server) {
616
1385
  }
617
1386
  });
618
1387
  }
1388
+ // ── STT Routes (Phase 4a — capability probe + model download) ──
1389
+ function registerSTTRoutes(s) {
1390
+ s.get('/api/stt/status', async (_request, reply) => {
1391
+ const { computeCapabilities, flushCapabilitiesCache } = await Promise.resolve().then(() => __importStar(require('./stt/capability-probe')));
1392
+ // Always recompute when the caller explicitly asks — status is meant
1393
+ // to be authoritative, not cached. Subsequent probe() calls from the
1394
+ // routing layer will repopulate the cache on demand.
1395
+ flushCapabilitiesCache();
1396
+ const report = computeCapabilities({ signedIn: (0, auth_1.isAuthenticated)() });
1397
+ return reply.code(200).send(report);
1398
+ });
1399
+ s.post('/api/stt/download-model', async (request, reply) => {
1400
+ const body = (request.body ?? {});
1401
+ const modelId = typeof body.modelId === 'string' && body.modelId ? body.modelId : '';
1402
+ if (!modelId) {
1403
+ return reply.code(400).send({ ok: false, error: 'missing_model_id', message: 'modelId is required' });
1404
+ }
1405
+ if (body.explicitConsent !== true) {
1406
+ return reply.code(403).send({
1407
+ ok: false,
1408
+ error: 'consent_required',
1409
+ modelId,
1410
+ message: 'explicitConsent:true is required. Downloads do not run implicitly.',
1411
+ consent_command: `superbased stt download ${modelId}`,
1412
+ });
1413
+ }
1414
+ reply.raw.writeHead(200, {
1415
+ 'Content-Type': 'text/event-stream',
1416
+ 'Cache-Control': 'no-cache',
1417
+ 'Connection': 'keep-alive',
1418
+ 'X-Accel-Buffering': 'no',
1419
+ });
1420
+ const send = (event, data) => {
1421
+ try {
1422
+ reply.raw.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
1423
+ }
1424
+ catch {
1425
+ // client disconnected
1426
+ }
1427
+ };
1428
+ send('connected', { modelId });
1429
+ const keepalive = setInterval(() => {
1430
+ try {
1431
+ reply.raw.write(':keepalive\n\n');
1432
+ }
1433
+ catch {
1434
+ clearInterval(keepalive);
1435
+ }
1436
+ }, 15000);
1437
+ try {
1438
+ const { ensureModel } = await Promise.resolve().then(() => __importStar(require('./stt/model-manager')));
1439
+ const result = await ensureModel({
1440
+ modelId,
1441
+ explicitConsent: true,
1442
+ onProgress: (p) => send('progress', p),
1443
+ });
1444
+ send('result', result);
1445
+ }
1446
+ catch (err) {
1447
+ send('result', { ok: false, error: 'io_error', modelId, message: err instanceof Error ? err.message : String(err) });
1448
+ }
1449
+ finally {
1450
+ clearInterval(keepalive);
1451
+ reply.raw.end();
1452
+ }
1453
+ return reply;
1454
+ });
1455
+ }
1456
+ // ── Project-state route (Phase 5.1 — orientation) ──
1457
+ function registerProjectRoutes(s) {
1458
+ // Bundled state endpoint so the `superbased_project` MCP tool only has to
1459
+ // make one HTTP round-trip instead of three (captures + dictation history
1460
+ // + recording status). The MCP server combines this with local-process
1461
+ // work (cwd, git info, framework detection) to produce the final tool
1462
+ // response. See mcp-server/src/project-sense.ts for the local side.
1463
+ s.get('/api/project/server-state', async (_request, reply) => {
1464
+ try {
1465
+ const capturesRaw = (0, database_1.getCaptures)(3);
1466
+ const recentCaptures = capturesRaw.map((c) => ({
1467
+ id: c.id,
1468
+ timestamp: c.timestamp,
1469
+ filename: c.filename ?? null,
1470
+ windowTitle: c.window_title ?? null,
1471
+ }));
1472
+ const dictationEntries = (0, database_1.getDictationHistory)(1);
1473
+ const lastDictation = dictationEntries[0]
1474
+ ? {
1475
+ id: dictationEntries[0].id,
1476
+ timestamp: dictationEntries[0].timestamp,
1477
+ textPreview: (dictationEntries[0].text || '').slice(0, 200),
1478
+ }
1479
+ : null;
1480
+ // Recording state — left null for now. The recording module doesn't
1481
+ // expose a direct in-process "is there an active session?" getter
1482
+ // that's safe to call from here without triggering module
1483
+ // initialization side effects. Agents can call `superbased_recording
1484
+ // action=status` when they specifically need it. Field kept in the
1485
+ // response shape so adding it back later is non-breaking.
1486
+ const activeRecording = null;
1487
+ return reply.code(200).send({
1488
+ recentCaptures,
1489
+ lastDictation,
1490
+ activeRecording,
1491
+ serverVersion: (0, config_1.getVersion)(),
1492
+ });
1493
+ }
1494
+ catch (err) {
1495
+ return reply.code(500).send({ error: err instanceof Error ? err.message : String(err) });
1496
+ }
1497
+ });
1498
+ // Bundled capture + OCR + window + timestamp for `superbased_workspace_sync`.
1499
+ // One HTTP call where an agent would otherwise chain capture → ocr →
1500
+ // window_list. Runs server-side so the image never leaves the box.
1501
+ s.get('/api/workspace/sync', async (_request, reply) => {
1502
+ try {
1503
+ const imageBuffer = await (0, capture_1.captureScreen)();
1504
+ const timestamp = new Date().toISOString();
1505
+ const active = await (0, active_window_1.getActiveWindowInfo)();
1506
+ // Run OCR on the capture. performOCR returns the full extracted text
1507
+ // directly; truncate long results so the JSON payload stays tractable
1508
+ // (agents who want the full OCR can call superbased_ocr separately).
1509
+ let ocrText = '';
1510
+ let ocrTruncated = false;
1511
+ try {
1512
+ const full = await (0, ocr_1.performOCR)(imageBuffer);
1513
+ if (typeof full === 'string') {
1514
+ if (full.length > 4000) {
1515
+ ocrText = full.slice(0, 4000);
1516
+ ocrTruncated = true;
1517
+ }
1518
+ else {
1519
+ ocrText = full;
1520
+ }
1521
+ }
1522
+ }
1523
+ catch (err) {
1524
+ logger_1.default.warn('[API] workspace sync OCR failed:', err);
1525
+ }
1526
+ // workspace_sync is intentionally read-only — does not persist to the
1527
+ // captures DB. Agents who want a captureId for follow-up calls should
1528
+ // use superbased_capture separately, which is the canonical
1529
+ // persistence path.
1530
+ return reply.code(200).send({
1531
+ imageBase64: imageBuffer.toString('base64'),
1532
+ imageBytes: imageBuffer.length,
1533
+ mimeType: 'image/png',
1534
+ timestamp,
1535
+ activeWindow: active,
1536
+ ocr: {
1537
+ text: ocrText,
1538
+ truncated: ocrTruncated,
1539
+ charsReturned: ocrText.length,
1540
+ },
1541
+ });
1542
+ }
1543
+ catch (err) {
1544
+ return reply.code(500).send({ error: err instanceof Error ? err.message : String(err) });
1545
+ }
1546
+ });
1547
+ }
1548
+ // ── Watcher Routes (Phase 3 — ambient event streams via SSE) ──
1549
+ function registerWatcherRoutes(s) {
1550
+ s.post('/api/watchers/subscribe', async (request, reply) => {
1551
+ const body = (request.body ?? {});
1552
+ const uri = typeof body.uri === 'string' ? body.uri : '';
1553
+ if (!uri) {
1554
+ return reply.code(400).send({ error: 'uri is required' });
1555
+ }
1556
+ if (!(0, store_1.getSetting)('watchers.enabled')) {
1557
+ return reply.code(403).send({ error: 'Watchers are disabled (watchers.enabled = false)' });
1558
+ }
1559
+ try {
1560
+ const { subscribe } = await Promise.resolve().then(() => __importStar(require('./watchers/registry')));
1561
+ const refcount = await subscribe(uri);
1562
+ return reply.code(200).send({ ok: true, uri, subscribers: refcount });
1563
+ }
1564
+ catch (err) {
1565
+ return reply.code(400).send({ error: err instanceof Error ? err.message : String(err) });
1566
+ }
1567
+ });
1568
+ s.post('/api/watchers/unsubscribe', async (request, reply) => {
1569
+ const body = (request.body ?? {});
1570
+ const uri = typeof body.uri === 'string' ? body.uri : '';
1571
+ if (!uri) {
1572
+ return reply.code(400).send({ error: 'uri is required' });
1573
+ }
1574
+ try {
1575
+ const { unsubscribe } = await Promise.resolve().then(() => __importStar(require('./watchers/registry')));
1576
+ const refcount = await unsubscribe(uri);
1577
+ return reply.code(200).send({ ok: true, uri, subscribers: refcount });
1578
+ }
1579
+ catch (err) {
1580
+ return reply.code(400).send({ error: err instanceof Error ? err.message : String(err) });
1581
+ }
1582
+ });
1583
+ s.get('/api/watchers/status', async (_request, reply) => {
1584
+ const { getStatus } = await Promise.resolve().then(() => __importStar(require('./watchers/registry')));
1585
+ return reply.code(200).send({ watchers: getStatus() });
1586
+ });
1587
+ s.get('/api/watchers/stream', async (request, reply) => {
1588
+ reply.raw.writeHead(200, {
1589
+ 'Content-Type': 'text/event-stream',
1590
+ 'Cache-Control': 'no-cache',
1591
+ 'Connection': 'keep-alive',
1592
+ 'X-Accel-Buffering': 'no',
1593
+ });
1594
+ reply.raw.write('event: connected\ndata: {}\n\n');
1595
+ const { onEvent } = await Promise.resolve().then(() => __importStar(require('./watchers/registry')));
1596
+ const unsubscribe = onEvent((event) => {
1597
+ try {
1598
+ reply.raw.write(`event: watcher\ndata: ${JSON.stringify(event)}\n\n`);
1599
+ }
1600
+ catch {
1601
+ // Client disconnected mid-write — cleanup handler below will fire.
1602
+ }
1603
+ });
1604
+ const keepalive = setInterval(() => {
1605
+ try {
1606
+ reply.raw.write(':keepalive\n\n');
1607
+ }
1608
+ catch {
1609
+ clearInterval(keepalive);
1610
+ }
1611
+ }, 15000);
1612
+ request.raw.on('close', () => {
1613
+ clearInterval(keepalive);
1614
+ unsubscribe();
1615
+ });
1616
+ return reply;
1617
+ });
1618
+ }
1619
+ // Register watcher factories exactly once per process.
1620
+ let watcherFactoriesRegistered = false;
1621
+ async function registerWatcherFactoriesOnce() {
1622
+ if (watcherFactoriesRegistered)
1623
+ return;
1624
+ watcherFactoriesRegistered = true;
1625
+ const { registerFactory } = await Promise.resolve().then(() => __importStar(require('./watchers/registry')));
1626
+ const { clipboardWatcherFactory } = await Promise.resolve().then(() => __importStar(require('./watchers/clipboard-watcher')));
1627
+ const { activeWindowWatcherFactory } = await Promise.resolve().then(() => __importStar(require('./watchers/active-window-watcher')));
1628
+ const { fileWatcherFactory } = await Promise.resolve().then(() => __importStar(require('./watchers/file-watcher')));
1629
+ const { screenRegionWatcherFactory } = await Promise.resolve().then(() => __importStar(require('./watchers/screen-region-watcher')));
1630
+ registerFactory(clipboardWatcherFactory);
1631
+ registerFactory(activeWindowWatcherFactory);
1632
+ registerFactory(fileWatcherFactory);
1633
+ registerFactory(screenRegionWatcherFactory);
1634
+ }
619
1635
  // ── Recording Routes (delegate to recording module if available) ──
620
1636
  let recordingRoutesRegistered = false;
621
1637
  function registerRecordingRoutesOnServer() {
@@ -926,154 +1942,148 @@ function registerExpandedRoutes(server) {
926
1942
  });
927
1943
  // POST /api/capture/fullscreen-image — capture with resolution + window targeting
928
1944
  server.post('/api/capture/fullscreen-image', async (req, reply) => {
1945
+ const t0 = Date.now();
1946
+ const timings = {};
1947
+ const mark = (k) => { timings[k] = Date.now() - t0; };
929
1948
  try {
930
1949
  const body = req.body || {};
931
1950
  if (body.projectDir && !isValidProjectDir(body.projectDir)) {
932
1951
  return reply.code(400).send({ error: 'Invalid projectDir' });
933
1952
  }
934
- // Window targeting: find matching window, bring to foreground, then capture
1953
+ // ── Window targeting (hardened per agent feedback 2026-04-21) ────────
1954
+ //
1955
+ // Previously this handler did a naive case-insensitive substring
1956
+ // match on window titles alone. That silently picked the wrong
1957
+ // window when a project name appeared in an IDE's window title
1958
+ // (e.g. target="superbased" matched both "SuperBased" Electron app
1959
+ // AND "superbased [WSL] — Antigravity" IDE; the IDE won). It also
1960
+ // had no retry or post-activation verification, so a silently-
1961
+ // failed SetForegroundWindow would still produce a screenshot of
1962
+ // the wrong window.
1963
+ //
1964
+ // New flow:
1965
+ // 1. resolveWindow() — scored matcher that refuses on ambiguous
1966
+ // matches and returns alternatives. Same path focus_window
1967
+ // uses. hwnd/processName/window all supported.
1968
+ // 2. activateWindow() — up-to-3-attempt activation with
1969
+ // GetForegroundWindow verification on Windows. Surfaces
1970
+ // `verified:boolean` + `postForeground:hwnd` in the diagnostic.
1971
+ // 3. If !verified, we STILL take the screenshot (so the agent
1972
+ // gets something) but the diagnostic includes broughtToFront:
1973
+ // false so the caller knows the result can't be trusted.
1974
+ // 4. restoreWindow() on the previous foreground token.
935
1975
  let windowInfo = null;
936
1976
  let buffer = null;
937
- if (body.window) {
938
- const sources = await (0, platform_1.getPlatform)().listWindows();
939
- const match = sources.find((s) => s.name.toLowerCase().includes(body.window.toLowerCase()));
940
- if (!match) {
941
- return reply.code(404).send({ error: `No window matching "${body.window}"`, availableWindows: sources.map((s) => s.name) });
1977
+ let diagnostic = null;
1978
+ let matchedWindow = null;
1979
+ let alternativesOut;
1980
+ const wantWindowTargeting = !!(body.window || body.processName || body.hwnd);
1981
+ if (wantWindowTargeting) {
1982
+ const { resolveWindow } = await Promise.resolve().then(() => __importStar(require('./window-resolver')));
1983
+ const matchResult = await resolveWindow({
1984
+ window: body.window,
1985
+ processName: body.processName,
1986
+ hwnd: body.hwnd,
1987
+ });
1988
+ mark('resolveMs');
1989
+ if (!matchResult.ok || !matchResult.best) {
1990
+ return reply.code(matchResult.reason === 'ambiguous' ? 409 : 404).send({
1991
+ ok: false,
1992
+ error: matchResult.error,
1993
+ reason: matchResult.reason,
1994
+ alternatives: matchResult.alternatives?.map((c) => ({
1995
+ title: c.name, processName: c.processName, hwnd: c.hwnd, score: c.score, scoreReason: c.scoreReason,
1996
+ })),
1997
+ hint: matchResult.reason === 'ambiguous'
1998
+ ? 'Multiple windows matched. Disambiguate with `processName` + `window` combined, or pass `hwnd` directly.'
1999
+ : matchResult.reason === 'no_match'
2000
+ ? 'No matching window. Call superbased_window_list to see what is open.'
2001
+ : undefined,
2002
+ });
942
2003
  }
2004
+ const match = matchResult.best;
943
2005
  windowInfo = { appName: match.name, windowTitle: match.name };
944
- // Bring target window to foreground, capture, then restore original window.
945
- // Uses a temp .ps1 script with Win32 P/Invoke to handle minimized windows
946
- // and bypass SetForegroundWindow restrictions (AttachThreadInput trick).
947
- const { execSync: execSyncCapture } = require('child_process');
948
- const osMod = require('os');
949
- const pathMod = require('path');
950
- const fsMod = require('fs');
951
- try {
952
- if (process.platform === 'win32') {
953
- const hwnd = match.hwnd;
954
- let previousHwnd = null;
955
- if (hwnd) {
956
- const activateScript = pathMod.join(osMod.tmpdir(), 'superbased-activate.ps1');
957
- fsMod.writeFileSync(activateScript, `
958
- param([long]$TargetHwnd)
959
- Add-Type -TypeDefinition @'
960
- using System; using System.Runtime.InteropServices;
961
- public class WinActivate {
962
- [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
963
- [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int c);
964
- [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
965
- [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr h);
966
- [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
967
- [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
968
- [DllImport("user32.dll")] public static extern bool AttachThreadInput(uint a, uint b, bool attach);
969
- [DllImport("user32.dll")] public static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
970
- public static IntPtr Activate(IntPtr target) {
971
- IntPtr prev = GetForegroundWindow();
972
- uint dummy;
973
- uint fgThread = GetWindowThreadProcessId(prev, out dummy);
974
- uint curThread = GetCurrentThreadId();
975
- AttachThreadInput(curThread, fgThread, true);
976
- ShowWindow(target, 9);
977
- keybd_event(0x12, 0, 1, UIntPtr.Zero);
978
- keybd_event(0x12, 0, 3, UIntPtr.Zero);
979
- SetForegroundWindow(target);
980
- BringWindowToTop(target);
981
- AttachThreadInput(curThread, fgThread, false);
982
- return prev;
983
- }
984
- }
985
- '@
986
- $h = [IntPtr]::new($TargetHwnd)
987
- $prev = [WinActivate]::Activate($h)
988
- $prev.ToInt64()
989
- `);
990
- try {
991
- previousHwnd = execSyncCapture(`powershell -ExecutionPolicy Bypass -File "${activateScript}" -TargetHwnd ${hwnd}`, { encoding: 'utf-8', timeout: 5000, stdio: 'pipe' }).trim();
992
- }
993
- catch { /* ignore */ }
994
- try {
995
- fsMod.unlinkSync(activateScript);
996
- }
997
- catch { /* cleanup */ }
998
- }
999
- else {
1000
- // Fallback: use AppActivate by title
1001
- const escapedTitle = match.name.replace(/'/g, "''");
1002
- execSyncCapture(`powershell -command "(New-Object -ComObject WScript.Shell).AppActivate('${escapedTitle}')"`, { timeout: 3000, stdio: 'pipe' });
1003
- }
1004
- await new Promise((r) => setTimeout(r, 300));
1005
- // Capture while target is in foreground
1006
- buffer = await (0, capture_1.captureScreen)();
1007
- // Restore the original window
1008
- if (previousHwnd && previousHwnd !== '0' && hwnd) {
1009
- const restoreScript = pathMod.join(osMod.tmpdir(), 'superbased-restore.ps1');
1010
- fsMod.writeFileSync(restoreScript, `
1011
- param([long]$Hwnd)
1012
- Add-Type -TypeDefinition @'
1013
- using System; using System.Runtime.InteropServices;
1014
- public class WinRestore {
1015
- [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
1016
- [DllImport("user32.dll")] public static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
1017
- public static void Restore(IntPtr target) {
1018
- keybd_event(0x12, 0, 1, UIntPtr.Zero);
1019
- keybd_event(0x12, 0, 3, UIntPtr.Zero);
1020
- SetForegroundWindow(target);
1021
- }
1022
- }
1023
- '@
1024
- [WinRestore]::Restore([IntPtr]::new($Hwnd))
1025
- `);
1026
- try {
1027
- execSyncCapture(`powershell -ExecutionPolicy Bypass -File "${restoreScript}" -Hwnd ${previousHwnd}`, { timeout: 3000, stdio: 'pipe' });
1028
- }
1029
- catch { /* ignore */ }
1030
- try {
1031
- fsMod.unlinkSync(restoreScript);
1032
- }
1033
- catch { /* cleanup */ }
1034
- }
1035
- }
1036
- else if (process.platform === 'darwin') {
1037
- // macOS: use AppleScript to get frontmost app, activate target, capture, restore
1038
- let previousApp = null;
1039
- try {
1040
- previousApp = execSyncCapture('osascript -e \'tell application "System Events" to get name of first process whose frontmost is true\'', { encoding: 'utf-8', timeout: 3000, stdio: 'pipe' }).trim();
1041
- }
1042
- catch { /* ignore */ }
1043
- // Extract app name from window title (format: "AppName - WindowTitle")
1044
- const dashIdx = match.name.indexOf(' - ');
1045
- const appName = dashIdx !== -1 ? match.name.substring(0, dashIdx) : match.name;
1046
- const windowTitle = dashIdx !== -1 ? match.name.substring(dashIdx + 3) : '';
1047
- // Activate the target window
1048
- const escapedApp = appName.replace(/"/g, '\\"');
2006
+ matchedWindow = {
2007
+ title: match.name,
2008
+ processName: match.processName,
2009
+ hwnd: match.hwnd,
2010
+ score: match.score,
2011
+ scoreReason: match.scoreReason,
2012
+ };
2013
+ if (matchResult.alternatives && matchResult.alternatives.length > 0) {
2014
+ alternativesOut = matchResult.alternatives.map((c) => ({
2015
+ title: c.name, processName: c.processName, hwnd: c.hwnd, score: c.score, scoreReason: c.scoreReason,
2016
+ }));
2017
+ }
2018
+ const { withActivatedWindow, captureWindowBackgroundWindows, } = await Promise.resolve().then(() => __importStar(require('./window-activate')));
2019
+ // ─── Fast path: background capture via PrintWindow ────────────
2020
+ //
2021
+ // When the caller requests background:true AND we're on Windows
2022
+ // AND we have a concrete hwnd, skip activation entirely and use
2023
+ // PrintWindow(PW_RENDERFULLCONTENT) to grab the window's pixels
2024
+ // directly. No focus change, no restore overhead, and ~5x faster
2025
+ // than the activation path (no 3× retry + verify sleeps). Falls
2026
+ // through to the activate path if the bitmap comes back empty
2027
+ // (GPU-composited surfaces — some games, fullscreen video).
2028
+ let backgroundMode = false;
2029
+ if (body.background && process.platform === 'win32' && match.hwnd) {
2030
+ const bg = await captureWindowBackgroundWindows(match.hwnd);
2031
+ mark('captureMs');
2032
+ if (bg) {
2033
+ buffer = fs.readFileSync(bg.path);
1049
2034
  try {
1050
- if (windowTitle) {
1051
- execSyncCapture(`osascript -e 'tell application "${escapedApp}" to activate' -e 'delay 0.2' -e 'tell application "System Events" to tell process "${escapedApp}" to set frontmost to true'`, { timeout: 3000, stdio: 'pipe' });
1052
- }
1053
- else {
1054
- execSyncCapture(`osascript -e 'tell application "${escapedApp}" to activate'`, { timeout: 3000, stdio: 'pipe' });
1055
- }
1056
- }
1057
- catch { /* ignore */ }
1058
- await new Promise((r) => setTimeout(r, 300));
1059
- // Capture while target is in foreground
1060
- buffer = await (0, capture_1.captureScreen)();
1061
- // Restore the previous app
1062
- if (previousApp) {
1063
- try {
1064
- const escapedPrev = previousApp.replace(/"/g, '\\"');
1065
- execSyncCapture(`osascript -e 'tell application "${escapedPrev}" to activate'`, { timeout: 3000, stdio: 'pipe' });
1066
- }
1067
- catch { /* ignore */ }
2035
+ fs.unlinkSync(bg.path);
1068
2036
  }
2037
+ catch { /* cleanup */ }
2038
+ backgroundMode = true;
2039
+ diagnostic = {
2040
+ broughtToFront: true, // target was never foregrounded — it didn't need to be
2041
+ foregroundAfterActivate: undefined,
2042
+ activationAttempts: 0,
2043
+ activationError: undefined,
2044
+ };
1069
2045
  }
2046
+ // else: fall through to activate path with a diagnostic note
1070
2047
  }
1071
- catch {
1072
- // Window activation failed — capture will get whatever is on screen
2048
+ if (!backgroundMode) {
2049
+ // Delegate the snapshot-activate-paint-capture-restore cycle to
2050
+ // withActivatedWindow. Paint delay is 150ms (Electron repaint
2051
+ // window); agents that need more for GPU-heavy targets can
2052
+ // request a second capture.
2053
+ const wrap = await withActivatedWindow(match, async () => {
2054
+ const tCap = Date.now();
2055
+ const buf = await (0, capture_1.captureScreen)();
2056
+ return { buffer: buf, captureMs: Date.now() - tCap };
2057
+ }, { paintDelayMs: 150 });
2058
+ buffer = wrap.result.buffer;
2059
+ if (wrap.timings.snapshotMs !== undefined)
2060
+ timings.snapshotMs = (timings.resolveMs ?? 0) + wrap.timings.snapshotMs;
2061
+ if (wrap.timings.activateMs !== undefined)
2062
+ timings.activateMs = (timings.snapshotMs ?? 0) + wrap.timings.activateMs;
2063
+ if (wrap.timings.paintMs !== undefined)
2064
+ timings.paintMs = (timings.activateMs ?? 0) + wrap.timings.paintMs;
2065
+ timings.captureMs = (timings.paintMs ?? timings.activateMs ?? timings.snapshotMs ?? timings.resolveMs ?? 0) + wrap.result.captureMs;
2066
+ if (wrap.timings.restoreMs !== undefined)
2067
+ timings.restoreMs = (timings.captureMs ?? 0) + wrap.timings.restoreMs;
2068
+ diagnostic = {
2069
+ broughtToFront: wrap.diag.verified === true
2070
+ || (process.platform !== 'win32' && wrap.diag.ok === true),
2071
+ foregroundAfterActivate: wrap.diag.postForeground,
2072
+ activationAttempts: wrap.diag.attempted,
2073
+ activationError: wrap.diag.error,
2074
+ };
2075
+ if (!wrap.restore.skipped) {
2076
+ diagnostic.restoredFocus = wrap.restore.restored;
2077
+ diagnostic.restoreAttempts = wrap.restore.attempts;
2078
+ diagnostic.foregroundAfterRestore = wrap.restore.finalForeground;
2079
+ }
1073
2080
  }
2081
+ diagnostic.backgroundMode = backgroundMode;
1074
2082
  }
1075
- if (!buffer)
2083
+ if (!buffer) {
1076
2084
  buffer = await (0, capture_1.captureScreen)();
2085
+ mark('captureMs');
2086
+ }
1077
2087
  // Auto-redact if enabled
1078
2088
  const redactSecrets = !!(0, store_1.getSetting)('autoRedactSecrets');
1079
2089
  const redactPII = !!(0, store_1.getSetting)('autoRedactPII');
@@ -1098,11 +2108,21 @@ public class WinRestore {
1098
2108
  sourceApp: windowInfo?.appName || 'API',
1099
2109
  windowTitle: windowInfo?.windowTitle || 'Fullscreen Capture',
1100
2110
  });
2111
+ mark('totalMs');
1101
2112
  return reply.code(200).send({
1102
2113
  captureId, width, height,
1103
2114
  imageBase64: buffer.toString('base64'),
1104
2115
  mimeType: 'image/png',
1105
2116
  windowInfo,
2117
+ // Per-call diagnostic — lets the MCP caller detect silent
2118
+ // foregrounding failures (broughtToFront:false) instead of
2119
+ // inferring from pixels. Present only when window targeting
2120
+ // was requested. `timings` is keyed by step; keys present only
2121
+ // when that step ran (e.g. no `restoreMs` for background mode).
2122
+ matchedWindow: matchedWindow ?? undefined,
2123
+ alternatives: alternativesOut,
2124
+ diagnostic: diagnostic ?? undefined,
2125
+ timings: Object.keys(timings).length > 0 ? timings : undefined,
1106
2126
  });
1107
2127
  }
1108
2128
  catch (err) {
@@ -1125,7 +2145,10 @@ public class WinRestore {
1125
2145
  else if (body.imageBase64) {
1126
2146
  imageBuffer = Buffer.from(body.imageBase64, 'base64');
1127
2147
  }
1128
- else if (body.screenshotPath && fs.existsSync(body.screenshotPath)) {
2148
+ else if (body.screenshotPath) {
2149
+ if (!isValidScreenshotPath(body.screenshotPath) || !fs.existsSync(body.screenshotPath)) {
2150
+ return reply.code(400).send({ error: 'Invalid or inaccessible screenshotPath' });
2151
+ }
1129
2152
  imageBuffer = fs.readFileSync(body.screenshotPath);
1130
2153
  }
1131
2154
  else {
@@ -1146,12 +2169,14 @@ public class WinRestore {
1146
2169
  return reply.code(500).send({ error: err instanceof Error ? err.message : String(err) });
1147
2170
  }
1148
2171
  });
1149
- // POST /api/transcribe — audio transcription via backend Whisper
2172
+ // POST /api/transcribe — audio transcription. Engine-routed (Phase 4b).
2173
+ // Route through stt/router so the `engine` parameter picks cloud / sherpa /
2174
+ // native, with `auto` resolving to the best available engine given the
2175
+ // current auth + model state. Structured engine errors are returned as
2176
+ // HTTP 200 with { ok: false, error, engine, ...remediation } bodies so
2177
+ // agents can branch on the error code rather than an HTTP status.
1150
2178
  server.post('/api/transcribe', async (req, reply) => {
1151
2179
  try {
1152
- if (!(0, auth_1.isAuthenticated)()) {
1153
- return reply.code(401).send({ error: 'Authentication required for transcription' });
1154
- }
1155
2180
  const body = req.body || {};
1156
2181
  let audioBase64 = body.audioBase64;
1157
2182
  if (!audioBase64 && body.audioPath && fs.existsSync(body.audioPath)) {
@@ -1160,8 +2185,18 @@ public class WinRestore {
1160
2185
  if (!audioBase64) {
1161
2186
  return reply.code(400).send({ error: 'audioBase64 or audioPath required' });
1162
2187
  }
1163
- const text = await (0, ai_client_1.transcribeViaBackend)(audioBase64, body.language, 'api');
1164
- return reply.code(200).send({ text });
2188
+ const { route } = await Promise.resolve().then(() => __importStar(require('./stt/router')));
2189
+ const engineRequested = body.engine ?? 'auto';
2190
+ const result = await route({
2191
+ engine: engineRequested,
2192
+ audioBase64,
2193
+ language: body.language,
2194
+ source: 'api',
2195
+ });
2196
+ if (result.ok === false) {
2197
+ return reply.code(200).send(result);
2198
+ }
2199
+ return reply.code(200).send({ text: result.text, engine: result.engine, latencyMs: result.latencyMs });
1165
2200
  }
1166
2201
  catch (err) {
1167
2202
  return reply.code(500).send({ error: err instanceof Error ? err.message : String(err) });
@@ -1178,6 +2213,7 @@ public class WinRestore {
1178
2213
  name: s.name,
1179
2214
  hwnd: s.hwnd,
1180
2215
  minimized: s.minimized,
2216
+ processName: s.processName,
1181
2217
  isActive: active.windowTitle ? s.name === active.windowTitle : false,
1182
2218
  })),
1183
2219
  activeWindow: active,
@@ -1283,12 +2319,11 @@ public class WinRestore {
1283
2319
  return reply.code(500).send({ error: err instanceof Error ? err.message : String(err) });
1284
2320
  }
1285
2321
  });
1286
- // POST /api/dictate — accept audio, transcribe, return text
2322
+ // POST /api/dictate — accept audio, transcribe, return text. Engine-routed
2323
+ // (Phase 4b). Post-processing (filler removal, dedup) is engine-agnostic
2324
+ // and runs on the engine's raw transcript before returning.
1287
2325
  server.post('/api/dictate', async (req, reply) => {
1288
2326
  try {
1289
- if (!(0, auth_1.isAuthenticated)()) {
1290
- return reply.code(401).send({ error: 'Authentication required for dictation' });
1291
- }
1292
2327
  const body = req.body || {};
1293
2328
  let audioBase64 = body.audioBase64;
1294
2329
  if (!audioBase64 && body.audioPath && fs.existsSync(body.audioPath)) {
@@ -1297,8 +2332,18 @@ public class WinRestore {
1297
2332
  if (!audioBase64) {
1298
2333
  return reply.code(400).send({ error: 'audioBase64 or audioPath required' });
1299
2334
  }
1300
- const rawText = await (0, ai_client_1.transcribeViaBackend)(audioBase64, body.language, 'dictation');
1301
- // Optional AI cleanup
2335
+ const { route } = await Promise.resolve().then(() => __importStar(require('./stt/router')));
2336
+ const engineRequested = body.engine ?? 'auto';
2337
+ const result = await route({
2338
+ engine: engineRequested,
2339
+ audioBase64,
2340
+ language: body.language,
2341
+ source: 'dictation',
2342
+ });
2343
+ if (result.ok === false) {
2344
+ return reply.code(200).send(result);
2345
+ }
2346
+ const rawText = result.text;
1302
2347
  let finalText = rawText;
1303
2348
  if (body.cleanup !== false) {
1304
2349
  try {
@@ -1309,18 +2354,17 @@ public class WinRestore {
1309
2354
  // Dictation module may not be available — return raw text
1310
2355
  }
1311
2356
  }
1312
- return reply.code(200).send({ text: finalText, rawText });
2357
+ return reply.code(200).send({ text: finalText, rawText, engine: result.engine, latencyMs: result.latencyMs });
1313
2358
  }
1314
2359
  catch (err) {
1315
2360
  return reply.code(500).send({ error: err instanceof Error ? err.message : String(err) });
1316
2361
  }
1317
2362
  });
1318
- // POST /api/dictate/mic — record from microphone, transcribe, return text
2363
+ // POST /api/dictate/mic — record from microphone, transcribe, return text.
2364
+ // Engine-routed (Phase 4b). Records via ffmpeg-static to an in-memory WAV,
2365
+ // then hands off to the router for engine selection.
1319
2366
  server.post('/api/dictate/mic', async (req, reply) => {
1320
2367
  try {
1321
- if (!(0, auth_1.isAuthenticated)()) {
1322
- return reply.code(401).send({ error: 'Authentication required for dictation' });
1323
- }
1324
2368
  const body = req.body || {};
1325
2369
  const duration = body.duration || 10;
1326
2370
  // Mic capture — pipes audio to memory (no temp file I/O)
@@ -1339,7 +2383,18 @@ public class WinRestore {
1339
2383
  catch (err) {
1340
2384
  return reply.code(400).send({ error: err instanceof Error ? err.message : String(err) });
1341
2385
  }
1342
- const rawText = await (0, ai_client_1.transcribeViaBackend)(audioBase64, body.language, 'dictation-mic');
2386
+ const { route } = await Promise.resolve().then(() => __importStar(require('./stt/router')));
2387
+ const engineRequested = body.engine ?? 'auto';
2388
+ const result = await route({
2389
+ engine: engineRequested,
2390
+ audioBase64,
2391
+ language: body.language,
2392
+ source: 'dictation-mic',
2393
+ });
2394
+ if (result.ok === false) {
2395
+ return reply.code(200).send(result);
2396
+ }
2397
+ const rawText = result.text;
1343
2398
  let finalText = rawText;
1344
2399
  if (body.cleanup !== false) {
1345
2400
  try {
@@ -1348,7 +2403,7 @@ public class WinRestore {
1348
2403
  }
1349
2404
  catch { /* fallback to raw */ }
1350
2405
  }
1351
- return reply.code(200).send({ text: finalText, rawText, source: 'mic', duration });
2406
+ return reply.code(200).send({ text: finalText, rawText, source: 'mic', duration, engine: result.engine, latencyMs: result.latencyMs });
1352
2407
  }
1353
2408
  catch (err) {
1354
2409
  return reply.code(500).send({ error: err instanceof Error ? err.message : String(err) });
@@ -1435,9 +2490,6 @@ public class WinRestore {
1435
2490
  // POST /api/recording/describe-frames — AI description of recording frames
1436
2491
  server.post('/api/recording/describe-frames', async (req, reply) => {
1437
2492
  try {
1438
- if (!(0, auth_1.isAuthenticated)()) {
1439
- return reply.code(401).send({ error: 'Authentication required' });
1440
- }
1441
2493
  const { getSessionFrames: getFrames } = await Promise.resolve().then(() => __importStar(require('../db/database')));
1442
2494
  const body = req.body || { sessionId: '' };
1443
2495
  if (!body.sessionId)
@@ -1448,21 +2500,46 @@ public class WinRestore {
1448
2500
  const limit = body.limit || 20;
1449
2501
  const selectedFrames = frames.slice(0, limit);
1450
2502
  const descriptions = [];
1451
- for (const frame of selectedFrames) {
1452
- if (!fs.existsSync(frame.screenshot_path))
1453
- continue;
1454
- const buf = fs.readFileSync(frame.screenshot_path);
1455
- const imageBase64 = await resizeImageForAI(buf);
1456
- let description = '';
1457
- for await (const chunk of (0, ai_client_1.streamAIFromBackend)({
1458
- imagesBase64: [imageBase64],
1459
- instruction: `Briefly describe what's visible in this screenshot (frame #${frame.frame_number} of a recording session). Focus on the application state, visible UI elements, and any notable changes. Keep it to 1-2 sentences.`,
1460
- })) {
1461
- description += chunk;
2503
+ const { dispatchAI } = await Promise.resolve().then(() => __importStar(require('./ollama/dispatcher')));
2504
+ let providerUsed = 'cloud';
2505
+ let modelUsed;
2506
+ try {
2507
+ for (const frame of selectedFrames) {
2508
+ if (!fs.existsSync(frame.screenshot_path))
2509
+ continue;
2510
+ const buf = fs.readFileSync(frame.screenshot_path);
2511
+ const imageBase64 = await (0, image_utils_1.resizeImageForAI)(buf);
2512
+ let description = '';
2513
+ const dispatch = await dispatchAI({
2514
+ task: 'vision',
2515
+ provider: body.provider,
2516
+ model: body.model,
2517
+ forceVision: body.forceVision,
2518
+ instruction: `Briefly describe what's visible in this screenshot (frame #${frame.frame_number} of a recording session). Focus on the application state, visible UI elements, and any notable changes. Keep it to 1-2 sentences.`,
2519
+ imagesBase64: [imageBase64],
2520
+ });
2521
+ providerUsed = dispatch.resolution.provider;
2522
+ modelUsed = dispatch.resolution.model;
2523
+ for await (const chunk of dispatch.stream) {
2524
+ description += chunk;
2525
+ }
2526
+ descriptions.push({ frameNumber: frame.frame_number, description });
1462
2527
  }
1463
- descriptions.push({ frameNumber: frame.frame_number, description });
1464
2528
  }
1465
- return reply.code(200).send({ sessionId: body.sessionId, descriptions });
2529
+ catch (err) {
2530
+ if (err && typeof err === 'object' && 'code' in err) {
2531
+ const de = err;
2532
+ const httpCode = de.code === 'not_signed_in' ? 401 : 400;
2533
+ return reply.code(httpCode).send({ error: de.message, code: de.code, hint: de.hint, provider: de.provider });
2534
+ }
2535
+ return reply.code(502).send({ error: err instanceof Error ? err.message : String(err) });
2536
+ }
2537
+ return reply.code(200).send({
2538
+ sessionId: body.sessionId,
2539
+ descriptions,
2540
+ provider: providerUsed,
2541
+ model: modelUsed,
2542
+ });
1466
2543
  }
1467
2544
  catch (err) {
1468
2545
  return reply.code(500).send({ error: err instanceof Error ? err.message : String(err) });
@@ -1471,26 +2548,47 @@ public class WinRestore {
1471
2548
  // POST /api/recording/narrate — generate prose summary of a session
1472
2549
  server.post('/api/recording/narrate', async (req, reply) => {
1473
2550
  try {
1474
- if (!(0, auth_1.isAuthenticated)()) {
1475
- return reply.code(401).send({ error: 'Authentication required' });
1476
- }
1477
2551
  const body = req.body || { sessionId: '' };
1478
2552
  if (!body.sessionId)
1479
2553
  return reply.code(400).send({ error: 'sessionId required' });
1480
2554
  // If descriptions not provided, generate them first
1481
- let descriptions = body.descriptions;
2555
+ const descriptions = body.descriptions;
1482
2556
  if (!descriptions) {
1483
2557
  return reply.code(400).send({ error: 'descriptions array required (use /api/recording/describe-frames first)' });
1484
2558
  }
1485
2559
  const frameList = descriptions.map((d) => `Frame ${d.frameNumber}: ${d.description}`).join('\n');
1486
2560
  let narration = '';
1487
- for await (const chunk of (0, ai_client_1.streamAIFromBackend)({
1488
- imagesBase64: [],
1489
- instruction: `You are narrating a screen recording session. Based on these frame descriptions, write a concise narrative summary of what happened during this session. Use past tense.\n\n${frameList}`,
1490
- })) {
1491
- narration += chunk;
2561
+ let providerUsed = 'cloud';
2562
+ let modelUsed;
2563
+ try {
2564
+ const { dispatchAI } = await Promise.resolve().then(() => __importStar(require('./ollama/dispatcher')));
2565
+ const dispatch = await dispatchAI({
2566
+ task: 'chat',
2567
+ provider: body.provider,
2568
+ model: body.model,
2569
+ instruction: `You are narrating a screen recording session. Based on these frame descriptions, write a concise narrative summary of what happened during this session. Use past tense.\n\n${frameList}`,
2570
+ imagesBase64: [],
2571
+ });
2572
+ providerUsed = dispatch.resolution.provider;
2573
+ modelUsed = dispatch.resolution.model;
2574
+ for await (const chunk of dispatch.stream) {
2575
+ narration += chunk;
2576
+ }
2577
+ }
2578
+ catch (err) {
2579
+ if (err && typeof err === 'object' && 'code' in err) {
2580
+ const de = err;
2581
+ const httpCode = de.code === 'not_signed_in' ? 401 : 400;
2582
+ return reply.code(httpCode).send({ error: de.message, code: de.code, hint: de.hint, provider: de.provider });
2583
+ }
2584
+ return reply.code(502).send({ error: err instanceof Error ? err.message : String(err) });
1492
2585
  }
1493
- return reply.code(200).send({ sessionId: body.sessionId, narration });
2586
+ return reply.code(200).send({
2587
+ sessionId: body.sessionId,
2588
+ narration,
2589
+ provider: providerUsed,
2590
+ model: modelUsed,
2591
+ });
1494
2592
  }
1495
2593
  catch (err) {
1496
2594
  return reply.code(500).send({ error: err instanceof Error ? err.message : String(err) });
@@ -1500,12 +2598,83 @@ public class WinRestore {
1500
2598
  function escapeXml(s) {
1501
2599
  return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
1502
2600
  }
2601
+ // ── MCP-over-HTTP Routes ──
2602
+ function registerMcpHttpRoutes(server) {
2603
+ let mcpHandler = null;
2604
+ function getHandler() {
2605
+ if (!mcpHandler) {
2606
+ try {
2607
+ // Try multiple paths — the MCP server module location varies between
2608
+ // desktop (electron-builder), headless dist, and npm global install
2609
+ const tryPaths = [
2610
+ path.join(__dirname, '..', '..', 'mcp-server', 'dist', 'index.js'), // from electron/modules/ → mcp-server/dist/
2611
+ path.join(__dirname, '..', '..', '..', 'mcp-server', 'dist', 'index.js'), // from dist/electron/modules/ → mcp-server/dist/
2612
+ ];
2613
+ let mod = null;
2614
+ for (const p of tryPaths) {
2615
+ try {
2616
+ if (fs.existsSync(p)) {
2617
+ mod = require(p);
2618
+ break;
2619
+ }
2620
+ }
2621
+ catch { /* try next */ }
2622
+ }
2623
+ if (mod?.createMcpHttpHandler) {
2624
+ mcpHandler = mod.createMcpHttpHandler(currentPort);
2625
+ }
2626
+ else {
2627
+ logger_1.default.warn('[API] MCP HTTP handler module not found');
2628
+ }
2629
+ }
2630
+ catch (err) {
2631
+ logger_1.default.error('[API] Failed to load MCP HTTP handler:', err);
2632
+ }
2633
+ }
2634
+ return mcpHandler;
2635
+ }
2636
+ server.post('/mcp', async (request, reply) => {
2637
+ const handler = getHandler();
2638
+ if (!handler) {
2639
+ return reply.code(503).send({ error: 'MCP HTTP handler not available' });
2640
+ }
2641
+ // Hand off to StreamableHTTPServerTransport with raw Node.js req/res
2642
+ await handler.handlePost(request.raw, reply.raw, request.body);
2643
+ // Tell Fastify we've handled the response ourselves
2644
+ reply.hijack();
2645
+ });
2646
+ server.get('/mcp', async (request, reply) => {
2647
+ const handler = getHandler();
2648
+ if (!handler) {
2649
+ return reply.code(503).send({ error: 'MCP HTTP handler not available' });
2650
+ }
2651
+ await handler.handleGet(request.raw, reply.raw);
2652
+ reply.hijack();
2653
+ });
2654
+ server.delete('/mcp', async (request, reply) => {
2655
+ const handler = getHandler();
2656
+ if (!handler) {
2657
+ return reply.code(503).send({ error: 'MCP HTTP handler not available' });
2658
+ }
2659
+ await handler.handleDelete(request.raw, reply.raw);
2660
+ reply.hijack();
2661
+ });
2662
+ logger_1.default.info('[API] MCP HTTP endpoint registered at /mcp');
2663
+ }
1503
2664
  // ── Server Lifecycle ──
1504
- async function startApiServer() {
2665
+ // Port resolution priority: explicit arg > SUPERBASED_API_PORT env > default.
2666
+ // The default 47592 is the canonical port that the desktop app, the MCP
2667
+ // stdio bridge, and headless serve all converge on.
2668
+ let currentPort = API_PORT;
2669
+ function getApiPort() {
2670
+ return currentPort;
2671
+ }
2672
+ async function startApiServer(opts) {
1505
2673
  if (server)
1506
2674
  return;
1507
2675
  startTime = Date.now();
1508
2676
  authToken = generateAuthToken();
2677
+ currentPort = opts?.port ?? (Number(process.env.SUPERBASED_API_PORT) || API_PORT);
1509
2678
  server = (0, fastify_1.default)({ logger: false, bodyLimit: 50 * 1024 * 1024 }); // 50MB body limit for images
1510
2679
  // Register all route groups
1511
2680
  registerHealthRoutes(server);
@@ -1514,8 +2683,21 @@ async function startApiServer() {
1514
2683
  registerGalleryRoutes(server);
1515
2684
  registerSettingsRoutes(server);
1516
2685
  registerPresetsRoutes(server);
2686
+ // GUI automation routes (Phase 2a)
2687
+ registerAutomationRoutes(server);
2688
+ // Watcher routes + factories (Phase 3)
2689
+ await registerWatcherFactoriesOnce();
2690
+ registerWatcherRoutes(server);
1517
2691
  // Token Compression Engine route
1518
2692
  registerCompressRoutes(server);
2693
+ // Local STT routes (Phase 4a — capability probe + model download)
2694
+ registerSTTRoutes(server);
2695
+ // Ollama detection routes (Phase 6.1 — detection only)
2696
+ registerOllamaRoutes(server);
2697
+ // Accessibility tree routes (Phase 8.1 — macOS AX / Windows UIA)
2698
+ registerAccessibilityRoutes(server);
2699
+ // Project-orientation + workspace-sync routes (Phase 5.1)
2700
+ registerProjectRoutes(server);
1519
2701
  // Expanded routes (auth, license, AI usage, redact, transcribe, windows, etc.)
1520
2702
  registerExpandedRoutes(server);
1521
2703
  // Recording routes are registered separately when the recording module is enabled
@@ -1523,9 +2705,16 @@ async function startApiServer() {
1523
2705
  if ((0, store_1.getSetting)('recordingFeatureEnabled')) {
1524
2706
  registerRecordingRoutesOnServer();
1525
2707
  }
2708
+ // MCP-over-HTTP endpoint — allows URL-based MCP clients (OpenAI Codex, etc.)
2709
+ // to connect at http://127.0.0.1:47592/mcp instead of requiring stdio transport
2710
+ registerMcpHttpRoutes(server);
1526
2711
  try {
1527
- await server.listen({ port: API_PORT, host: API_HOST });
1528
- logger_1.default.info(`[API] HTTP API listening on http://${API_HOST}:${API_PORT}`);
2712
+ await server.listen({ port: currentPort, host: API_HOST });
2713
+ logger_1.default.info(`[API] HTTP API listening on http://${API_HOST}:${currentPort}`);
2714
+ // Fire-and-forget Ollama detection probe. On positive detection, logs one
2715
+ // line listing models; on absence, silent. Never blocks startup.
2716
+ Promise.resolve().then(() => __importStar(require('./ollama/detector'))).then(({ logStartupDetection }) => logStartupDetection())
2717
+ .catch(() => { });
1529
2718
  }
1530
2719
  catch (err) {
1531
2720
  logger_1.default.error('[API] Failed to start HTTP API:', err);
@@ -1534,6 +2723,13 @@ async function startApiServer() {
1534
2723
  }
1535
2724
  async function stopApiServer() {
1536
2725
  if (server) {
2726
+ try {
2727
+ const { shutdown } = await Promise.resolve().then(() => __importStar(require('./watchers/registry')));
2728
+ await shutdown();
2729
+ }
2730
+ catch (err) {
2731
+ logger_1.default.warn('[API] error shutting down watchers:', err);
2732
+ }
1537
2733
  await server.close();
1538
2734
  server = null;
1539
2735
  recordingRoutesRegistered = false;