superbased 1.6.4 → 2.0.1

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 +230 -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 +1349 -219
  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 +1349 -219
  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 +66 -8
  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 +1566 -46
  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
@@ -42,6 +42,7 @@ exports.startMcpServer = startMcpServer;
42
42
  exports.createMcpHttpHandler = createMcpHttpHandler;
43
43
  const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
44
44
  const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
45
+ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
45
46
  const zod_1 = require("zod");
46
47
  const api_client_1 = require("./api-client");
47
48
  const fs = __importStar(require("fs"));
@@ -87,6 +88,156 @@ function parseArgs() {
87
88
  function formatResponse(data) {
88
89
  return JSON.stringify(data, null, 2);
89
90
  }
91
+ // Build MCP content array for write-action tools (click / type / hotkey /
92
+ // scroll). When the response carries an observation, emits:
93
+ // 1. a text block with the response JSON — imageBase64 stripped to keep
94
+ // the text block tiny (the base64 shows up in the image block below).
95
+ // 2. an image block (MCP image content) with the PNG bytes.
96
+ // 3. the text block ALSO carries `textElements` when returnObservation=
97
+ // 'full' — agents can grep / filter without waiting on a follow-up
98
+ // ui_dump call.
99
+ // When no observation present (returnObservation='none' or upstream error),
100
+ // emits just the text block.
101
+ function buildWriteActionContent(data) {
102
+ const obs = data.observation;
103
+ // Strip imageBase64 from the text-block projection — carried separately
104
+ // as an image content block to keep the text output readable.
105
+ const textProjection = {
106
+ ok: data.ok,
107
+ error: data.error,
108
+ method: data.method,
109
+ confidence: data.confidence,
110
+ hint: data.hint,
111
+ details: data.details,
112
+ observation: obs
113
+ ? {
114
+ width: obs.width,
115
+ height: obs.height,
116
+ mimeType: obs.mimeType,
117
+ backgroundMode: obs.backgroundMode,
118
+ dpiScale: obs.dpiScale,
119
+ textElementCount: obs.textElements?.length ?? 0,
120
+ textElements: obs.textElements,
121
+ }
122
+ : undefined,
123
+ };
124
+ const content = [
125
+ { type: 'text', text: formatResponse(textProjection) },
126
+ ];
127
+ if (obs?.imageBase64) {
128
+ content.push({ type: 'image', data: obs.imageBase64, mimeType: obs.mimeType });
129
+ }
130
+ return content;
131
+ }
132
+ /**
133
+ * Phase 5.2 — generate optional `next_steps` suggestions based on tool +
134
+ * context. Agents can ignore the field entirely; populating it nudges
135
+ * common next actions for workflows where agents consistently forget the
136
+ * follow-up (e.g., the stop → describe_frames → narrate chain on recording).
137
+ *
138
+ * Keep suggestions short and executable — each entry should be a literal
139
+ * tool-call-looking string the agent can paste or adapt. No narrative
140
+ * prose, no alternatives with "or": that belongs in the tool descriptions.
141
+ */
142
+ /**
143
+ * Phase 5.3 — accept capture references as either an integer id or as the
144
+ * URI form `superbased://capture/{id}`. The URI form lines up with the MCP
145
+ * resource-URI convention (see `superbased://captures/recent`) and lets
146
+ * agents that deal primarily in resource URIs pass them through to capture-
147
+ * accepting tools without a manual integer extract step.
148
+ *
149
+ * Accepts:
150
+ * - number (e.g. 42)
151
+ * - "42"
152
+ * - "superbased://capture/42"
153
+ * - "superbased://captures/42" (plural — lenient)
154
+ *
155
+ * Returns the numeric id, or null if the input can't be parsed as a
156
+ * non-negative integer. Callers treat null as "no reference provided"
157
+ * (consistent with the optional-captureId semantics).
158
+ */
159
+ function parseCaptureRef(ref) {
160
+ if (ref === undefined || ref === null)
161
+ return null;
162
+ if (typeof ref === 'number') {
163
+ return Number.isFinite(ref) && ref >= 0 ? Math.floor(ref) : null;
164
+ }
165
+ if (typeof ref !== 'string')
166
+ return null;
167
+ const trimmed = ref.trim();
168
+ if (trimmed.length === 0)
169
+ return null;
170
+ const uriMatch = trimmed.match(/^superbased:\/\/captures?\/(\d+)$/i);
171
+ if (uriMatch) {
172
+ const n = Number(uriMatch[1]);
173
+ return Number.isFinite(n) && n >= 0 ? n : null;
174
+ }
175
+ if (/^\d+$/.test(trimmed)) {
176
+ const n = Number(trimmed);
177
+ return Number.isFinite(n) && n >= 0 ? n : null;
178
+ }
179
+ return null;
180
+ }
181
+ /** Zod schema fragment reused across tools that accept a capture reference. */
182
+ const captureRefSchema = zod_1.z.union([zod_1.z.number(), zod_1.z.string()]);
183
+ const captureRefDescription = 'Capture reference: numeric id (42), numeric string ("42"), or MCP URI form ("superbased://capture/42").';
184
+ /**
185
+ * Zod schema fragment for returnObservation. String form is the v1 shape.
186
+ * Object form (6.3 / 6.4) adds `settleMs` (wait N ms before capturing so the
187
+ * UI can repaint post-action) + `region` (subrect in virtual-screen coords —
188
+ * narrow the capture to just what matters, smaller bytes + faster OCR).
189
+ */
190
+ const returnObservationSchema = zod_1.z.union([
191
+ zod_1.z.enum(['none', 'screenshot', 'full']),
192
+ zod_1.z.object({
193
+ mode: zod_1.z.enum(['screenshot', 'full']),
194
+ settleMs: zod_1.z.number().min(0).optional(),
195
+ region: zod_1.z.object({
196
+ x: zod_1.z.number(),
197
+ y: zod_1.z.number(),
198
+ width: zod_1.z.number().min(1),
199
+ height: zod_1.z.number().min(1),
200
+ }).optional(),
201
+ }),
202
+ ]);
203
+ function nextStepsForCapture(captureId) {
204
+ if (captureId === null || captureId === undefined || !Number.isFinite(captureId))
205
+ return [];
206
+ return [
207
+ `superbased_ai captureId=${captureId} instruction="describe this screen"`,
208
+ `superbased_ocr captureId=${captureId}`,
209
+ `superbased_annotate captureId=${captureId} annotations=[...]`,
210
+ ];
211
+ }
212
+ function nextStepsForRecordingStart(sessionId, mode) {
213
+ if (!sessionId)
214
+ return [];
215
+ const steps = [`superbased_recording action=status`];
216
+ if (mode === 'monitor') {
217
+ steps.push(`superbased_recording action=get_analysis sessionId="${sessionId}"`);
218
+ }
219
+ steps.push(`superbased_recording action=stop`);
220
+ return steps;
221
+ }
222
+ function nextStepsForRecordingStop(sessionId) {
223
+ if (!sessionId)
224
+ return [];
225
+ return [
226
+ `superbased_describe_frames sessionId="${sessionId}"`,
227
+ `superbased_narrate sessionId="${sessionId}" descriptions=[...]`,
228
+ `superbased_sessions action=frames sessionId="${sessionId}"`,
229
+ ];
230
+ }
231
+ function nextStepsForDictate(cleanup, hadText) {
232
+ if (!hadText)
233
+ return [];
234
+ // Most of the time the agent uses the transcript directly and has no
235
+ // "next tool call" — only surface a follow-up when it's genuinely useful.
236
+ if (cleanup) {
237
+ return [`superbased_dictation_history limit=5`];
238
+ }
239
+ return [];
240
+ }
90
241
  /**
91
242
  * Register all MCP tools and resources on a McpServer instance.
92
243
  * Shared between stdio transport (CLI) and HTTP transport (API server).
@@ -156,17 +307,20 @@ function registerMcpTools(server, client, projectDir) {
156
307
  }
157
308
  const res = await client.captureRegion(x, y, width, height, dir);
158
309
  const { imageBase64: _img, ...summary } = res.data;
159
- return { content: [{ type: 'text', text: formatResponse({ ...summary, imageSizeBytes: res.data.imageBase64?.length || 0 }) }] };
310
+ const payload = { ...summary, imageSizeBytes: res.data.imageBase64?.length || 0, next_steps: nextStepsForCapture(summary.captureId) };
311
+ return { content: [{ type: 'text', text: formatResponse(payload) }] };
160
312
  }
161
313
  case 'active_window': {
162
314
  const res = await client.captureActiveWindow();
163
- return { content: [{ type: 'text', text: formatResponse({ windowInfo: res.data.windowInfo, imageSizeBytes: res.data.imageBase64?.length || 0 }) }] };
315
+ const payload = { windowInfo: res.data.windowInfo, imageSizeBytes: res.data.imageBase64?.length || 0, next_steps: nextStepsForCapture(res.data.captureId) };
316
+ return { content: [{ type: 'text', text: formatResponse(payload) }] };
164
317
  }
165
318
  case 'fullscreen':
166
319
  default: {
167
320
  const res = await client.captureFullscreen(dir);
168
321
  const { imageBase64: _img, ...summary } = res.data;
169
- return { content: [{ type: 'text', text: formatResponse({ ...summary, imageSizeBytes: res.data.imageBase64?.length || 0 }) }] };
322
+ const payload = { ...summary, imageSizeBytes: res.data.imageBase64?.length || 0, next_steps: nextStepsForCapture(summary.captureId) };
323
+ return { content: [{ type: 'text', text: formatResponse(payload) }] };
170
324
  }
171
325
  }
172
326
  }
@@ -178,16 +332,23 @@ function registerMcpTools(server, client, projectDir) {
178
332
  // ── Tool: superbased_ai ──
179
333
  server.tool('superbased_ai', 'Send a screenshot to AI for analysis. Auto-captures the screen if no image is provided. Use when you need AI to analyze, explain, or extract information from what is on the user\'s screen.', {
180
334
  instruction: zod_1.z.string().describe('What to do with the image. Slash commands: /extract, /summarize, /code, /explain, /translate, /table, /edit, /reformat. Or free text.'),
181
- captureId: zod_1.z.number().optional().describe('ID of an existing capture from the gallery'),
335
+ captureId: captureRefSchema.optional().describe(`ID of an existing capture from the gallery. ${captureRefDescription}`),
182
336
  screenshotPath: zod_1.z.string().optional().describe('Path to a screenshot file on disk'),
183
337
  projectDir: zod_1.z.string().optional().describe('Project directory for auto-captures. Defaults to CWD.'),
184
- }, async ({ instruction, captureId, screenshotPath, projectDir: pd }) => {
338
+ provider: zod_1.z.string().optional().describe('AI provider override (Phase 6.3). "auto" (default) respects settings. "cloud" forces the backend proxy. "ollama" routes to the local daemon. "ollama:<model>" is a convenience shorthand for provider="ollama" + model="<model>".'),
339
+ model: zod_1.z.string().optional().describe('Per-call Ollama model tag (e.g. "llama3.2-vision:11b"). Only valid when provider is a concrete value ("ollama" or "cloud"); passing model with provider="auto" returns a structured validation error. Empty with provider="ollama" falls back to settings (ollama.model.vision for image calls, ollama.model.chat otherwise).'),
340
+ forceVision: zod_1.z.boolean().optional().describe('Bypass the vision-capable model pre-check (M4 escape hatch). Use when you know a model is vision-capable but it is newer than SuperBased\'s allowlist. Default false.'),
341
+ }, async ({ instruction, captureId, screenshotPath, projectDir: pd, provider, model, forceVision }) => {
185
342
  try {
343
+ const captureIdNum = parseCaptureRef(captureId);
186
344
  const res = await client.processAI({
187
345
  instruction,
188
- captureId,
346
+ captureId: captureIdNum ?? undefined,
189
347
  screenshotPath,
190
348
  projectDir: pd || projectDir,
349
+ provider,
350
+ model,
351
+ forceVision,
191
352
  });
192
353
  if (res.status >= 400) {
193
354
  return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: true };
@@ -202,21 +363,22 @@ function registerMcpTools(server, client, projectDir) {
202
363
  // ── Tool: superbased_ocr ──
203
364
  server.tool('superbased_ocr', 'Extract text from a screenshot using local OCR (Tesseract). Use when you need to read text from an image without sending it to an external AI.', {
204
365
  screenshotPath: zod_1.z.string().optional().describe('Path to a screenshot file on disk'),
205
- captureId: zod_1.z.number().optional().describe('ID of an existing capture — loads the image from gallery'),
366
+ captureId: captureRefSchema.optional().describe(`ID of an existing capture — loads the image from gallery. ${captureRefDescription}`),
206
367
  }, async ({ screenshotPath, captureId }) => {
207
368
  try {
369
+ const captureIdNum = parseCaptureRef(captureId);
208
370
  let params = {};
209
371
  if (screenshotPath) {
210
372
  params = { screenshotPath };
211
373
  }
212
- else if (captureId) {
213
- const captureRes = await client.getCapture(captureId);
374
+ else if (captureIdNum !== null) {
375
+ const captureRes = await client.getCapture(captureIdNum);
214
376
  const capture = captureRes.data.capture;
215
377
  if (capture?.screenshot_path) {
216
378
  params = { screenshotPath: capture.screenshot_path };
217
379
  }
218
380
  else {
219
- return { content: [{ type: 'text', text: `Capture ${captureId} not found or has no image` }], isError: true };
381
+ return { content: [{ type: 'text', text: `Capture ${captureIdNum} not found or has no image` }], isError: true };
220
382
  }
221
383
  }
222
384
  else {
@@ -233,17 +395,18 @@ function registerMcpTools(server, client, projectDir) {
233
395
  // ── Tool: superbased_gallery ──
234
396
  server.tool('superbased_gallery', 'Browse and search past screenshots. Use when you need to find a previously captured image or check capture history.', {
235
397
  action: zod_1.z.enum(['list', 'get', 'search', 'stats']).describe('list=recent captures, get=specific capture, search=full-text, stats=statistics'),
236
- captureId: zod_1.z.number().optional().describe('Capture ID (for get action)'),
398
+ captureId: captureRefSchema.optional().describe(`Capture ID (for get action). ${captureRefDescription}`),
237
399
  query: zod_1.z.string().optional().describe('Search query (for search action)'),
238
400
  limit: zod_1.z.number().optional().describe('Max results to return (default 20)'),
239
401
  }, async ({ action, captureId, query, limit }) => {
240
402
  try {
403
+ const captureIdNum = parseCaptureRef(captureId);
241
404
  switch (action) {
242
405
  case 'get': {
243
- if (!captureId) {
406
+ if (captureIdNum === null) {
244
407
  return { content: [{ type: 'text', text: 'captureId is required for get action' }], isError: true };
245
408
  }
246
- const res = await client.getCapture(captureId);
409
+ const res = await client.getCapture(captureIdNum);
247
410
  return { content: [{ type: 'text', text: formatResponse(res.data) }] };
248
411
  }
249
412
  case 'search': {
@@ -271,18 +434,22 @@ function registerMcpTools(server, client, projectDir) {
271
434
  });
272
435
  // ── Tool: superbased_gallery_update ──
273
436
  server.tool('superbased_gallery_update', 'Update tags or notes on a saved capture.', {
274
- captureId: zod_1.z.number().describe('Capture ID to update'),
437
+ captureId: captureRefSchema.describe(`Capture ID to update. ${captureRefDescription}`),
275
438
  tags: zod_1.z.string().optional().describe('Comma-separated tags (replaces existing tags)'),
276
439
  notes: zod_1.z.string().optional().describe('Notes text (replaces existing notes)'),
277
440
  }, async ({ captureId, tags, notes }) => {
278
441
  try {
442
+ const captureIdNum = parseCaptureRef(captureId);
443
+ if (captureIdNum === null) {
444
+ return { content: [{ type: 'text', text: `Invalid captureId: ${String(captureId)}` }], isError: true };
445
+ }
279
446
  const results = [];
280
447
  if (tags !== undefined) {
281
- await client.updateTags(captureId, tags);
448
+ await client.updateTags(captureIdNum, tags);
282
449
  results.push(`Tags updated to: ${tags}`);
283
450
  }
284
451
  if (notes !== undefined) {
285
- await client.updateNotes(captureId, notes);
452
+ await client.updateNotes(captureIdNum, notes);
286
453
  results.push(`Notes updated`);
287
454
  }
288
455
  if (results.length === 0) {
@@ -417,12 +584,14 @@ function registerMcpTools(server, client, projectDir) {
417
584
  if ((mode === 'monitor' || res.data?.mode === 'monitor') && res.data?.sessionId) {
418
585
  startMonitorPoller(res.data.sessionId);
419
586
  }
420
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
587
+ const payload = { ...res.data, next_steps: nextStepsForRecordingStart(res.data.sessionId, mode || res.data.mode) };
588
+ return { content: [{ type: 'text', text: formatResponse(payload) }] };
421
589
  }
422
590
  case 'stop': {
423
591
  stopMonitorPoller();
424
592
  const res = await client.recordingStop();
425
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
593
+ const payload = { ...res.data, next_steps: nextStepsForRecordingStop(res.data.sessionId) };
594
+ return { content: [{ type: 'text', text: formatResponse(payload) }] };
426
595
  }
427
596
  case 'pause': {
428
597
  const res = await client.recordingPause();
@@ -523,11 +692,142 @@ function registerMcpTools(server, client, projectDir) {
523
692
  return { content: [{ type: 'text', text: msg }], isError: true };
524
693
  }
525
694
  });
526
- // ── Tool: superbased_capture_image ──
527
- server.tool('superbased_capture_image', 'Capture the screen and return the image inline so you can SEE it. This is the primary tool for looking at the user\'s screen, checking UI state, reading what\'s visible, or verifying visual changes. Use this whenever you need to see what the user sees.', {
695
+ // ── Tool: superbased_screenshot (Phase 8 — single preferred screenshot entry point) ──
696
+ //
697
+ // Why a dedicated tool when superbased_capture_image already supports
698
+ // `window=`?
699
+ //
700
+ // Observed agent behaviour: faced with a capture-a-window request,
701
+ // agents often chain `superbased_focus_window` → (permission prompt) →
702
+ // `superbased_capture_image` → (second permission prompt). Each
703
+ // permission prompt forces the user to click Approve in the agent
704
+ // window, which steals focus back to the agent. The second prompt
705
+ // comes AFTER focus_window already switched the foreground to the
706
+ // target — so clicking Approve defeats the whole point, and the
707
+ // subsequent capture fires against the agent window, not the target.
708
+ //
709
+ // This tool exists to break that pattern. Single call, minimal
710
+ // signature, registered in CORE_TOOLS so it's always the first option
711
+ // an agent sees. Server-side delegates to the same `captureFullscreenImage`
712
+ // path as `superbased_capture_image`; all the activate-then-capture-
713
+ // then-restore plumbing lives there.
714
+ server.tool('superbased_screenshot', [
715
+ 'Take a screenshot. Returns the image inline — for visual inspection by the user / agent.',
716
+ '',
717
+ 'IMPORTANT — IF YOU NEED CLICK COORDINATES, DO NOT USE THIS TOOL. Use superbased_ui_dump instead — it returns the same screenshot PLUS every visible text element with ready-to-click screen coordinates in one call. Eyeballing pixel coords off a screenshot is unreliable (the image may be downscaled per `resolution=`, DPI scaling may differ, etc.) and costs an extra click-then-verify round-trip when the first estimate misses.',
718
+ '',
719
+ 'Use superbased_screenshot ONLY when you genuinely need the raw image (visual inspection, comparing frames, reporting a bug to the user). Use superbased_ui_dump when you will act on what you see.',
720
+ '',
721
+ 'Targeting modes (most to least specific — prefer more specific when possible):',
722
+ ' • hwnd="3149370" — direct Windows handle from superbased_window_list. Unambiguous.',
723
+ ' • processName="electron" — match by .exe. Combine with `target=` to disambiguate same-process windows.',
724
+ ' • target="SuperBased" — case-insensitive title match with scored best-match and ambiguous-match refusal.',
725
+ ' • (none) — fullscreen.',
726
+ '',
727
+ 'Window-specific captures run server-side in one call: activate → capture → restore focus. SINGLE permission approval.',
728
+ '',
729
+ 'NEVER chain superbased_focus_window before this. Each MCP tool call requires a permission approval in the agent UI, and clicking Approve steals focus back to the agent — which defeats the first focus change and captures the agent window instead of the target. Always express the whole intent to this tool.',
730
+ '',
731
+ 'If target/processName is ambiguous, this tool REFUSES and returns `alternatives[]` — then retry with hwnd from that list.',
732
+ '',
733
+ 'Fast path: on Windows, pass `background: true` AND a concrete window target (hwnd or a unique target/processName) to skip the activation+restore dance entirely. Uses PrintWindow(PW_RENDERFULLCONTENT) — about 5x faster, no focus flicker, works even if the target is occluded by another window. Falls back to the activation path if the background capture comes back empty (some GPU-composited surfaces render outside the window DC). RECOMMENDED for iterative screenshot workflows where the user is watching something else.',
734
+ '',
735
+ 'The response includes `diagnostic.broughtToFront`: if false, the OS silently refused to switch focus (topmost window, UIA lock, etc.) and the screenshot likely shows what was already foreground. Always check this flag before trusting the image. Timing metrics (`timings.*Ms`) are returned so you can see which step is the bottleneck.',
736
+ ].join('\n'), {
737
+ target: zod_1.z.string().optional().describe('Window title substring (case-insensitive). Scored matcher — returns alternatives on ambiguous matches.'),
738
+ processName: zod_1.z.string().optional().describe('Process executable name (e.g. "electron", "notepad"). Use with `target` to disambiguate same-process windows.'),
739
+ hwnd: zod_1.z.string().optional().describe('Windows window handle from superbased_window_list. Unambiguous; bypasses scoring.'),
740
+ background: zod_1.z.boolean().default(false).describe('Windows only: capture without changing foreground. Uses PrintWindow(PW_RENDERFULLCONTENT) to grab the target window\'s pixels directly. ~5x faster and does not flicker focus. Falls back to the activate-and-capture path if the result is empty (GPU-composited surfaces like fullscreen video, some games). Requires hwnd or a successfully-resolved target window.'),
741
+ resolution: zod_1.z.enum(['full', 'high', 'half', 'quarter', 'thumbnail']).default('half').describe('Image resolution (half saves ~4x tokens vs full).'),
742
+ }, async ({ target, processName, hwnd, background, resolution }) => {
743
+ try {
744
+ const res = await client.captureFullscreenImage({
745
+ resolution,
746
+ window: target,
747
+ processName,
748
+ hwnd,
749
+ background,
750
+ projectDir,
751
+ });
752
+ const d = res.data;
753
+ const targetDescr = hwnd ? `hwnd=${hwnd}` : processName && target ? `${processName}/"${target}"` : processName ? processName : target ? `"${target}"` : 'fullscreen';
754
+ const lines = [`Screenshot of ${targetDescr} (#${d.captureId}, ${d.width}x${d.height})`];
755
+ if (d.matchedWindow) {
756
+ lines.push(`Matched: ${d.matchedWindow.title} [pid: ${d.matchedWindow.processName ?? '?'}, hwnd: ${d.matchedWindow.hwnd ?? '?'}, score: ${d.matchedWindow.score} — ${d.matchedWindow.scoreReason}]`);
757
+ }
758
+ if (d.diagnostic) {
759
+ if (d.diagnostic.backgroundMode) {
760
+ // Fast path: no focus change happened at all.
761
+ lines.push('✓ Background capture via PrintWindow (no focus change)');
762
+ }
763
+ else {
764
+ const bf = d.diagnostic.broughtToFront;
765
+ const note = bf === false
766
+ ? '⚠ OS refused to bring target to front (broughtToFront:false). Screenshot likely shows the original foreground window, NOT the target. Retry with hwnd= for reliability, or investigate topmost/overlay flags on the covering window.'
767
+ : bf === true
768
+ ? '✓ Activation verified'
769
+ : 'Activation status unknown (non-Windows platform)';
770
+ lines.push(note);
771
+ if (d.diagnostic.foregroundAfterActivate && d.matchedWindow?.hwnd && d.diagnostic.foregroundAfterActivate !== d.matchedWindow.hwnd) {
772
+ lines.push(`Foreground after activate: hwnd=${d.diagnostic.foregroundAfterActivate} (expected ${d.matchedWindow.hwnd})`);
773
+ }
774
+ if (d.diagnostic.activationAttempts && d.diagnostic.activationAttempts > 1) {
775
+ lines.push(`Activation attempts: ${d.diagnostic.activationAttempts}`);
776
+ }
777
+ if (d.diagnostic.restoredFocus === false) {
778
+ lines.push(`⚠ Focus restore did not verify after ${d.diagnostic.restoreAttempts ?? '?'} attempts (final foreground=${d.diagnostic.foregroundAfterRestore ?? 'unknown'}). The agent window may still be behind the target — user may need to Alt-Tab back manually.`);
779
+ }
780
+ else if (d.diagnostic.restoredFocus === true) {
781
+ lines.push('✓ Focus restored to original window');
782
+ }
783
+ }
784
+ }
785
+ if (d.timings) {
786
+ // Render as cumulative-from-start markers so the caller can
787
+ // see which step is the slow one. Values are ms from
788
+ // request-start; subtract consecutive entries for step
789
+ // durations.
790
+ const order = ['resolveMs', 'snapshotMs', 'activateMs', 'paintMs', 'captureMs', 'restoreMs', 'totalMs'];
791
+ const present = order.filter((k) => d.timings && k in d.timings).map((k) => `${k.replace(/Ms$/, '')}=${d.timings?.[k]}ms`);
792
+ if (present.length > 0)
793
+ lines.push(`Timings: ${present.join(' · ')}`);
794
+ }
795
+ if (d.alternatives && d.alternatives.length > 0) {
796
+ lines.push(`Other candidates (not picked): ${d.alternatives.map((a) => `${a.title} [hwnd:${a.hwnd ?? '?'}, score:${a.score}]`).join('; ')}`);
797
+ }
798
+ // Coordinate-space warning: when resolution is not 'full', the returned
799
+ // image is downscaled. Pixel coords measured off the image do NOT map
800
+ // to screen pixels (which is what superbased_click takes). Agents that
801
+ // need click coords should use superbased_ui_dump instead.
802
+ if (resolution && resolution !== 'full') {
803
+ lines.push(`⚠ Image is downscaled (resolution=${resolution}). Pixel coords off this image DO NOT match screen coords. For clickable coordinates, use superbased_ui_dump (returns screen-space coords + this same screenshot in one call).`);
804
+ }
805
+ const content = [
806
+ { type: 'text', text: lines.join('\n') },
807
+ ];
808
+ if (d.imageBase64) {
809
+ content.push({ type: 'image', data: d.imageBase64, mimeType: ('mimeType' in d ? d.mimeType : null) || 'image/png' });
810
+ }
811
+ return { content };
812
+ }
813
+ catch (err) {
814
+ // Ambiguous / no_match / hwnd_not_found errors arrive here with
815
+ // the structured body in err.message; forward to the agent so
816
+ // it can retry with a more specific target.
817
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
818
+ }
819
+ });
820
+ // ── Tool: superbased_capture_image (advanced — region + explicit mode) ──
821
+ //
822
+ // Prefer `superbased_screenshot` for the common case. This tool stays
823
+ // for the advanced surface (region coordinates, explicit fullscreen
824
+ // vs active-window modes). Still supports `window=` — but most agents
825
+ // should be routed to superbased_screenshot via that tool's more
826
+ // prominent advertisement (it's in CORE_TOOLS).
827
+ server.tool('superbased_capture_image', 'Advanced screenshot variant with region + mode control. For the common case of "take a screenshot" or "take a screenshot of X window", USE `superbased_screenshot` INSTEAD — it is simpler, has the same window auto-focus behaviour, and is less likely to be chained incorrectly. Use this tool only when you need region coordinates or explicit mode control.', {
528
828
  mode: zod_1.z.enum(['fullscreen', 'region', 'active_window']).default('fullscreen').describe('Capture mode'),
529
829
  resolution: zod_1.z.enum(['full', 'high', 'half', 'quarter', 'thumbnail']).default('half').describe('Image resolution (half saves ~4x tokens vs full)'),
530
- window: zod_1.z.string().optional().describe('Capture a specific window by name substring (use superbased_window_list to find names). Activates the window, captures, then restores focus. Works even on minimized windows.'),
830
+ window: zod_1.z.string().optional().describe('Target window name substring. Triggers the one-shot focus→capture→restore-focus flow. Use superbased_window_list first if you need to see available names; after that, this parameter is all you need.'),
531
831
  x: zod_1.z.number().optional(), y: zod_1.z.number().optional(),
532
832
  width: zod_1.z.number().optional(), height: zod_1.z.number().optional(),
533
833
  }, async ({ mode, resolution, window: windowName, x, y, width, height }) => {
@@ -554,13 +854,17 @@ function registerMcpTools(server, client, projectDir) {
554
854
  });
555
855
  // ── Tool: superbased_gallery_image ──
556
856
  server.tool('superbased_gallery_image', 'Retrieve a previously saved capture image from the gallery so you can see it.', {
557
- captureId: zod_1.z.number().describe('Gallery capture ID'),
857
+ captureId: captureRefSchema.describe(`Gallery capture ID. ${captureRefDescription}`),
558
858
  resolution: zod_1.z.enum(['full', 'high', 'half', 'quarter', 'thumbnail']).default('half').describe('Image resolution'),
559
859
  }, async ({ captureId, resolution }) => {
560
860
  try {
561
- const res = await client.getCaptureImage(captureId, resolution);
861
+ const captureIdNum = parseCaptureRef(captureId);
862
+ if (captureIdNum === null) {
863
+ return { content: [{ type: 'text', text: `Invalid captureId: ${String(captureId)}` }], isError: true };
864
+ }
865
+ const res = await client.getCaptureImage(captureIdNum, resolution);
562
866
  const content = [
563
- { type: 'text', text: `Gallery capture #${captureId}` },
867
+ { type: 'text', text: `Gallery capture #${captureIdNum}` },
564
868
  ];
565
869
  if (res.data.imageBase64) {
566
870
  content.push({ type: 'image', data: res.data.imageBase64, mimeType: res.data.mimeType || 'image/png' });
@@ -585,7 +889,7 @@ function registerMcpTools(server, client, projectDir) {
585
889
  }
586
890
  });
587
891
  // ── Tool: superbased_health ──
588
- server.tool('superbased_health', 'Check if SuperBased is running, its version, uptime, and available features.', {}, async () => {
892
+ server.tool('superbased_health', 'Check if SuperBased is running, its version, uptime, and available features. Also surfaces `capabilities` (GUI automation feature matrix — what works on the current OS), `ollama` (local Ollama detection), and — when `guiAutomation.telemetryOptIn` is on — `telemetry` (in-process §6.11 counters: approvalsPerIntent, sequenceCompletionRateByStepCount, activationFailedRatePerTargetClass, targetHostileRatePerProcess, dryRunToExecuteRate — all derived from the audit log in-process, no external shipping).', {}, async () => {
589
893
  try {
590
894
  const res = await client.health();
591
895
  return { content: [{ type: 'text', text: formatResponse(res.data) }] };
@@ -596,13 +900,14 @@ function registerMcpTools(server, client, projectDir) {
596
900
  });
597
901
  // ── Tool: superbased_redact ──
598
902
  server.tool('superbased_redact', 'Auto-redact secrets (API keys, tokens) and PII (emails, phones) from a screenshot before sharing.', {
599
- captureId: zod_1.z.number().optional().describe('Capture to redact'),
903
+ captureId: captureRefSchema.optional().describe(`Capture to redact. ${captureRefDescription}`),
600
904
  screenshotPath: zod_1.z.string().optional().describe('Path to image file'),
601
905
  secrets: zod_1.z.boolean().default(true).describe('Redact API keys, tokens, passwords'),
602
906
  pii: zod_1.z.boolean().default(false).describe('Redact emails, phone numbers, names'),
603
907
  }, async ({ captureId, screenshotPath, secrets, pii }) => {
604
908
  try {
605
- const res = await client.redact({ captureId, screenshotPath, secrets, pii });
909
+ const captureIdNum = parseCaptureRef(captureId);
910
+ const res = await client.redact({ captureId: captureIdNum ?? undefined, screenshotPath, secrets, pii });
606
911
  const content = [
607
912
  { type: 'text', text: `Redacted ${res.data.regionsFound} sensitive region(s)` },
608
913
  ];
@@ -638,14 +943,20 @@ function registerMcpTools(server, client, projectDir) {
638
943
  }
639
944
  });
640
945
  // ── Tool: superbased_transcribe ──
641
- server.tool('superbased_transcribe', 'Transcribe an audio file to text using Whisper (raw, no cleanup). Use superbased_dictate for cleanup + mic support.', {
946
+ server.tool('superbased_transcribe', 'Transcribe an audio file to text. engine: "auto" (default — signed-in → cloud, signed-out + sherpa model downloaded → sherpa, else structured error) | "cloud" (Whisper via backend; 401 if signed out) | "sherpa" (offline; model_required error if not downloaded, binary_load_failed if sherpa-onnx-node unavailable) | "native" (Phase 4c/4d — returns unavailable today). Check `superbased_stt_status` before requesting engine="sherpa" to avoid a model-required round-trip. Structured errors ({ok:false, error, engine, model?, consent_command?, ...}) are returned via isError:true so agents can branch.', {
642
947
  audioPath: zod_1.z.string().optional().describe('Path to audio file (wav, mp3, webm, etc.)'),
643
948
  audioBase64: zod_1.z.string().optional().describe('Base64-encoded audio data'),
644
949
  language: zod_1.z.string().optional().describe('BCP 47 language code (e.g. en-US)'),
645
- }, async ({ audioPath, audioBase64, language }) => {
950
+ engine: zod_1.z.enum(['auto', 'native', 'sherpa', 'cloud']).optional().default('auto').describe('Which STT engine to use. Default "auto" picks the best available engine for the current sign-in / model state.'),
951
+ }, async ({ audioPath, audioBase64, language, engine }) => {
646
952
  try {
647
- const res = await client.transcribe({ audioPath, audioBase64, language });
648
- return { content: [{ type: 'text', text: res.data.text }] };
953
+ const res = await client.transcribe({ audioPath, audioBase64, language, engine });
954
+ const body = res.data;
955
+ if (body.ok === false) {
956
+ // Structured engine error — surface the full JSON so agents can branch.
957
+ return { content: [{ type: 'text', text: formatResponse(body) }], isError: true };
958
+ }
959
+ return { content: [{ type: 'text', text: body.text ?? '' }] };
649
960
  }
650
961
  catch (err) {
651
962
  return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
@@ -662,7 +973,7 @@ function registerMcpTools(server, client, projectDir) {
662
973
  }
663
974
  });
664
975
  // ── Tool: superbased_window_list ──
665
- server.tool('superbased_window_list', 'List all visible windows with names, active status, and minimized state. Use window names with superbased_capture_image to target specific windows.', {}, async () => {
976
+ server.tool('superbased_window_list', 'List all visible windows with title, hwnd, processName, minimized state, and active status. Use processName="<exe>" with type/click/hotkey/scroll/focus_window for highest-precision targeting (more reliable than window= title substring).', {}, async () => {
666
977
  try {
667
978
  const res = await client.listWindows();
668
979
  return { content: [{ type: 'text', text: formatResponse(res.data) }] };
@@ -687,9 +998,15 @@ function registerMcpTools(server, client, projectDir) {
687
998
  server.tool('superbased_describe_frames', 'AI-describe each frame in a recording session (UI state, visible elements, changes).', {
688
999
  sessionId: zod_1.z.string().describe('Recording session ID'),
689
1000
  limit: zod_1.z.number().default(20).describe('Max frames to describe'),
690
- }, async ({ sessionId, limit }) => {
1001
+ provider: zod_1.z.string().optional().describe('AI provider override (Phase 6.3). "auto" (default), "cloud", "ollama", or "ollama:<model>". Each frame is a vision call; settings field is ollama.model.vision.'),
1002
+ model: zod_1.z.string().optional().describe('Per-call Ollama model tag. Only valid when provider is concrete. Must be vision-capable; pre-check hits Ollama /api/show then falls back to a static allowlist.'),
1003
+ forceVision: zod_1.z.boolean().optional().describe('Bypass the vision-capable model pre-check. Default false.'),
1004
+ }, async ({ sessionId, limit, provider, model, forceVision }) => {
691
1005
  try {
692
- const res = await client.describeFrames(sessionId, limit);
1006
+ const res = await client.describeFrames(sessionId, limit, { provider, model, forceVision });
1007
+ if (res.status >= 400) {
1008
+ return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: true };
1009
+ }
693
1010
  return { content: [{ type: 'text', text: formatResponse(res.data) }] };
694
1011
  }
695
1012
  catch (err) {
@@ -703,9 +1020,14 @@ function registerMcpTools(server, client, projectDir) {
703
1020
  frameNumber: zod_1.z.number(),
704
1021
  description: zod_1.z.string(),
705
1022
  })).describe('Frame descriptions (from superbased_describe_frames)'),
706
- }, async ({ sessionId, descriptions }) => {
1023
+ provider: zod_1.z.string().optional().describe('AI provider override (Phase 6.3). "auto" (default), "cloud", "ollama", or "ollama:<model>". Text-only; settings field is ollama.model.chat.'),
1024
+ model: zod_1.z.string().optional().describe('Per-call Ollama model tag. Only valid when provider is concrete.'),
1025
+ }, async ({ sessionId, descriptions, provider, model }) => {
707
1026
  try {
708
- const res = await client.narrate(sessionId, descriptions);
1027
+ const res = await client.narrate(sessionId, descriptions, { provider, model });
1028
+ if (res.status >= 400) {
1029
+ return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: true };
1030
+ }
709
1031
  return { content: [{ type: 'text', text: res.data.narration }] };
710
1032
  }
711
1033
  catch (err) {
@@ -727,22 +1049,168 @@ function registerMcpTools(server, client, projectDir) {
727
1049
  }
728
1050
  });
729
1051
  // ── Tool: superbased_dictate ──
730
- server.tool('superbased_dictate', 'Transcribe audio with text cleanup (filler removal, deduplication). Supports file input, base64, or live microphone recording.', {
1052
+ server.tool('superbased_dictate', 'Transcribe audio with engine-agnostic cleanup (filler removal, deduplication). Supports file input, base64, or live microphone recording. engine: "auto" (default) | "cloud" | "sherpa" | "native" — see superbased_transcribe description for the structured errors each engine can return. The `cleanup` post-processing is identical across all engines; only the transcription source differs.', {
731
1053
  audioPath: zod_1.z.string().optional().describe('Path to audio file to transcribe with text cleanup'),
732
1054
  audioBase64: zod_1.z.string().optional().describe('Base64-encoded audio data'),
733
1055
  mic: zod_1.z.boolean().optional().describe('Record from microphone (requires ffmpeg). Set to true to capture live audio.'),
734
1056
  duration: zod_1.z.number().optional().describe('Mic recording duration in seconds (default 10)'),
735
1057
  language: zod_1.z.string().optional().describe('BCP 47 language code'),
736
1058
  cleanup: zod_1.z.boolean().default(true).describe('Apply filler word removal and deduplication'),
737
- }, async ({ audioPath, audioBase64, mic, duration, language, cleanup }) => {
1059
+ engine: zod_1.z.enum(['auto', 'native', 'sherpa', 'cloud']).optional().default('auto').describe('Which STT engine to use. Default "auto" picks the best available engine. Offline dictation: engine="sherpa" (requires `superbased stt download zipformer-en-20M`). Force cloud: engine="cloud" (requires sign-in).'),
1060
+ }, async ({ audioPath, audioBase64, mic, duration, language, cleanup, engine }) => {
738
1061
  try {
739
- if (mic) {
740
- // Live mic recording
741
- const res = await client.dictateMic(duration || 10, language, cleanup);
742
- return { content: [{ type: 'text', text: res.data.text }] };
1062
+ const res = mic
1063
+ ? await client.dictateMic(duration || 10, language, cleanup, engine)
1064
+ : await client.dictate({ audioPath, audioBase64, language, cleanup, engine });
1065
+ const body = res.data;
1066
+ if (body.ok === false) {
1067
+ return { content: [{ type: 'text', text: formatResponse(body) }], isError: true };
743
1068
  }
744
- const res = await client.dictate({ audioPath, audioBase64, language, cleanup });
745
- return { content: [{ type: 'text', text: res.data.text }] };
1069
+ const text = body.text ?? '';
1070
+ // Phase 5.2: append a second text block with next_steps only when
1071
+ // suggestions are meaningful. Keeps the primary transcript-first
1072
+ // interface (existing agents reading content[0].text unchanged)
1073
+ // and surfaces hints to agents that inspect the full content array.
1074
+ const hints = nextStepsForDictate(cleanup !== false, text.length > 0);
1075
+ const content = [{ type: 'text', text }];
1076
+ if (hints.length > 0) {
1077
+ content.push({ type: 'text', text: formatResponse({ next_steps: hints }) });
1078
+ }
1079
+ return { content };
1080
+ }
1081
+ catch (err) {
1082
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1083
+ }
1084
+ });
1085
+ // ── Tool: superbased_tools (Phase 5.5 — progressive-disclosure dispatcher) ──
1086
+ server.tool('superbased_tools', 'Progressive-disclosure dispatcher. When `progressiveDisclosure.enabled = true` in settings, only the 15 core tools appear in tools/list; the other ~50 tools are hidden but still callable. Call this with a category to get the names and descriptions of the hidden tools in that group: capture | record | dictate | interact | window | layout | ax | ai | edit | clipboard | system. Omitting category returns the full index (all categories + the tools in each). Counts + core membership are included so agents can confirm which tools are always advertised vs gated. The returned schemas are names-and-descriptions only; once an agent knows a hidden tool name, it can call it directly and the MCP server accepts the call (the feature is about trimming `tools/list` token cost, not access restriction).', {
1087
+ category: zod_1.z.enum(['capture', 'record', 'dictate', 'interact', 'window', 'layout', 'ax', 'ai', 'edit', 'clipboard', 'system']).optional().describe('Category to expand. Omit for the full index across all categories.'),
1088
+ }, async ({ category }) => {
1089
+ try {
1090
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
1091
+ const mod = require('./tool-categories');
1092
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1093
+ const registered = server._registeredTools ?? {};
1094
+ const getDescription = (name) => {
1095
+ const tool = registered[name];
1096
+ return tool?.description ? tool.description.slice(0, 240) : '';
1097
+ };
1098
+ if (category) {
1099
+ const names = mod.toolsInCategory(category);
1100
+ const tools = names.map((name) => ({ name, description: getDescription(name), core: mod.CORE_TOOLS.has(name) }));
1101
+ return {
1102
+ content: [{ type: 'text', text: formatResponse({
1103
+ category,
1104
+ count: tools.length,
1105
+ tools,
1106
+ }) }],
1107
+ };
1108
+ }
1109
+ const index = {};
1110
+ for (const cat of mod.CATEGORIES) {
1111
+ index[cat] = mod.toolsInCategory(cat).map((name) => ({ name, description: getDescription(name), core: mod.CORE_TOOLS.has(name) }));
1112
+ }
1113
+ const coreList = [...mod.CORE_TOOLS].map((name) => ({ name, description: getDescription(name) }));
1114
+ return {
1115
+ content: [{ type: 'text', text: formatResponse({
1116
+ core: { count: coreList.length, tools: coreList },
1117
+ categories: index,
1118
+ totalTools: coreList.length + mod.allNonCoreTools().length,
1119
+ }) }],
1120
+ };
1121
+ }
1122
+ catch (err) {
1123
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1124
+ }
1125
+ });
1126
+ // ── Tool: superbased_undo_last (Phase 5.4 — per-session undo) ──
1127
+ server.tool('superbased_undo_last', 'Reverse the last GUI automation action from this server process\'s in-memory stack. `type` actions undo via Backspace keystrokes matching the typed length. `click`, `hotkey`, `scroll`, `focus-window` actions are recorded but NOT reversible (returns ok:false with error="not_reversible" — the entry is still popped, so calling undo_last again reverses the NEXT-most-recent action). Returns ok:false with error="stack_empty" when nothing to undo. Stack is per-session (cleared on process restart) and does not persist.', {}, async () => {
1128
+ try {
1129
+ const res = await client.undoLast();
1130
+ const body = res.data;
1131
+ return { content: [{ type: 'text', text: formatResponse(body) }], isError: body.ok === false };
1132
+ }
1133
+ catch (err) {
1134
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1135
+ }
1136
+ });
1137
+ // ── Tool: superbased_project (Phase 5.1 — orientation snapshot) ──
1138
+ server.tool('superbased_project', 'Return a read-only "where am I" snapshot for agents: cwd, git branch + status + ahead/behind, detected framework(s), recent captures, active recording (if any), and last dictation preview. First call for many sessions — gives the agent enough context to pick the right tool without extra round-trips. Local git + framework detection runs in the MCP server process; capture/recording/dictation state fetched from /api/project/server-state.', {}, async () => {
1139
+ try {
1140
+ const cwd = projectDir ?? process.cwd();
1141
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
1142
+ const { detectFrameworks, getGitSummary } = require('./project-sense');
1143
+ const git = getGitSummary(cwd);
1144
+ const frameworks = detectFrameworks(cwd);
1145
+ let serverState = null;
1146
+ let serverError = null;
1147
+ try {
1148
+ const res = await client.projectServerState();
1149
+ serverState = res.data;
1150
+ }
1151
+ catch (err) {
1152
+ serverError = err instanceof Error ? err.message : String(err);
1153
+ }
1154
+ const response = {
1155
+ cwd,
1156
+ git,
1157
+ frameworks,
1158
+ server: serverState,
1159
+ serverError,
1160
+ };
1161
+ return { content: [{ type: 'text', text: formatResponse(response) }] };
1162
+ }
1163
+ catch (err) {
1164
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1165
+ }
1166
+ });
1167
+ // ── Tool: superbased_workspace_sync (Phase 5.1 — bundled snapshot) ──
1168
+ server.tool('superbased_workspace_sync', 'One-call bundled snapshot of the user\'s current workspace: fullscreen capture (base64 PNG), OCR text (truncated at 4000 chars), active window metadata, timestamp, and project dir. Replaces a chain of superbased_capture → superbased_ocr → superbased_window_list with a single HTTP round-trip. Read-only — does NOT persist the capture to the gallery DB; use superbased_capture for that.', {}, async () => {
1169
+ try {
1170
+ const cwd = projectDir ?? process.cwd();
1171
+ const res = await client.workspaceSync();
1172
+ const data = res.data;
1173
+ // Return both structured JSON (for agent reasoning) and the image
1174
+ // itself (so the agent can pass it through to vision models without
1175
+ // a second fetch). Matches the superbased_capture_image shape.
1176
+ const summary = {
1177
+ projectDir: cwd,
1178
+ imageBytes: data.imageBytes,
1179
+ timestamp: data.timestamp,
1180
+ activeWindow: data.activeWindow,
1181
+ ocr: data.ocr,
1182
+ };
1183
+ return {
1184
+ content: [
1185
+ { type: 'text', text: formatResponse(summary) },
1186
+ { type: 'image', data: data.imageBase64, mimeType: 'image/png' },
1187
+ ],
1188
+ };
1189
+ }
1190
+ catch (err) {
1191
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1192
+ }
1193
+ });
1194
+ // ── Tool: superbased_stt_status (Phase 4a — local STT probe) ──
1195
+ server.tool('superbased_stt_status', 'Report which local speech-to-text engines are available on this machine. Returns { sherpa: { binaryInstalled, binaryError?, modelDownloaded, modelId }, cloud: { signedIn }, native: { platform, available, reason }, autoResolvedTo }. Use before requesting engine="sherpa" on superbased_dictate / superbased_transcribe (Phase 4b) to avoid a model-required round-trip. autoResolvedTo shows which engine "auto" routing would currently pick.', {}, async () => {
1196
+ try {
1197
+ const res = await client.sttStatus();
1198
+ return { content: [{ type: 'text', text: formatResponse(res.data) }] };
1199
+ }
1200
+ catch (err) {
1201
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1202
+ }
1203
+ });
1204
+ // ── Tool: superbased_accessibility_tree (Phase 8.1 — native AX / UIA) ──
1205
+ server.tool('superbased_accessibility_tree', 'Return the native accessibility tree (macOS AXUIElement / Windows UIA) for a running application. More reliable than OCR for structured UI dumps — roles, labels, values, bounding rects, and hierarchy come straight from the OS. Requires the optional @superbased/macos-ax (darwin) or @superbased/win-uia (win32) binding to be installed, and Accessibility permission granted on macOS. On darwin pass { pid }; on win32 pass { pid } or { hwnd }. Returns { ok, tree?: { role, title, value, frame, children, ... }, error?, message? }.', {
1206
+ pid: zod_1.z.number().int().positive().optional().describe('Target process id. Required on darwin; optional on win32 (defaults to foreground).'),
1207
+ hwnd: zod_1.z.number().int().positive().optional().describe('Windows window handle (win32 only). Mutually exclusive with pid.'),
1208
+ maxDepth: zod_1.z.number().int().min(1).max(64).optional().default(24).describe('Tree walker depth limit. Lower values reduce latency + JSON size on rich GUIs.'),
1209
+ includeAttributes: zod_1.z.boolean().optional().default(false).describe('Include the full per-node attribute list. Noisy but useful for debugging.'),
1210
+ }, async ({ pid, hwnd, maxDepth, includeAttributes }) => {
1211
+ try {
1212
+ const res = await client.accessibilityTree({ pid, hwnd, maxDepth, includeAttributes });
1213
+ return { content: [{ type: 'text', text: formatResponse(res.data) }] };
746
1214
  }
747
1215
  catch (err) {
748
1216
  return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
@@ -750,7 +1218,7 @@ function registerMcpTools(server, client, projectDir) {
750
1218
  });
751
1219
  // ── Tool: superbased_annotate ──
752
1220
  server.tool('superbased_annotate', 'Add visual annotations to a capture: rectangles, highlights, blur regions, text labels, or arrows. Use for bug reports or visual callouts.', {
753
- captureId: zod_1.z.number().describe('Capture to annotate'),
1221
+ captureId: captureRefSchema.describe(`Capture to annotate. ${captureRefDescription}`),
754
1222
  annotations: zod_1.z.array(zod_1.z.object({
755
1223
  type: zod_1.z.enum(['rectangle', 'highlight', 'blur', 'text', 'arrow']),
756
1224
  x: zod_1.z.number(), y: zod_1.z.number(),
@@ -762,7 +1230,11 @@ function registerMcpTools(server, client, projectDir) {
762
1230
  save: zod_1.z.boolean().default(false).describe('Save annotated image over the original'),
763
1231
  }, async ({ captureId, annotations, save }) => {
764
1232
  try {
765
- const res = await client.annotate(captureId, annotations, save);
1233
+ const captureIdNum = parseCaptureRef(captureId);
1234
+ if (captureIdNum === null) {
1235
+ return { content: [{ type: 'text', text: `Invalid captureId: ${String(captureId)}` }], isError: true };
1236
+ }
1237
+ const res = await client.annotate(captureIdNum, annotations, save);
766
1238
  const content = [
767
1239
  { type: 'text', text: `Applied ${res.data.annotationsApplied} annotation(s)${res.data.saved ? ' (saved)' : ''}` },
768
1240
  ];
@@ -795,6 +1267,815 @@ function registerMcpTools(server, client, projectDir) {
795
1267
  return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
796
1268
  }
797
1269
  });
1270
+ // ── GUI Automation tools (Phase 2a) ──
1271
+ // All actions OFF by default — user must enable via `superbased config set
1272
+ // guiAutomation.enabled true` or in `superbased settings`. Refused actions
1273
+ // return ok:false with a hint, never a tool error.
1274
+ server.tool('superbased_click', 'Click at screen coordinates OR a resolved UI element (0.10). Pass EITHER x+y OR one of label/automationId/role+name — the label/AX fields resolve via the reliability pyramid (automationId → role+name → label). GUI automation must be enabled first (off by default — use superbased_health to check). Pass confirm:true unless the user has disabled the requirement. PREFERRED: pass processName= / hwnd= on THIS call — the tool handles the full focus→click→restore cycle in ONE MCP turn. NEVER chain superbased_focus_window before this. Each MCP call requires a permission approval in the agent UI; clicking Approve steals focus back to the agent and defeats the activation. Loose window= matching is scored: process-name match (100) > title-suffix " - Notepad" (80) > prefix (60) > substring (40); score below 80 is refused with alternatives. restoreFocus (default true) brings your AI editor back to foreground after the click via AttachThreadInput + verify + retry — so focus actually lands, instead of the old SetForegroundWindow one-shot that silently failed under idle-input-timeout. 2.1: `clickCount: 2|3` for double/triple click (doubleClick:true is back-compat sugar for clickCount:2); `modifiers: ["shift"|"ctrl"|"alt"|"meta"]` held for the duration of the click — e.g. Shift-click to extend selection, Ctrl-click to multi-select. AUTO-SNAPSHOT (default): this tool returns the post-action screenshot INLINE as an MCP image content block — no separate screenshot call needed. Set returnObservation:"none" in tight loops to suppress, or "full" to also include OCR + accessibility-tree text elements (adds ~200-500ms).', {
1275
+ x: zod_1.z.number().optional().describe('Absolute x coordinate (px from left edge of primary display). Pass EITHER x+y OR label/automationId/role+name.'),
1276
+ y: zod_1.z.number().optional().describe('Absolute y coordinate (px from top edge)'),
1277
+ label: zod_1.z.string().optional().describe('0.10: Visible text to click (OCR-resolved). Saves one round-trip vs ui_dump→click. Falls back to LOCATE_NO_MATCH if not visible in a fresh ui_dump.'),
1278
+ automationId: zod_1.z.string().optional().describe('0.10: AX AutomationId (Windows UIA) / AXIdentifier (macOS). Most reliable locator — prefer over label when available.'),
1279
+ role: zod_1.z.string().optional().describe('0.10: AX role (e.g. "button", "textbox") — pair with name=.'),
1280
+ name: zod_1.z.string().optional().describe('0.10: AX accessible name — required when role= is set.'),
1281
+ caseSensitive: zod_1.z.boolean().optional().describe('Match label/role-name case-sensitively (default false).'),
1282
+ button: zod_1.z.enum(['left', 'right', 'middle']).optional().describe('Mouse button (default: left)'),
1283
+ doubleClick: zod_1.z.boolean().optional().describe('Send a double-click instead of single (default: false). Back-compat alias for clickCount:2 — prefer clickCount when both are needed.'),
1284
+ clickCount: zod_1.z.union([zod_1.z.literal(1), zod_1.z.literal(2), zod_1.z.literal(3)]).optional().describe('2.1: Number of clicks (1 = single, 2 = double, 3 = triple-click for word → line selection in text fields). Default 1. Back-compat: doubleClick:true overrides to 2.'),
1285
+ modifiers: zod_1.z.array(zod_1.z.enum(['shift', 'ctrl', 'alt', 'meta'])).optional().describe('2.1: Modifier keys held throughout the click. Shift = extend selection, Ctrl = multi-select / Ctrl-click (open-in-new-tab in browsers), Alt = alt-click, Meta = Cmd on macOS / Win on Windows. Multiple modifiers combine.'),
1286
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1287
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Use processName= when you know the exe name — that is more reliable than fuzzy title match.'),
1288
+ processName: zod_1.z.string().optional().describe('Exact process executable name (e.g. "Notepad", "Notepad.exe"). Highest-confidence target.'),
1289
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely — guaranteed to target this exact window. Use when matcher refuses on ambiguity.'),
1290
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore the previous foreground window after the click. Set false to leave the target window focused.'),
1291
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-action PNG inline, eliminating the separate screenshot call. "full" adds OCR + accessibility-tree textElements with bbox+center coords (ready for the next click). "none" suppresses capture (use in tight loops).'),
1292
+ humanize: zod_1.z.enum(['off', 'light', 'human', 'paranoid']).optional().describe('Per-call override of the global humanInputDefault setting. When non-"off", the cursor follows a Bezier curve from its current position to (x, y) BEFORE the click fires — defeats trajectory classifiers that flag teleport-then-click as bot input. "light" (default global) adds modest curvature; "human" adds 2 control points + 15% overshoot; "paranoid" adds 3 control points + 40% overshoot at ~5-10x slower travel. Move skipped for tiny hops (<4px) — the click already lands on target. Cross-platform via getCursorPosition (GetCursorPos on win32, CGEventSourceGetMouseLocation on darwin).'),
1293
+ }, async ({ x, y, label, automationId, role, name, caseSensitive, button, doubleClick, clickCount, modifiers, confirm, window, processName, hwnd, restoreFocus, returnObservation, humanize }) => {
1294
+ try {
1295
+ const res = await client.automationClick({ x, y, label, automationId, role, name, caseSensitive, button, doubleClick, clickCount, modifiers, confirm, window, processName, hwnd, restoreFocus, returnObservation, humanize });
1296
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1297
+ }
1298
+ catch (err) {
1299
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1300
+ }
1301
+ });
1302
+ server.tool('superbased_type', 'Type a string into the focused field, OR into a specific target window via PostMessage / UIA when window= or processName= is set. 0.10: accepts label/automationId/role+name to click the target field FIRST (via the reliability pyramid) then type — saves one round-trip vs superbased_click→superbased_type. Special keys via {Enter}, {Tab}, etc. are NOT interpreted — use superbased_hotkey for those. GUI automation must be enabled. PREFERRED: pass processName= / hwnd= on THIS call — the tool focuses, types, and restores in ONE MCP turn. NEVER chain superbased_focus_window before this; the second permission prompt steals focus back to the agent window and the keystrokes land in the wrong app. restoreFocus (default true) uses verified AttachThreadInput + retry to bring your AI editor back afterwards. 2.6: `clearFirst: true` sends a platform-native select-all + delete (Ctrl+A / Cmd+A, then Delete) BEFORE typing — use to overwrite a pre-populated field in one call instead of chaining hotkey→type. `delayMs` adds per-keystroke pacing in ms (0 = fastest, default); raise to 20-50 when the target field runs per-keystroke validation / IME composition that coalesces fast input. Note: delayMs is only honored on the SendInput paths (no-target or activated target); the focus-free PostMessage path fires WM_CHAR in a burst regardless. 5.3: `ime: true` routes the text through the layout-independent Unicode primitive (Windows: SendInput + VK_PACKET; macOS: CGEventKeyboardSetUnicodeString) instead of layout-aware nut-js — use for Japanese / Korean / Chinese (JKC) and other non-Latin text that the default path drops or misrenders. V1 delivers completed Unicode only — no TSF / WM_IME_COMPOSITION interactive composition window. ime:true is honored on the SendInput paths (no-target OR activated target); on the Windows focus-free PostMessage path (triggered by window=/processName=/hwnd=) it is a no-op because WM_CHAR already carries Unicode. AUTO-SNAPSHOT (default): returns post-action PNG inline; set returnObservation:"none" to suppress.', {
1303
+ text: zod_1.z.string().describe('Literal characters to type into the active text field'),
1304
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1305
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Less precise than processName.'),
1306
+ processName: zod_1.z.string().optional().describe('Exact process executable name (e.g. "Notepad"). Highest-precision target.'),
1307
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1308
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore the previous foreground window after typing.'),
1309
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-action PNG. "full" adds OCR + AX tree textElements. "none" suppresses.'),
1310
+ label: zod_1.z.string().optional().describe('0.10: Click-target field label (OCR-resolved) before typing.'),
1311
+ automationId: zod_1.z.string().optional().describe('0.10: AX AutomationId for the target field — most reliable locator.'),
1312
+ role: zod_1.z.string().optional().describe('0.10: AX role (e.g. "textbox") — pair with name=.'),
1313
+ name: zod_1.z.string().optional().describe('0.10: AX accessible name — required when role= is set.'),
1314
+ caseSensitive: zod_1.z.boolean().optional().describe('Match label/role-name case-sensitively (default false).'),
1315
+ clearFirst: zod_1.z.boolean().optional().describe('2.6: Send a platform-native select-all + delete (Ctrl+A on Windows, Cmd+A on macOS, then Delete) BEFORE typing. Empties a pre-populated field in one call. Works on all paths (PostMessage via hotkey-to-window on Windows + target; SendInput on all other paths).'),
1316
+ delayMs: zod_1.z.number().optional().describe('2.6: Inter-key delay in ms (0 = fastest). Honored on the SendInput paths (no-target OR activated target). The PostMessage path fires WM_CHAR in a burst so delayMs is ignored there. Raise to 20-50ms when the target runs per-keystroke validation / IME composition; 100ms+ simulates human typing speed.'),
1317
+ ime: zod_1.z.boolean().optional().describe('5.3: Route through the layout-independent Unicode primitive (Windows VK_PACKET / macOS CGEventKeyboardSetUnicodeString) — required for Japanese / Korean / Chinese and other non-Latin text that the layout-aware default drops. V1 delivers completed Unicode only (no TSF / WM_IME_COMPOSITION composition-window simulation). Honored on the SendInput paths; no-op on the Windows focus-free PostMessage path (WM_CHAR already carries Unicode there). Verify via details.mode === "sendinput-unicode" in the response.'),
1318
+ humanize: zod_1.z.enum(['off', 'light', 'human', 'paranoid']).optional().describe('Per-call override of the global humanInputDefault setting. "off" sends machine-fast SendInput (current burst); "light" (default global) adds gamma-distributed inter-key delays so the typing rhythm varies; "human" cranks delays + bigram timing to ~3-5x slower for CAPTCHA / banking / Cloudflare-Turnstile flows; "paranoid" goes to ~5-10x with longer pauses. IGNORED when delayMs is set — the caller asked for that exact pacing. NOT a substitute for browser stealth: this only addresses keystroke timing, not TLS / canvas / CDP fingerprints.'),
1319
+ }, async ({ text, confirm, window, processName, hwnd, restoreFocus, returnObservation, label, automationId, role, name, caseSensitive, clearFirst, delayMs, ime, humanize }) => {
1320
+ try {
1321
+ const res = await client.automationType({ text, confirm, window, processName, hwnd, restoreFocus, returnObservation, label, automationId, role, name, caseSensitive, clearFirst, delayMs, ime, humanize });
1322
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1323
+ }
1324
+ catch (err) {
1325
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1326
+ }
1327
+ });
1328
+ server.tool('superbased_hotkey', 'Send a keyboard shortcut. Combo strings like "Cmd+A", "Ctrl+Shift+P", "Tab", "{Enter}". "Cmd"/"Meta"/"Win"/"Super" auto-map to the platform mod key. "CmdOrCtrl" maps to Cmd on macOS, Ctrl elsewhere. Window/process targeting same as superbased_type — PREFERRED: pass processName= / hwnd= on THIS call. NEVER chain superbased_focus_window before this; the approval-prompt click steals focus back to the agent and the combo fires on the wrong window. App-level shortcuts (Ctrl+Tab, Win+V) only fire via global SendInput — omit window/processName for those. DELIVERY (1.1): Windows automatically picks PostMessage (focus-free, fast) for classic Win32 apps, or activate+SendInput for browsers / Electron / modern WPF (Chrome, Edge, VS Code, Discord, etc. — where PostMessage silently no-ops). Override via method:"postmessage"|"sendinput" when needed. AUTO-SNAPSHOT (default): returns post-action PNG inline; set returnObservation:"none" to suppress.', {
1329
+ combo: zod_1.z.string().describe('Key combo string (e.g. "Cmd+A", "Ctrl+Shift+P", "Tab", "F5")'),
1330
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1331
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1332
+ processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision target.'),
1333
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1334
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the hotkey.'),
1335
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-action PNG. "full" adds OCR + AX tree textElements. "none" suppresses.'),
1336
+ method: zod_1.z.enum(['auto', 'postmessage', 'sendinput']).optional().describe('Windows delivery override. Default "auto": classifier forces SendInput+activation for browsers / Electron / modern WPF (Chrome, Edge, VS Code, Discord, etc. — where PostMessage silently no-ops), PostMessage for classic Win32 controls. "postmessage" forces focus-free delivery (fast, no flicker, fails on modern apps). "sendinput" forces activate+OS-level keystroke (works everywhere, steals focus ~200ms). macOS: ignored; uses CGEventPost.'),
1337
+ }, async ({ combo, confirm, window, processName, hwnd, restoreFocus, returnObservation, method }) => {
1338
+ try {
1339
+ const res = await client.automationHotkey({ combo, confirm, window, processName, hwnd, restoreFocus, returnObservation, method });
1340
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1341
+ }
1342
+ catch (err) {
1343
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1344
+ }
1345
+ });
1346
+ server.tool('superbased_resize_window', 'Resize a target window to a device preset or custom width/height (Windows-only in S1; macOS lands in Phase 7). Presets cover common phone/tablet/desktop viewports for responsive-design testing: "iphone-se"/"iphone-12"/"iphone-pro-max"/"pixel-7" (phones), "ipad-mini"/"ipad"/"ipad-pro-11"/"ipad-pro-13" (tablets), "desktop-hd" (1920×1080), "desktop-qhd" (2560×1440), "fullscreen" (SW_MAXIMIZE), "custom" (requires width + height). `contentArea: true` compensates for window chrome so the *inner* area matches the requested dims (crucial for browser device-emulation: Chrome on Win10 has ~8px borders + ~70px tabstrip, so an "iphone-12" OUTER window renders a 374×774 content area; contentArea:true grows the outer window to deliver a 390×844 viewport). Auto-invalidates the scroll-calibration cache for the target since pixelsPerScroll depends on viewport height. Returns actual bounds read back from GetWindowRect.', {
1347
+ preset: zod_1.z.enum(['iphone-se', 'iphone-12', 'iphone-pro-max', 'pixel-7', 'ipad-mini', 'ipad', 'ipad-pro-11', 'ipad-pro-13', 'desktop-hd', 'desktop-qhd', 'fullscreen', 'custom']).optional().describe('Device preset. Use "custom" with explicit width/height for non-standard sizes; "fullscreen" = maximize.'),
1348
+ width: zod_1.z.number().optional().describe('Width in pixels. Required for preset "custom". Ignored for "fullscreen".'),
1349
+ height: zod_1.z.number().optional().describe('Height in pixels. Required for preset "custom". Ignored for "fullscreen".'),
1350
+ x: zod_1.z.number().optional().describe('Optional X position (virtual-screen logical pixels). Omit to keep current position.'),
1351
+ y: zod_1.z.number().optional().describe('Optional Y position. Omit to keep current position.'),
1352
+ contentArea: zod_1.z.boolean().optional().describe('Default false. When true, the OUTER window grows so that the CLIENT (content) area matches width×height — accounts for titlebar/borders/tabstrip. Use for browser device-emulation where the rendered viewport matters, not the OS-level window frame.'),
1353
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1354
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1355
+ processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision target.'),
1356
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1357
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-resize PNG of the target.'),
1358
+ }, async ({ preset, width, height, x, y, contentArea, confirm, window, processName, hwnd, returnObservation }) => {
1359
+ try {
1360
+ const res = await client.automationResizeWindow({ preset, width, height, x, y, contentArea, confirm, window, processName, hwnd, returnObservation });
1361
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1362
+ }
1363
+ catch (err) {
1364
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1365
+ }
1366
+ });
1367
+ server.tool('superbased_window_bounds', 'Read a window\'s current screen rect + minimized / maximized state. PURE QUERY — no activation, no focus change, no side effects. Use when the agent needs to reason about positioning (e.g. "is this window in the top-left corner yet?", "does the target fit on the primary display?") without disturbing the user\'s foreground. Fills the gap where agents previously had to shell focus_window + fullscreen screenshot or trigger a resize_window to learn a rect. Returns `{ ok, details: { hwnd, rect:{x,y,width,height}, minimized, maximized, matchedWindow } }` on success. Rect is in virtual-screen physical pixels (post-P4 DPI-aware capture chain), directly usable as inputs to resize_window / click / drag / screenshot region. Windows: GetWindowRect + IsIconic + IsZoomed via one PowerShell call. macOS: osascript position + size + AXMinimized + AXFullScreen via System Events AX. Not gated by confirm (same policy as window_list / mouse_position — reads don\'t need approval).', {
1368
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Use superbased_window_list to enumerate.'),
1369
+ processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision non-hwnd target.'),
1370
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from a prior tool\'s details.matchedWindow.hwnd or superbased_window_list). Bypasses scoring — preferred for chained operations where the title may drift.'),
1371
+ }, async ({ window, processName, hwnd }) => {
1372
+ try {
1373
+ const res = await client.automationWindowBounds({ window, processName, hwnd });
1374
+ return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
1375
+ }
1376
+ catch (err) {
1377
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1378
+ }
1379
+ });
1380
+ server.tool('superbased_find_title_bar_drag_region', 'Resolve a safe pickup coordinate for generic title-bar drag on a target window. PURE QUERY — no activation, no focus change, no input injected. Runs ui_dump internally (AX tree + OCR — no screenshot; ~1-3s) and returns the midpoint of the widest interactive-free horizontal strip in the window\'s title-bar band. Prefers AX classification (precise role-based) and falls back to OCR (treats every title-bar text box as an exclusion) when the AX binding is unavailable — works on machines without @superbased/win-uia. USE BEFORE superbased_drag WHEN MOVING A WINDOW: Win11 WinUI 3 title bars are tab-container owned and have resize-frame hit-test zones extending 8-15px inside the visible edges, so fixed-coord recipes like `(bounds.x+10, bounds.y+15)` are unreliable — this tool does the math for you. Returns `{ ok, details: { hwnd, bounds, pickup:{x,y}, gap:{x1,x2,widthPx}, source:"ax"|"ocr", matchedWindow } }` on success; `source` reveals which path produced the pickup (confidence is 1.0 for AX, 0.8 for OCR). On failure returns errorCode:"DRAG_NO_SAFE_PICKUP" — in that case the drag WILL fail; use superbased_resize_window for window placement instead (SetWindowPos bypasses the drag surface entirely). Windows + macOS. Not gated (pure read).', {
1381
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Use superbased_window_list to enumerate.'),
1382
+ processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision non-hwnd target.'),
1383
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from a prior tool\'s details.matchedWindow.hwnd or superbased_window_list). Bypasses scoring — preferred for chained operations.'),
1384
+ }, async ({ window, processName, hwnd }) => {
1385
+ try {
1386
+ const res = await client.automationFindTitleBarDragRegion({ window, processName, hwnd });
1387
+ return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
1388
+ }
1389
+ catch (err) {
1390
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1391
+ }
1392
+ });
1393
+ server.tool('superbased_window_state', 'Change a target window\'s state: "minimize" (taskbar), "maximize", "restore" (un-minimize or un-maximize), "close" (send WM_CLOSE — app can still prompt for unsaved-work), "always_on_top_on"/"always_on_top_off"/"always_on_top_toggle" (float above other windows), "move_to_display" (re-home to another monitor — pass displayId from superbased_display_list). ONE approval for the whole action; when action is "close", a secondary gate guiAutomation.actions.destructive (OFF by default) must also be enabled since close can lose unsaved work. Windows-only in S3; macOS lands Phase 7 (NSWindow miniaturize/zoom/close via AX). AUTO-SNAPSHOT: returns post-action PNG for maximize/restore/always-on-top/move-to-display; suppressed for close/minimize (target no longer visible).', {
1394
+ action: zod_1.z.enum(['minimize', 'maximize', 'restore', 'close', 'always_on_top_on', 'always_on_top_off', 'always_on_top_toggle', 'move_to_display']).describe('Window state action. "close" requires guiAutomation.actions.destructive to be ON. "move_to_display" requires displayId.'),
1395
+ displayId: zod_1.z.number().optional().describe('Required for action="move_to_display". Get IDs from superbased_display_list (S4/3.6) or platform.capture.enumerateDisplays(). Window is re-positioned and centered on the target display; if larger than the display it is clamped.'),
1396
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1397
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1398
+ processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision target.'),
1399
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1400
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" for maximize/restore/always-on-top/move-to-display; forced "none" for close and minimize (target not visible).'),
1401
+ }, async ({ action, displayId, confirm, window, processName, hwnd, returnObservation }) => {
1402
+ try {
1403
+ const res = await client.automationWindowState({ action, displayId, confirm, window, processName, hwnd, returnObservation });
1404
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1405
+ }
1406
+ catch (err) {
1407
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1408
+ }
1409
+ });
1410
+ server.tool('superbased_display_list', 'Enumerate all connected displays with virtual-screen bounds, scale factor, primary flag, and color space. Use BEFORE targeting a non-primary monitor: the returned `bounds` are in the SAME virtual-screen coordinate frame that all positional tools (click, type, drag, hover, find_image, screenshot region, etc.) use — feed a display\'s `bounds` into `region:` for capture / search, or use `id` with `superbased_window_state action:"move_to_display"` to re-home a window. VIRTUAL-SCREEN POLICY: coords everywhere in the SuperBased MCP surface are virtual-screen logical units (design principle 12). Primary at (0,0); secondary at negative X if to the left, positive X beyond primary.width if to the right. There is NO `display?: number` half-measure on positional tools — learn coords from this enumeration and pass them through directly. Pure read; no safety gate (no pixels exposed, no input injected). Cross-platform (Windows + macOS both work today). Returns `{ ok, displays: [{ id, primary, bounds:{x,y,width,height}, scaleFactor, name?, colorSpace? }] }`.', {}, async () => {
1411
+ try {
1412
+ const res = await client.automationDisplayList();
1413
+ const data = res.data;
1414
+ const content = [
1415
+ { type: 'text', text: formatResponse(data) },
1416
+ ];
1417
+ return { content, isError: !data.ok };
1418
+ }
1419
+ catch (err) {
1420
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1421
+ }
1422
+ });
1423
+ server.tool('superbased_find_image', 'Visual template match — locate a small PNG template (icon, button, logo, glyph) inside the current screen OR inside a virtual-screen region. Returns { matches: [{x, y, width, height, center, confidence}] } in virtual-screen coords, top-confidence first. Use this when reliability-pyramid rungs above (automationId / role+name / label via OCR) don\'t work: pixel-perfect button-shaped matches in a canvas, game UI, PDF viewers, color-keyed state indicators, or any surface where OCR misses and there\'s no AX tree. ALSO UNBLOCKS the `locate:{imageTemplate: "<path>"}` resolver across click / type / drag / hover / scroll / sequence — one template, reuse anywhere. Pass EITHER `templateBase64` (inline PNG) OR `templatePath` (filesystem path; metadata `.meta.json` sidecar auto-loaded from the same dir). Metadata GUARDS: capture DPI + theme are stored in the sidecar; match REFUSES under different DPI or theme unless `ignoreDpiScale:true` / `ignoreTheme:true`. Always pair with `superbased_capture_template` to produce templates with metadata correctly set. `region` constrains the search to a virtual-screen rect — strongly recommended for speed + false-positive rejection. `multi:true` returns all non-overlapping matches ≥ threshold. Algorithm: downsampled grayscale NCC (Rec. 601) — pure JS, no native deps. Confidence ∈ [0, 1]; typical thresholds: 0.95+ near-identical, 0.85-0.95 visually similar (default), 0.70-0.85 loose. Cost ~200-800ms on typical viewports.', {
1424
+ templateBase64: zod_1.z.string().optional().describe('Base64-encoded PNG template. Pass EITHER templateBase64 OR templatePath — not both.'),
1425
+ templatePath: zod_1.z.string().optional().describe('Filesystem path to a PNG template. Sidecar `<path>.meta.json` is auto-loaded (dpiScale + theme) — recapture via superbased_capture_template if absent or stale.'),
1426
+ region: zod_1.z.object({
1427
+ x: zod_1.z.number().describe('Region top-left X (virtual-screen logical pixels).'),
1428
+ y: zod_1.z.number().describe('Region top-left Y.'),
1429
+ width: zod_1.z.number().describe('Region width.'),
1430
+ height: zod_1.z.number().describe('Region height.'),
1431
+ }).optional().describe('Virtual-screen rect to search. Default = full virtual screen. Recommended: constrain when you know approximately where the match is.'),
1432
+ threshold: zod_1.z.number().optional().describe('Minimum NCC confidence in [0, 1]. Default 0.85. Raise to 0.95 for exact matches; lower to 0.75 for antialiasing-tolerant matches.'),
1433
+ multi: zod_1.z.boolean().optional().describe('Default false (top-1). Set true to return all non-overlapping matches ≥ threshold (useful: count instances of an icon; enumerate rows in a table).'),
1434
+ maxMatches: zod_1.z.number().optional().describe('Cap on matches in multi mode. Default 10.'),
1435
+ ignoreDpiScale: zod_1.z.boolean().optional().describe('Default false — refuse match when current DPI scale differs from the template\'s captured DPI. Set true ONLY when the template is DPI-robust (vector icons rasterized at multiple scales, etc.); confidence will drop.'),
1436
+ ignoreTheme: zod_1.z.boolean().optional().describe('Default false — refuse match when current system theme differs from the template\'s captured theme. Set true for theme-agnostic templates (brand logos, product screenshots not affected by OS theme).'),
1437
+ maxSearchDim: zod_1.z.number().optional().describe('Longer-side downsample budget for the NCC pass. Default 400. Lower = faster, lower precision; higher = slower, more precise. Rarely needs changing.'),
1438
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt. find_image is pure screen-read (+ file-read if templatePath is set) — consent checkpoint only.'),
1439
+ }, async ({ templateBase64, templatePath, region, threshold, multi, maxMatches, ignoreDpiScale, ignoreTheme, maxSearchDim, confirm }) => {
1440
+ try {
1441
+ const res = await client.automationFindImage({ templateBase64, templatePath, region, threshold, multi, maxMatches, ignoreDpiScale, ignoreTheme, maxSearchDim, confirm });
1442
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1443
+ }
1444
+ catch (err) {
1445
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1446
+ }
1447
+ });
1448
+ server.tool('superbased_capture_template', 'Capture a virtual-screen region to a PNG + write a `<path>.meta.json` sidecar recording the DPI scale, theme, source bounds, and timestamp. PAIRED with `superbased_find_image`: the metadata guards that find_image uses to refuse matches under different conditions all come from this capture. Use BEFORE building any automation that relies on `locate:{imageTemplate:...}` — one recapture per theme / DPI environment the automation will run in. Default destination: `~/.superbased/templates/<tag>-<timestamp>.png`; pass `destPath` for a custom location. Returns { path, metaPath, dpiScale, theme, width, height, ... }.', {
1449
+ region: zod_1.z.object({
1450
+ x: zod_1.z.number().describe('Region top-left X (virtual-screen logical pixels).'),
1451
+ y: zod_1.z.number().describe('Region top-left Y.'),
1452
+ width: zod_1.z.number().describe('Region width. Must be > 0.'),
1453
+ height: zod_1.z.number().describe('Region height. Must be > 0.'),
1454
+ }).describe('Virtual-screen rect to capture. Required.'),
1455
+ destPath: zod_1.z.string().optional().describe('Absolute PNG path to write. Default: `~/.superbased/templates/<tag>-<timestamp>.png`. Parent directory is created if missing.'),
1456
+ tag: zod_1.z.string().optional().describe('Short human-readable tag — used in the default filename and stored in metadata. Example: "save-button", "nav-item-settings".'),
1457
+ displayId: zod_1.z.number().optional().describe('Display id the region belongs to — stored in metadata for later cross-monitor checks. Resolve via superbased_display_list (S4/3.6) or platform.capture.enumerateDisplays().'),
1458
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt. capture_template is a screenshot + file write — consent checkpoint.'),
1459
+ }, async ({ region, destPath, tag, displayId, confirm }) => {
1460
+ try {
1461
+ const res = await client.automationCaptureTemplate({ region, destPath, tag, displayId, confirm });
1462
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1463
+ }
1464
+ catch (err) {
1465
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1466
+ }
1467
+ });
1468
+ server.tool('superbased_dry_run', 'Preview a tool call WITHOUT executing it. Returns `ok: false` with `errorCode: "DRYRUN"`, echoing `{ tool, args }` in details. USE WHEN: sanity-checking a composed args object before committing (helpful for complex tools like superbased_form_fill / superbased_sequence where argument validation failures waste an approval). WHAT IT DOES: validates `tool` is a string + writes an audit entry (visible in ~/.superbased/audit.log with event="dryrun") + returns the structured preview. NOT a full simulation — does NOT resolve locate specs, run gate checks, or activate windows. Sequences have their own `dryRun: true` flag (S0) for per-step-level preview; this wrapper is the single-call equivalent. NO sequence step variant — cross-tool modifier, not a side-effecting action.', {
1469
+ tool: zod_1.z.string().describe('Name of the tool that would be invoked, e.g. "superbased_click", "superbased_type", "superbased_sequence".'),
1470
+ args: zod_1.z.record(zod_1.z.string(), zod_1.z.any()).optional().describe('The args object that would be passed to `tool`. Echoed in the response; not validated against the target tool\'s schema in v1 (the wrapper is deliberately light — each tool\'s own zod validates on the actual call).'),
1471
+ }, async ({ tool, args }) => {
1472
+ try {
1473
+ const res = await client.automationDryRun({ tool, args });
1474
+ return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: false };
1475
+ }
1476
+ catch (err) {
1477
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1478
+ }
1479
+ });
1480
+ server.tool('superbased_replay', 'Re-execute a previously-recorded sequence from the audit log. Reads `~/.superbased/audit.log`, filters by time range / sessionId, reconstructs SequenceStep[] from the ORIGINAL locate specs (label / automationId / role+name) preserved in each entry — NOT the resolved coords — and dispatches via runSequence. §6.8 determinism guarantee: "same locate spec resolves to same element" (re-resolves against the CURRENT UI), not pixel-identical coords. DEFAULT-SAFE: `dryRun: true` by default — returns a preview. To actually re-execute, pass BOTH `dryRun: false` AND `confirm: true` (wrapper refuses with INVALID_ARGS if only one is set; runSequence\'s own confirm gate still applies on top). NOT REPLAYABLE (audit strips critical info): `type` (text redacted for privacy), `find_in_page` (query → queryLength), `tab_management` (url not logged), `form_fill` (fields array not preserved), `launch_app` (args collapsed to target string) — these go in `details.skipped[]`. USE WHEN: reproducing a recorded flow (demo, regression test, rollback), or re-running an approved sequence after a model turnover. NO sequence step variant — replay IS a sequence orchestrator.', {
1481
+ from: zod_1.z.string().optional().describe('ISO-8601 timestamp lower bound (inclusive), e.g. "2026-04-23T14:00:00.000Z". Omit to include entries from the start of the audit log.'),
1482
+ to: zod_1.z.string().optional().describe('ISO-8601 timestamp upper bound (inclusive). Omit to include entries up to the end of the audit log.'),
1483
+ sessionId: zod_1.z.string().optional().describe('Filter entries to one audit sessionId (e.g. a prior form_fill or sequence macro). Independent of `from`/`to` — combine to narrow further.'),
1484
+ dryRun: zod_1.z.boolean().optional().describe('Default TRUE. When true (or omitted), replay reconstructs + returns the sequence preview without executing. When false, the wrapper ALSO requires `confirm: true` to actually re-execute.'),
1485
+ confirm: zod_1.z.boolean().optional().describe('Must be TRUE alongside `dryRun: false` to re-execute. Ignored when dryRun is true (no side effects to confirm).'),
1486
+ }, async ({ from, to, sessionId, dryRun, confirm }) => {
1487
+ try {
1488
+ const res = await client.automationReplay({ from, to, sessionId, dryRun, confirm });
1489
+ return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: false };
1490
+ }
1491
+ catch (err) {
1492
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1493
+ }
1494
+ });
1495
+ server.tool('superbased_doctor_gui_automation', 'Hermetic end-to-end probe of the GUI-automation adapter seam. Launches a canned target (Notepad on Windows, TextEdit on macOS) BYPASSING `launchAllowlist` (direct adapter call — the target is a hard-coded first-party system binary, so the user-surface allowlist doesn\'t apply) and runs each input primitive against it: click / type / hotkey / scroll / drag / hover / resize / AX dumpTree. Reports per-primitive `{ primitive, ok, durationMs, error?, errorCode? }` plus summary counts + macOS TCC status (accessibility + screenRecording permissions). Closes the target afterward (best-effort: tries window.setState("close"), falls back to Alt+N to dismiss the save-changes modal). USE WHEN: verifying GUI automation works after an OS upgrade, driver change, or permission grant; diagnosing "my clicks don\'t work" issues. VALIDATION MODEL: a passing click only proves the adapter accepted the call — it doesn\'t verify the OS routed the event to the right widget. For effect-level validation use `superbased_ui_dump` afterward. NOT A SIMULATION: writes real events into the target window (typed text, clicks, drag selection) — that\'s why the canned target is a first-party text editor you can discard. The master toggle (`guiAutomation.enabled`) still applies; individual action toggles (click/type/hotkey/…) do NOT gate the doctor since the target is controlled by the tool, not the agent. NO sequence step variant — pure probe.', {
1496
+ skipPrimitives: zod_1.z.array(zod_1.z.string()).optional().describe('Skip specific primitives by name (case-insensitive). Valid: "click", "type", "hotkey", "scroll", "drag", "hover", "resize", "ax". Skipped entries still appear in results with `skipped: true`.'),
1497
+ timeoutMs: zod_1.z.number().optional().describe('waitForWindow deadline in ms after launch. Default 10000. Bump when cold-start is slow (first-boot, slow disk, PowerShell-policy interference).'),
1498
+ }, async ({ skipPrimitives, timeoutMs }) => {
1499
+ try {
1500
+ const res = await client.automationDoctorGuiAutomation({ skipPrimitives, timeoutMs });
1501
+ return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: false };
1502
+ }
1503
+ catch (err) {
1504
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1505
+ }
1506
+ });
1507
+ server.tool('superbased_open_url', 'Open a URL, optionally in a specific browser. Tighter surface than superbased_launch_app({url}): (a) `browser?:` picks a specific browser binary (path or name — "chrome.exe", "C:\\\\...\\\\msedge.exe", "firefox") rather than always routing through the default, and (b) `waitForLoad:` defaults TRUE (polls for the browser window to appear via PlatformLaunchAdapter.waitForWindow) so the follow-up step has a window to target. REUSES the `actions.launch` gate + guiAutomation.launchAllowlist — an allowlist entry must match the url (when no browser) OR the browser binary (when browser provided). USE WHEN: agent wants to hand off to a visible browser for follow-up interaction (scroll, type, click), or open a URL in a non-default browser for isolation. PAIRED WITH: tab_management (for opening additional URLs in the same browser without a fresh process) and find_in_page (to jump to specific text after the page loads). Windows-only in S6; macOS (NSWorkspace.openURL:) lands Phase 7. Sequence step variant: `{ action: "open_url", url, browser?, waitForLoad? }`.', {
1508
+ url: zod_1.z.string().min(1).describe('Fully-qualified URL. HTTP/HTTPS are the common cases; ShellExecute also handles mailto: / file: / custom schemes registered on the system.'),
1509
+ browser: zod_1.z.string().optional().describe('Optional browser selection. Absolute path ("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe") or resolvable name ("chrome", "msedge", "firefox"). When omitted, the OS default handler opens the URL.'),
1510
+ waitForLoad: zod_1.z.boolean().optional().describe('Default true — polls for the browser window to appear after launch. Set false to return immediately (fire-and-forget). Requires `browser` OR `processNameMatch` — otherwise polling skips with a note.'),
1511
+ timeoutMs: zod_1.z.number().optional().describe('waitForLoad deadline in ms. Default 10000. Browsers can be slow to cold-start; pages that pop separate windows (popup blocker off) may need more.'),
1512
+ processNameMatch: zod_1.z.string().optional().describe('Override the derived processName needle for waitForWindow. Useful when `browser` basename doesn\'t match the actual exe (launchers, wrappers).'),
1513
+ titleMatch: zod_1.z.string().optional().describe('Title substring needle for waitForWindow. Case-insensitive.'),
1514
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1515
+ returnObservation: returnObservationSchema.optional().describe('Default "none" — freshly-opened URLs usually haven\'t rendered yet; agents typically pair with a wait_for + screenshot step.'),
1516
+ }, async ({ url, browser, waitForLoad, timeoutMs, processNameMatch, titleMatch, confirm, returnObservation }) => {
1517
+ try {
1518
+ const res = await client.automationOpenUrl({ url, browser, waitForLoad, timeoutMs, processNameMatch, titleMatch, confirm, returnObservation });
1519
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1520
+ }
1521
+ catch (err) {
1522
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1523
+ }
1524
+ });
1525
+ server.tool('superbased_drag_file', 'SCAFFOLD ONLY — drag a file from a source coord to a drop target. Returns errorCode:"UNSUPPORTED_YET" in v1 because the implementation needs a native Windows helper hosting IDataObject + IDropSource + DoDragDrop (COM STA message loop blocks the calling thread, so it cannot run inline in the adapter). The API SHAPE is stable and committed — { filePath, toX, toY, fromX?, fromY?, button?, path?, durationMs? } will remain unchanged when the helper lands in a follow-up phase, so code written against this tool today will work unmodified once the native path ships. WORKAROUNDS for agents that need file drag today: (a) manually arrange Explorer to show the file, then use superbased_drag with source coords at the file thumbnail and target coords at the drop destination; (b) for most apps, clipboard + superbased_hotkey Ctrl+V is equivalent to a drop; (c) browser file inputs accept superbased_click + superbased_dialog_handle fill_path instead of drag. See roadmap §5.1 for the deferred-implementation reference material. Sequence step variant: `{ action: "drag_file", filePath, toX, toY, ... }`.', {
1526
+ filePath: zod_1.z.string().min(1).describe('Absolute path to the file being dragged. Surfaced via CF_HDROP when the native helper lands.'),
1527
+ toX: zod_1.z.number().describe('Screen-space target x coordinate (virtual-screen pixels).'),
1528
+ toY: zod_1.z.number().describe('Screen-space target y coordinate.'),
1529
+ fromX: zod_1.z.number().optional().describe('Optional source coordinate. Defaults to current cursor position when unset.'),
1530
+ fromY: zod_1.z.number().optional().describe('Optional source coordinate.'),
1531
+ button: zod_1.z.enum(['left', 'right']).optional().describe('Default "left". "right" surfaces the shell\'s drag context menu (Copy here / Move here / Create shortcut / Cancel) on drop.'),
1532
+ path: zod_1.z.array(zod_1.z.object({ x: zod_1.z.number(), y: zod_1.z.number(), atMs: zod_1.z.number().optional() })).optional().describe('Optional non-linear drag path. Same waypoint contract as superbased_drag.'),
1533
+ durationMs: zod_1.z.number().optional().describe('Total drag duration in ms. Default 400ms — slightly slower than cursor drag because OLE targets need time to highlight hover states.'),
1534
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1535
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot". Ignored in the scaffold since the tool always returns UNSUPPORTED_YET.'),
1536
+ }, async ({ filePath, toX, toY, fromX, fromY, button, path, durationMs, confirm, returnObservation }) => {
1537
+ try {
1538
+ const res = await client.automationDragFile({ filePath, toX, toY, fromX, fromY, button, path, durationMs, confirm, returnObservation });
1539
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1540
+ }
1541
+ catch (err) {
1542
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1543
+ }
1544
+ });
1545
+ server.tool('superbased_virtual_desktop', 'Switch virtual desktops (Windows) or Spaces (macOS) one step to the left or right. Pure hotkey wrapper: Windows sends Win+Ctrl+Left or Win+Ctrl+Right via SendInput (system-scoped — no window target needed); macOS Spaces would send Ctrl+Left / Ctrl+Right but macOS sendHotkey is UNSUPPORTED_PLATFORM until Phase 7. Windows wraps at the edges: Win+Ctrl+Right on the last desktop stays there, and Win+Ctrl+Left on the first desktop stays there. To move multiple desktops, invoke this tool repeatedly (or use superbased_sequence to batch). ABSOLUTE "switch to desktop N" is NOT supported in v1 — Windows exposes that only via undocumented IVirtualDesktopManager COM interfaces with GUIDs that change between Windows builds; deferred until a user reports need. Returns a post-switch screenshot by default so the agent sees the new desktop\'s contents. Sequence step variant: `{ action: "virtual_desktop", direction }`.', {
1546
+ direction: zod_1.z.enum(['left', 'right']).describe('Relative direction. Windows: Win+Ctrl+Left / Win+Ctrl+Right. macOS Spaces (Phase 7): Ctrl+Left / Ctrl+Right.'),
1547
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1548
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-switch PNG. The tool waits 300ms after the hotkey to let the switch animation settle.'),
1549
+ }, async ({ direction, confirm, returnObservation }) => {
1550
+ try {
1551
+ const res = await client.automationVirtualDesktop({ direction, confirm, returnObservation });
1552
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1553
+ }
1554
+ catch (err) {
1555
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1556
+ }
1557
+ });
1558
+ server.tool('superbased_tray_click', 'Click a Windows system-tray (notification-area) icon by tooltip match. Enumerates Shell_TrayWnd\'s ToolbarWindow32 children via cross-process read of explorer.exe\'s button array (TBBUTTON + TB_GETBUTTONTEXTW + TB_GETITEMRECT), finds the single icon whose tooltip contains `tooltipMatch` (substring, case-insensitive by default), and issues a real OS-level click at that icon\'s center in virtual-screen coords. Use for "click the Slack tray icon to focus Slack", "right-click the OneDrive tray icon to open its menu", "click my background-app tray icon to restore its window". Default button is left (primary action, usually toggles the app window); button="right" opens the icon\'s context menu. Set `includeOverflow: true` to also search the caret "^" flyout (hidden icons the user moved behind the overflow popup). ERRORS: no-match → `TRAY_ICON_NOT_FOUND` with the full tooltip list surfaced in details.tooltips[] so the agent can self-correct; multi-match → `LOCATE_AMBIGUOUS` with details.alternatives[] — tighten the tooltipMatch or pass caseSensitive:true. Windows-only in S8 — macOS NSStatusItem enumeration requires private AppKit APIs; as a macOS fallback, use superbased_capture_template + superbased_find_image against a menu-bar region. Sequence step variant: `{ action: "tray_click", tooltipMatch, button?, caseSensitive?, includeOverflow? }`.', {
1559
+ tooltipMatch: zod_1.z.string().min(1).describe('Substring to match against the icon tooltip. Case-insensitive unless caseSensitive:true. Match must be unique — multiple matches return LOCATE_AMBIGUOUS.'),
1560
+ button: zod_1.z.enum(['left', 'right']).optional().describe('Default "left" (primary action, usually toggles the owning app). "right" opens the icon\'s context menu.'),
1561
+ caseSensitive: zod_1.z.boolean().optional().describe('Default false. Affects both tooltipMatch resolution and audit logging.'),
1562
+ includeOverflow: zod_1.z.boolean().optional().describe('Default false. When true, also enumerates the caret "^" overflow flyout (NotifyIconOverflowWindow). Windows 11 keeps overflow enumerable without opening the flyout; on Windows 10 some icons may only surface after the user has clicked the caret at least once this session.'),
1563
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1564
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-click PNG so the agent sees whatever menu / window the click triggered.'),
1565
+ }, async ({ tooltipMatch, button, caseSensitive, includeOverflow, confirm, returnObservation }) => {
1566
+ try {
1567
+ const res = await client.automationTrayClick({ tooltipMatch, button, caseSensitive, includeOverflow, confirm, returnObservation });
1568
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1569
+ }
1570
+ catch (err) {
1571
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1572
+ }
1573
+ });
1574
+ server.tool('superbased_tab_management', 'Browser tab operations via hotkey: new (Ctrl+T) / close (Ctrl+W) / next (Ctrl+Tab) / prev (Ctrl+Shift+Tab) / switch_to (Ctrl+<index>). ONE approval for ONE hotkey — useful for orchestration tasks like "open these three URLs", "close the trailing tabs", "cycle through tabs to find the Gmail one". FIVE actions: "new" opens a new tab (with optional `url` — types it into the focused address bar + Enter); "close" closes the active tab (typically fine; browsers prompt for unsaved forms); "next" / "prev" cycle through tabs (wraps around); "switch_to" jumps to a specific tab via Ctrl+<index> (1-indexed, values >=9 land on the LAST tab via Ctrl+9 on Chrome / Edge / Firefox). Requires window / processName / hwnd so the hotkey fires inside the right browser. NOT a replacement for superbased_open_url — use that when the target browser isn\'t running and you want to launch it. Windows-only in S6; macOS (Cmd+<letter>) lands Phase 7. Sequence step variant: `{ action: "tab_management", tabAction, url?, index? }` — note `tabAction` (not `action`) on the step to avoid colliding with the step discriminator.', {
1575
+ tabAction: zod_1.z.enum(['new', 'close', 'next', 'prev', 'switch_to']).describe('"new" = Ctrl+T (optionally plus `url` to navigate). "close" = Ctrl+W. "next" / "prev" = Ctrl+Tab / Ctrl+Shift+Tab. "switch_to" = Ctrl+<index> (requires `index`).'),
1576
+ url: zod_1.z.string().optional().describe('Optional for tabAction="new". When set, types the url + Enter after Ctrl+T (address bar auto-focuses on new tab in Chrome / Edge / Firefox). Ignored for other tabActions.'),
1577
+ index: zod_1.z.number().int().min(1).optional().describe('Required for tabAction="switch_to". 1-indexed. Browsers map Ctrl+1..Ctrl+8 to tabs 1..8 and Ctrl+9 to the LAST tab — pass index:9 to switch to last.'),
1578
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1579
+ window: zod_1.z.string().optional().describe('Window-title needle. ONE of window / processName / hwnd required — the hotkey fires inside this window.'),
1580
+ processName: zod_1.z.string().optional().describe('Exact process executable name. Common values: "chrome.exe", "msedge.exe", "firefox.exe".'),
1581
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring.'),
1582
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the action.'),
1583
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-action PNG.'),
1584
+ }, async ({ tabAction, url, index, confirm, window, processName, hwnd, restoreFocus, returnObservation }) => {
1585
+ try {
1586
+ const res = await client.automationTabManagement({ tabAction, url, index, confirm, window, processName, hwnd, restoreFocus, returnObservation });
1587
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1588
+ }
1589
+ catch (err) {
1590
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1591
+ }
1592
+ });
1593
+ server.tool('superbased_find_in_page', 'Browser find-in-page shortcut: Ctrl+F → type `query` → Enter (direction="next", default) or Shift+Enter (direction="prev") → optional Escape (when closeAfter=true) to close the find bar. Useful for jumping an agent to specific text on a long page BEFORE reading / clicking — faster than OCR + pixel scan, and works in any web content the browser renders (regular HTML, PDFs, docs.google.com, web IDEs). BEST-EFFORT: browsers occasionally change find-bar signatures across versions; a `FIND_BAR_UNKNOWN` errorCode means Ctrl+F fired but the target did not open a find bar (e.g. Notepad, a native UI, or a custom-skinned app). Agents should branch on that code. PATTERN: after the tool returns ok:true, the first match is scrolled into view + highlighted; the agent typically follows up with a screenshot or scroll to read the surrounding context. `closeAfter: true` is the right choice when the next step needs to type into the page itself (the find bar otherwise captures keystrokes). Requires window / processName / hwnd — the find bar opens in the active tab of the targeted window. Windows-only in S6; macOS (Cmd+F) lands Phase 7. Sequence step variant: `{ action: "find_in_page", query, direction?, closeAfter? }`.', {
1594
+ query: zod_1.z.string().min(1).describe('Text to search for on the page. Case-sensitivity matches the browser\'s find-bar default (usually case-insensitive; Chrome / Edge treat uppercase queries as case-sensitive when "Match case" is toggled — not controllable from this tool).'),
1595
+ direction: zod_1.z.enum(['next', 'prev']).optional().describe('Default "next" — Enter advances forward through matches. "prev" sends Shift+Enter to cycle backward. Matters only when the page has multiple matches.'),
1596
+ closeAfter: zod_1.z.boolean().optional().describe('Default false. When true, presses Escape after the navigate to close the find bar — useful when the next step needs to type into the page itself (otherwise the find bar captures keystrokes).'),
1597
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1598
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). ONE of window / processName / hwnd is required — the find bar opens in this window\'s active tab.'),
1599
+ processName: zod_1.z.string().optional().describe('Exact process executable name. Use "chrome.exe" / "msedge.exe" / "firefox.exe" for standard browsers; also works for any Electron app that honours Ctrl+F.'),
1600
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring.'),
1601
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the navigate.'),
1602
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-navigate PNG so the agent sees the highlighted match in context.'),
1603
+ }, async ({ query, direction, closeAfter, confirm, window, processName, hwnd, restoreFocus, returnObservation }) => {
1604
+ try {
1605
+ const res = await client.automationFindInPage({ query, direction, closeAfter, confirm, window, processName, hwnd, restoreFocus, returnObservation });
1606
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1607
+ }
1608
+ catch (err) {
1609
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1610
+ }
1611
+ });
1612
+ server.tool('superbased_dialog_handle', 'One-approval handling of common modal dialogs: confirm / dismiss / fill_path. Auto-detects the active dialog via the foreground window (modals own the foreground while open) — caller can also pin one explicitly via window/processName/hwnd. THREE actions: "confirm" clicks `buttonLabel` when set, else presses Enter (default dialog action — works for >95% of Windows MessageBox / File Save/Open / custom #32770 dialogs); "dismiss" presses Escape (cancels the dialog without saving); "fill_path" routes `path` into the dialog\'s filename field (AX-first via ValuePattern.SetValue on the first Edit control; falls back to Ctrl+A + Delete + type on SendInput) then presses Enter to confirm. USE WHEN: a click / launch / hotkey step triggered a modal and the agent needs to respond in the next turn without hand-crafting keystrokes. SAVE-AS PATTERN: preceding step triggers Save As (e.g. Ctrl+Shift+S) → dialog_handle dialogAction="fill_path" path="C:\\Users\\...\\file.txt" → done. Windows-only in S5 (NSSavePanel / NSOpenPanel / NSAlert land Phase 7). Sequence step variant: `{ action: "dialog_handle", dialogAction, path?, buttonLabel? }`.', {
1613
+ dialogAction: zod_1.z.enum(['confirm', 'dismiss', 'fill_path']).describe('"confirm" = click buttonLabel OR press Enter (default action). "dismiss" = press Escape. "fill_path" = route `path` into filename field (AX ValuePattern → type fallback) + Enter.'),
1614
+ path: zod_1.z.string().optional().describe('Required when dialogAction="fill_path". Absolute path to route into the dialog\'s filename field. Use forward or backslashes — File dialogs normalize both.'),
1615
+ buttonLabel: zod_1.z.string().optional().describe('Optional for dialogAction="confirm" — click the button with this label / visible text instead of pressing Enter. Useful for dialogs with multiple non-default options ("Yes to All", "Keep Both", etc.).'),
1616
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1617
+ window: zod_1.z.string().optional().describe('Optional: pin a specific dialog. Default = foreground window (modal dialogs own foreground while open).'),
1618
+ processName: zod_1.z.string().optional().describe('Exact process executable name. Use when multiple dialogs are stacked.'),
1619
+ hwnd: zod_1.z.string().optional().describe('Direct window handle. Bypasses scoring.'),
1620
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the action.'),
1621
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-action PNG (may show underlying app after dismiss / confirm closes the dialog).'),
1622
+ }, async ({ dialogAction, path, buttonLabel, confirm, window, processName, hwnd, restoreFocus, returnObservation }) => {
1623
+ try {
1624
+ const res = await client.automationDialogHandle({ dialogAction, path, buttonLabel, confirm, window, processName, hwnd, restoreFocus, returnObservation });
1625
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1626
+ }
1627
+ catch (err) {
1628
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1629
+ }
1630
+ });
1631
+ server.tool('superbased_form_fill', 'Macro: fill a multi-field form with ONE approval. Each field resolves via the reliability pyramid (automationId → role+name → label); value is written via UIA ValuePattern.SetValue (one shot, bypasses typing) when the control supports it, else falls back to click + clearFirst + type. Inter-field Tab advances focus (default; disable with tabBetweenFields:false). Optional submitLabel / submitAutomationId clicks / ax_invokes the Submit button after all fields are filled. ONE activation window for the whole form — focus leakage is impossible between steps. AUDIT: stores the macro invocation AND per-field events with a shared sessionId so "wrong field filled" is reviewable by querying ~/.superbased/audit.log for `sessionId=<id>`. USE WHEN: filling sign-up / checkout / config forms; any multi-field form where agents would otherwise chain N x click + type. AVOID WHEN: the form has conditional fields that appear/disappear based on prior entries (form_fill pre-validates all fields before starting — insert a wait_for / assert / separate form_fill call between dynamic sections). Windows-only in S5; macOS lands Phase 7. Sequence step variant: `{ action: "form_fill", fields: [...], submitLabel?, ... }`.', {
1632
+ fields: zod_1.z.array(zod_1.z.object({
1633
+ label: zod_1.z.string().optional().describe('OCR-based label resolution (pyramid bottom rung). Matches visible text NEAR the field — works when dev-tools-inspector-free UIs are the only option.'),
1634
+ automationId: zod_1.z.string().optional().describe('UIA AutomationId — top of pyramid; preferred. One field per UIA id.'),
1635
+ role: zod_1.z.string().optional().describe('UIA ControlType (e.g. "Edit", "ComboBox"). Paired with name.'),
1636
+ name: zod_1.z.string().optional().describe('Element Name. Paired with role.'),
1637
+ caseSensitive: zod_1.z.boolean().optional().describe('Default false for role+name and label.'),
1638
+ value: zod_1.z.string().describe('Text to enter. Routes through ValuePattern.SetValue when supported (bypasses typing); falls back to click + clearFirst + type.'),
1639
+ clearFirst: zod_1.z.boolean().optional().describe('Default true — Ctrl+A + Delete before typing on the fallback path. Ignored on ValuePattern.SetValue (SetValue always overwrites).'),
1640
+ })).min(1).max(50).describe('Fields to fill in order. Max 50 per call — agents should split larger forms across multiple form_fill calls. EACH field needs automationId OR role+name OR label; value is always required.'),
1641
+ submitLabel: zod_1.z.string().optional().describe('Label / visible text of the Submit button. Clicked after all fields are filled.'),
1642
+ submitAutomationId: zod_1.z.string().optional().describe('AutomationId of the Submit button. Preferred over submitLabel. Routed through ax_invoke with InvokePattern — more reliable than clicking.'),
1643
+ tabBetweenFields: zod_1.z.boolean().optional().describe('Default true. When false, no Tab between fields — the macro moves on only if each field keeps its value after the next click (some forms use explicit focus mgmt via automationId).'),
1644
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1645
+ window: zod_1.z.string().optional().describe('Window-title needle. Required (or processName/hwnd) — the whole macro runs inside this window.'),
1646
+ processName: zod_1.z.string().optional().describe('Exact process executable name.'),
1647
+ hwnd: zod_1.z.string().optional().describe('Direct window handle. Bypasses scoring.'),
1648
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the macro.'),
1649
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-macro PNG so agent can verify form state.'),
1650
+ }, async ({ fields, submitLabel, submitAutomationId, tabBetweenFields, confirm, window, processName, hwnd, restoreFocus, returnObservation }) => {
1651
+ try {
1652
+ const res = await client.automationFormFill({ fields, submitLabel, submitAutomationId, tabBetweenFields, confirm, window, processName, hwnd, restoreFocus, returnObservation });
1653
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1654
+ }
1655
+ catch (err) {
1656
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1657
+ }
1658
+ });
1659
+ server.tool('superbased_ax_invoke', 'Top-of-reliability-pyramid invocation: resolve a UI element via its AutomationId (preferred) or role+name, then call the matching UIA pattern directly — without synthesizing click / keystrokes. More reliable than coord-based click for controls that expose semantic patterns: buttons (Invoke), checkboxes / toggles (Toggle), radios / list items (SelectionItem.Select), text fields (Value.SetValue — overwrites existing contents in one shot, bypasses typing), tree / treeview / combobox (ExpandCollapse.Expand / ExpandCollapse.Collapse). USE WHEN: the control has a stable AutomationId, OR click-by-coord keeps missing hitboxes (custom-skinned UI), OR you need to set a long text field without typing overhead, OR you want to trigger a hidden/offscreen button the user can\'t see. AVOID WHEN: the control has no AutomationId AND no clean role+name (use superbased_click label=... instead — OCR-based); OR the pattern doesn\'t map to the action (e.g. "click a hyperlink" — links are InvokePattern in browsers but coord-click works equally). Returns ok:false errorCode:"LOCATE_NO_MATCH" if the element isn\'t in the UIA tree, "TARGET_HOSTILE" if the control doesn\'t support the requested pattern. Windows-only in S5 (UIA via managed-code PowerShell); macOS lands Phase 7 with @superbased/macos-ax. Sequence step variant: `{ action: "ax_invoke", automationId, pattern, ... }`.', {
1660
+ automationId: zod_1.z.string().optional().describe('UIA AutomationId — the stable dev-provided identifier (e.g. "SaveBtn", "EmailField"). TOP pyramid rung. Preferred. Pass EITHER automationId OR role+name.'),
1661
+ role: zod_1.z.string().optional().describe('UIA ControlType (e.g. "Button", "Edit", "CheckBox", "ListItem", "TreeItem"). Fallback when automationId is missing. Paired with name.'),
1662
+ name: zod_1.z.string().optional().describe('Element Name (UIA Name property — usually the visible text). Paired with role.'),
1663
+ caseSensitive: zod_1.z.boolean().optional().describe('Default false — role+name matching is case-insensitive.'),
1664
+ pattern: zod_1.z.enum(['Invoke', 'Toggle', 'SelectionItem.Select', 'Value.SetValue', 'ExpandCollapse.Expand', 'ExpandCollapse.Collapse']).describe('UIA pattern to invoke. "Invoke" = buttons / menu items (executes default action). "Toggle" = checkboxes / toggle-buttons (flips state). "SelectionItem.Select" = radio / list item (selects, may deselect siblings). "Value.SetValue" = text fields / combos (requires `value`; overwrites existing text in one shot). "ExpandCollapse.Expand" / ".Collapse" = tree nodes / combos / expander UI.'),
1665
+ value: zod_1.z.string().optional().describe('Required when pattern="Value.SetValue". The text to write into the field. Bypasses typing entirely — no per-character events, no autocomplete interference. If the ValuePattern is read-only (e.g. a disabled field), returns ok:false errorCode:"TARGET_HOSTILE".'),
1666
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1667
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Required (or processName/hwnd) — pattern invocation walks the UIA tree starting from the target window.'),
1668
+ processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision target.'),
1669
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring.'),
1670
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-invoke PNG so the agent can verify state.'),
1671
+ }, async ({ automationId, role, name, caseSensitive, pattern, value, confirm, window, processName, hwnd, returnObservation }) => {
1672
+ try {
1673
+ const res = await client.automationAxInvoke({ automationId, role, name, caseSensitive, pattern, value, confirm, window, processName, hwnd, returnObservation });
1674
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1675
+ }
1676
+ catch (err) {
1677
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1678
+ }
1679
+ });
1680
+ server.tool('superbased_launch_app', 'Start a process or open a URL via ShellExecute. Pass EXACTLY ONE of { path, name, url }: `path` = absolute or relative path to exe/document (resolved to absolute before allowlist match); `name` = app name resolvable via PATH (e.g. "notepad"); `url` = http/https (opens in default browser). TWO gates: (a) guiAutomation.actions.launch must be true (OFF by default), AND (b) the target must match an entry in guiAutomation.launchAllowlist (EMPTY by default = deny-all). Allowlist entries: plain substring (case-insensitive against resolved path/name/url), or `"sha256:<hex>"` binary-hash pin for path mode (recommended for password managers). Optional `waitForWindow: true` polls for the launched app\'s window to appear (matches on processName + titleMatch; derives processName from path basename by default). Windows-only in S3; macOS lands Phase 7. Returns { pid, window? } in details; does not auto-focus — chain superbased_focus_window or use superbased_sequence targets[] for follow-up actions.', {
1681
+ path: zod_1.z.string().optional().describe('Path to executable or document. Resolved to absolute BEFORE allowlist match. Pass EITHER path, name, OR url — not multiple.'),
1682
+ name: zod_1.z.string().optional().describe('App name resolvable via PATH (e.g. "notepad", "code"). Substring-matched against the allowlist.'),
1683
+ url: zod_1.z.string().optional().describe('URL to open (http/https). Opens in default browser via ShellExecute; use superbased_open_url (4.7, S6) for explicit browser selection.'),
1684
+ args: zod_1.z.array(zod_1.z.string()).optional().describe('Arguments passed to the process. Ignored for URL mode.'),
1685
+ workingDir: zod_1.z.string().optional().describe('Working directory for the spawned process. Ignored for URL mode.'),
1686
+ waitForWindow: zod_1.z.boolean().optional().describe('When true, polls listWindows() until a window appears matching processNameMatch / titleMatch (or defaults derived from path basename / name). Default 5000ms timeout. Returns ok:false errorCode:"TIMEOUT" if the window doesn\'t appear — the process is still running.'),
1687
+ timeoutMs: zod_1.z.number().optional().describe('waitForWindow deadline in ms. Default 5000.'),
1688
+ processNameMatch: zod_1.z.string().optional().describe('Override for the derived processName needle used by waitForWindow. Case-insensitive substring match.'),
1689
+ titleMatch: zod_1.z.string().optional().describe('Title substring needle for waitForWindow. Case-insensitive.'),
1690
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1691
+ returnObservation: returnObservationSchema.optional().describe('Default "none" — freshly-launched apps may still be loading, so we don\'t auto-screenshot. Pass "screenshot" to capture the launched window after waitForWindow finds it.'),
1692
+ }, async ({ path, name, url, args, workingDir, waitForWindow, timeoutMs, processNameMatch, titleMatch, confirm, returnObservation }) => {
1693
+ try {
1694
+ const res = await client.automationLaunchApp({ path, name, url, args, workingDir, waitForWindow, timeoutMs, processNameMatch, titleMatch, confirm, returnObservation });
1695
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1696
+ }
1697
+ catch (err) {
1698
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1699
+ }
1700
+ });
1701
+ server.tool('superbased_drag', 'Drag from (fromX, fromY) to (toX, toY) with the specified mouse button. Press → interpolate (linear, configurable steps + duration) → release. 3.3: accepts `path` with multi-point waypoints for non-linear trajectories (signature-style drags, curved reorder gestures, chain selection) — each waypoint may carry `atMs` to pace segments unevenly. When path is provided AND fromX/Y/toX/Y are set, waypoints are inserted BETWEEN start and end. When path is provided WITHOUT from/to, path is used as-is (must have ≥2 waypoints). Use cases: reordering list items, dragging files/icons, resizing via a handle, moving sliders, HTML5 drag-and-drop on websites (real OS-level mouse events trigger Chromium\'s dragstart/dragend), shape-drawing. Modifiers (Shift/Ctrl/Alt/Meta) wrap the whole drag — e.g. Ctrl+drag to copy in many file managers. Window/process targeting same as superbased_click. AUTO-SNAPSHOT: returns post-drag PNG inline.', {
1702
+ fromX: zod_1.z.number().optional().describe('Start X (virtual-screen logical pixels). Optional when `path` has ≥2 waypoints — otherwise required.'),
1703
+ fromY: zod_1.z.number().optional().describe('Start Y. Required together with fromX.'),
1704
+ toX: zod_1.z.number().optional().describe('End X. Required together with fromX/fromY unless path-only mode.'),
1705
+ toY: zod_1.z.number().optional().describe('End Y.'),
1706
+ path: zod_1.z.array(zod_1.z.object({
1707
+ x: zod_1.z.number().describe('Waypoint X.'),
1708
+ y: zod_1.z.number().describe('Waypoint Y.'),
1709
+ atMs: zod_1.z.number().optional().describe('Target elapsed time (ms from drag start) when cursor should reach this waypoint. Enables non-linear pacing: e.g. a 300ms total drag with waypoints at atMs=0/50/250/300 lingers mid-path. Missing atMs = equal time-slicing across `durationMs`.'),
1710
+ })).optional().describe('Waypoints between start and end (or the full path in path-only mode). Segment timings honour per-waypoint atMs deltas when set; otherwise split totalDuration equally.'),
1711
+ durationMs: zod_1.z.number().optional().describe('Total drag duration in ms. Default 200. Drag-sensitive UIs (Chromium DnD) need ~150-300ms with intermediate moves. Ignored per-segment when atMs is on every waypoint.'),
1712
+ steps: zod_1.z.number().optional().describe('Number of intermediate move events per segment. Default 10. Higher = smoother for animation-tracking UIs.'),
1713
+ button: zod_1.z.enum(['left', 'right']).optional().describe('Default "left". Right-button drag is rare but used by some file managers (drag-with-context-menu).'),
1714
+ modifiers: zod_1.z.array(zod_1.z.enum(['shift', 'ctrl', 'alt', 'meta'])).optional().describe('Modifier keys held during the entire drag. E.g. ["ctrl"] for Ctrl+drag (copy in Explorer / Finder).'),
1715
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1716
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1717
+ processName: zod_1.z.string().optional().describe('Exact process executable name.'),
1718
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1719
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the drag.'),
1720
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-drag PNG.'),
1721
+ humanize: zod_1.z.enum(['off', 'light', 'human', 'paranoid']).optional().describe('Per-call override of the global humanInputDefault setting. Substitutes each linear segment with a Bezier curve — perpendicular jittered control points, optional overshoot+pullback at the endpoints. "off" keeps linear paths; "light" (default global) adds modest curvature; "human" / "paranoid" raise control-point count and overshoot probability for adversarial detectors. Windows pre/post-press dwells (20/50/100/50ms) stay intact regardless of profile — they live inside the platform adapter, outside the path.'),
1722
+ }, async ({ fromX, fromY, toX, toY, path, durationMs, steps, button, modifiers, confirm, window, processName, hwnd, restoreFocus, returnObservation, humanize }) => {
1723
+ try {
1724
+ const res = await client.automationDrag({ fromX, fromY, toX, toY, path, durationMs, steps, button, modifiers, confirm, window, processName, hwnd, restoreFocus, returnObservation, humanize });
1725
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1726
+ }
1727
+ catch (err) {
1728
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1729
+ }
1730
+ });
1731
+ server.tool('superbased_pixel_color', 'Read the RGBA color of a single pixel at virtual-screen (x, y). Pure screen-read; no input injection. Use to verify visual state that text/AX can\'t express: dark-mode vs light-mode toggle state, status LEDs in toolbars, tab-active highlight colors, progress bars, canvas pixel inspection. Pass `expected: "#RRGGBB"` to get an automatic `matches` boolean in the response, with optional `tolerance` (0-255 per channel, default 0 for exact match). ALSO UNBLOCKS sequence primitives: `step.action:"wait_for" condition:{type:"pixelColor", x, y, expected, tolerance?}` to wait for a visual state change; same shape under `step.action:"assert"` to fail a sequence early; `step.locate:{pixelColor:"#RRGGBB", near:{x,y}}` to drive coord-based actions off a color check. Windows-only today; macOS lands with Phase 7 (CGDisplayCreateImage + 1×1 crop) — returns UNSUPPORTED_PLATFORM until then. Per-call cost is ~80-150ms (fullscreen capture + 1×1 sharp crop) — avoid hammering; use wait_for for polling.', {
1732
+ x: zod_1.z.number().describe('Absolute x (virtual-screen logical pixels).'),
1733
+ y: zod_1.z.number().describe('Absolute y.'),
1734
+ expected: zod_1.z.string().optional().describe('Expected color as #RRGGBB or #RRGGBBAA hex. When set, the response includes a `matches` boolean comparing actual vs expected within `tolerance`.'),
1735
+ tolerance: zod_1.z.number().optional().describe('Per-channel tolerance (0-255) for the `matches` compare. Default 0 (exact). Raise to 8-16 for antialiased UI edges, 32+ for theme-variant robustness.'),
1736
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt. pixel_color is read-only so the confirm is purely a consent checkpoint.'),
1737
+ }, async ({ x, y, expected, tolerance, confirm }) => {
1738
+ try {
1739
+ const res = await client.automationPixelColor({ x, y, expected, tolerance, confirm });
1740
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1741
+ }
1742
+ catch (err) {
1743
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1744
+ }
1745
+ });
1746
+ server.tool('superbased_hover', 'Move the cursor to (x, y) — or a resolved UI element — and dwell for `dwellMs` so tooltips and hover-reveal UIs can render. No button press. Use BEFORE superbased_ui_dump when the target only renders on hover (tooltip text, dropdown preview, hover-only buttons in a toolbar). Pass label/automationId/role+name instead of x/y to resolve by reliability pyramid (same rails as superbased_click). Window/process targeting: PREFERRED pass processName= / hwnd= on THIS call — the tool activates, hovers+dwells, and restores in ONE MCP turn; chaining superbased_focus_window before defeats the activation (the approval prompt steals focus back). AUTO-SNAPSHOT (default): returns post-hover PNG inline so the tooltip or revealed element is visible to the agent without a separate screenshot call.', {
1747
+ x: zod_1.z.number().optional().describe('Absolute x (virtual-screen logical pixels). Pass EITHER x+y OR label/automationId/role+name.'),
1748
+ y: zod_1.z.number().optional().describe('Absolute y.'),
1749
+ label: zod_1.z.string().optional().describe('Visible text to hover over (OCR-resolved).'),
1750
+ automationId: zod_1.z.string().optional().describe('AX AutomationId — most reliable locator.'),
1751
+ role: zod_1.z.string().optional().describe('AX role (pair with name=).'),
1752
+ name: zod_1.z.string().optional().describe('AX accessible name (pair with role=).'),
1753
+ caseSensitive: zod_1.z.boolean().optional().describe('Default false — case-insensitive label/role-name match.'),
1754
+ dwellMs: zod_1.z.number().optional().describe('How long to dwell after the move (ms). Default 0. Set 400-800ms for tooltips to appear; some apps need 1000-1500ms. Counted against sequence maxDurationMs when used inside superbased_sequence.'),
1755
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1756
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1757
+ processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision target.'),
1758
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1759
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the hover.'),
1760
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-hover PNG inline so the tooltip is visible. "full" adds OCR + AX textElements with coords. "none" suppresses.'),
1761
+ humanize: zod_1.z.enum(['off', 'light', 'human', 'paranoid']).optional().describe('Per-call override of the global humanInputDefault setting. When non-"off", the cursor follows a Bezier curve from its current position to (x, y) BEFORE the dwell starts. Useful for hover-reveal UIs that watch for natural-looking approach paths (some tooltips suppress on teleport-then-stop heuristics). Move skipped for tiny hops (<4px). Cross-platform.'),
1762
+ }, async ({ x, y, label, automationId, role, name, caseSensitive, dwellMs, confirm, window, processName, hwnd, restoreFocus, returnObservation, humanize }) => {
1763
+ try {
1764
+ const res = await client.automationHover({ x, y, label, automationId, role, name, caseSensitive, dwellMs, confirm, window, processName, hwnd, restoreFocus, returnObservation, humanize });
1765
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1766
+ }
1767
+ catch (err) {
1768
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1769
+ }
1770
+ });
1771
+ server.tool('superbased_context_menu_select', 'Right-click at (x, y) → wait for the context-menu popup → click the menu item matching `menuItemText`. ONE approval covers the whole flow (vs the 4-call dance: right-click + ui_dump + locate + click). Match prefers exact text over substring; ties broken by shortest item text. Returns CONTEXT_MENU_NOT_DETECTED when the popup is invisible to EnumWindows — typical for WPF/WinUI custom-drawn menus, shell-IContextMenu integrations (Explorer right-click), and ownerless popups. On those, fall back to a fullscreen `superbased_ui_dump` + `superbased_click` on the matched item. RELATED: `superbased_click button:"right" returnObservation:"screenshot"` attaches `observation.contextMenu: { hwnd, bounds }` automatically when a popup is detected — use that for inspecting the menu items first; use `superbased_context_menu_select` when you already know which item to click. Windows-only in S1; macOS uses kAXMenuOpenedNotification (Phase 7).', {
1772
+ x: zod_1.z.number().describe('Right-click X (virtual-screen logical pixels).'),
1773
+ y: zod_1.z.number().describe('Right-click Y.'),
1774
+ menuItemText: zod_1.z.string().describe('Text of the menu item to click. Matched against OCR + AX text in the popup; exact match preferred over substring.'),
1775
+ caseSensitive: zod_1.z.boolean().optional().describe('Default false — menuItemText match is case-insensitive.'),
1776
+ timeoutMs: zod_1.z.number().optional().describe('How long to wait for the popup to appear after the right-click. Default 2000ms; bump to 4000+ for slow apps.'),
1777
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1778
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Required when targeting a non-foreground window.'),
1779
+ processName: zod_1.z.string().optional().describe('Exact process executable name.'),
1780
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list).'),
1781
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the menu item is clicked.'),
1782
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-click PNG.'),
1783
+ }, async ({ x, y, menuItemText, caseSensitive, timeoutMs, confirm, window, processName, hwnd, restoreFocus, returnObservation }) => {
1784
+ try {
1785
+ const res = await client.automationContextMenuSelect({ x, y, menuItemText, caseSensitive, timeoutMs, confirm, window, processName, hwnd, restoreFocus, returnObservation });
1786
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1787
+ }
1788
+ catch (err) {
1789
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1790
+ }
1791
+ });
1792
+ server.tool('superbased_scroll', 'Single-step scroll. If your goal is to walk through a whole scrollable section / page, STOP and use `superbased_scroll_capture` instead — one approval gives you N calibrated viewports with frames back; chaining this tool in a loop costs one approval per step. Use THIS tool only for (a) a single targeted scroll (e.g. "bring row X into view"), (b) scrolling after you already know exactly how much to move, or (c) when you need keyboard-delivery semantics (unit="line" arrow nudges). Scroll with CALIBRATED pixel-accuracy for unit="page" — same algorithm SuperBased\'s auto-scroll-capture uses. Measures pixels-per-tick for the target window on first use (~600-900ms one-time cost per hwnd; cached 10min), then uses that measurement to scroll exactly one viewport with 10% overlap. Delivery uses Win32 mouse_event (bypasses nut-js synthetic events that Electron drops). ANCHOR: pass anchorX + anchorY to position the cursor BEFORE the scroll fires — critical when the target window has multiple scroll containers (sidebar + content). Windows routes wheel events to the window under the cursor, so without an anchor, the scroll hits whatever the cursor was last over (usually the wrong panel). Grab anchor coords from a ui_dump textElement\'s center.{x,y} inside the container you want to scroll. Positive amount = down, negative = up. unit="ticks" (default, legacy): amount = wheel ticks. unit="page" (RECOMMENDED for pagination): amount = viewport pages. unit="line": amount = arrow-key nudges. ATEND SIGNAL: response details.atEnd = true when pre/post screenshots show no movement = hit end of content. Use to terminate pagination loops without follow-up ui_dump. AUTO-SNAPSHOT: returns post-scroll PNG inline (no separate screenshot needed). Window/process targeting same as superbased_click — pass processName/hwnd on THIS call; NEVER chain superbased_focus_window before.', {
1793
+ amount: zod_1.z.number().describe('Scroll amount. unit="ticks" (default): wheel ticks. unit="page": viewport pages (calibrated). unit="line": arrow-key presses. Positive = down, negative = up.'),
1794
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1795
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1796
+ processName: zod_1.z.string().optional().describe('Exact process executable name.'),
1797
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1798
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after scroll.'),
1799
+ method: zod_1.z.enum(['wheel', 'keys', 'auto']).optional().describe('Default "auto". Windows+hasTarget: uses Win32 mouse_event (bypasses Electron synthetic-event drops). "keys" forces keyboard-only (requires keyboard focus on the container — unreliable on Electron).'),
1800
+ unit: zod_1.z.enum(['ticks', 'page', 'line']).optional().describe('Default "ticks". "page" = CALIBRATED scroll of one viewport per unit (RECOMMENDED for vertical pagination; axis="x" falls back to tick count since calibration is vertical-only). "line" = arrow-key nudges.'),
1801
+ axis: zod_1.z.enum(['y', 'x']).optional().describe('2.5: Scroll axis. Default "y" (vertical). "x" uses Windows MOUSEEVENTF_HWHEEL (with Shift+Wheel fallback) so real horizontal-scroll bars (Excel, wide tables, Chromium horizontal overflow) actually move. Positive amount = RIGHT, negative = LEFT. unit="page" is not calibrated for axis="x" and reverts to tick count.'),
1802
+ anchorX: zod_1.z.number().optional().describe('Physical screen X where the cursor moves before scrolling. Pass a point INSIDE the scroll container you want to page (typically grabbed from a ui_dump textElement.center.x). Windows routes wheel events to the window under the cursor.'),
1803
+ anchorY: zod_1.z.number().optional().describe('Physical screen Y for the anchor. See anchorX.'),
1804
+ recalibrate: zod_1.z.boolean().optional().describe('Force a fresh calibration even if cache has a valid entry. Use after resizing or re-laying-out the target window.'),
1805
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-scroll PNG. "full" adds OCR + AX textElements. "none" suppresses.'),
1806
+ }, async ({ amount, confirm, window, processName, hwnd, restoreFocus, method, unit, axis, anchorX, anchorY, recalibrate, returnObservation }) => {
1807
+ try {
1808
+ const res = await client.automationScroll({ amount, confirm, window, processName, hwnd, restoreFocus, method, unit, axis, anchorX, anchorY, recalibrate, returnObservation });
1809
+ return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1810
+ }
1811
+ catch (err) {
1812
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1813
+ }
1814
+ });
1815
+ server.tool('superbased_ui_dump', 'Read the CURRENT viewport state in ONE call — screenshot + every visible text element with ready-to-click coordinates + AX tree. Use this when the page fits on screen OR you just need to see / act on what\'s CURRENTLY visible. If the page is longer than the viewport and you need to WALK THROUGH it (settings panel, long list, scrollable section), use `superbased_scroll_capture` instead — one approval walks the whole section and returns N frames with coords for each. ui_dump is one viewport; scroll_capture is N viewports. Returns screenshot + all visible text elements (OCR words + OCR lines + accessibility-tree-labeled nodes) with coordinates + accessibility tree (when the optional @superbased/win-uia / @superbased/macos-ax binding is installed) + window metadata. Replaces the screenshot → superbased_locate → "label not found" → screenshot → guess-coordinates loop that floods the agent UI with calls. Use this BEFORE reaching for individual click/type calls whenever you need to "see what is on the page." All returned text elements come with `bbox` + `center` coordinates ready to feed into `superbased_click` / `superbased_sequence`. textElements are sorted top-to-bottom, left-to-right reading order, deduplicated across OCR + AX sources (AX-tree labels win over OCR when both see the same element). `background: true` on Windows uses PrintWindow for zero focus flicker. `ocrScaleFactor: 2` rescues small-text UIs. `includeAxTree` (default true) auto-skips with a structured note when the native binding is missing. Returns the screenshot as an MCP image content block.', {
1816
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). When omitted, dumps the foreground window / full screen.'),
1817
+ processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision target.'),
1818
+ hwnd: zod_1.z.string().optional().describe('Direct window handle from superbased_window_list.'),
1819
+ background: zod_1.z.boolean().optional().describe('Default true — use PrintWindow on Windows for zero focus flicker (requires hwnd resolvable). Falls back to captureScreen when not applicable.'),
1820
+ includeScreenshot: zod_1.z.boolean().optional().describe('Default true — emit PNG as an MCP image content block.'),
1821
+ includeOcr: zod_1.z.boolean().optional().describe('Default true — run Tesseract OCR and include words + lines with coordinates.'),
1822
+ includeAxTree: zod_1.z.boolean().optional().describe('Default true — include accessibility tree when the native binding is installed. Auto-skips with a structured note otherwise.'),
1823
+ ocrScaleFactor: zod_1.z.number().optional().describe('Default 1. Set 2 to upscale before OCR — rescues small-text UIs (sidebar labels, status bars) that native-resolution Tesseract misses.'),
1824
+ ocrMinConfidence: zod_1.z.number().optional().describe('Default 30 (0-100). Raise to filter low-confidence OCR noise.'),
1825
+ }, async ({ window, processName, hwnd, background, includeScreenshot, includeOcr, includeAxTree, ocrScaleFactor, ocrMinConfidence }) => {
1826
+ try {
1827
+ const res = await client.automationUiDump({ window, processName, hwnd, background, includeScreenshot, includeOcr, includeAxTree, ocrScaleFactor, ocrMinConfidence });
1828
+ const data = res.data;
1829
+ const content = [
1830
+ { type: 'text', text: formatResponse({
1831
+ ok: data.ok,
1832
+ error: data.error,
1833
+ window: data.window,
1834
+ screenshot: data.screenshot ? { width: data.screenshot.width, height: data.screenshot.height, mimeType: data.screenshot.mimeType } : undefined,
1835
+ textElementCount: data.textElements?.length ?? 0,
1836
+ textElements: data.textElements,
1837
+ axTree: data.axTree ? { available: data.axTree.available, error: data.axTree.error, nodeCount: data.axTree.nodeCount } : undefined,
1838
+ timings: data.timings,
1839
+ backgroundMode: data.backgroundMode,
1840
+ capturePathUsed: data.capturePathUsed,
1841
+ dpiScale: data.dpiScale,
1842
+ diagnostic: data.diagnostic,
1843
+ }) },
1844
+ ];
1845
+ if (data.screenshot?.imageBase64) {
1846
+ content.push({ type: 'image', data: data.screenshot.imageBase64, mimeType: 'image/png' });
1847
+ }
1848
+ return { content, isError: !data.ok };
1849
+ }
1850
+ catch (err) {
1851
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1852
+ }
1853
+ });
1854
+ server.tool('superbased_scroll_to', 'Scroll until a text label is visible — PREFERRED when you know WHAT to find but not WHERE in a long scrollable region. Runs a bounded loop server-side in ONE MCP call under ONE permission approval: (1) ui_dump the current viewport (OCR + AX tree), (2) search textElements for targetText, (3) if found return coords + final screenshot; else (4) scroll one page (PageDown keys — predictable regardless of wheel-tick sensitivity), (5) check atEnd via pre/post similarity; bail if the viewport didn\'t move (end of scrollable content). Up to maxPages iterations (default 10, capped at 50). Replaces the 15-20+ call "scroll → screenshot → scroll → screenshot" loop agents fall into when exploring a long sidebar / menu / list. Returns { found, match: UiTextElement with center coords, matches: all hits, pagesScrolled, atEnd } — agent feeds match.center.{x,y} directly into superbased_click or superbased_sequence. matchMode defaults to substring (most useful for agents); set "exact" for whole-element match. caseSensitive defaults false. ocrScaleFactor forwarded to inner ui_dump — bump to 2 for small-text sidebars.', {
1855
+ targetText: zod_1.z.string().describe('Text to scroll to. Substring match by default (see matchMode).'),
1856
+ direction: zod_1.z.enum(['down', 'up']).optional().describe('Scroll direction. Default "down".'),
1857
+ maxPages: zod_1.z.number().optional().describe('Max page-scroll iterations before giving up. Default 10, capped at 50. Each iteration = 1 PageDown + 1 ui_dump.'),
1858
+ matchMode: zod_1.z.enum(['exact', 'substring']).optional().describe('Default "substring" (element text INCLUDES target). "exact" requires whole-element match.'),
1859
+ caseSensitive: zod_1.z.boolean().optional().describe('Default false.'),
1860
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt. ONE confirm covers the whole loop.'),
1861
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Applied ONCE at loop start.'),
1862
+ processName: zod_1.z.string().optional().describe('Exact process executable name (highest precision).'),
1863
+ hwnd: zod_1.z.string().optional().describe('Direct window handle from superbased_window_list.'),
1864
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the entire loop completes.'),
1865
+ returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — returns final-state PNG (the frame where target was found, or where we bailed). "full" adds OCR + AX textElements. "none" suppresses.'),
1866
+ ocrScaleFactor: zod_1.z.number().optional().describe('Default 1. Set 2 to upscale before OCR — rescues small-text sidebars / menus where native-res Tesseract misses labels.'),
1867
+ }, async ({ targetText, direction, maxPages, matchMode, caseSensitive, confirm, window, processName, hwnd, restoreFocus, returnObservation, ocrScaleFactor }) => {
1868
+ try {
1869
+ const res = await client.automationScrollTo({ targetText, direction, maxPages, matchMode, caseSensitive, confirm, window, processName, hwnd, restoreFocus, returnObservation, ocrScaleFactor });
1870
+ const data = res.data;
1871
+ // Emit image content block (the final observation) + text with full JSON
1872
+ // (with imageBase64 stripped — image goes separately).
1873
+ const obs = data.observation;
1874
+ const textProjection = {
1875
+ ok: data.ok,
1876
+ error: data.error,
1877
+ found: data.found,
1878
+ pagesScrolled: data.pagesScrolled,
1879
+ atEnd: data.atEnd,
1880
+ match: data.match,
1881
+ matches: data.matches,
1882
+ method: data.method,
1883
+ confidence: data.confidence,
1884
+ details: data.details,
1885
+ observation: obs ? { width: obs.width, height: obs.height, mimeType: obs.mimeType, backgroundMode: obs.backgroundMode, dpiScale: obs.dpiScale, textElementCount: obs.textElements?.length ?? 0 } : undefined,
1886
+ };
1887
+ const content = [
1888
+ { type: 'text', text: formatResponse(textProjection) },
1889
+ ];
1890
+ if (obs?.imageBase64) {
1891
+ content.push({ type: 'image', data: obs.imageBase64, mimeType: obs.mimeType });
1892
+ }
1893
+ return { content, isError: !data.ok };
1894
+ }
1895
+ catch (err) {
1896
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1897
+ }
1898
+ });
1899
+ server.tool('superbased_scroll_capture', 'EXPLORATORY SCROLL — the MCP equivalent of the desktop Ctrl+Shift+A / Cmd+Shift+A hotkey. ONE permission approval walks the full scrollable section: calibrate → scroll → capture → repeat until end. PREFERRED whenever the task is "scroll through X and show me what\'s on the page" or "walk through this settings panel." DO NOT chain individual superbased_scroll calls for this pattern — each costs its own approval. This tool gives you N frames under ONE approval. Behavior under that one approval: (1) capture initial frame. (2) Inline calibration — first scroll IS the measurement (no visible rewind dance; natural forward scrolling only). When calibration is low-confidence on noisy content, the tool falls back to a typical Chromium/Electron heuristic (40 px/tick) with lowConfidence:true flagged — never returns a hard calibration error. (3) Continue scrolling one calibrated viewport at a time with 10% overlap, capturing each frame. (4) Stops when pixel-offset between consecutive frames < 3 px (atEnd) or maxPages hit. Returns ALL frames inline as MCP image content blocks + per-frame scrolledPx + calibration diagnostic. A Settings-page walkthrough that previously took 5-10 separate scroll-then-screenshot approvals now takes 1. Requires a target window (hwnd / processName / window) and an anchor inside the scroll container (grab from a ui_dump textElement). Windows only (uses Win32 mouse_event + PrintWindow; cross-platform is a follow-up).', {
1900
+ anchorX: zod_1.z.number().describe('Physical screen X inside the scroll container you want to page through. Grab from a ui_dump textElement\'s center.x.'),
1901
+ anchorY: zod_1.z.number().describe('Physical screen Y for the anchor. See anchorX.'),
1902
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1903
+ processName: zod_1.z.string().optional().describe('Exact process executable name (highest precision).'),
1904
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1905
+ direction: zod_1.z.enum(['down', 'up']).optional().describe('Scroll direction. Default "down".'),
1906
+ maxPages: zod_1.z.number().optional().describe('Max page-scroll iterations (default 8, capped at 20). Each iteration = 1 calibrated viewport advance + 1 captured frame. Bumping this past 8 blows up response size; prefer targeted maxPages + re-invocation if you need to keep going.'),
1907
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt. ONE confirm covers the whole loop.'),
1908
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the entire capture loop completes.'),
1909
+ recalibrate: zod_1.z.boolean().optional().describe('Force a fresh calibration even if cache has a valid entry. Use after resizing / re-laying-out the target window.'),
1910
+ stopOnAtEnd: zod_1.z.boolean().optional().describe('Default true — stop when a scroll yields <3px of content movement (end of scrollable content). Set false to capture exactly maxPages frames regardless of content.'),
1911
+ settleMs: zod_1.z.number().optional().describe('Post-scroll settle delay per iteration in ms. Default 400. Bump to 600-800 if the target does heavy smooth-scroll animations and early captures look mid-frame.'),
1912
+ }, async ({ anchorX, anchorY, window, processName, hwnd, direction, maxPages, confirm, restoreFocus, recalibrate, stopOnAtEnd, settleMs }) => {
1913
+ try {
1914
+ const res = await client.automationScrollCapture({ anchorX, anchorY, window, processName, hwnd, direction, maxPages, confirm, restoreFocus, recalibrate, stopOnAtEnd, settleMs });
1915
+ const data = res.data;
1916
+ // Emit each captured frame as an MCP image content block. Text
1917
+ // block carries metadata + scrolledPx per frame (stripped of the
1918
+ // base64 duplicates).
1919
+ const frames = data.frames ?? [];
1920
+ const framesMeta = frames.map((f) => ({ page: f.page, width: f.width, height: f.height, fullResWidth: f.fullResWidth, fullResHeight: f.fullResHeight, savedPath: f.savedPath, scrolledPx: f.scrolledPx, timestampMs: f.timestampMs }));
1921
+ const textProjection = {
1922
+ ok: data.ok,
1923
+ error: data.error,
1924
+ framesCaptured: data.framesCaptured,
1925
+ pagesScrolled: data.pagesScrolled,
1926
+ atEnd: data.atEnd,
1927
+ atEndReason: data.atEndReason,
1928
+ calibration: data.calibration,
1929
+ calibrationFramesPath: data.calibrationFramesPath,
1930
+ dpiScale: data.dpiScale,
1931
+ sessionDir: data.sessionDir,
1932
+ frames: framesMeta,
1933
+ details: data.details,
1934
+ };
1935
+ const content = [
1936
+ { type: 'text', text: formatResponse(textProjection) },
1937
+ ];
1938
+ for (const f of frames) {
1939
+ if (f.imageBase64) {
1940
+ content.push({ type: 'image', data: f.imageBase64, mimeType: 'image/png' });
1941
+ }
1942
+ }
1943
+ return { content, isError: !data.ok };
1944
+ }
1945
+ catch (err) {
1946
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1947
+ }
1948
+ });
1949
+ server.tool('superbased_sequence', 'Run MULTIPLE GUI-automation steps in ONE MCP call under ONE permission approval. This is the PREFERRED tool for any multi-step GUI task — replaces the 10-20+ call loop of screenshot → locate → click → screenshot → click → ... that floods the agent UI with approval prompts and steals focus on each prompt click. Steps execute server-side inside ONE activation window: target is focused once at sequence start, restored once at the end, all steps run with stable focus context. Pass window= / processName= / hwnd= on THIS call to target a specific window (ONE activation for the whole flow, zero mid-sequence focus flicker). GUI automation master toggle + per-action toggles still apply; sequence refuses if any action type used inside is disabled. `confirm: true` required ONCE — same approval covers all steps. `stopOnError` defaults true (halts + returns results so far). Each step returns `{ step, action, ok, error?, imageBase64?, width?, height?, durationMs }` — screenshot steps include the image inline so the agent can read multiple frames across the flow without extra calls. Max 50 steps per sequence.', {
1950
+ steps: zod_1.z.array(zod_1.z.discriminatedUnion('action', [
1951
+ zod_1.z.object({
1952
+ action: zod_1.z.literal('click'),
1953
+ x: zod_1.z.number().describe('Absolute x px'),
1954
+ y: zod_1.z.number().describe('Absolute y px'),
1955
+ button: zod_1.z.enum(['left', 'right', 'middle']).optional(),
1956
+ doubleClick: zod_1.z.boolean().optional(),
1957
+ returnObservation: returnObservationSchema.optional().describe('Default "none" in sequences (payload-size safe). Set "screenshot" on individual steps you need a frame for (e.g. after the final click), or "full" to also include OCR + AX textElements.'),
1958
+ }),
1959
+ zod_1.z.object({
1960
+ action: zod_1.z.literal('type'),
1961
+ text: zod_1.z.string().describe('Literal characters to type (no special-key interpretation — use hotkey for {Enter}/{Tab}/etc)'),
1962
+ returnObservation: returnObservationSchema.optional().describe('Default "none" in sequences.'),
1963
+ }),
1964
+ zod_1.z.object({
1965
+ action: zod_1.z.literal('hotkey'),
1966
+ combo: zod_1.z.string().describe('Combo like "Ctrl+S", "Enter", "Cmd+A"'),
1967
+ returnObservation: returnObservationSchema.optional().describe('Default "none" in sequences.'),
1968
+ }),
1969
+ zod_1.z.object({
1970
+ action: zod_1.z.literal('scroll'),
1971
+ amount: zod_1.z.number().describe('Scroll amount. Interpreted per `unit` (default ticks = wheel ticks).'),
1972
+ method: zod_1.z.enum(['wheel', 'keys', 'auto']).optional().describe('Default "auto" (wheel + keyboard fallback). Only honored for unit="ticks". Use "keys" inside Electron/React scroll containers where wheel events no-op.'),
1973
+ unit: zod_1.z.enum(['ticks', 'page', 'line']).optional().describe('Default "ticks". "page" = PageDown per unit (RECOMMENDED for pagination inside a sequence). "line" = arrow-key per unit.'),
1974
+ returnObservation: returnObservationSchema.optional().describe('Default "none" in sequences.'),
1975
+ }),
1976
+ zod_1.z.object({
1977
+ action: zod_1.z.literal('screenshot'),
1978
+ background: zod_1.z.boolean().optional().describe('Windows-only: use PrintWindow instead of captureScreen for zero focus flicker inside the sequence (requires hwnd on the top-level sequence call)'),
1979
+ }),
1980
+ zod_1.z.object({
1981
+ action: zod_1.z.literal('wait'),
1982
+ ms: zod_1.z.number().describe('Delay in ms (0-60000). Useful between steps that trigger UI animations'),
1983
+ }),
1984
+ zod_1.z.object({
1985
+ action: zod_1.z.literal('move'),
1986
+ x: zod_1.z.number(),
1987
+ y: zod_1.z.number(),
1988
+ }).describe('Mouse move only (no click) — useful to position cursor before a scroll, or to hover over a tooltip target'),
1989
+ ])).describe('Ordered array of steps (max 50). All steps inherit the top-level window/processName/hwnd target. Per-step returnObservation defaults to "none" (payload-safe) — opt in on individual steps where you need a frame.'),
1990
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Applied ONCE at sequence start. Subsequent activation not re-triggered mid-sequence.'),
1991
+ processName: zod_1.z.string().optional().describe('Exact process executable name (highest precision).'),
1992
+ hwnd: zod_1.z.string().optional().describe('Direct window handle from superbased_window_list. Bypasses scoring entirely.'),
1993
+ restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the ENTIRE sequence completes. Set false when the sequence is followed by another sequence in the same target.'),
1994
+ confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt. ONE confirm covers all steps.'),
1995
+ stopOnError: zod_1.z.boolean().optional().describe('Default true — halt on first failed step. Set false to continue through failures (e.g. best-effort cleanup sequences).'),
1996
+ }, async ({ steps, window, processName, hwnd, restoreFocus, confirm, stopOnError }) => {
1997
+ try {
1998
+ const res = await client.automationSequence({ steps, window, processName, hwnd, restoreFocus, confirm, stopOnError });
1999
+ const data = res.data;
2000
+ const imageBlocks = (data.results || [])
2001
+ .filter((r) => typeof r.imageBase64 === 'string' && r.imageBase64.length > 0)
2002
+ .map((r) => ({ type: 'image', data: r.imageBase64, mimeType: 'image/png' }));
2003
+ // Text summary first; image blocks follow in step order.
2004
+ return {
2005
+ content: [
2006
+ { type: 'text', text: formatResponse(data) },
2007
+ ...imageBlocks,
2008
+ ],
2009
+ isError: !data.ok,
2010
+ };
2011
+ }
2012
+ catch (err) {
2013
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
2014
+ }
2015
+ });
2016
+ server.tool('superbased_focus_window', 'Bring a window to the foreground and leave it there. Use processName="Notepad" for highest precision, or window="<title substring>" for fuzzy match. Refuses on ambiguous matches and returns alternatives. IMPORTANT: NEVER use this as a setup step for another tool. All of superbased_screenshot / superbased_click / superbased_type / superbased_hotkey / superbased_scroll accept window= / processName= / hwnd= on their own calls and do the focus→action→restore cycle in ONE MCP turn — which is the only reliable pattern under per-tool approval UIs like Claude Code. Chaining focus_window before any of those produces TWO permission prompts; clicking Approve on the second one steals focus back to the agent window, so the action fires on the wrong app. This tool is only for STANDALONE focus changes (activating a window so the user can interact with it manually).', {
2017
+ window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). When combined with processName, used to disambiguate among same-process windows.'),
2018
+ processName: zod_1.z.string().optional().describe('Exact process executable name (e.g. "Notepad", "Notepad.exe").'),
2019
+ hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
2020
+ }, async ({ window, processName, hwnd }) => {
2021
+ try {
2022
+ const res = await client.automationFocusWindow({ window, processName, hwnd });
2023
+ return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
2024
+ }
2025
+ catch (err) {
2026
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
2027
+ }
2028
+ });
2029
+ server.tool('superbased_mouse_position', 'Read the current cursor position (no input is generated). Read-only — no safety gate.', {}, async () => {
2030
+ try {
2031
+ const res = await client.automationMousePosition();
2032
+ return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
2033
+ }
2034
+ catch (err) {
2035
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
2036
+ }
2037
+ });
2038
+ server.tool('superbased_wait_for', 'Poll a condition until it holds or timeoutMs elapses. Read-only (no actions.* gate). Conditions: text (OCR-visible string), window (title/process matches — appeared:true by default, pass appeared:false to wait for disappearance), idle (foreground window stable for N ms — useful for "wait for page to settle"), pixelColor (ships in S2). Returns { ok:true, matchedAtMs } on success, { ok:false, errorCode:"TIMEOUT" } on timeout. Replaces the old "screenshot-in-a-loop" pattern and saves agent round-trips across async UIs.', {
2039
+ condition: zod_1.z.union([
2040
+ zod_1.z.object({ type: zod_1.z.literal('text'), value: zod_1.z.string(), caseSensitive: zod_1.z.boolean().optional() }),
2041
+ zod_1.z.object({ type: zod_1.z.literal('window'), title: zod_1.z.string().optional(), processName: zod_1.z.string().optional(), appeared: zod_1.z.boolean().optional() }),
2042
+ zod_1.z.object({ type: zod_1.z.literal('idle'), ms: zod_1.z.number() }),
2043
+ zod_1.z.object({ type: zod_1.z.literal('pixelColor'), x: zod_1.z.number(), y: zod_1.z.number(), expected: zod_1.z.string(), tolerance: zod_1.z.number().optional() }),
2044
+ ]).describe('Condition to poll.'),
2045
+ timeoutMs: zod_1.z.number().describe('Max wait duration (required, >0).'),
2046
+ intervalMs: zod_1.z.number().optional().describe('Polling interval in ms (default 250).'),
2047
+ }, async ({ condition, timeoutMs, intervalMs }) => {
2048
+ try {
2049
+ const res = await client.automationWaitFor({ condition, timeoutMs, intervalMs });
2050
+ return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
2051
+ }
2052
+ catch (err) {
2053
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
2054
+ }
2055
+ });
2056
+ server.tool('superbased_wait', 'Pause execution for a fixed duration (0–60000 ms). Useful between automation steps that need time for UI animations.', {
2057
+ ms: zod_1.z.number().describe('Milliseconds to wait (clamped to 0–60000)'),
2058
+ }, async ({ ms }) => {
2059
+ try {
2060
+ const res = await client.automationWait({ ms });
2061
+ return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
2062
+ }
2063
+ catch (err) {
2064
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
2065
+ }
2066
+ });
2067
+ server.tool('superbased_locate', 'Find a UI element by its visible text label. Tries the native accessibility tree first (method="ax_tree" on darwin/win32 when @superbased/macos-ax or @superbased/win-uia is installed + permission granted); falls back to OCR on a fresh screen capture (method="ocr_locator"). Returns matching regions with bounding boxes and centers. Use bestMatch.center coordinates with superbased_click.', {
2068
+ label: zod_1.z.string().describe('Visible text on the UI element (button label, link text, etc.)'),
2069
+ caseSensitive: zod_1.z.boolean().optional().describe('Match label case-sensitively (default: false)'),
2070
+ }, async ({ label, caseSensitive }) => {
2071
+ try {
2072
+ const res = await client.automationLocate({ label, caseSensitive });
2073
+ return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
2074
+ }
2075
+ catch (err) {
2076
+ return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
2077
+ }
2078
+ });
798
2079
  // ── Resources ──
799
2080
  server.resource('superbased-status', 'superbased://status', async () => {
800
2081
  try {
@@ -887,6 +2168,245 @@ function registerMcpTools(server, client, projectDir) {
887
2168
  return { contents: [{ uri: 'superbased://ai/usage', mimeType: 'text/plain', text: 'Cannot read AI usage' }] };
888
2169
  }
889
2170
  });
2171
+ // ── Watcher Resources (Phase 3 — subscribable event streams) ──
2172
+ server.resource('superbased-watcher-clipboard', 'superbased://watchers/clipboard', {
2173
+ description: 'Clipboard change events. Subscribe with resources/subscribe to receive notifications/resources/updated on every clipboard text change. Text-only for v1.',
2174
+ }, async () => {
2175
+ // Synchronous read returns the current subscriber count + poll interval.
2176
+ try {
2177
+ const res = await client.watcherStatus();
2178
+ const entry = res.data.watchers.find((w) => w.uri === 'superbased://watchers/clipboard');
2179
+ return {
2180
+ contents: [{
2181
+ uri: 'superbased://watchers/clipboard',
2182
+ mimeType: 'application/json',
2183
+ text: formatResponse({
2184
+ description: 'Subscribe for clipboard-change notifications. Text-only.',
2185
+ subscribers: entry?.subscribers ?? 0,
2186
+ }),
2187
+ }],
2188
+ };
2189
+ }
2190
+ catch {
2191
+ return { contents: [{ uri: 'superbased://watchers/clipboard', mimeType: 'text/plain', text: 'Cannot read watcher status' }] };
2192
+ }
2193
+ });
2194
+ server.resource('superbased-watcher-active-window', 'superbased://watchers/active-window', {
2195
+ description: 'Foreground-window change events. Subscribe to receive notifications when the active application or window title changes. Payload: { appName, windowTitle, source }.',
2196
+ }, async () => {
2197
+ try {
2198
+ const res = await client.watcherStatus();
2199
+ const entry = res.data.watchers.find((w) => w.uri === 'superbased://watchers/active-window');
2200
+ return {
2201
+ contents: [{
2202
+ uri: 'superbased://watchers/active-window',
2203
+ mimeType: 'application/json',
2204
+ text: formatResponse({
2205
+ description: 'Subscribe for foreground-window change notifications.',
2206
+ subscribers: entry?.subscribers ?? 0,
2207
+ }),
2208
+ }],
2209
+ };
2210
+ }
2211
+ catch {
2212
+ return { contents: [{ uri: 'superbased://watchers/active-window', mimeType: 'text/plain', text: 'Cannot read watcher status' }] };
2213
+ }
2214
+ });
2215
+ server.resource('superbased-watcher-screen-region-fullscreen', 'superbased://watchers/screen-region/fullscreen', {
2216
+ description: 'Fullscreen visual-change events. Shares a single provider with `superbased_recording mode=monitor` so both can run concurrently without double-polling. Per-region (non-fullscreen) subscriptions are a future extension.',
2217
+ }, async () => {
2218
+ try {
2219
+ const res = await client.watcherStatus();
2220
+ const entry = res.data.watchers.find((w) => w.uri === 'superbased://watchers/screen-region/fullscreen');
2221
+ return {
2222
+ contents: [{
2223
+ uri: 'superbased://watchers/screen-region/fullscreen',
2224
+ mimeType: 'application/json',
2225
+ text: formatResponse({
2226
+ description: 'Subscribe for fullscreen visual-change notifications.',
2227
+ subscribers: entry?.subscribers ?? 0,
2228
+ }),
2229
+ }],
2230
+ };
2231
+ }
2232
+ catch {
2233
+ return { contents: [{ uri: 'superbased://watchers/screen-region/fullscreen', mimeType: 'text/plain', text: 'Cannot read watcher status' }] };
2234
+ }
2235
+ });
2236
+ // File watcher is URI-templated — one subscription per filesystem path.
2237
+ // Advertised via listResourceTemplates so clients can construct concrete URIs.
2238
+ server.resource('superbased-watcher-file', new mcp_js_1.ResourceTemplate('superbased://watchers/file/{+path}', { list: undefined }), {
2239
+ description: 'File-change events for a specific path. Subscribe to superbased://watchers/file/{absolute_path} (URL-encoded) to receive add/change/unlink notifications. Uses chokidar with awaitWriteFinish so editor-style atomic saves are debounced.',
2240
+ }, async (uri) => {
2241
+ try {
2242
+ const res = await client.watcherStatus();
2243
+ const entry = res.data.watchers.find((w) => w.uri === uri.toString());
2244
+ return {
2245
+ contents: [{
2246
+ uri: uri.toString(),
2247
+ mimeType: 'application/json',
2248
+ text: formatResponse({
2249
+ description: 'Subscribe for file-change notifications on this path.',
2250
+ subscribers: entry?.subscribers ?? 0,
2251
+ }),
2252
+ }],
2253
+ };
2254
+ }
2255
+ catch {
2256
+ return { contents: [{ uri: uri.toString(), mimeType: 'text/plain', text: 'Cannot read watcher status' }] };
2257
+ }
2258
+ });
2259
+ // ── Subscribe / Unsubscribe wiring ──
2260
+ // Advertise subscribe capability. Must be done before transport connects.
2261
+ server.server.registerCapabilities({ resources: { subscribe: true } });
2262
+ const subscribedUris = new Set();
2263
+ let closeSseStream = null;
2264
+ function ensureSseOpen() {
2265
+ if (closeSseStream)
2266
+ return;
2267
+ closeSseStream = client.openWatcherStream((event) => {
2268
+ // Only forward to the client if we have an active subscription to this URI.
2269
+ if (!subscribedUris.has(event.uri))
2270
+ return;
2271
+ void server.server.sendResourceUpdated({ uri: event.uri }).catch(() => {
2272
+ // Transport may be in the middle of shutdown — swallow.
2273
+ });
2274
+ }, () => {
2275
+ // SSE dropped. Null out so next subscribe reconnects. No aggressive retry —
2276
+ // subscriptions are long-lived and the MCP client can reconnect the server
2277
+ // if it wants a fresh stream.
2278
+ closeSseStream = null;
2279
+ });
2280
+ }
2281
+ server.server.setRequestHandler(types_js_1.SubscribeRequestSchema, async (request) => {
2282
+ const uri = request.params.uri;
2283
+ try {
2284
+ await client.subscribeWatcher(uri);
2285
+ }
2286
+ catch (err) {
2287
+ throw new Error(err instanceof Error ? err.message : String(err));
2288
+ }
2289
+ subscribedUris.add(uri);
2290
+ ensureSseOpen();
2291
+ return {};
2292
+ });
2293
+ server.server.setRequestHandler(types_js_1.UnsubscribeRequestSchema, async (request) => {
2294
+ const uri = request.params.uri;
2295
+ subscribedUris.delete(uri);
2296
+ try {
2297
+ await client.unsubscribeWatcher(uri);
2298
+ }
2299
+ catch {
2300
+ // Server-side refcount will leak, but we've already dropped local state —
2301
+ // api-server's `stopApiServer` shutdown hook handles final cleanup.
2302
+ }
2303
+ return {};
2304
+ });
2305
+ // On transport close, send unsubscribes for every URI we own so the api-server
2306
+ // refcount decrements correctly. Without this, watchers would keep running
2307
+ // after the MCP client disconnects.
2308
+ const originalOnClose = server.server.onclose;
2309
+ server.server.onclose = () => {
2310
+ if (closeSseStream) {
2311
+ try {
2312
+ closeSseStream();
2313
+ }
2314
+ catch { /* ignore */ }
2315
+ closeSseStream = null;
2316
+ }
2317
+ const uris = Array.from(subscribedUris);
2318
+ subscribedUris.clear();
2319
+ // Fire-and-forget — process may exit before these resolve, which is fine:
2320
+ // api-server also calls registry.shutdown() on its own stop path.
2321
+ for (const uri of uris) {
2322
+ void client.unsubscribeWatcher(uri).catch(() => { });
2323
+ }
2324
+ if (originalOnClose) {
2325
+ try {
2326
+ originalOnClose();
2327
+ }
2328
+ catch { /* ignore */ }
2329
+ }
2330
+ };
2331
+ // ── Phase 5.5: progressive-disclosure filter on tools/list ──
2332
+ //
2333
+ // If the user has opted into progressive disclosure, override the SDK's
2334
+ // default ListTools handler to surface only the core-11 subset. Non-core
2335
+ // tools remain registered with the server's call handler (they're callable
2336
+ // by name from plugin slash commands); we only filter what's advertised
2337
+ // via tools/list. See src/tool-categories.ts for the category map and
2338
+ // `superbased_tools` registration above for the discovery dispatcher.
2339
+ //
2340
+ // Setting is read once at startup; flipping it requires an MCP server
2341
+ // restart (marked `requiresRestart: true` in the schema). Documented.
2342
+ //
2343
+ // Read the setting directly from the shared settings file instead of
2344
+ // importing from electron/core — mcp-server ships as a separate package
2345
+ // and doesn't bundle electron modules. This matches the convention used
2346
+ // elsewhere for cross-process config (e.g., paths.ts resolution).
2347
+ try {
2348
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
2349
+ const fs = require('fs');
2350
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
2351
+ const pathMod = require('path');
2352
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
2353
+ const os = require('os');
2354
+ const settingsPath = process.env.SUPERBASED_DATA_DIR
2355
+ ? pathMod.join(process.env.SUPERBASED_DATA_DIR, 'superbased-settings.json')
2356
+ : pathMod.join(os.homedir(), '.superbased', 'superbased-settings.json');
2357
+ let progressiveOn = false;
2358
+ try {
2359
+ if (fs.existsSync(settingsPath)) {
2360
+ const raw = fs.readFileSync(settingsPath, 'utf-8');
2361
+ const settings = JSON.parse(raw);
2362
+ const pd = (settings.progressiveDisclosure ?? {});
2363
+ progressiveOn = pd.enabled === true;
2364
+ }
2365
+ }
2366
+ catch {
2367
+ // Settings file unreadable or malformed — default to off.
2368
+ }
2369
+ if (progressiveOn) {
2370
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
2371
+ const { CORE_TOOLS } = require('./tool-categories');
2372
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
2373
+ const { ListToolsRequestSchema } = require('@modelcontextprotocol/sdk/types.js');
2374
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
2375
+ const zodCompat = require('@modelcontextprotocol/sdk/server/zod-compat.js');
2376
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
2377
+ const schemaCompat = require('@modelcontextprotocol/sdk/server/zod-json-schema-compat.js');
2378
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2379
+ const registered = server._registeredTools;
2380
+ server.server.setRequestHandler(ListToolsRequestSchema, async () => {
2381
+ const tools = [];
2382
+ for (const [name, tool] of Object.entries(registered)) {
2383
+ if (tool.enabled === false)
2384
+ continue;
2385
+ if (!CORE_TOOLS.has(name))
2386
+ continue;
2387
+ const inputSchemaObj = tool.inputSchema ? zodCompat.normalizeObjectSchema(tool.inputSchema) : null;
2388
+ const inputSchema = inputSchemaObj
2389
+ ? schemaCompat.toJsonSchemaCompat(inputSchemaObj, { strictUnions: true, pipeStrategy: 'input' })
2390
+ : { type: 'object' };
2391
+ tools.push({
2392
+ name,
2393
+ title: tool.title,
2394
+ description: tool.description,
2395
+ inputSchema,
2396
+ annotations: tool.annotations,
2397
+ _meta: tool._meta,
2398
+ });
2399
+ }
2400
+ return { tools };
2401
+ });
2402
+ }
2403
+ }
2404
+ catch (err) {
2405
+ // If the override fails (SDK internals moved, etc.), degrade gracefully
2406
+ // to the default full-list behaviour. Users hit the same token cost as
2407
+ // before but nothing is broken.
2408
+ console.error('[mcp] Progressive-disclosure override failed to install; falling back to full tools/list:', err);
2409
+ }
890
2410
  return { startMonitorPoller, stopMonitorPoller };
891
2411
  }
892
2412
  /**