superbased 2.0.6 → 3.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (709) hide show
  1. package/LICENSE +15 -26
  2. package/README.md +198 -290
  3. package/bin/superbased.js +7 -0
  4. package/package.json +42 -140
  5. package/SUPERBASED_SKILL.md +0 -1660
  6. package/dist/electron/ai/ai-client.d.ts +0 -45
  7. package/dist/electron/ai/ai-client.d.ts.map +0 -1
  8. package/dist/electron/ai/ai-client.js +0 -205
  9. package/dist/electron/ai/ai-client.js.map +0 -1
  10. package/dist/electron/ai/context-builder.d.ts +0 -8
  11. package/dist/electron/ai/context-builder.d.ts.map +0 -1
  12. package/dist/electron/ai/context-builder.js +0 -28
  13. package/dist/electron/ai/context-builder.js.map +0 -1
  14. package/dist/electron/ai/instruction-parser.d.ts +0 -11
  15. package/dist/electron/ai/instruction-parser.d.ts.map +0 -1
  16. package/dist/electron/ai/instruction-parser.js +0 -47
  17. package/dist/electron/ai/instruction-parser.js.map +0 -1
  18. package/dist/electron/ai/orchestrator.d.ts +0 -17
  19. package/dist/electron/ai/orchestrator.d.ts.map +0 -1
  20. package/dist/electron/ai/orchestrator.js +0 -53
  21. package/dist/electron/ai/orchestrator.js.map +0 -1
  22. package/dist/electron/ai/providers/anthropic.d.ts +0 -6
  23. package/dist/electron/ai/providers/anthropic.d.ts.map +0 -1
  24. package/dist/electron/ai/providers/anthropic.js +0 -67
  25. package/dist/electron/ai/providers/anthropic.js.map +0 -1
  26. package/dist/electron/ai/providers/azure-openai.d.ts +0 -12
  27. package/dist/electron/ai/providers/azure-openai.d.ts.map +0 -1
  28. package/dist/electron/ai/providers/azure-openai.js +0 -87
  29. package/dist/electron/ai/providers/azure-openai.js.map +0 -1
  30. package/dist/electron/ai/providers/gemini.d.ts +0 -6
  31. package/dist/electron/ai/providers/gemini.d.ts.map +0 -1
  32. package/dist/electron/ai/providers/gemini.js +0 -49
  33. package/dist/electron/ai/providers/gemini.js.map +0 -1
  34. package/dist/electron/ai/providers/openai.d.ts +0 -6
  35. package/dist/electron/ai/providers/openai.d.ts.map +0 -1
  36. package/dist/electron/ai/providers/openai.js +0 -68
  37. package/dist/electron/ai/providers/openai.js.map +0 -1
  38. package/dist/electron/core/auth-store.d.ts +0 -15
  39. package/dist/electron/core/auth-store.d.ts.map +0 -1
  40. package/dist/electron/core/auth-store.js +0 -86
  41. package/dist/electron/core/auth-store.js.map +0 -1
  42. package/dist/electron/core/config.d.ts +0 -6
  43. package/dist/electron/core/config.d.ts.map +0 -1
  44. package/dist/electron/core/config.js +0 -81
  45. package/dist/electron/core/config.js.map +0 -1
  46. package/dist/electron/core/file-logger.d.ts +0 -17
  47. package/dist/electron/core/file-logger.d.ts.map +0 -1
  48. package/dist/electron/core/file-logger.js +0 -74
  49. package/dist/electron/core/file-logger.js.map +0 -1
  50. package/dist/electron/core/input-injection/index.d.ts +0 -6
  51. package/dist/electron/core/input-injection/index.d.ts.map +0 -1
  52. package/dist/electron/core/input-injection/index.js +0 -31
  53. package/dist/electron/core/input-injection/index.js.map +0 -1
  54. package/dist/electron/core/input-injection/macos.d.ts +0 -3
  55. package/dist/electron/core/input-injection/macos.d.ts.map +0 -1
  56. package/dist/electron/core/input-injection/macos.js +0 -14
  57. package/dist/electron/core/input-injection/macos.js.map +0 -1
  58. package/dist/electron/core/input-injection/windows.d.ts +0 -3
  59. package/dist/electron/core/input-injection/windows.d.ts.map +0 -1
  60. package/dist/electron/core/input-injection/windows.js +0 -119
  61. package/dist/electron/core/input-injection/windows.js.map +0 -1
  62. package/dist/electron/core/json-store.d.ts +0 -26
  63. package/dist/electron/core/json-store.d.ts.map +0 -1
  64. package/dist/electron/core/json-store.js +0 -132
  65. package/dist/electron/core/json-store.js.map +0 -1
  66. package/dist/electron/core/paths.d.ts +0 -17
  67. package/dist/electron/core/paths.d.ts.map +0 -1
  68. package/dist/electron/core/paths.js +0 -117
  69. package/dist/electron/core/paths.js.map +0 -1
  70. package/dist/electron/core/platform.d.ts +0 -24
  71. package/dist/electron/core/platform.d.ts.map +0 -1
  72. package/dist/electron/core/platform.js +0 -18
  73. package/dist/electron/core/platform.js.map +0 -1
  74. package/dist/electron/core/process-coord.d.ts +0 -19
  75. package/dist/electron/core/process-coord.d.ts.map +0 -1
  76. package/dist/electron/core/process-coord.js +0 -124
  77. package/dist/electron/core/process-coord.js.map +0 -1
  78. package/dist/electron/core/serialize-schema.d.ts +0 -35
  79. package/dist/electron/core/serialize-schema.d.ts.map +0 -1
  80. package/dist/electron/core/serialize-schema.js +0 -89
  81. package/dist/electron/core/serialize-schema.js.map +0 -1
  82. package/dist/electron/core/settings-schema.d.ts +0 -81
  83. package/dist/electron/core/settings-schema.d.ts.map +0 -1
  84. package/dist/electron/core/settings-schema.js +0 -1370
  85. package/dist/electron/core/settings-schema.js.map +0 -1
  86. package/dist/electron/db/database.d.ts +0 -154
  87. package/dist/electron/db/database.d.ts.map +0 -1
  88. package/dist/electron/db/database.js +0 -637
  89. package/dist/electron/db/database.js.map +0 -1
  90. package/dist/electron/db/models.d.ts +0 -26
  91. package/dist/electron/db/models.d.ts.map +0 -1
  92. package/dist/electron/db/models.js +0 -4
  93. package/dist/electron/db/models.js.map +0 -1
  94. package/dist/electron/logger.d.ts +0 -9
  95. package/dist/electron/logger.d.ts.map +0 -1
  96. package/dist/electron/logger.js +0 -32
  97. package/dist/electron/logger.js.map +0 -1
  98. package/dist/electron/main.js +0 -3652
  99. package/dist/electron/modules/accessibility/macos-provider.d.ts +0 -8
  100. package/dist/electron/modules/accessibility/macos-provider.d.ts.map +0 -1
  101. package/dist/electron/modules/accessibility/macos-provider.js +0 -94
  102. package/dist/electron/modules/accessibility/macos-provider.js.map +0 -1
  103. package/dist/electron/modules/accessibility/provider.d.ts +0 -12
  104. package/dist/electron/modules/accessibility/provider.d.ts.map +0 -1
  105. package/dist/electron/modules/accessibility/provider.js +0 -52
  106. package/dist/electron/modules/accessibility/provider.js.map +0 -1
  107. package/dist/electron/modules/accessibility/types.d.ts +0 -63
  108. package/dist/electron/modules/accessibility/types.d.ts.map +0 -1
  109. package/dist/electron/modules/accessibility/types.js +0 -6
  110. package/dist/electron/modules/accessibility/types.js.map +0 -1
  111. package/dist/electron/modules/accessibility/windows-provider.d.ts +0 -8
  112. package/dist/electron/modules/accessibility/windows-provider.d.ts.map +0 -1
  113. package/dist/electron/modules/accessibility/windows-provider.js +0 -85
  114. package/dist/electron/modules/accessibility/windows-provider.js.map +0 -1
  115. package/dist/electron/modules/active-window.d.ts +0 -6
  116. package/dist/electron/modules/active-window.d.ts.map +0 -1
  117. package/dist/electron/modules/active-window.js +0 -76
  118. package/dist/electron/modules/active-window.js.map +0 -1
  119. package/dist/electron/modules/api-server.d.ts +0 -11
  120. package/dist/electron/modules/api-server.d.ts.map +0 -1
  121. package/dist/electron/modules/api-server.js +0 -2759
  122. package/dist/electron/modules/api-server.js.map +0 -1
  123. package/dist/electron/modules/auth.d.ts +0 -42
  124. package/dist/electron/modules/auth.d.ts.map +0 -1
  125. package/dist/electron/modules/auth.js +0 -193
  126. package/dist/electron/modules/auth.js.map +0 -1
  127. package/dist/electron/modules/azure-speech-realtime.d.ts +0 -48
  128. package/dist/electron/modules/azure-speech-realtime.d.ts.map +0 -1
  129. package/dist/electron/modules/azure-speech-realtime.js +0 -543
  130. package/dist/electron/modules/azure-speech-realtime.js.map +0 -1
  131. package/dist/electron/modules/capture-modes.d.ts +0 -19
  132. package/dist/electron/modules/capture-modes.d.ts.map +0 -1
  133. package/dist/electron/modules/capture-modes.js +0 -100
  134. package/dist/electron/modules/capture-modes.js.map +0 -1
  135. package/dist/electron/modules/capture.d.ts +0 -24
  136. package/dist/electron/modules/capture.d.ts.map +0 -1
  137. package/dist/electron/modules/capture.js +0 -191
  138. package/dist/electron/modules/capture.js.map +0 -1
  139. package/dist/electron/modules/clipboard.d.ts +0 -6
  140. package/dist/electron/modules/clipboard.d.ts.map +0 -1
  141. package/dist/electron/modules/clipboard.js +0 -26
  142. package/dist/electron/modules/clipboard.js.map +0 -1
  143. package/dist/electron/modules/color-picker.d.ts +0 -4
  144. package/dist/electron/modules/color-picker.d.ts.map +0 -1
  145. package/dist/electron/modules/color-picker.js +0 -233
  146. package/dist/electron/modules/color-picker.js.map +0 -1
  147. package/dist/electron/modules/compose-screenshots.d.ts +0 -8
  148. package/dist/electron/modules/compose-screenshots.d.ts.map +0 -1
  149. package/dist/electron/modules/compose-screenshots.js +0 -86
  150. package/dist/electron/modules/compose-screenshots.js.map +0 -1
  151. package/dist/electron/modules/context-menu-detect.d.ts +0 -47
  152. package/dist/electron/modules/context-menu-detect.d.ts.map +0 -1
  153. package/dist/electron/modules/context-menu-detect.js +0 -272
  154. package/dist/electron/modules/context-menu-detect.js.map +0 -1
  155. package/dist/electron/modules/dictation.d.ts +0 -27
  156. package/dist/electron/modules/dictation.d.ts.map +0 -1
  157. package/dist/electron/modules/dictation.js +0 -1231
  158. package/dist/electron/modules/dictation.js.map +0 -1
  159. package/dist/electron/modules/error-reporter.d.ts +0 -7
  160. package/dist/electron/modules/error-reporter.d.ts.map +0 -1
  161. package/dist/electron/modules/error-reporter.js +0 -65
  162. package/dist/electron/modules/error-reporter.js.map +0 -1
  163. package/dist/electron/modules/gif-util.d.ts +0 -9
  164. package/dist/electron/modules/gif-util.d.ts.map +0 -1
  165. package/dist/electron/modules/gif-util.js +0 -63
  166. package/dist/electron/modules/gif-util.js.map +0 -1
  167. package/dist/electron/modules/gui-automation-errors.d.ts +0 -11
  168. package/dist/electron/modules/gui-automation-errors.d.ts.map +0 -1
  169. package/dist/electron/modules/gui-automation-errors.js +0 -79
  170. package/dist/electron/modules/gui-automation-errors.js.map +0 -1
  171. package/dist/electron/modules/gui-automation-telemetry.d.ts +0 -38
  172. package/dist/electron/modules/gui-automation-telemetry.d.ts.map +0 -1
  173. package/dist/electron/modules/gui-automation-telemetry.js +0 -200
  174. package/dist/electron/modules/gui-automation-telemetry.js.map +0 -1
  175. package/dist/electron/modules/gui-automation.d.ts +0 -1143
  176. package/dist/electron/modules/gui-automation.d.ts.map +0 -1
  177. package/dist/electron/modules/gui-automation.js +0 -8769
  178. package/dist/electron/modules/gui-automation.js.map +0 -1
  179. package/dist/electron/modules/hotkeys.d.ts +0 -5
  180. package/dist/electron/modules/hotkeys.d.ts.map +0 -1
  181. package/dist/electron/modules/hotkeys.js +0 -64
  182. package/dist/electron/modules/hotkeys.js.map +0 -1
  183. package/dist/electron/modules/human-input/index.d.ts +0 -35
  184. package/dist/electron/modules/human-input/index.d.ts.map +0 -1
  185. package/dist/electron/modules/human-input/index.js +0 -163
  186. package/dist/electron/modules/human-input/index.js.map +0 -1
  187. package/dist/electron/modules/human-input/keyboard/timing.d.ts +0 -38
  188. package/dist/electron/modules/human-input/keyboard/timing.d.ts.map +0 -1
  189. package/dist/electron/modules/human-input/keyboard/timing.js +0 -57
  190. package/dist/electron/modules/human-input/keyboard/timing.js.map +0 -1
  191. package/dist/electron/modules/human-input/mouse/path.d.ts +0 -24
  192. package/dist/electron/modules/human-input/mouse/path.d.ts.map +0 -1
  193. package/dist/electron/modules/human-input/mouse/path.js +0 -80
  194. package/dist/electron/modules/human-input/mouse/path.js.map +0 -1
  195. package/dist/electron/modules/human-input/mouse/velocity.d.ts +0 -48
  196. package/dist/electron/modules/human-input/mouse/velocity.d.ts.map +0 -1
  197. package/dist/electron/modules/human-input/mouse/velocity.js +0 -93
  198. package/dist/electron/modules/human-input/mouse/velocity.js.map +0 -1
  199. package/dist/electron/modules/human-input/profiles.d.ts +0 -90
  200. package/dist/electron/modules/human-input/profiles.d.ts.map +0 -1
  201. package/dist/electron/modules/human-input/profiles.js +0 -124
  202. package/dist/electron/modules/human-input/profiles.js.map +0 -1
  203. package/dist/electron/modules/human-input/rng.d.ts +0 -16
  204. package/dist/electron/modules/human-input/rng.d.ts.map +0 -1
  205. package/dist/electron/modules/human-input/rng.js +0 -101
  206. package/dist/electron/modules/human-input/rng.js.map +0 -1
  207. package/dist/electron/modules/human-input/salt.d.ts +0 -15
  208. package/dist/electron/modules/human-input/salt.d.ts.map +0 -1
  209. package/dist/electron/modules/human-input/salt.js +0 -48
  210. package/dist/electron/modules/human-input/salt.js.map +0 -1
  211. package/dist/electron/modules/image-utils.d.ts +0 -20
  212. package/dist/electron/modules/image-utils.d.ts.map +0 -1
  213. package/dist/electron/modules/image-utils.js +0 -80
  214. package/dist/electron/modules/image-utils.js.map +0 -1
  215. package/dist/electron/modules/keystroke.d.ts +0 -7
  216. package/dist/electron/modules/keystroke.d.ts.map +0 -1
  217. package/dist/electron/modules/keystroke.js +0 -53
  218. package/dist/electron/modules/keystroke.js.map +0 -1
  219. package/dist/electron/modules/license.d.ts +0 -25
  220. package/dist/electron/modules/license.d.ts.map +0 -1
  221. package/dist/electron/modules/license.js +0 -175
  222. package/dist/electron/modules/license.js.map +0 -1
  223. package/dist/electron/modules/mcp-config.d.ts +0 -16
  224. package/dist/electron/modules/mcp-config.d.ts.map +0 -1
  225. package/dist/electron/modules/mcp-config.js +0 -146
  226. package/dist/electron/modules/mcp-config.js.map +0 -1
  227. package/dist/electron/modules/ocr.d.ts +0 -3
  228. package/dist/electron/modules/ocr.d.ts.map +0 -1
  229. package/dist/electron/modules/ocr.js +0 -188
  230. package/dist/electron/modules/ocr.js.map +0 -1
  231. package/dist/electron/modules/ollama/capability.d.ts +0 -32
  232. package/dist/electron/modules/ollama/capability.d.ts.map +0 -1
  233. package/dist/electron/modules/ollama/capability.js +0 -117
  234. package/dist/electron/modules/ollama/capability.js.map +0 -1
  235. package/dist/electron/modules/ollama/client.d.ts +0 -14
  236. package/dist/electron/modules/ollama/client.d.ts.map +0 -1
  237. package/dist/electron/modules/ollama/client.js +0 -134
  238. package/dist/electron/modules/ollama/client.js.map +0 -1
  239. package/dist/electron/modules/ollama/detector.d.ts +0 -29
  240. package/dist/electron/modules/ollama/detector.d.ts.map +0 -1
  241. package/dist/electron/modules/ollama/detector.js +0 -177
  242. package/dist/electron/modules/ollama/detector.js.map +0 -1
  243. package/dist/electron/modules/ollama/dispatcher.d.ts +0 -36
  244. package/dist/electron/modules/ollama/dispatcher.d.ts.map +0 -1
  245. package/dist/electron/modules/ollama/dispatcher.js +0 -97
  246. package/dist/electron/modules/ollama/dispatcher.js.map +0 -1
  247. package/dist/electron/modules/ollama/router.d.ts +0 -51
  248. package/dist/electron/modules/ollama/router.d.ts.map +0 -1
  249. package/dist/electron/modules/ollama/router.js +0 -201
  250. package/dist/electron/modules/ollama/router.js.map +0 -1
  251. package/dist/electron/modules/pin-window.d.ts +0 -3
  252. package/dist/electron/modules/pin-window.d.ts.map +0 -1
  253. package/dist/electron/modules/pin-window.js +0 -64
  254. package/dist/electron/modules/pin-window.js.map +0 -1
  255. package/dist/electron/modules/platform/dpi.d.ts +0 -2
  256. package/dist/electron/modules/platform/dpi.d.ts.map +0 -1
  257. package/dist/electron/modules/platform/dpi.js +0 -48
  258. package/dist/electron/modules/platform/dpi.js.map +0 -1
  259. package/dist/electron/modules/platform/errors.d.ts +0 -13
  260. package/dist/electron/modules/platform/errors.d.ts.map +0 -1
  261. package/dist/electron/modules/platform/errors.js +0 -36
  262. package/dist/electron/modules/platform/errors.js.map +0 -1
  263. package/dist/electron/modules/platform/index.d.ts +0 -24
  264. package/dist/electron/modules/platform/index.d.ts.map +0 -1
  265. package/dist/electron/modules/platform/index.js +0 -133
  266. package/dist/electron/modules/platform/index.js.map +0 -1
  267. package/dist/electron/modules/platform/interfaces.d.ts +0 -140
  268. package/dist/electron/modules/platform/interfaces.d.ts.map +0 -1
  269. package/dist/electron/modules/platform/interfaces.js +0 -14
  270. package/dist/electron/modules/platform/interfaces.js.map +0 -1
  271. package/dist/electron/modules/platform/macos/ax.d.ts +0 -15
  272. package/dist/electron/modules/platform/macos/ax.d.ts.map +0 -1
  273. package/dist/electron/modules/platform/macos/ax.js +0 -222
  274. package/dist/electron/modules/platform/macos/ax.js.map +0 -1
  275. package/dist/electron/modules/platform/macos/capture.d.ts +0 -14
  276. package/dist/electron/modules/platform/macos/capture.d.ts.map +0 -1
  277. package/dist/electron/modules/platform/macos/capture.js +0 -106
  278. package/dist/electron/modules/platform/macos/capture.js.map +0 -1
  279. package/dist/electron/modules/platform/macos/input.d.ts +0 -16
  280. package/dist/electron/modules/platform/macos/input.d.ts.map +0 -1
  281. package/dist/electron/modules/platform/macos/input.js +0 -342
  282. package/dist/electron/modules/platform/macos/input.js.map +0 -1
  283. package/dist/electron/modules/platform/macos/launch.d.ts +0 -10
  284. package/dist/electron/modules/platform/macos/launch.d.ts.map +0 -1
  285. package/dist/electron/modules/platform/macos/launch.js +0 -114
  286. package/dist/electron/modules/platform/macos/launch.js.map +0 -1
  287. package/dist/electron/modules/platform/macos/session.d.ts +0 -8
  288. package/dist/electron/modules/platform/macos/session.d.ts.map +0 -1
  289. package/dist/electron/modules/platform/macos/session.js +0 -17
  290. package/dist/electron/modules/platform/macos/session.js.map +0 -1
  291. package/dist/electron/modules/platform/macos/window.d.ts +0 -31
  292. package/dist/electron/modules/platform/macos/window.d.ts.map +0 -1
  293. package/dist/electron/modules/platform/macos/window.js +0 -271
  294. package/dist/electron/modules/platform/macos/window.js.map +0 -1
  295. package/dist/electron/modules/platform/shared.d.ts +0 -10
  296. package/dist/electron/modules/platform/shared.d.ts.map +0 -1
  297. package/dist/electron/modules/platform/shared.js +0 -201
  298. package/dist/electron/modules/platform/shared.js.map +0 -1
  299. package/dist/electron/modules/platform/types.d.ts +0 -182
  300. package/dist/electron/modules/platform/types.d.ts.map +0 -1
  301. package/dist/electron/modules/platform/types.js +0 -24
  302. package/dist/electron/modules/platform/types.js.map +0 -1
  303. package/dist/electron/modules/platform/windows/ax.d.ts +0 -15
  304. package/dist/electron/modules/platform/windows/ax.d.ts.map +0 -1
  305. package/dist/electron/modules/platform/windows/ax.js +0 -277
  306. package/dist/electron/modules/platform/windows/ax.js.map +0 -1
  307. package/dist/electron/modules/platform/windows/capture.d.ts +0 -14
  308. package/dist/electron/modules/platform/windows/capture.d.ts.map +0 -1
  309. package/dist/electron/modules/platform/windows/capture.js +0 -115
  310. package/dist/electron/modules/platform/windows/capture.js.map +0 -1
  311. package/dist/electron/modules/platform/windows/input.d.ts +0 -17
  312. package/dist/electron/modules/platform/windows/input.d.ts.map +0 -1
  313. package/dist/electron/modules/platform/windows/input.js +0 -422
  314. package/dist/electron/modules/platform/windows/input.js.map +0 -1
  315. package/dist/electron/modules/platform/windows/launch.d.ts +0 -10
  316. package/dist/electron/modules/platform/windows/launch.d.ts.map +0 -1
  317. package/dist/electron/modules/platform/windows/launch.js +0 -185
  318. package/dist/electron/modules/platform/windows/launch.js.map +0 -1
  319. package/dist/electron/modules/platform/windows/session.d.ts +0 -8
  320. package/dist/electron/modules/platform/windows/session.d.ts.map +0 -1
  321. package/dist/electron/modules/platform/windows/session.js +0 -87
  322. package/dist/electron/modules/platform/windows/session.js.map +0 -1
  323. package/dist/electron/modules/platform/windows/tray.d.ts +0 -13
  324. package/dist/electron/modules/platform/windows/tray.d.ts.map +0 -1
  325. package/dist/electron/modules/platform/windows/tray.js +0 -390
  326. package/dist/electron/modules/platform/windows/tray.js.map +0 -1
  327. package/dist/electron/modules/platform/windows/window.d.ts +0 -30
  328. package/dist/electron/modules/platform/windows/window.d.ts.map +0 -1
  329. package/dist/electron/modules/platform/windows/window.js +0 -444
  330. package/dist/electron/modules/platform/windows/window.js.map +0 -1
  331. package/dist/electron/modules/recording/ai-analysis.d.ts +0 -8
  332. package/dist/electron/modules/recording/ai-analysis.d.ts.map +0 -1
  333. package/dist/electron/modules/recording/ai-analysis.js +0 -88
  334. package/dist/electron/modules/recording/ai-analysis.js.map +0 -1
  335. package/dist/electron/modules/recording/capture-queue.d.ts +0 -48
  336. package/dist/electron/modules/recording/capture-queue.d.ts.map +0 -1
  337. package/dist/electron/modules/recording/capture-queue.js +0 -409
  338. package/dist/electron/modules/recording/capture-queue.js.map +0 -1
  339. package/dist/electron/modules/recording/cli.d.ts +0 -13
  340. package/dist/electron/modules/recording/cli.d.ts.map +0 -1
  341. package/dist/electron/modules/recording/cli.js +0 -135
  342. package/dist/electron/modules/recording/cli.js.map +0 -1
  343. package/dist/electron/modules/recording/http-api.d.ts +0 -3
  344. package/dist/electron/modules/recording/http-api.d.ts.map +0 -1
  345. package/dist/electron/modules/recording/http-api.js +0 -236
  346. package/dist/electron/modules/recording/http-api.js.map +0 -1
  347. package/dist/electron/modules/recording/index.d.ts +0 -15
  348. package/dist/electron/modules/recording/index.d.ts.map +0 -1
  349. package/dist/electron/modules/recording/index.js +0 -154
  350. package/dist/electron/modules/recording/index.js.map +0 -1
  351. package/dist/electron/modules/recording/input-hook-provider.d.ts +0 -15
  352. package/dist/electron/modules/recording/input-hook-provider.d.ts.map +0 -1
  353. package/dist/electron/modules/recording/input-hook-provider.js +0 -5
  354. package/dist/electron/modules/recording/input-hook-provider.js.map +0 -1
  355. package/dist/electron/modules/recording/mcp-tool.d.ts +0 -13
  356. package/dist/electron/modules/recording/mcp-tool.d.ts.map +0 -1
  357. package/dist/electron/modules/recording/mcp-tool.js +0 -81
  358. package/dist/electron/modules/recording/mcp-tool.js.map +0 -1
  359. package/dist/electron/modules/recording/monitor-analyzer.d.ts +0 -40
  360. package/dist/electron/modules/recording/monitor-analyzer.d.ts.map +0 -1
  361. package/dist/electron/modules/recording/monitor-analyzer.js +0 -220
  362. package/dist/electron/modules/recording/monitor-analyzer.js.map +0 -1
  363. package/dist/electron/modules/recording/providers/change-detect-provider.d.ts +0 -28
  364. package/dist/electron/modules/recording/providers/change-detect-provider.d.ts.map +0 -1
  365. package/dist/electron/modules/recording/providers/change-detect-provider.js +0 -181
  366. package/dist/electron/modules/recording/providers/change-detect-provider.js.map +0 -1
  367. package/dist/electron/modules/recording/providers/change-detect-shared-wrapper.d.ts +0 -15
  368. package/dist/electron/modules/recording/providers/change-detect-shared-wrapper.d.ts.map +0 -1
  369. package/dist/electron/modules/recording/providers/change-detect-shared-wrapper.js +0 -62
  370. package/dist/electron/modules/recording/providers/change-detect-shared-wrapper.js.map +0 -1
  371. package/dist/electron/modules/recording/providers/periodic-provider.d.ts +0 -15
  372. package/dist/electron/modules/recording/providers/periodic-provider.d.ts.map +0 -1
  373. package/dist/electron/modules/recording/providers/periodic-provider.js +0 -55
  374. package/dist/electron/modules/recording/providers/periodic-provider.js.map +0 -1
  375. package/dist/electron/modules/recording/providers/provider-factory.d.ts +0 -15
  376. package/dist/electron/modules/recording/providers/provider-factory.d.ts.map +0 -1
  377. package/dist/electron/modules/recording/providers/provider-factory.js +0 -97
  378. package/dist/electron/modules/recording/providers/provider-factory.js.map +0 -1
  379. package/dist/electron/modules/recording/providers/uiohook-provider.d.ts +0 -19
  380. package/dist/electron/modules/recording/providers/uiohook-provider.d.ts.map +0 -1
  381. package/dist/electron/modules/recording/providers/uiohook-provider.js +0 -267
  382. package/dist/electron/modules/recording/providers/uiohook-provider.js.map +0 -1
  383. package/dist/electron/modules/recording/recording-session.d.ts +0 -29
  384. package/dist/electron/modules/recording/recording-session.d.ts.map +0 -1
  385. package/dist/electron/modules/recording/recording-session.js +0 -389
  386. package/dist/electron/modules/recording/recording-session.js.map +0 -1
  387. package/dist/electron/modules/recording/session-alignment.d.ts +0 -32
  388. package/dist/electron/modules/recording/session-alignment.d.ts.map +0 -1
  389. package/dist/electron/modules/recording/session-alignment.js +0 -103
  390. package/dist/electron/modules/recording/session-alignment.js.map +0 -1
  391. package/dist/electron/modules/recording/session-export.d.ts +0 -2
  392. package/dist/electron/modules/recording/session-export.d.ts.map +0 -1
  393. package/dist/electron/modules/recording/session-export.js +0 -287
  394. package/dist/electron/modules/recording/session-export.js.map +0 -1
  395. package/dist/electron/modules/recording/trigger-engine.d.ts +0 -62
  396. package/dist/electron/modules/recording/trigger-engine.d.ts.map +0 -1
  397. package/dist/electron/modules/recording/trigger-engine.js +0 -553
  398. package/dist/electron/modules/recording/trigger-engine.js.map +0 -1
  399. package/dist/electron/modules/recording/visual-diff.d.ts +0 -17
  400. package/dist/electron/modules/recording/visual-diff.d.ts.map +0 -1
  401. package/dist/electron/modules/recording/visual-diff.js +0 -109
  402. package/dist/electron/modules/recording/visual-diff.js.map +0 -1
  403. package/dist/electron/modules/redact.d.ts +0 -34
  404. package/dist/electron/modules/redact.d.ts.map +0 -1
  405. package/dist/electron/modules/redact.js +0 -583
  406. package/dist/electron/modules/redact.js.map +0 -1
  407. package/dist/electron/modules/scroll-calibration.d.ts +0 -152
  408. package/dist/electron/modules/scroll-calibration.d.ts.map +0 -1
  409. package/dist/electron/modules/scroll-calibration.js +0 -271
  410. package/dist/electron/modules/scroll-calibration.js.map +0 -1
  411. package/dist/electron/modules/scroll-capture.d.ts +0 -21
  412. package/dist/electron/modules/scroll-capture.d.ts.map +0 -1
  413. package/dist/electron/modules/scroll-capture.js +0 -134
  414. package/dist/electron/modules/scroll-capture.js.map +0 -1
  415. package/dist/electron/modules/sequence-locate.d.ts +0 -126
  416. package/dist/electron/modules/sequence-locate.d.ts.map +0 -1
  417. package/dist/electron/modules/sequence-locate.js +0 -356
  418. package/dist/electron/modules/sequence-locate.js.map +0 -1
  419. package/dist/electron/modules/store.d.ts +0 -18
  420. package/dist/electron/modules/store.d.ts.map +0 -1
  421. package/dist/electron/modules/store.js +0 -126
  422. package/dist/electron/modules/store.js.map +0 -1
  423. package/dist/electron/modules/stt/capability-probe.d.ts +0 -67
  424. package/dist/electron/modules/stt/capability-probe.d.ts.map +0 -1
  425. package/dist/electron/modules/stt/capability-probe.js +0 -331
  426. package/dist/electron/modules/stt/capability-probe.js.map +0 -1
  427. package/dist/electron/modules/stt/macos-engine.d.ts +0 -20
  428. package/dist/electron/modules/stt/macos-engine.d.ts.map +0 -1
  429. package/dist/electron/modules/stt/macos-engine.js +0 -231
  430. package/dist/electron/modules/stt/macos-engine.js.map +0 -1
  431. package/dist/electron/modules/stt/model-manager.d.ts +0 -87
  432. package/dist/electron/modules/stt/model-manager.d.ts.map +0 -1
  433. package/dist/electron/modules/stt/model-manager.js +0 -321
  434. package/dist/electron/modules/stt/model-manager.js.map +0 -1
  435. package/dist/electron/modules/stt/router.d.ts +0 -35
  436. package/dist/electron/modules/stt/router.d.ts.map +0 -1
  437. package/dist/electron/modules/stt/router.js +0 -263
  438. package/dist/electron/modules/stt/router.js.map +0 -1
  439. package/dist/electron/modules/stt/sherpa-engine.d.ts +0 -43
  440. package/dist/electron/modules/stt/sherpa-engine.d.ts.map +0 -1
  441. package/dist/electron/modules/stt/sherpa-engine.js +0 -521
  442. package/dist/electron/modules/stt/sherpa-engine.js.map +0 -1
  443. package/dist/electron/modules/stt/types.d.ts +0 -72
  444. package/dist/electron/modules/stt/types.d.ts.map +0 -1
  445. package/dist/electron/modules/stt/types.js +0 -16
  446. package/dist/electron/modules/stt/types.js.map +0 -1
  447. package/dist/electron/modules/stt/winrt-engine.d.ts +0 -20
  448. package/dist/electron/modules/stt/winrt-engine.d.ts.map +0 -1
  449. package/dist/electron/modules/stt/winrt-engine.js +0 -238
  450. package/dist/electron/modules/stt/winrt-engine.js.map +0 -1
  451. package/dist/electron/modules/tce/content-analyzer.d.ts +0 -20
  452. package/dist/electron/modules/tce/content-analyzer.d.ts.map +0 -1
  453. package/dist/electron/modules/tce/content-analyzer.js +0 -123
  454. package/dist/electron/modules/tce/content-analyzer.js.map +0 -1
  455. package/dist/electron/modules/tce/index.d.ts +0 -54
  456. package/dist/electron/modules/tce/index.d.ts.map +0 -1
  457. package/dist/electron/modules/tce/index.js +0 -174
  458. package/dist/electron/modules/tce/index.js.map +0 -1
  459. package/dist/electron/modules/tce/layout-engine.d.ts +0 -68
  460. package/dist/electron/modules/tce/layout-engine.d.ts.map +0 -1
  461. package/dist/electron/modules/tce/layout-engine.js +0 -313
  462. package/dist/electron/modules/tce/layout-engine.js.map +0 -1
  463. package/dist/electron/modules/tce/renderer.d.ts +0 -16
  464. package/dist/electron/modules/tce/renderer.d.ts.map +0 -1
  465. package/dist/electron/modules/tce/renderer.js +0 -196
  466. package/dist/electron/modules/tce/renderer.js.map +0 -1
  467. package/dist/electron/modules/tce/themes.d.ts +0 -14
  468. package/dist/electron/modules/tce/themes.d.ts.map +0 -1
  469. package/dist/electron/modules/tce/themes.js +0 -68
  470. package/dist/electron/modules/tce/themes.js.map +0 -1
  471. package/dist/electron/modules/tce/token-estimator.d.ts +0 -30
  472. package/dist/electron/modules/tce/token-estimator.d.ts.map +0 -1
  473. package/dist/electron/modules/tce/token-estimator.js +0 -59
  474. package/dist/electron/modules/tce/token-estimator.js.map +0 -1
  475. package/dist/electron/modules/telemetry.d.ts +0 -44
  476. package/dist/electron/modules/telemetry.d.ts.map +0 -1
  477. package/dist/electron/modules/telemetry.js +0 -316
  478. package/dist/electron/modules/telemetry.js.map +0 -1
  479. package/dist/electron/modules/template-match.d.ts +0 -62
  480. package/dist/electron/modules/template-match.d.ts.map +0 -1
  481. package/dist/electron/modules/template-match.js +0 -205
  482. package/dist/electron/modules/template-match.js.map +0 -1
  483. package/dist/electron/modules/tray.d.ts +0 -24
  484. package/dist/electron/modules/tray.d.ts.map +0 -1
  485. package/dist/electron/modules/tray.js +0 -349
  486. package/dist/electron/modules/tray.js.map +0 -1
  487. package/dist/electron/modules/uiohook-manager.d.ts +0 -19
  488. package/dist/electron/modules/uiohook-manager.d.ts.map +0 -1
  489. package/dist/electron/modules/uiohook-manager.js +0 -101
  490. package/dist/electron/modules/uiohook-manager.js.map +0 -1
  491. package/dist/electron/modules/undo-stack.d.ts +0 -22
  492. package/dist/electron/modules/undo-stack.d.ts.map +0 -1
  493. package/dist/electron/modules/undo-stack.js +0 -41
  494. package/dist/electron/modules/undo-stack.js.map +0 -1
  495. package/dist/electron/modules/updater.d.ts +0 -14
  496. package/dist/electron/modules/updater.d.ts.map +0 -1
  497. package/dist/electron/modules/updater.js +0 -102
  498. package/dist/electron/modules/updater.js.map +0 -1
  499. package/dist/electron/modules/usage-link.d.ts +0 -7
  500. package/dist/electron/modules/usage-link.d.ts.map +0 -1
  501. package/dist/electron/modules/usage-link.js +0 -63
  502. package/dist/electron/modules/usage-link.js.map +0 -1
  503. package/dist/electron/modules/version-check.d.ts +0 -3
  504. package/dist/electron/modules/version-check.d.ts.map +0 -1
  505. package/dist/electron/modules/version-check.js +0 -76
  506. package/dist/electron/modules/version-check.js.map +0 -1
  507. package/dist/electron/modules/watchers/active-window-watcher.d.ts +0 -5
  508. package/dist/electron/modules/watchers/active-window-watcher.d.ts.map +0 -1
  509. package/dist/electron/modules/watchers/active-window-watcher.js +0 -152
  510. package/dist/electron/modules/watchers/active-window-watcher.js.map +0 -1
  511. package/dist/electron/modules/watchers/clipboard-watcher.d.ts +0 -5
  512. package/dist/electron/modules/watchers/clipboard-watcher.d.ts.map +0 -1
  513. package/dist/electron/modules/watchers/clipboard-watcher.js +0 -90
  514. package/dist/electron/modules/watchers/clipboard-watcher.js.map +0 -1
  515. package/dist/electron/modules/watchers/file-watcher.d.ts +0 -5
  516. package/dist/electron/modules/watchers/file-watcher.d.ts.map +0 -1
  517. package/dist/electron/modules/watchers/file-watcher.js +0 -91
  518. package/dist/electron/modules/watchers/file-watcher.js.map +0 -1
  519. package/dist/electron/modules/watchers/registry.d.ts +0 -34
  520. package/dist/electron/modules/watchers/registry.d.ts.map +0 -1
  521. package/dist/electron/modules/watchers/registry.js +0 -108
  522. package/dist/electron/modules/watchers/registry.js.map +0 -1
  523. package/dist/electron/modules/watchers/screen-region-service.d.ts +0 -18
  524. package/dist/electron/modules/watchers/screen-region-service.d.ts.map +0 -1
  525. package/dist/electron/modules/watchers/screen-region-service.js +0 -126
  526. package/dist/electron/modules/watchers/screen-region-service.js.map +0 -1
  527. package/dist/electron/modules/watchers/screen-region-watcher.d.ts +0 -6
  528. package/dist/electron/modules/watchers/screen-region-watcher.d.ts.map +0 -1
  529. package/dist/electron/modules/watchers/screen-region-watcher.js +0 -70
  530. package/dist/electron/modules/watchers/screen-region-watcher.js.map +0 -1
  531. package/dist/electron/modules/window-activate.d.ts +0 -103
  532. package/dist/electron/modules/window-activate.d.ts.map +0 -1
  533. package/dist/electron/modules/window-activate.js +0 -630
  534. package/dist/electron/modules/window-activate.js.map +0 -1
  535. package/dist/electron/modules/window-input.d.ts +0 -43
  536. package/dist/electron/modules/window-input.d.ts.map +0 -1
  537. package/dist/electron/modules/window-input.js +0 -623
  538. package/dist/electron/modules/window-input.js.map +0 -1
  539. package/dist/electron/modules/window-picker.d.ts +0 -6
  540. package/dist/electron/modules/window-picker.d.ts.map +0 -1
  541. package/dist/electron/modules/window-picker.js +0 -192
  542. package/dist/electron/modules/window-picker.js.map +0 -1
  543. package/dist/electron/modules/window-resolver.d.ts +0 -35
  544. package/dist/electron/modules/window-resolver.d.ts.map +0 -1
  545. package/dist/electron/modules/window-resolver.js +0 -210
  546. package/dist/electron/modules/window-resolver.js.map +0 -1
  547. package/dist/headless/electron/ai/ai-client.js +0 -204
  548. package/dist/headless/electron/ai/context-builder.js +0 -27
  549. package/dist/headless/electron/ai/instruction-parser.js +0 -46
  550. package/dist/headless/electron/core/auth-store.js +0 -85
  551. package/dist/headless/electron/core/config.js +0 -80
  552. package/dist/headless/electron/core/file-logger.js +0 -73
  553. package/dist/headless/electron/core/input-injection/index.js +0 -30
  554. package/dist/headless/electron/core/input-injection/macos.js +0 -13
  555. package/dist/headless/electron/core/input-injection/windows.js +0 -118
  556. package/dist/headless/electron/core/json-store.js +0 -131
  557. package/dist/headless/electron/core/paths.js +0 -116
  558. package/dist/headless/electron/core/platform.js +0 -17
  559. package/dist/headless/electron/core/process-coord.js +0 -123
  560. package/dist/headless/electron/core/serialize-schema.js +0 -88
  561. package/dist/headless/electron/core/settings-schema.js +0 -1369
  562. package/dist/headless/electron/db/database.js +0 -636
  563. package/dist/headless/electron/db/models.js +0 -3
  564. package/dist/headless/electron/logger.js +0 -31
  565. package/dist/headless/electron/modules/accessibility/macos-provider.js +0 -93
  566. package/dist/headless/electron/modules/accessibility/provider.js +0 -51
  567. package/dist/headless/electron/modules/accessibility/types.js +0 -5
  568. package/dist/headless/electron/modules/accessibility/windows-provider.js +0 -84
  569. package/dist/headless/electron/modules/active-window.js +0 -75
  570. package/dist/headless/electron/modules/api-server.js +0 -2758
  571. package/dist/headless/electron/modules/auth.js +0 -192
  572. package/dist/headless/electron/modules/azure-speech-realtime.js +0 -542
  573. package/dist/headless/electron/modules/capture.js +0 -190
  574. package/dist/headless/electron/modules/clipboard.js +0 -25
  575. package/dist/headless/electron/modules/context-menu-detect.js +0 -271
  576. package/dist/headless/electron/modules/dictation.js +0 -1230
  577. package/dist/headless/electron/modules/gui-automation-errors.js +0 -78
  578. package/dist/headless/electron/modules/gui-automation-telemetry.js +0 -199
  579. package/dist/headless/electron/modules/gui-automation.js +0 -8768
  580. package/dist/headless/electron/modules/human-input/keyboard/timing.js +0 -56
  581. package/dist/headless/electron/modules/human-input/mouse/path.js +0 -79
  582. package/dist/headless/electron/modules/human-input/mouse/velocity.js +0 -92
  583. package/dist/headless/electron/modules/human-input/profiles.js +0 -123
  584. package/dist/headless/electron/modules/human-input/rng.js +0 -100
  585. package/dist/headless/electron/modules/human-input/salt.js +0 -47
  586. package/dist/headless/electron/modules/image-utils.js +0 -79
  587. package/dist/headless/electron/modules/keystroke.js +0 -52
  588. package/dist/headless/electron/modules/license.js +0 -174
  589. package/dist/headless/electron/modules/mcp-config.js +0 -145
  590. package/dist/headless/electron/modules/ocr.js +0 -187
  591. package/dist/headless/electron/modules/ollama/capability.js +0 -116
  592. package/dist/headless/electron/modules/ollama/client.js +0 -133
  593. package/dist/headless/electron/modules/ollama/detector.js +0 -176
  594. package/dist/headless/electron/modules/ollama/dispatcher.js +0 -96
  595. package/dist/headless/electron/modules/ollama/router.js +0 -200
  596. package/dist/headless/electron/modules/platform/dpi.js +0 -47
  597. package/dist/headless/electron/modules/platform/errors.js +0 -35
  598. package/dist/headless/electron/modules/platform/index.js +0 -132
  599. package/dist/headless/electron/modules/platform/interfaces.js +0 -13
  600. package/dist/headless/electron/modules/platform/macos/ax.js +0 -221
  601. package/dist/headless/electron/modules/platform/macos/capture.js +0 -105
  602. package/dist/headless/electron/modules/platform/macos/input.js +0 -341
  603. package/dist/headless/electron/modules/platform/macos/launch.js +0 -113
  604. package/dist/headless/electron/modules/platform/macos/session.js +0 -16
  605. package/dist/headless/electron/modules/platform/macos/window.js +0 -270
  606. package/dist/headless/electron/modules/platform/shared.js +0 -200
  607. package/dist/headless/electron/modules/platform/types.js +0 -23
  608. package/dist/headless/electron/modules/platform/windows/ax.js +0 -276
  609. package/dist/headless/electron/modules/platform/windows/capture.js +0 -114
  610. package/dist/headless/electron/modules/platform/windows/input.js +0 -421
  611. package/dist/headless/electron/modules/platform/windows/launch.js +0 -184
  612. package/dist/headless/electron/modules/platform/windows/session.js +0 -86
  613. package/dist/headless/electron/modules/platform/windows/tray.js +0 -389
  614. package/dist/headless/electron/modules/platform/windows/window.js +0 -443
  615. package/dist/headless/electron/modules/recording/ai-analysis.js +0 -87
  616. package/dist/headless/electron/modules/recording/capture-queue.js +0 -408
  617. package/dist/headless/electron/modules/recording/cli.js +0 -134
  618. package/dist/headless/electron/modules/recording/http-api.js +0 -235
  619. package/dist/headless/electron/modules/recording/index.js +0 -153
  620. package/dist/headless/electron/modules/recording/input-hook-provider.js +0 -4
  621. package/dist/headless/electron/modules/recording/mcp-tool.js +0 -80
  622. package/dist/headless/electron/modules/recording/monitor-analyzer.js +0 -219
  623. package/dist/headless/electron/modules/recording/providers/change-detect-provider.js +0 -180
  624. package/dist/headless/electron/modules/recording/providers/change-detect-shared-wrapper.js +0 -61
  625. package/dist/headless/electron/modules/recording/providers/periodic-provider.js +0 -54
  626. package/dist/headless/electron/modules/recording/providers/provider-factory.js +0 -96
  627. package/dist/headless/electron/modules/recording/providers/uiohook-provider.js +0 -266
  628. package/dist/headless/electron/modules/recording/recording-session.js +0 -388
  629. package/dist/headless/electron/modules/recording/session-alignment.js +0 -102
  630. package/dist/headless/electron/modules/recording/session-export.js +0 -286
  631. package/dist/headless/electron/modules/recording/trigger-engine.js +0 -552
  632. package/dist/headless/electron/modules/recording/visual-diff.js +0 -108
  633. package/dist/headless/electron/modules/redact.js +0 -582
  634. package/dist/headless/electron/modules/scroll-calibration.js +0 -270
  635. package/dist/headless/electron/modules/sequence-locate.js +0 -355
  636. package/dist/headless/electron/modules/store.js +0 -125
  637. package/dist/headless/electron/modules/stt/capability-probe.js +0 -330
  638. package/dist/headless/electron/modules/stt/macos-engine.js +0 -230
  639. package/dist/headless/electron/modules/stt/model-manager.js +0 -320
  640. package/dist/headless/electron/modules/stt/router.js +0 -262
  641. package/dist/headless/electron/modules/stt/sherpa-engine.js +0 -520
  642. package/dist/headless/electron/modules/stt/types.js +0 -15
  643. package/dist/headless/electron/modules/stt/winrt-engine.js +0 -237
  644. package/dist/headless/electron/modules/tce/content-analyzer.js +0 -122
  645. package/dist/headless/electron/modules/tce/index.js +0 -173
  646. package/dist/headless/electron/modules/tce/layout-engine.js +0 -312
  647. package/dist/headless/electron/modules/tce/renderer.js +0 -195
  648. package/dist/headless/electron/modules/tce/themes.js +0 -67
  649. package/dist/headless/electron/modules/tce/token-estimator.js +0 -58
  650. package/dist/headless/electron/modules/telemetry.js +0 -315
  651. package/dist/headless/electron/modules/template-match.js +0 -204
  652. package/dist/headless/electron/modules/uiohook-manager.js +0 -100
  653. package/dist/headless/electron/modules/undo-stack.js +0 -40
  654. package/dist/headless/electron/modules/watchers/active-window-watcher.js +0 -151
  655. package/dist/headless/electron/modules/watchers/clipboard-watcher.js +0 -89
  656. package/dist/headless/electron/modules/watchers/file-watcher.js +0 -90
  657. package/dist/headless/electron/modules/watchers/registry.js +0 -107
  658. package/dist/headless/electron/modules/watchers/screen-region-service.js +0 -125
  659. package/dist/headless/electron/modules/watchers/screen-region-watcher.js +0 -69
  660. package/dist/headless/electron/modules/window-activate.js +0 -629
  661. package/dist/headless/electron/modules/window-input.js +0 -622
  662. package/dist/headless/electron/modules/window-resolver.js +0 -209
  663. package/dist/headless/headless/capture-hotkey.js +0 -155
  664. package/dist/headless/headless/cli-auth.js +0 -158
  665. package/dist/headless/headless/cli.js +0 -278
  666. package/dist/headless/headless/config-cmd.js +0 -306
  667. package/dist/headless/headless/dictation-hotkey.js +0 -525
  668. package/dist/headless/headless/dictation-overlay.js +0 -218
  669. package/dist/headless/headless/doctor.js +0 -599
  670. package/dist/headless/headless/mic-capture.js +0 -406
  671. package/dist/headless/headless/ollama-cmd.js +0 -211
  672. package/dist/headless/headless/platform-headless.js +0 -233
  673. package/dist/headless/headless/server.js +0 -195
  674. package/dist/headless/headless/stt-cmd.js +0 -213
  675. package/dist/headless/headless/tui/index.mjs +0 -7
  676. package/dist/headless/headless/tui/plain-dump.js +0 -41
  677. package/dist/headless/headless/tui/settings-app.mjs +0 -744
  678. package/dist/headless/headless/tui/setup-wizard.mjs +0 -257
  679. package/dist/headless/headless/tui-bridge.js +0 -80
  680. package/dist/headless/headless/win32-text-injector.js +0 -359
  681. package/dist/headless/mic-capture.d.ts +0 -49
  682. package/dist/headless/mic-capture.d.ts.map +0 -1
  683. package/dist/headless/mic-capture.js +0 -407
  684. package/dist/headless/mic-capture.js.map +0 -1
  685. package/dist/headless/shared/constants.js +0 -65
  686. package/dist/headless/shared/design-tokens.js +0 -189
  687. package/dist/headless/shared/recording-types.js +0 -93
  688. package/dist/headless/shared/types.js +0 -3
  689. package/dist/shared/constants.d.ts +0 -100
  690. package/dist/shared/constants.d.ts.map +0 -1
  691. package/dist/shared/constants.js +0 -66
  692. package/dist/shared/constants.js.map +0 -1
  693. package/dist/shared/design-tokens.d.ts +0 -112
  694. package/dist/shared/design-tokens.d.ts.map +0 -1
  695. package/dist/shared/design-tokens.js +0 -190
  696. package/dist/shared/design-tokens.js.map +0 -1
  697. package/dist/shared/recording-types.d.ts +0 -186
  698. package/dist/shared/recording-types.d.ts.map +0 -1
  699. package/dist/shared/recording-types.js +0 -94
  700. package/dist/shared/recording-types.js.map +0 -1
  701. package/dist/shared/types.d.ts +0 -143
  702. package/dist/shared/types.d.ts.map +0 -1
  703. package/dist/shared/types.js +0 -4
  704. package/dist/shared/types.js.map +0 -1
  705. package/mcp-server/dist/api-client.js +0 -521
  706. package/mcp-server/dist/index.js +0 -2550
  707. package/mcp-server/dist/project-sense.js +0 -161
  708. package/mcp-server/dist/tool-categories.js +0 -161
  709. package/mcp-server/package.json +0 -22
@@ -1,2550 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- // SuperBased MCP Server — exposes desktop app capabilities to AI coding CLIs.
4
- // Connects via stdio transport. Proxies tool calls to SuperBased HTTP API.
5
- // Usage: node index.js [--port PORT] [--project-dir DIR]
6
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
- if (k2 === undefined) k2 = k;
8
- var desc = Object.getOwnPropertyDescriptor(m, k);
9
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
- desc = { enumerable: true, get: function() { return m[k]; } };
11
- }
12
- Object.defineProperty(o, k2, desc);
13
- }) : (function(o, m, k, k2) {
14
- if (k2 === undefined) k2 = k;
15
- o[k2] = m[k];
16
- }));
17
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
- Object.defineProperty(o, "default", { enumerable: true, value: v });
19
- }) : function(o, v) {
20
- o["default"] = v;
21
- });
22
- var __importStar = (this && this.__importStar) || (function () {
23
- var ownKeys = function(o) {
24
- ownKeys = Object.getOwnPropertyNames || function (o) {
25
- var ar = [];
26
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
- return ar;
28
- };
29
- return ownKeys(o);
30
- };
31
- return function (mod) {
32
- if (mod && mod.__esModule) return mod;
33
- var result = {};
34
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
- __setModuleDefault(result, mod);
36
- return result;
37
- };
38
- })();
39
- Object.defineProperty(exports, "__esModule", { value: true });
40
- exports.registerMcpTools = registerMcpTools;
41
- exports.startMcpServer = startMcpServer;
42
- exports.createMcpHttpHandler = createMcpHttpHandler;
43
- const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
44
- const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
45
- const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
46
- const zod_1 = require("zod");
47
- const api_client_1 = require("./api-client");
48
- const fs = __importStar(require("fs"));
49
- const path = __importStar(require("path"));
50
- const os = __importStar(require("os"));
51
- // Parse CLI args
52
- function parseArgs() {
53
- const args = process.argv.slice(2);
54
- let port = 47592;
55
- let projectDir;
56
- for (let i = 0; i < args.length; i++) {
57
- if (args[i] === '--port' && args[i + 1]) {
58
- port = parseInt(args[i + 1], 10);
59
- i++;
60
- }
61
- else if (args[i] === '--project-dir' && args[i + 1]) {
62
- projectDir = args[i + 1];
63
- i++;
64
- }
65
- }
66
- // Try to read config file for port discovery
67
- if (port === 47592) {
68
- const configPath = path.join(os.homedir(), '.superbased', 'mcp.json');
69
- try {
70
- if (fs.existsSync(configPath)) {
71
- const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
72
- if (config.apiUrl) {
73
- const url = new URL(config.apiUrl);
74
- port = parseInt(url.port, 10) || 47592;
75
- }
76
- }
77
- }
78
- catch {
79
- // Config not found or invalid — use default
80
- }
81
- }
82
- // Default projectDir to CWD (which is typically the project dir when invoked from Claude Code)
83
- if (!projectDir) {
84
- projectDir = process.cwd();
85
- }
86
- return { port, projectDir };
87
- }
88
- function formatResponse(data) {
89
- return JSON.stringify(data, null, 2);
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
- }
241
- /**
242
- * Register all MCP tools and resources on a McpServer instance.
243
- * Shared between stdio transport (CLI) and HTTP transport (API server).
244
- */
245
- function registerMcpTools(server, client, projectDir) {
246
- // Compatibility shim for MCP clients that reject `{ type: 'image' }` content
247
- // blocks despite the MCP spec accepting them. Observed concrete failure:
248
- // OpenCode's MCP client validates each block with a Zod schema that only
249
- // permits `type: 'text'`, surfacing as `-32602 Invalid params: expected
250
- // "text"` on every tool that returns a screenshot (workspace_sync, ui_dump,
251
- // capture_image, scroll_capture, …).
252
- // When SUPERBASED_MCP_TEXT_ONLY=1 is set on the bridge process (configurable
253
- // per-client in the MCP server's `env` block), we transparently filter image
254
- // content blocks out of every tool response before they reach the transport.
255
- // The text block is kept — agents still see the metadata + base64 byte count;
256
- // they just lose direct vision-model handoff. Non-strict clients (Claude
257
- // Code, Cursor, Windsurf, Codex) leave the var unset and keep getting the
258
- // image blocks they asked for.
259
- const stripImageBlocks = process.env.SUPERBASED_MCP_TEXT_ONLY === '1';
260
- if (stripImageBlocks) {
261
- const origTool = server.tool.bind(server);
262
- server.tool = (...toolArgs) => {
263
- // server.tool's last positional arg is always the handler callback.
264
- const handler = toolArgs[toolArgs.length - 1];
265
- if (typeof handler === 'function') {
266
- const wrapped = async (...handlerArgs) => {
267
- const result = await handler(...handlerArgs);
268
- if (result && typeof result === 'object' && 'content' in result) {
269
- const r = result;
270
- if (Array.isArray(r.content)) {
271
- r.content = r.content.filter((b) => {
272
- return !(b && typeof b === 'object' && b.type === 'image');
273
- });
274
- // MCP spec allows empty content, but some clients reject zero-
275
- // length arrays. Guarantee at least one block.
276
- if (r.content.length === 0) {
277
- r.content.push({ type: 'text', text: '(image content stripped — SUPERBASED_MCP_TEXT_ONLY=1)' });
278
- }
279
- }
280
- }
281
- return result;
282
- };
283
- toolArgs[toolArgs.length - 1] = wrapped;
284
- }
285
- return origTool(...toolArgs);
286
- };
287
- }
288
- // Monitor alert poller state
289
- let monitorPoller = null;
290
- let monitorSessionId = null;
291
- let lastSeenFrame = 0;
292
- function startMonitorPoller(sessionId) {
293
- stopMonitorPoller();
294
- monitorSessionId = sessionId;
295
- lastSeenFrame = 0;
296
- monitorPoller = setInterval(async () => {
297
- try {
298
- const res = await client.recordingGetAnalysis(sessionId, lastSeenFrame);
299
- const analyses = res.data?.analyses || [];
300
- for (const a of analyses) {
301
- lastSeenFrame = Math.max(lastSeenFrame, a.frameNumber);
302
- try {
303
- await server.server.sendLoggingMessage({
304
- level: 'info',
305
- logger: 'superbased-monitor',
306
- data: {
307
- type: 'monitor_alert',
308
- sessionId,
309
- frameId: a.frameId,
310
- frameNumber: a.frameNumber,
311
- analysis: a.analysis,
312
- timestamp: a.timestamp,
313
- },
314
- });
315
- }
316
- catch {
317
- // Client may not support logging notifications
318
- }
319
- }
320
- }
321
- catch {
322
- // API not available — session may have ended
323
- }
324
- }, 10000);
325
- }
326
- function stopMonitorPoller() {
327
- if (monitorPoller) {
328
- clearInterval(monitorPoller);
329
- monitorPoller = null;
330
- }
331
- monitorSessionId = null;
332
- lastSeenFrame = 0;
333
- }
334
- // ── Tool: superbased_capture ──
335
- server.tool('superbased_capture', 'Take a screenshot (returns metadata only, not the image). Use superbased_capture_image instead if you need to SEE the screen.', {
336
- mode: zod_1.z.enum(['fullscreen', 'region', 'active_window']).describe('Capture mode'),
337
- x: zod_1.z.number().optional().describe('Left coordinate for region capture'),
338
- y: zod_1.z.number().optional().describe('Top coordinate for region capture'),
339
- width: zod_1.z.number().optional().describe('Width for region capture'),
340
- height: zod_1.z.number().optional().describe('Height for region capture'),
341
- projectDir: zod_1.z.string().optional().describe('Project directory — captures save to {projectDir}/.superbased/captures/'),
342
- }, async ({ mode, x, y, width, height, projectDir: pd }) => {
343
- try {
344
- const dir = pd || projectDir;
345
- switch (mode) {
346
- case 'region': {
347
- if (x === undefined || y === undefined || width === undefined || height === undefined) {
348
- return { content: [{ type: 'text', text: 'Error: x, y, width, height are required for region capture' }], isError: true };
349
- }
350
- const res = await client.captureRegion(x, y, width, height, dir);
351
- const { imageBase64: _img, ...summary } = res.data;
352
- const payload = { ...summary, imageSizeBytes: res.data.imageBase64?.length || 0, next_steps: nextStepsForCapture(summary.captureId) };
353
- return { content: [{ type: 'text', text: formatResponse(payload) }] };
354
- }
355
- case 'active_window': {
356
- const res = await client.captureActiveWindow();
357
- const payload = { windowInfo: res.data.windowInfo, imageSizeBytes: res.data.imageBase64?.length || 0, next_steps: nextStepsForCapture(res.data.captureId) };
358
- return { content: [{ type: 'text', text: formatResponse(payload) }] };
359
- }
360
- case 'fullscreen':
361
- default: {
362
- const res = await client.captureFullscreen(dir);
363
- const { imageBase64: _img, ...summary } = res.data;
364
- const payload = { ...summary, imageSizeBytes: res.data.imageBase64?.length || 0, next_steps: nextStepsForCapture(summary.captureId) };
365
- return { content: [{ type: 'text', text: formatResponse(payload) }] };
366
- }
367
- }
368
- }
369
- catch (err) {
370
- const msg = err instanceof Error ? err.message : String(err);
371
- return { content: [{ type: 'text', text: msg }], isError: true };
372
- }
373
- });
374
- // ── Tool: superbased_ai ──
375
- 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.', {
376
- 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.'),
377
- captureId: captureRefSchema.optional().describe(`ID of an existing capture from the gallery. ${captureRefDescription}`),
378
- screenshotPath: zod_1.z.string().optional().describe('Path to a screenshot file on disk'),
379
- projectDir: zod_1.z.string().optional().describe('Project directory for auto-captures. Defaults to CWD.'),
380
- 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>".'),
381
- 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).'),
382
- 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.'),
383
- }, async ({ instruction, captureId, screenshotPath, projectDir: pd, provider, model, forceVision }) => {
384
- try {
385
- const captureIdNum = parseCaptureRef(captureId);
386
- const res = await client.processAI({
387
- instruction,
388
- captureId: captureIdNum ?? undefined,
389
- screenshotPath,
390
- projectDir: pd || projectDir,
391
- provider,
392
- model,
393
- forceVision,
394
- });
395
- if (res.status >= 400) {
396
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: true };
397
- }
398
- return { content: [{ type: 'text', text: res.data.response }] };
399
- }
400
- catch (err) {
401
- const msg = err instanceof Error ? err.message : String(err);
402
- return { content: [{ type: 'text', text: msg }], isError: true };
403
- }
404
- });
405
- // ── Tool: superbased_ocr ──
406
- 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.', {
407
- screenshotPath: zod_1.z.string().optional().describe('Path to a screenshot file on disk'),
408
- captureId: captureRefSchema.optional().describe(`ID of an existing capture — loads the image from gallery. ${captureRefDescription}`),
409
- }, async ({ screenshotPath, captureId }) => {
410
- try {
411
- const captureIdNum = parseCaptureRef(captureId);
412
- let params = {};
413
- if (screenshotPath) {
414
- params = { screenshotPath };
415
- }
416
- else if (captureIdNum !== null) {
417
- const captureRes = await client.getCapture(captureIdNum);
418
- const capture = captureRes.data.capture;
419
- if (capture?.screenshot_path) {
420
- params = { screenshotPath: capture.screenshot_path };
421
- }
422
- else {
423
- return { content: [{ type: 'text', text: `Capture ${captureIdNum} not found or has no image` }], isError: true };
424
- }
425
- }
426
- else {
427
- return { content: [{ type: 'text', text: 'screenshotPath or captureId is required' }], isError: true };
428
- }
429
- const res = await client.ocr(params);
430
- return { content: [{ type: 'text', text: res.data.text }] };
431
- }
432
- catch (err) {
433
- const msg = err instanceof Error ? err.message : String(err);
434
- return { content: [{ type: 'text', text: msg }], isError: true };
435
- }
436
- });
437
- // ── Tool: superbased_gallery ──
438
- server.tool('superbased_gallery', 'Browse and search past screenshots. Use when you need to find a previously captured image or check capture history.', {
439
- action: zod_1.z.enum(['list', 'get', 'search', 'stats']).describe('list=recent captures, get=specific capture, search=full-text, stats=statistics'),
440
- captureId: captureRefSchema.optional().describe(`Capture ID (for get action). ${captureRefDescription}`),
441
- query: zod_1.z.string().optional().describe('Search query (for search action)'),
442
- limit: zod_1.z.number().optional().describe('Max results to return (default 20)'),
443
- }, async ({ action, captureId, query, limit }) => {
444
- try {
445
- const captureIdNum = parseCaptureRef(captureId);
446
- switch (action) {
447
- case 'get': {
448
- if (captureIdNum === null) {
449
- return { content: [{ type: 'text', text: 'captureId is required for get action' }], isError: true };
450
- }
451
- const res = await client.getCapture(captureIdNum);
452
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
453
- }
454
- case 'search': {
455
- if (!query) {
456
- return { content: [{ type: 'text', text: 'query is required for search action' }], isError: true };
457
- }
458
- const res = await client.searchCaptures(query, limit || 20);
459
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
460
- }
461
- case 'stats': {
462
- const res = await client.getStats();
463
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
464
- }
465
- case 'list':
466
- default: {
467
- const res = await client.getCaptures(limit || 20);
468
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
469
- }
470
- }
471
- }
472
- catch (err) {
473
- const msg = err instanceof Error ? err.message : String(err);
474
- return { content: [{ type: 'text', text: msg }], isError: true };
475
- }
476
- });
477
- // ── Tool: superbased_gallery_update ──
478
- server.tool('superbased_gallery_update', 'Update tags or notes on a saved capture.', {
479
- captureId: captureRefSchema.describe(`Capture ID to update. ${captureRefDescription}`),
480
- tags: zod_1.z.string().optional().describe('Comma-separated tags (replaces existing tags)'),
481
- notes: zod_1.z.string().optional().describe('Notes text (replaces existing notes)'),
482
- }, async ({ captureId, tags, notes }) => {
483
- try {
484
- const captureIdNum = parseCaptureRef(captureId);
485
- if (captureIdNum === null) {
486
- return { content: [{ type: 'text', text: `Invalid captureId: ${String(captureId)}` }], isError: true };
487
- }
488
- const results = [];
489
- if (tags !== undefined) {
490
- await client.updateTags(captureIdNum, tags);
491
- results.push(`Tags updated to: ${tags}`);
492
- }
493
- if (notes !== undefined) {
494
- await client.updateNotes(captureIdNum, notes);
495
- results.push(`Notes updated`);
496
- }
497
- if (results.length === 0) {
498
- return { content: [{ type: 'text', text: 'Provide tags or notes to update' }], isError: true };
499
- }
500
- return { content: [{ type: 'text', text: results.join('\n') }] };
501
- }
502
- catch (err) {
503
- const msg = err instanceof Error ? err.message : String(err);
504
- return { content: [{ type: 'text', text: msg }], isError: true };
505
- }
506
- });
507
- // ── Tool: superbased_settings ──
508
- server.tool('superbased_settings', 'View or change SuperBased settings (theme, provider, model, screenshot folder).', {
509
- action: zod_1.z.enum(['get', 'set', 'get_provider']).describe('get=all settings, set=update a setting, get_provider=current AI provider'),
510
- key: zod_1.z.string().optional().describe('Setting key (for set action). Common: theme, activeProvider, activeModel, screenshotFolder'),
511
- value: zod_1.z.string().optional().describe('New value (for set action). Use JSON for complex values.'),
512
- }, async ({ action, key, value }) => {
513
- try {
514
- switch (action) {
515
- case 'set': {
516
- if (!key) {
517
- return { content: [{ type: 'text', text: 'key is required for set action' }], isError: true };
518
- }
519
- let parsedValue = value;
520
- if (typeof value === 'string') {
521
- try {
522
- parsedValue = JSON.parse(value);
523
- }
524
- catch {
525
- parsedValue = value;
526
- }
527
- }
528
- const res = await client.setSetting(key, parsedValue);
529
- if (res.status >= 400) {
530
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: true };
531
- }
532
- return { content: [{ type: 'text', text: `Setting '${key}' updated successfully` }] };
533
- }
534
- case 'get_provider': {
535
- const res = await client.getProvider();
536
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
537
- }
538
- case 'get':
539
- default: {
540
- const res = await client.getSettings();
541
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
542
- }
543
- }
544
- }
545
- catch (err) {
546
- const msg = err instanceof Error ? err.message : String(err);
547
- return { content: [{ type: 'text', text: msg }], isError: true };
548
- }
549
- });
550
- // ── Tool: superbased_presets ──
551
- server.tool('superbased_presets', 'Manage saved AI instruction presets (templates with optional keyboard shortcuts).', {
552
- action: zod_1.z.enum(['list', 'create', 'update', 'delete']).describe('list, create, update, or delete a preset'),
553
- id: zod_1.z.number().optional().describe('Preset ID (for update/delete)'),
554
- name: zod_1.z.string().optional().describe('Preset name (for create/update)'),
555
- instruction: zod_1.z.string().optional().describe('AI instruction template (for create/update)'),
556
- shortcut: zod_1.z.string().optional().describe('Keyboard shortcut (optional)'),
557
- }, async ({ action, id, name, instruction, shortcut }) => {
558
- try {
559
- switch (action) {
560
- case 'create': {
561
- if (!name || !instruction) {
562
- return { content: [{ type: 'text', text: 'name and instruction are required' }], isError: true };
563
- }
564
- const res = await client.createPreset(name, instruction, shortcut);
565
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
566
- }
567
- case 'update': {
568
- if (!id || !name || !instruction) {
569
- return { content: [{ type: 'text', text: 'id, name, and instruction are required' }], isError: true };
570
- }
571
- await client.updatePreset(id, name, instruction, shortcut);
572
- return { content: [{ type: 'text', text: `Preset ${id} updated` }] };
573
- }
574
- case 'delete': {
575
- if (!id) {
576
- return { content: [{ type: 'text', text: 'id is required' }], isError: true };
577
- }
578
- await client.deletePreset(id);
579
- return { content: [{ type: 'text', text: `Preset ${id} deleted` }] };
580
- }
581
- case 'list':
582
- default: {
583
- const res = await client.getPresets();
584
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
585
- }
586
- }
587
- }
588
- catch (err) {
589
- const msg = err instanceof Error ? err.message : String(err);
590
- return { content: [{ type: 'text', text: msg }], isError: true };
591
- }
592
- });
593
- // ── Tool: superbased_recording ──
594
- server.tool('superbased_recording', 'Record the screen over time. Use smart mode for change-detection capture, monitor mode for AI-powered screen watching that alerts on errors/issues. Works in headless and desktop.', {
595
- action: zod_1.z.enum(['start', 'stop', 'pause', 'resume', 'status', 'capture', 'get_analysis']).describe('Recording action'),
596
- name: zod_1.z.string().optional().describe('Session name (for start)'),
597
- profile: zod_1.z.enum(['automated_test', 'bug_report', 'user_journey', 'compliance']).optional().describe('Recording profile (for start)'),
598
- targetApp: zod_1.z.string().optional().describe('Process name to scope recording to (for start)'),
599
- mode: zod_1.z.enum(['interaction', 'periodic', 'smart', 'monitor']).optional().describe('Recording mode: interaction (input hooks, desktop only), periodic (fixed interval), smart (change detection, headless default), monitor (smart + AI analysis)'),
600
- interval: zod_1.z.number().optional().describe('Capture interval in seconds (default: 3 for smart, 5 for monitor)'),
601
- changeThreshold: zod_1.z.number().optional().describe('0-1, minimum visual change to trigger capture (default: 0.05 = 5%)'),
602
- analysisPrompt: zod_1.z.string().optional().describe('Custom AI instruction for monitor mode analysis'),
603
- analyzeEvery: zod_1.z.number().optional().describe('AI analysis every N significant frames (monitor mode, default: 5)'),
604
- analyzeInterval: zod_1.z.number().optional().describe('Minimum seconds between AI analyses (monitor mode, default: 30)'),
605
- analysisDetail: zod_1.z.enum(['low', 'high']).optional().describe('Image resolution for AI analysis: low=512px, high=1024px (monitor mode, default: low)'),
606
- sessionId: zod_1.z.string().optional().describe('Session ID (for get_analysis)'),
607
- since: zod_1.z.number().optional().describe('Only analyses after frame N (for get_analysis)'),
608
- }, async ({ action, name, profile, targetApp, mode, interval, changeThreshold, analysisPrompt, analyzeEvery, analyzeInterval, analysisDetail, sessionId, since }) => {
609
- try {
610
- switch (action) {
611
- case 'start': {
612
- const res = await client.recordingStart({
613
- name: name || undefined,
614
- profile: profile || undefined,
615
- scope: targetApp ? 'specific_app' : undefined,
616
- targetProcessName: targetApp || undefined,
617
- mode: mode || undefined,
618
- interval: interval || undefined,
619
- changeThreshold: changeThreshold ?? undefined,
620
- analysisPrompt: analysisPrompt || undefined,
621
- analyzeEvery: analyzeEvery ?? undefined,
622
- analyzeInterval: analyzeInterval ?? undefined,
623
- analysisDetail: analysisDetail || undefined,
624
- });
625
- // Start monitor alert poller if in monitor mode
626
- if ((mode === 'monitor' || res.data?.mode === 'monitor') && res.data?.sessionId) {
627
- startMonitorPoller(res.data.sessionId);
628
- }
629
- const payload = { ...res.data, next_steps: nextStepsForRecordingStart(res.data.sessionId, mode || res.data.mode) };
630
- return { content: [{ type: 'text', text: formatResponse(payload) }] };
631
- }
632
- case 'stop': {
633
- stopMonitorPoller();
634
- const res = await client.recordingStop();
635
- const payload = { ...res.data, next_steps: nextStepsForRecordingStop(res.data.sessionId) };
636
- return { content: [{ type: 'text', text: formatResponse(payload) }] };
637
- }
638
- case 'pause': {
639
- const res = await client.recordingPause();
640
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
641
- }
642
- case 'resume': {
643
- const res = await client.recordingResume();
644
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
645
- }
646
- case 'capture': {
647
- const res = await client.recordingCapture();
648
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
649
- }
650
- case 'get_analysis': {
651
- if (!sessionId) {
652
- return { content: [{ type: 'text', text: 'sessionId is required for get_analysis action' }], isError: true };
653
- }
654
- const res = await client.recordingGetAnalysis(sessionId, since ?? undefined);
655
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
656
- }
657
- case 'status':
658
- default: {
659
- const res = await client.recordingStatus();
660
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
661
- }
662
- }
663
- }
664
- catch (err) {
665
- const msg = err instanceof Error ? err.message : String(err);
666
- return { content: [{ type: 'text', text: msg }], isError: true };
667
- }
668
- });
669
- // ── Tool: superbased_sessions ──
670
- server.tool('superbased_sessions', 'List past recording sessions or get frames from a specific session.', {
671
- action: zod_1.z.enum(['list', 'frames']).describe('list=all sessions, frames=frames for a session'),
672
- sessionId: zod_1.z.string().optional().describe('Session ID (required for frames action)'),
673
- }, async ({ action, sessionId }) => {
674
- try {
675
- if (action === 'frames') {
676
- if (!sessionId) {
677
- return { content: [{ type: 'text', text: 'sessionId is required for frames action' }], isError: true };
678
- }
679
- const framesRes = await client.getSessionFrames(sessionId);
680
- return { content: [{ type: 'text', text: formatResponse(framesRes.data) }] };
681
- }
682
- const res = await client.getSessions();
683
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
684
- }
685
- catch (err) {
686
- const msg = err instanceof Error ? err.message : String(err);
687
- return { content: [{ type: 'text', text: msg }], isError: true };
688
- }
689
- });
690
- // ── Tool: superbased_export ──
691
- server.tool('superbased_export', 'Export a recording session as ZIP, Markdown, PDF, HTML, or GIF.', {
692
- sessionId: zod_1.z.string().describe('Session ID to export'),
693
- format: zod_1.z.enum(['zip', 'markdown', 'pdf', 'html', 'gif']).describe('Export format'),
694
- output: zod_1.z.string().optional().describe('Output file path (optional, defaults to exports folder)'),
695
- }, async ({ sessionId, format, output }) => {
696
- try {
697
- const res = await client.exportSession(sessionId, format, output);
698
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
699
- }
700
- catch (err) {
701
- const msg = err instanceof Error ? err.message : String(err);
702
- return { content: [{ type: 'text', text: msg }], isError: true };
703
- }
704
- });
705
- // ── Tool: superbased_compress_text ──
706
- server.tool('superbased_compress_text', 'Convert large text to token-efficient images. Saves tokens when sending long text (logs, code, docs) to vision models.', {
707
- text: zod_1.z.string().describe('Text content to compress into optimized screenshot images'),
708
- preset: zod_1.z.enum(['compact', 'standard', 'tall', 'wide', 'full', 'auto']).optional().describe('Resolution preset (default: standard)'),
709
- columns: zod_1.z.union([zod_1.z.literal('auto'), zod_1.z.literal(1), zod_1.z.literal(2), zod_1.z.literal(3)]).optional().describe('Column layout (default: auto)'),
710
- theme: zod_1.z.enum(['dark', 'light', 'terminal', 'high-contrast', 'paper']).optional().describe('Visual theme (default: dark)'),
711
- render_style: zod_1.z.enum(['auto', 'code', 'document', 'terminal']).optional().describe('Rendering style (default: auto-detect)'),
712
- overlap_lines: zod_1.z.number().optional().describe('Lines repeated across page boundaries (default: 3)'),
713
- }, async ({ text, preset, columns, theme, render_style, overlap_lines }) => {
714
- try {
715
- const res = await client.compressText(text, { preset, columns, theme, render_style, overlap_lines });
716
- const meta = res.data.metadata;
717
- const summary = `Compressed ${meta.estimated_text_tokens} text tokens → ${meta.total_image_tokens} image tokens (${meta.compression_ratio}x, ${meta.savings_percent}% savings)\n` +
718
- `${res.data.pages.length} page(s) at ${meta.resolution}, ${meta.columns_used}-column, ${meta.content_type}${meta.language ? ` (${meta.language})` : ''}\n` +
719
- `Preset: ${meta.preset_used}`;
720
- const content = [
721
- { type: 'text', text: summary },
722
- ];
723
- for (const page of res.data.pages) {
724
- content.push({
725
- type: 'image',
726
- data: page.data,
727
- mimeType: 'image/png',
728
- });
729
- }
730
- return { content };
731
- }
732
- catch (err) {
733
- const msg = err instanceof Error ? err.message : String(err);
734
- return { content: [{ type: 'text', text: msg }], isError: true };
735
- }
736
- });
737
- // ── Tool: superbased_screenshot (Phase 8 — single preferred screenshot entry point) ──
738
- //
739
- // Why a dedicated tool when superbased_capture_image already supports
740
- // `window=`?
741
- //
742
- // Observed agent behaviour: faced with a capture-a-window request,
743
- // agents often chain `superbased_focus_window` → (permission prompt) →
744
- // `superbased_capture_image` → (second permission prompt). Each
745
- // permission prompt forces the user to click Approve in the agent
746
- // window, which steals focus back to the agent. The second prompt
747
- // comes AFTER focus_window already switched the foreground to the
748
- // target — so clicking Approve defeats the whole point, and the
749
- // subsequent capture fires against the agent window, not the target.
750
- //
751
- // This tool exists to break that pattern. Single call, minimal
752
- // signature, registered in CORE_TOOLS so it's always the first option
753
- // an agent sees. Server-side delegates to the same `captureFullscreenImage`
754
- // path as `superbased_capture_image`; all the activate-then-capture-
755
- // then-restore plumbing lives there.
756
- server.tool('superbased_screenshot', [
757
- 'Take a screenshot. Returns the image inline — for visual inspection by the user / agent.',
758
- '',
759
- '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.',
760
- '',
761
- '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.',
762
- '',
763
- 'Targeting modes (most to least specific — prefer more specific when possible):',
764
- ' • hwnd="3149370" — direct Windows handle from superbased_window_list. Unambiguous.',
765
- ' • processName="electron" — match by .exe. Combine with `target=` to disambiguate same-process windows.',
766
- ' • target="SuperBased" — case-insensitive title match with scored best-match and ambiguous-match refusal.',
767
- ' • (none) — fullscreen.',
768
- '',
769
- 'Window-specific captures run server-side in one call: activate → capture → restore focus. SINGLE permission approval.',
770
- '',
771
- '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.',
772
- '',
773
- 'If target/processName is ambiguous, this tool REFUSES and returns `alternatives[]` — then retry with hwnd from that list.',
774
- '',
775
- '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.',
776
- '',
777
- '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.',
778
- ].join('\n'), {
779
- target: zod_1.z.string().optional().describe('Window title substring (case-insensitive). Scored matcher — returns alternatives on ambiguous matches.'),
780
- processName: zod_1.z.string().optional().describe('Process executable name (e.g. "electron", "notepad"). Use with `target` to disambiguate same-process windows.'),
781
- hwnd: zod_1.z.string().optional().describe('Windows window handle from superbased_window_list. Unambiguous; bypasses scoring.'),
782
- 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.'),
783
- resolution: zod_1.z.enum(['full', 'high', 'half', 'quarter', 'thumbnail']).default('half').describe('Image resolution (half saves ~4x tokens vs full).'),
784
- }, async ({ target, processName, hwnd, background, resolution }) => {
785
- try {
786
- const res = await client.captureFullscreenImage({
787
- resolution,
788
- window: target,
789
- processName,
790
- hwnd,
791
- background,
792
- projectDir,
793
- });
794
- const d = res.data;
795
- const targetDescr = hwnd ? `hwnd=${hwnd}` : processName && target ? `${processName}/"${target}"` : processName ? processName : target ? `"${target}"` : 'fullscreen';
796
- const lines = [`Screenshot of ${targetDescr} (#${d.captureId}, ${d.width}x${d.height})`];
797
- if (d.matchedWindow) {
798
- lines.push(`Matched: ${d.matchedWindow.title} [pid: ${d.matchedWindow.processName ?? '?'}, hwnd: ${d.matchedWindow.hwnd ?? '?'}, score: ${d.matchedWindow.score} — ${d.matchedWindow.scoreReason}]`);
799
- }
800
- if (d.diagnostic) {
801
- if (d.diagnostic.backgroundMode) {
802
- // Fast path: no focus change happened at all.
803
- lines.push('✓ Background capture via PrintWindow (no focus change)');
804
- }
805
- else {
806
- const bf = d.diagnostic.broughtToFront;
807
- const note = bf === false
808
- ? '⚠ 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.'
809
- : bf === true
810
- ? '✓ Activation verified'
811
- : 'Activation status unknown (non-Windows platform)';
812
- lines.push(note);
813
- if (d.diagnostic.foregroundAfterActivate && d.matchedWindow?.hwnd && d.diagnostic.foregroundAfterActivate !== d.matchedWindow.hwnd) {
814
- lines.push(`Foreground after activate: hwnd=${d.diagnostic.foregroundAfterActivate} (expected ${d.matchedWindow.hwnd})`);
815
- }
816
- if (d.diagnostic.activationAttempts && d.diagnostic.activationAttempts > 1) {
817
- lines.push(`Activation attempts: ${d.diagnostic.activationAttempts}`);
818
- }
819
- if (d.diagnostic.restoredFocus === false) {
820
- 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.`);
821
- }
822
- else if (d.diagnostic.restoredFocus === true) {
823
- lines.push('✓ Focus restored to original window');
824
- }
825
- }
826
- }
827
- if (d.timings) {
828
- // Render as cumulative-from-start markers so the caller can
829
- // see which step is the slow one. Values are ms from
830
- // request-start; subtract consecutive entries for step
831
- // durations.
832
- const order = ['resolveMs', 'snapshotMs', 'activateMs', 'paintMs', 'captureMs', 'restoreMs', 'totalMs'];
833
- const present = order.filter((k) => d.timings && k in d.timings).map((k) => `${k.replace(/Ms$/, '')}=${d.timings?.[k]}ms`);
834
- if (present.length > 0)
835
- lines.push(`Timings: ${present.join(' · ')}`);
836
- }
837
- if (d.alternatives && d.alternatives.length > 0) {
838
- lines.push(`Other candidates (not picked): ${d.alternatives.map((a) => `${a.title} [hwnd:${a.hwnd ?? '?'}, score:${a.score}]`).join('; ')}`);
839
- }
840
- // Coordinate-space warning: when resolution is not 'full', the returned
841
- // image is downscaled. Pixel coords measured off the image do NOT map
842
- // to screen pixels (which is what superbased_click takes). Agents that
843
- // need click coords should use superbased_ui_dump instead.
844
- if (resolution && resolution !== 'full') {
845
- 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).`);
846
- }
847
- const content = [
848
- { type: 'text', text: lines.join('\n') },
849
- ];
850
- if (d.imageBase64) {
851
- content.push({ type: 'image', data: d.imageBase64, mimeType: ('mimeType' in d ? d.mimeType : null) || 'image/png' });
852
- }
853
- return { content };
854
- }
855
- catch (err) {
856
- // Ambiguous / no_match / hwnd_not_found errors arrive here with
857
- // the structured body in err.message; forward to the agent so
858
- // it can retry with a more specific target.
859
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
860
- }
861
- });
862
- // ── Tool: superbased_capture_image (advanced — region + explicit mode) ──
863
- //
864
- // Prefer `superbased_screenshot` for the common case. This tool stays
865
- // for the advanced surface (region coordinates, explicit fullscreen
866
- // vs active-window modes). Still supports `window=` — but most agents
867
- // should be routed to superbased_screenshot via that tool's more
868
- // prominent advertisement (it's in CORE_TOOLS).
869
- 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.', {
870
- mode: zod_1.z.enum(['fullscreen', 'region', 'active_window']).default('fullscreen').describe('Capture mode'),
871
- resolution: zod_1.z.enum(['full', 'high', 'half', 'quarter', 'thumbnail']).default('half').describe('Image resolution (half saves ~4x tokens vs full)'),
872
- 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.'),
873
- x: zod_1.z.number().optional(), y: zod_1.z.number().optional(),
874
- width: zod_1.z.number().optional(), height: zod_1.z.number().optional(),
875
- }, async ({ mode, resolution, window: windowName, x, y, width, height }) => {
876
- try {
877
- let res;
878
- if (mode === 'region' && x !== undefined && y !== undefined && width && height) {
879
- res = await client.captureRegion(x, y, width, height, projectDir);
880
- }
881
- else {
882
- res = await client.captureFullscreenImage({ resolution, window: windowName, projectDir });
883
- }
884
- const d = res.data;
885
- const content = [
886
- { type: 'text', text: `Capture #${d.captureId} (${d.width}x${d.height})` },
887
- ];
888
- if (d.imageBase64) {
889
- content.push({ type: 'image', data: d.imageBase64, mimeType: ('mimeType' in d ? d.mimeType : null) || 'image/png' });
890
- }
891
- return { content };
892
- }
893
- catch (err) {
894
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
895
- }
896
- });
897
- // ── Tool: superbased_gallery_image ──
898
- server.tool('superbased_gallery_image', 'Retrieve a previously saved capture image from the gallery so you can see it.', {
899
- captureId: captureRefSchema.describe(`Gallery capture ID. ${captureRefDescription}`),
900
- resolution: zod_1.z.enum(['full', 'high', 'half', 'quarter', 'thumbnail']).default('half').describe('Image resolution'),
901
- }, async ({ captureId, resolution }) => {
902
- try {
903
- const captureIdNum = parseCaptureRef(captureId);
904
- if (captureIdNum === null) {
905
- return { content: [{ type: 'text', text: `Invalid captureId: ${String(captureId)}` }], isError: true };
906
- }
907
- const res = await client.getCaptureImage(captureIdNum, resolution);
908
- const content = [
909
- { type: 'text', text: `Gallery capture #${captureIdNum}` },
910
- ];
911
- if (res.data.imageBase64) {
912
- content.push({ type: 'image', data: res.data.imageBase64, mimeType: res.data.mimeType || 'image/png' });
913
- }
914
- return { content };
915
- }
916
- catch (err) {
917
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
918
- }
919
- });
920
- // ── Tool: superbased_diff ──
921
- server.tool('superbased_diff', 'Compare two recording sessions for visual differences. Use for visual regression testing.', {
922
- baselineSessionId: zod_1.z.string().describe('Baseline recording session ID'),
923
- currentSessionId: zod_1.z.string().describe('Current recording session ID'),
924
- }, async ({ baselineSessionId, currentSessionId }) => {
925
- try {
926
- const res = await client.diffSessions(baselineSessionId, currentSessionId);
927
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
928
- }
929
- catch (err) {
930
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
931
- }
932
- });
933
- // ── Tool: superbased_health ──
934
- 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 () => {
935
- try {
936
- const res = await client.health();
937
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
938
- }
939
- catch (err) {
940
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
941
- }
942
- });
943
- // ── Tool: superbased_redact ──
944
- server.tool('superbased_redact', 'Auto-redact secrets (API keys, tokens) and PII (emails, phones) from a screenshot before sharing.', {
945
- captureId: captureRefSchema.optional().describe(`Capture to redact. ${captureRefDescription}`),
946
- screenshotPath: zod_1.z.string().optional().describe('Path to image file'),
947
- secrets: zod_1.z.boolean().default(true).describe('Redact API keys, tokens, passwords'),
948
- pii: zod_1.z.boolean().default(false).describe('Redact emails, phone numbers, names'),
949
- }, async ({ captureId, screenshotPath, secrets, pii }) => {
950
- try {
951
- const captureIdNum = parseCaptureRef(captureId);
952
- const res = await client.redact({ captureId: captureIdNum ?? undefined, screenshotPath, secrets, pii });
953
- const content = [
954
- { type: 'text', text: `Redacted ${res.data.regionsFound} sensitive region(s)` },
955
- ];
956
- if (res.data.imageBase64) {
957
- content.push({ type: 'image', data: res.data.imageBase64, mimeType: 'image/png' });
958
- }
959
- return { content };
960
- }
961
- catch (err) {
962
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
963
- }
964
- });
965
- // ── Tool: superbased_auth ──
966
- server.tool('superbased_auth', 'Check SuperBased authentication status (signed in, email, plan).', {
967
- action: zod_1.z.enum(['status']).default('status').describe('Auth action (status)'),
968
- }, async () => {
969
- try {
970
- const res = await client.authStatus();
971
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
972
- }
973
- catch (err) {
974
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
975
- }
976
- });
977
- // ── Tool: superbased_license ──
978
- server.tool('superbased_license', 'View plan limits, feature gates, and device info.', {}, async () => {
979
- try {
980
- const res = await client.licenseInfo();
981
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
982
- }
983
- catch (err) {
984
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
985
- }
986
- });
987
- // ── Tool: superbased_transcribe ──
988
- 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.', {
989
- audioPath: zod_1.z.string().optional().describe('Path to audio file (wav, mp3, webm, etc.)'),
990
- audioBase64: zod_1.z.string().optional().describe('Base64-encoded audio data'),
991
- language: zod_1.z.string().optional().describe('BCP 47 language code (e.g. en-US)'),
992
- 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.'),
993
- }, async ({ audioPath, audioBase64, language, engine }) => {
994
- try {
995
- const res = await client.transcribe({ audioPath, audioBase64, language, engine });
996
- const body = res.data;
997
- if (body.ok === false) {
998
- // Structured engine error — surface the full JSON so agents can branch.
999
- return { content: [{ type: 'text', text: formatResponse(body) }], isError: true };
1000
- }
1001
- return { content: [{ type: 'text', text: body.text ?? '' }] };
1002
- }
1003
- catch (err) {
1004
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1005
- }
1006
- });
1007
- // ── Tool: superbased_ai_usage ──
1008
- server.tool('superbased_ai_usage', 'Check daily AI quota usage (calls used, tokens consumed, limits).', {}, async () => {
1009
- try {
1010
- const res = await client.aiUsage();
1011
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
1012
- }
1013
- catch (err) {
1014
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1015
- }
1016
- });
1017
- // ── Tool: superbased_window_list ──
1018
- 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 () => {
1019
- try {
1020
- const res = await client.listWindows();
1021
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
1022
- }
1023
- catch (err) {
1024
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1025
- }
1026
- });
1027
- // ── Tool: superbased_dictation_history ──
1028
- server.tool('superbased_dictation_history', 'Query past voice transcriptions.', {
1029
- limit: zod_1.z.number().default(20).describe('Max entries to return'),
1030
- }, async ({ limit }) => {
1031
- try {
1032
- const res = await client.dictationHistory(limit);
1033
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
1034
- }
1035
- catch (err) {
1036
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1037
- }
1038
- });
1039
- // ── Tool: superbased_describe_frames ──
1040
- server.tool('superbased_describe_frames', 'AI-describe each frame in a recording session (UI state, visible elements, changes).', {
1041
- sessionId: zod_1.z.string().describe('Recording session ID'),
1042
- limit: zod_1.z.number().default(20).describe('Max frames to describe'),
1043
- 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.'),
1044
- 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.'),
1045
- forceVision: zod_1.z.boolean().optional().describe('Bypass the vision-capable model pre-check. Default false.'),
1046
- }, async ({ sessionId, limit, provider, model, forceVision }) => {
1047
- try {
1048
- const res = await client.describeFrames(sessionId, limit, { provider, model, forceVision });
1049
- if (res.status >= 400) {
1050
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: true };
1051
- }
1052
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
1053
- }
1054
- catch (err) {
1055
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1056
- }
1057
- });
1058
- // ── Tool: superbased_narrate ──
1059
- server.tool('superbased_narrate', 'Generate a prose narrative summary of a recording session from frame descriptions.', {
1060
- sessionId: zod_1.z.string().describe('Recording session ID'),
1061
- descriptions: zod_1.z.array(zod_1.z.object({
1062
- frameNumber: zod_1.z.number(),
1063
- description: zod_1.z.string(),
1064
- })).describe('Frame descriptions (from superbased_describe_frames)'),
1065
- 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.'),
1066
- model: zod_1.z.string().optional().describe('Per-call Ollama model tag. Only valid when provider is concrete.'),
1067
- }, async ({ sessionId, descriptions, provider, model }) => {
1068
- try {
1069
- const res = await client.narrate(sessionId, descriptions, { provider, model });
1070
- if (res.status >= 400) {
1071
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: true };
1072
- }
1073
- return { content: [{ type: 'text', text: res.data.narration }] };
1074
- }
1075
- catch (err) {
1076
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1077
- }
1078
- });
1079
- // ── Tool: superbased_baseline ──
1080
- server.tool('superbased_baseline', 'Manage workflow baselines for visual regression testing (set, get, or list history).', {
1081
- action: zod_1.z.enum(['set', 'get', 'history']).describe('Baseline action'),
1082
- workflowName: zod_1.z.string().describe('Workflow name (e.g. "checkout-flow")'),
1083
- sessionId: zod_1.z.string().optional().describe('Session ID (required for set)'),
1084
- }, async ({ action, workflowName, sessionId }) => {
1085
- try {
1086
- const res = await client.baseline(action, workflowName, sessionId);
1087
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
1088
- }
1089
- catch (err) {
1090
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1091
- }
1092
- });
1093
- // ── Tool: superbased_dictate ──
1094
- 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.', {
1095
- audioPath: zod_1.z.string().optional().describe('Path to audio file to transcribe with text cleanup'),
1096
- audioBase64: zod_1.z.string().optional().describe('Base64-encoded audio data'),
1097
- mic: zod_1.z.boolean().optional().describe('Record from microphone (requires ffmpeg). Set to true to capture live audio.'),
1098
- duration: zod_1.z.number().optional().describe('Mic recording duration in seconds (default 10)'),
1099
- language: zod_1.z.string().optional().describe('BCP 47 language code'),
1100
- cleanup: zod_1.z.boolean().default(true).describe('Apply filler word removal and deduplication'),
1101
- 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).'),
1102
- }, async ({ audioPath, audioBase64, mic, duration, language, cleanup, engine }) => {
1103
- try {
1104
- const res = mic
1105
- ? await client.dictateMic(duration || 10, language, cleanup, engine)
1106
- : await client.dictate({ audioPath, audioBase64, language, cleanup, engine });
1107
- const body = res.data;
1108
- if (body.ok === false) {
1109
- return { content: [{ type: 'text', text: formatResponse(body) }], isError: true };
1110
- }
1111
- const text = body.text ?? '';
1112
- // Phase 5.2: append a second text block with next_steps only when
1113
- // suggestions are meaningful. Keeps the primary transcript-first
1114
- // interface (existing agents reading content[0].text unchanged)
1115
- // and surfaces hints to agents that inspect the full content array.
1116
- const hints = nextStepsForDictate(cleanup !== false, text.length > 0);
1117
- const content = [{ type: 'text', text }];
1118
- if (hints.length > 0) {
1119
- content.push({ type: 'text', text: formatResponse({ next_steps: hints }) });
1120
- }
1121
- return { content };
1122
- }
1123
- catch (err) {
1124
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1125
- }
1126
- });
1127
- // ── Tool: superbased_tools (Phase 5.5 — progressive-disclosure dispatcher) ──
1128
- 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).', {
1129
- 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.'),
1130
- }, async ({ category }) => {
1131
- try {
1132
- // eslint-disable-next-line @typescript-eslint/no-require-imports
1133
- const mod = require('./tool-categories');
1134
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1135
- const registered = server._registeredTools ?? {};
1136
- const getDescription = (name) => {
1137
- const tool = registered[name];
1138
- return tool?.description ? tool.description.slice(0, 240) : '';
1139
- };
1140
- if (category) {
1141
- const names = mod.toolsInCategory(category);
1142
- const tools = names.map((name) => ({ name, description: getDescription(name), core: mod.CORE_TOOLS.has(name) }));
1143
- return {
1144
- content: [{ type: 'text', text: formatResponse({
1145
- category,
1146
- count: tools.length,
1147
- tools,
1148
- }) }],
1149
- };
1150
- }
1151
- const index = {};
1152
- for (const cat of mod.CATEGORIES) {
1153
- index[cat] = mod.toolsInCategory(cat).map((name) => ({ name, description: getDescription(name), core: mod.CORE_TOOLS.has(name) }));
1154
- }
1155
- const coreList = [...mod.CORE_TOOLS].map((name) => ({ name, description: getDescription(name) }));
1156
- return {
1157
- content: [{ type: 'text', text: formatResponse({
1158
- core: { count: coreList.length, tools: coreList },
1159
- categories: index,
1160
- totalTools: coreList.length + mod.allNonCoreTools().length,
1161
- }) }],
1162
- };
1163
- }
1164
- catch (err) {
1165
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1166
- }
1167
- });
1168
- // ── Tool: superbased_undo_last (Phase 5.4 — per-session undo) ──
1169
- 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 () => {
1170
- try {
1171
- const res = await client.undoLast();
1172
- const body = res.data;
1173
- return { content: [{ type: 'text', text: formatResponse(body) }], isError: body.ok === false };
1174
- }
1175
- catch (err) {
1176
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1177
- }
1178
- });
1179
- // ── Tool: superbased_project (Phase 5.1 — orientation snapshot) ──
1180
- 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 () => {
1181
- try {
1182
- const cwd = projectDir ?? process.cwd();
1183
- // eslint-disable-next-line @typescript-eslint/no-require-imports
1184
- const { detectFrameworks, getGitSummary } = require('./project-sense');
1185
- const git = getGitSummary(cwd);
1186
- const frameworks = detectFrameworks(cwd);
1187
- let serverState = null;
1188
- let serverError = null;
1189
- try {
1190
- const res = await client.projectServerState();
1191
- serverState = res.data;
1192
- }
1193
- catch (err) {
1194
- serverError = err instanceof Error ? err.message : String(err);
1195
- }
1196
- const response = {
1197
- cwd,
1198
- git,
1199
- frameworks,
1200
- server: serverState,
1201
- serverError,
1202
- };
1203
- return { content: [{ type: 'text', text: formatResponse(response) }] };
1204
- }
1205
- catch (err) {
1206
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1207
- }
1208
- });
1209
- // ── Tool: superbased_workspace_sync (Phase 5.1 — bundled snapshot) ──
1210
- 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 () => {
1211
- try {
1212
- const cwd = projectDir ?? process.cwd();
1213
- const res = await client.workspaceSync();
1214
- const data = res.data;
1215
- // Return both structured JSON (for agent reasoning) and the image
1216
- // itself (so the agent can pass it through to vision models without
1217
- // a second fetch). Matches the superbased_capture_image shape.
1218
- const summary = {
1219
- projectDir: cwd,
1220
- imageBytes: data.imageBytes,
1221
- timestamp: data.timestamp,
1222
- activeWindow: data.activeWindow,
1223
- ocr: data.ocr,
1224
- };
1225
- return {
1226
- content: [
1227
- { type: 'text', text: formatResponse(summary) },
1228
- { type: 'image', data: data.imageBase64, mimeType: 'image/png' },
1229
- ],
1230
- };
1231
- }
1232
- catch (err) {
1233
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1234
- }
1235
- });
1236
- // ── Tool: superbased_stt_status (Phase 4a — local STT probe) ──
1237
- 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 () => {
1238
- try {
1239
- const res = await client.sttStatus();
1240
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
1241
- }
1242
- catch (err) {
1243
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1244
- }
1245
- });
1246
- // ── Tool: superbased_accessibility_tree (Phase 8.1 — native AX / UIA) ──
1247
- 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? }.', {
1248
- pid: zod_1.z.number().int().positive().optional().describe('Target process id. Required on darwin; optional on win32 (defaults to foreground).'),
1249
- hwnd: zod_1.z.number().int().positive().optional().describe('Windows window handle (win32 only). Mutually exclusive with pid.'),
1250
- 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.'),
1251
- includeAttributes: zod_1.z.boolean().optional().default(false).describe('Include the full per-node attribute list. Noisy but useful for debugging.'),
1252
- }, async ({ pid, hwnd, maxDepth, includeAttributes }) => {
1253
- try {
1254
- const res = await client.accessibilityTree({ pid, hwnd, maxDepth, includeAttributes });
1255
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
1256
- }
1257
- catch (err) {
1258
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1259
- }
1260
- });
1261
- // ── Tool: superbased_annotate ──
1262
- 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.', {
1263
- captureId: captureRefSchema.describe(`Capture to annotate. ${captureRefDescription}`),
1264
- annotations: zod_1.z.array(zod_1.z.object({
1265
- type: zod_1.z.enum(['rectangle', 'highlight', 'blur', 'text', 'arrow']),
1266
- x: zod_1.z.number(), y: zod_1.z.number(),
1267
- width: zod_1.z.number().optional(), height: zod_1.z.number().optional(),
1268
- text: zod_1.z.string().optional(), color: zod_1.z.string().optional(),
1269
- fontSize: zod_1.z.number().optional(),
1270
- toX: zod_1.z.number().optional(), toY: zod_1.z.number().optional(),
1271
- })).describe('Annotations to add (rectangles, highlights, blur, text labels, arrows)'),
1272
- save: zod_1.z.boolean().default(false).describe('Save annotated image over the original'),
1273
- }, async ({ captureId, annotations, save }) => {
1274
- try {
1275
- const captureIdNum = parseCaptureRef(captureId);
1276
- if (captureIdNum === null) {
1277
- return { content: [{ type: 'text', text: `Invalid captureId: ${String(captureId)}` }], isError: true };
1278
- }
1279
- const res = await client.annotate(captureIdNum, annotations, save);
1280
- const content = [
1281
- { type: 'text', text: `Applied ${res.data.annotationsApplied} annotation(s)${res.data.saved ? ' (saved)' : ''}` },
1282
- ];
1283
- if (res.data.imageBase64) {
1284
- content.push({ type: 'image', data: res.data.imageBase64, mimeType: 'image/png' });
1285
- }
1286
- return { content };
1287
- }
1288
- catch (err) {
1289
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1290
- }
1291
- });
1292
- // ── Tool: superbased_clipboard ──
1293
- server.tool('superbased_clipboard', 'Read or write the system clipboard. Use readImage to see an image the user copied (e.g. a screenshot from another app).', {
1294
- action: zod_1.z.enum(['read', 'write', 'readImage']).describe('Clipboard action'),
1295
- text: zod_1.z.string().optional().describe('Text to write (for write action)'),
1296
- }, async ({ action, text }) => {
1297
- try {
1298
- const res = await client.clipboard(action, text);
1299
- const d = res.data;
1300
- if (action === 'readImage' && d.imageBase64) {
1301
- return { content: [
1302
- { type: 'text', text: 'Clipboard image:' },
1303
- { type: 'image', data: d.imageBase64, mimeType: 'image/png' },
1304
- ] };
1305
- }
1306
- return { content: [{ type: 'text', text: formatResponse(res.data) }] };
1307
- }
1308
- catch (err) {
1309
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1310
- }
1311
- });
1312
- // ── GUI Automation tools (Phase 2a) ──
1313
- // All actions OFF by default — user must enable via `superbased config set
1314
- // guiAutomation.enabled true` or in `superbased settings`. Refused actions
1315
- // return ok:false with a hint, never a tool error.
1316
- 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).', {
1317
- 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.'),
1318
- y: zod_1.z.number().optional().describe('Absolute y coordinate (px from top edge)'),
1319
- 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.'),
1320
- automationId: zod_1.z.string().optional().describe('0.10: AX AutomationId (Windows UIA) / AXIdentifier (macOS). Most reliable locator — prefer over label when available.'),
1321
- role: zod_1.z.string().optional().describe('0.10: AX role (e.g. "button", "textbox") — pair with name=.'),
1322
- name: zod_1.z.string().optional().describe('0.10: AX accessible name — required when role= is set.'),
1323
- caseSensitive: zod_1.z.boolean().optional().describe('Match label/role-name case-sensitively (default false).'),
1324
- button: zod_1.z.enum(['left', 'right', 'middle']).optional().describe('Mouse button (default: left)'),
1325
- 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.'),
1326
- 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.'),
1327
- 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.'),
1328
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1329
- 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.'),
1330
- processName: zod_1.z.string().optional().describe('Exact process executable name (e.g. "Notepad", "Notepad.exe"). Highest-confidence target.'),
1331
- 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.'),
1332
- 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.'),
1333
- 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).'),
1334
- 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).'),
1335
- }, async ({ x, y, label, automationId, role, name, caseSensitive, button, doubleClick, clickCount, modifiers, confirm, window, processName, hwnd, restoreFocus, returnObservation, humanize }) => {
1336
- try {
1337
- const res = await client.automationClick({ x, y, label, automationId, role, name, caseSensitive, button, doubleClick, clickCount, modifiers, confirm, window, processName, hwnd, restoreFocus, returnObservation, humanize });
1338
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1339
- }
1340
- catch (err) {
1341
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1342
- }
1343
- });
1344
- 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.', {
1345
- text: zod_1.z.string().describe('Literal characters to type into the active text field'),
1346
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1347
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Less precise than processName.'),
1348
- processName: zod_1.z.string().optional().describe('Exact process executable name (e.g. "Notepad"). Highest-precision target.'),
1349
- hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1350
- restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore the previous foreground window after typing.'),
1351
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-action PNG. "full" adds OCR + AX tree textElements. "none" suppresses.'),
1352
- label: zod_1.z.string().optional().describe('0.10: Click-target field label (OCR-resolved) before typing.'),
1353
- automationId: zod_1.z.string().optional().describe('0.10: AX AutomationId for the target field — most reliable locator.'),
1354
- role: zod_1.z.string().optional().describe('0.10: AX role (e.g. "textbox") — pair with name=.'),
1355
- name: zod_1.z.string().optional().describe('0.10: AX accessible name — required when role= is set.'),
1356
- caseSensitive: zod_1.z.boolean().optional().describe('Match label/role-name case-sensitively (default false).'),
1357
- 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).'),
1358
- 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.'),
1359
- 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.'),
1360
- 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.'),
1361
- }, async ({ text, confirm, window, processName, hwnd, restoreFocus, returnObservation, label, automationId, role, name, caseSensitive, clearFirst, delayMs, ime, humanize }) => {
1362
- try {
1363
- const res = await client.automationType({ text, confirm, window, processName, hwnd, restoreFocus, returnObservation, label, automationId, role, name, caseSensitive, clearFirst, delayMs, ime, humanize });
1364
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1365
- }
1366
- catch (err) {
1367
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1368
- }
1369
- });
1370
- 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.', {
1371
- combo: zod_1.z.string().describe('Key combo string (e.g. "Cmd+A", "Ctrl+Shift+P", "Tab", "F5")'),
1372
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1373
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1374
- processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision target.'),
1375
- hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1376
- restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the hotkey.'),
1377
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-action PNG. "full" adds OCR + AX tree textElements. "none" suppresses.'),
1378
- 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.'),
1379
- }, async ({ combo, confirm, window, processName, hwnd, restoreFocus, returnObservation, method }) => {
1380
- try {
1381
- const res = await client.automationHotkey({ combo, confirm, window, processName, hwnd, restoreFocus, returnObservation, method });
1382
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1383
- }
1384
- catch (err) {
1385
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1386
- }
1387
- });
1388
- 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.', {
1389
- 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.'),
1390
- width: zod_1.z.number().optional().describe('Width in pixels. Required for preset "custom". Ignored for "fullscreen".'),
1391
- height: zod_1.z.number().optional().describe('Height in pixels. Required for preset "custom". Ignored for "fullscreen".'),
1392
- x: zod_1.z.number().optional().describe('Optional X position (virtual-screen logical pixels). Omit to keep current position.'),
1393
- y: zod_1.z.number().optional().describe('Optional Y position. Omit to keep current position.'),
1394
- 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.'),
1395
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1396
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1397
- processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision target.'),
1398
- hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1399
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-resize PNG of the target.'),
1400
- }, async ({ preset, width, height, x, y, contentArea, confirm, window, processName, hwnd, returnObservation }) => {
1401
- try {
1402
- const res = await client.automationResizeWindow({ preset, width, height, x, y, contentArea, confirm, window, processName, hwnd, returnObservation });
1403
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1404
- }
1405
- catch (err) {
1406
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1407
- }
1408
- });
1409
- 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).', {
1410
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Use superbased_window_list to enumerate.'),
1411
- processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision non-hwnd target.'),
1412
- 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.'),
1413
- }, async ({ window, processName, hwnd }) => {
1414
- try {
1415
- const res = await client.automationWindowBounds({ window, processName, hwnd });
1416
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
1417
- }
1418
- catch (err) {
1419
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1420
- }
1421
- });
1422
- 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).', {
1423
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Use superbased_window_list to enumerate.'),
1424
- processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision non-hwnd target.'),
1425
- 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.'),
1426
- }, async ({ window, processName, hwnd }) => {
1427
- try {
1428
- const res = await client.automationFindTitleBarDragRegion({ window, processName, hwnd });
1429
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
1430
- }
1431
- catch (err) {
1432
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1433
- }
1434
- });
1435
- 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).', {
1436
- 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.'),
1437
- 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.'),
1438
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1439
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1440
- processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision target.'),
1441
- hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1442
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" for maximize/restore/always-on-top/move-to-display; forced "none" for close and minimize (target not visible).'),
1443
- }, async ({ action, displayId, confirm, window, processName, hwnd, returnObservation }) => {
1444
- try {
1445
- const res = await client.automationWindowState({ action, displayId, confirm, window, processName, hwnd, returnObservation });
1446
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1447
- }
1448
- catch (err) {
1449
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1450
- }
1451
- });
1452
- 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 () => {
1453
- try {
1454
- const res = await client.automationDisplayList();
1455
- const data = res.data;
1456
- const content = [
1457
- { type: 'text', text: formatResponse(data) },
1458
- ];
1459
- return { content, isError: !data.ok };
1460
- }
1461
- catch (err) {
1462
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1463
- }
1464
- });
1465
- 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.', {
1466
- templateBase64: zod_1.z.string().optional().describe('Base64-encoded PNG template. Pass EITHER templateBase64 OR templatePath — not both.'),
1467
- 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.'),
1468
- region: zod_1.z.object({
1469
- x: zod_1.z.number().describe('Region top-left X (virtual-screen logical pixels).'),
1470
- y: zod_1.z.number().describe('Region top-left Y.'),
1471
- width: zod_1.z.number().describe('Region width.'),
1472
- height: zod_1.z.number().describe('Region height.'),
1473
- }).optional().describe('Virtual-screen rect to search. Default = full virtual screen. Recommended: constrain when you know approximately where the match is.'),
1474
- 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.'),
1475
- 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).'),
1476
- maxMatches: zod_1.z.number().optional().describe('Cap on matches in multi mode. Default 10.'),
1477
- 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.'),
1478
- 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).'),
1479
- 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.'),
1480
- 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.'),
1481
- }, async ({ templateBase64, templatePath, region, threshold, multi, maxMatches, ignoreDpiScale, ignoreTheme, maxSearchDim, confirm }) => {
1482
- try {
1483
- const res = await client.automationFindImage({ templateBase64, templatePath, region, threshold, multi, maxMatches, ignoreDpiScale, ignoreTheme, maxSearchDim, confirm });
1484
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1485
- }
1486
- catch (err) {
1487
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1488
- }
1489
- });
1490
- 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, ... }.', {
1491
- region: zod_1.z.object({
1492
- x: zod_1.z.number().describe('Region top-left X (virtual-screen logical pixels).'),
1493
- y: zod_1.z.number().describe('Region top-left Y.'),
1494
- width: zod_1.z.number().describe('Region width. Must be > 0.'),
1495
- height: zod_1.z.number().describe('Region height. Must be > 0.'),
1496
- }).describe('Virtual-screen rect to capture. Required.'),
1497
- destPath: zod_1.z.string().optional().describe('Absolute PNG path to write. Default: `~/.superbased/templates/<tag>-<timestamp>.png`. Parent directory is created if missing.'),
1498
- 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".'),
1499
- 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().'),
1500
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt. capture_template is a screenshot + file write — consent checkpoint.'),
1501
- }, async ({ region, destPath, tag, displayId, confirm }) => {
1502
- try {
1503
- const res = await client.automationCaptureTemplate({ region, destPath, tag, displayId, confirm });
1504
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1505
- }
1506
- catch (err) {
1507
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1508
- }
1509
- });
1510
- 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.', {
1511
- tool: zod_1.z.string().describe('Name of the tool that would be invoked, e.g. "superbased_click", "superbased_type", "superbased_sequence".'),
1512
- 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).'),
1513
- }, async ({ tool, args }) => {
1514
- try {
1515
- const res = await client.automationDryRun({ tool, args });
1516
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: false };
1517
- }
1518
- catch (err) {
1519
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1520
- }
1521
- });
1522
- 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.', {
1523
- 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.'),
1524
- 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.'),
1525
- 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.'),
1526
- 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.'),
1527
- 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).'),
1528
- }, async ({ from, to, sessionId, dryRun, confirm }) => {
1529
- try {
1530
- const res = await client.automationReplay({ from, to, sessionId, dryRun, confirm });
1531
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: false };
1532
- }
1533
- catch (err) {
1534
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1535
- }
1536
- });
1537
- 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.', {
1538
- 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`.'),
1539
- 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).'),
1540
- }, async ({ skipPrimitives, timeoutMs }) => {
1541
- try {
1542
- const res = await client.automationDoctorGuiAutomation({ skipPrimitives, timeoutMs });
1543
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: false };
1544
- }
1545
- catch (err) {
1546
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1547
- }
1548
- });
1549
- 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? }`.', {
1550
- 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.'),
1551
- 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.'),
1552
- 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.'),
1553
- 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.'),
1554
- 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).'),
1555
- titleMatch: zod_1.z.string().optional().describe('Title substring needle for waitForWindow. Case-insensitive.'),
1556
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1557
- returnObservation: returnObservationSchema.optional().describe('Default "none" — freshly-opened URLs usually haven\'t rendered yet; agents typically pair with a wait_for + screenshot step.'),
1558
- }, async ({ url, browser, waitForLoad, timeoutMs, processNameMatch, titleMatch, confirm, returnObservation }) => {
1559
- try {
1560
- const res = await client.automationOpenUrl({ url, browser, waitForLoad, timeoutMs, processNameMatch, titleMatch, confirm, returnObservation });
1561
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1562
- }
1563
- catch (err) {
1564
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1565
- }
1566
- });
1567
- 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, ... }`.', {
1568
- filePath: zod_1.z.string().min(1).describe('Absolute path to the file being dragged. Surfaced via CF_HDROP when the native helper lands.'),
1569
- toX: zod_1.z.number().describe('Screen-space target x coordinate (virtual-screen pixels).'),
1570
- toY: zod_1.z.number().describe('Screen-space target y coordinate.'),
1571
- fromX: zod_1.z.number().optional().describe('Optional source coordinate. Defaults to current cursor position when unset.'),
1572
- fromY: zod_1.z.number().optional().describe('Optional source coordinate.'),
1573
- 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.'),
1574
- 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.'),
1575
- 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.'),
1576
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1577
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot". Ignored in the scaffold since the tool always returns UNSUPPORTED_YET.'),
1578
- }, async ({ filePath, toX, toY, fromX, fromY, button, path, durationMs, confirm, returnObservation }) => {
1579
- try {
1580
- const res = await client.automationDragFile({ filePath, toX, toY, fromX, fromY, button, path, durationMs, confirm, returnObservation });
1581
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1582
- }
1583
- catch (err) {
1584
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1585
- }
1586
- });
1587
- 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 }`.', {
1588
- 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.'),
1589
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1590
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-switch PNG. The tool waits 300ms after the hotkey to let the switch animation settle.'),
1591
- }, async ({ direction, confirm, returnObservation }) => {
1592
- try {
1593
- const res = await client.automationVirtualDesktop({ direction, confirm, returnObservation });
1594
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1595
- }
1596
- catch (err) {
1597
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1598
- }
1599
- });
1600
- 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? }`.', {
1601
- 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.'),
1602
- 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.'),
1603
- caseSensitive: zod_1.z.boolean().optional().describe('Default false. Affects both tooltipMatch resolution and audit logging.'),
1604
- 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.'),
1605
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1606
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-click PNG so the agent sees whatever menu / window the click triggered.'),
1607
- }, async ({ tooltipMatch, button, caseSensitive, includeOverflow, confirm, returnObservation }) => {
1608
- try {
1609
- const res = await client.automationTrayClick({ tooltipMatch, button, caseSensitive, includeOverflow, confirm, returnObservation });
1610
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1611
- }
1612
- catch (err) {
1613
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1614
- }
1615
- });
1616
- 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.', {
1617
- 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`).'),
1618
- 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.'),
1619
- 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.'),
1620
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1621
- window: zod_1.z.string().optional().describe('Window-title needle. ONE of window / processName / hwnd required — the hotkey fires inside this window.'),
1622
- processName: zod_1.z.string().optional().describe('Exact process executable name. Common values: "chrome.exe", "msedge.exe", "firefox.exe".'),
1623
- hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring.'),
1624
- restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the action.'),
1625
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-action PNG.'),
1626
- }, async ({ tabAction, url, index, confirm, window, processName, hwnd, restoreFocus, returnObservation }) => {
1627
- try {
1628
- const res = await client.automationTabManagement({ tabAction, url, index, confirm, window, processName, hwnd, restoreFocus, returnObservation });
1629
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1630
- }
1631
- catch (err) {
1632
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1633
- }
1634
- });
1635
- 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? }`.', {
1636
- 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).'),
1637
- 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.'),
1638
- 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).'),
1639
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1640
- 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.'),
1641
- 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.'),
1642
- hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring.'),
1643
- restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the navigate.'),
1644
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-navigate PNG so the agent sees the highlighted match in context.'),
1645
- }, async ({ query, direction, closeAfter, confirm, window, processName, hwnd, restoreFocus, returnObservation }) => {
1646
- try {
1647
- const res = await client.automationFindInPage({ query, direction, closeAfter, confirm, window, processName, hwnd, restoreFocus, returnObservation });
1648
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1649
- }
1650
- catch (err) {
1651
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1652
- }
1653
- });
1654
- 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? }`.', {
1655
- 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.'),
1656
- 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.'),
1657
- 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.).'),
1658
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1659
- window: zod_1.z.string().optional().describe('Optional: pin a specific dialog. Default = foreground window (modal dialogs own foreground while open).'),
1660
- processName: zod_1.z.string().optional().describe('Exact process executable name. Use when multiple dialogs are stacked.'),
1661
- hwnd: zod_1.z.string().optional().describe('Direct window handle. Bypasses scoring.'),
1662
- restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the action.'),
1663
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-action PNG (may show underlying app after dismiss / confirm closes the dialog).'),
1664
- }, async ({ dialogAction, path, buttonLabel, confirm, window, processName, hwnd, restoreFocus, returnObservation }) => {
1665
- try {
1666
- const res = await client.automationDialogHandle({ dialogAction, path, buttonLabel, confirm, window, processName, hwnd, restoreFocus, returnObservation });
1667
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1668
- }
1669
- catch (err) {
1670
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1671
- }
1672
- });
1673
- 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?, ... }`.', {
1674
- fields: zod_1.z.array(zod_1.z.object({
1675
- 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.'),
1676
- automationId: zod_1.z.string().optional().describe('UIA AutomationId — top of pyramid; preferred. One field per UIA id.'),
1677
- role: zod_1.z.string().optional().describe('UIA ControlType (e.g. "Edit", "ComboBox"). Paired with name.'),
1678
- name: zod_1.z.string().optional().describe('Element Name. Paired with role.'),
1679
- caseSensitive: zod_1.z.boolean().optional().describe('Default false for role+name and label.'),
1680
- value: zod_1.z.string().describe('Text to enter. Routes through ValuePattern.SetValue when supported (bypasses typing); falls back to click + clearFirst + type.'),
1681
- 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).'),
1682
- })).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.'),
1683
- submitLabel: zod_1.z.string().optional().describe('Label / visible text of the Submit button. Clicked after all fields are filled.'),
1684
- 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.'),
1685
- 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).'),
1686
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1687
- window: zod_1.z.string().optional().describe('Window-title needle. Required (or processName/hwnd) — the whole macro runs inside this window.'),
1688
- processName: zod_1.z.string().optional().describe('Exact process executable name.'),
1689
- hwnd: zod_1.z.string().optional().describe('Direct window handle. Bypasses scoring.'),
1690
- restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the macro.'),
1691
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-macro PNG so agent can verify form state.'),
1692
- }, async ({ fields, submitLabel, submitAutomationId, tabBetweenFields, confirm, window, processName, hwnd, restoreFocus, returnObservation }) => {
1693
- try {
1694
- const res = await client.automationFormFill({ fields, submitLabel, submitAutomationId, tabBetweenFields, confirm, window, processName, hwnd, restoreFocus, 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_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, ... }`.', {
1702
- 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.'),
1703
- role: zod_1.z.string().optional().describe('UIA ControlType (e.g. "Button", "Edit", "CheckBox", "ListItem", "TreeItem"). Fallback when automationId is missing. Paired with name.'),
1704
- name: zod_1.z.string().optional().describe('Element Name (UIA Name property — usually the visible text). Paired with role.'),
1705
- caseSensitive: zod_1.z.boolean().optional().describe('Default false — role+name matching is case-insensitive.'),
1706
- 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.'),
1707
- 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".'),
1708
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1709
- 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.'),
1710
- processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision target.'),
1711
- hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring.'),
1712
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-invoke PNG so the agent can verify state.'),
1713
- }, async ({ automationId, role, name, caseSensitive, pattern, value, confirm, window, processName, hwnd, returnObservation }) => {
1714
- try {
1715
- const res = await client.automationAxInvoke({ automationId, role, name, caseSensitive, pattern, value, confirm, window, processName, hwnd, returnObservation });
1716
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1717
- }
1718
- catch (err) {
1719
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1720
- }
1721
- });
1722
- 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.', {
1723
- 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.'),
1724
- name: zod_1.z.string().optional().describe('App name resolvable via PATH (e.g. "notepad", "code"). Substring-matched against the allowlist.'),
1725
- 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.'),
1726
- args: zod_1.z.array(zod_1.z.string()).optional().describe('Arguments passed to the process. Ignored for URL mode.'),
1727
- workingDir: zod_1.z.string().optional().describe('Working directory for the spawned process. Ignored for URL mode.'),
1728
- 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.'),
1729
- timeoutMs: zod_1.z.number().optional().describe('waitForWindow deadline in ms. Default 5000.'),
1730
- processNameMatch: zod_1.z.string().optional().describe('Override for the derived processName needle used by waitForWindow. Case-insensitive substring match.'),
1731
- titleMatch: zod_1.z.string().optional().describe('Title substring needle for waitForWindow. Case-insensitive.'),
1732
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt.'),
1733
- 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.'),
1734
- }, async ({ path, name, url, args, workingDir, waitForWindow, timeoutMs, processNameMatch, titleMatch, confirm, returnObservation }) => {
1735
- try {
1736
- const res = await client.automationLaunchApp({ path, name, url, args, workingDir, waitForWindow, timeoutMs, processNameMatch, titleMatch, confirm, returnObservation });
1737
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1738
- }
1739
- catch (err) {
1740
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1741
- }
1742
- });
1743
- 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.', {
1744
- fromX: zod_1.z.number().optional().describe('Start X (virtual-screen logical pixels). Optional when `path` has ≥2 waypoints — otherwise required.'),
1745
- fromY: zod_1.z.number().optional().describe('Start Y. Required together with fromX.'),
1746
- toX: zod_1.z.number().optional().describe('End X. Required together with fromX/fromY unless path-only mode.'),
1747
- toY: zod_1.z.number().optional().describe('End Y.'),
1748
- path: zod_1.z.array(zod_1.z.object({
1749
- x: zod_1.z.number().describe('Waypoint X.'),
1750
- y: zod_1.z.number().describe('Waypoint Y.'),
1751
- 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`.'),
1752
- })).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.'),
1753
- 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.'),
1754
- steps: zod_1.z.number().optional().describe('Number of intermediate move events per segment. Default 10. Higher = smoother for animation-tracking UIs.'),
1755
- 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).'),
1756
- 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).'),
1757
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1758
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1759
- processName: zod_1.z.string().optional().describe('Exact process executable name.'),
1760
- hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1761
- restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the drag.'),
1762
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-drag PNG.'),
1763
- 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.'),
1764
- }, async ({ fromX, fromY, toX, toY, path, durationMs, steps, button, modifiers, confirm, window, processName, hwnd, restoreFocus, returnObservation, humanize }) => {
1765
- try {
1766
- const res = await client.automationDrag({ fromX, fromY, toX, toY, path, durationMs, steps, button, modifiers, confirm, window, processName, hwnd, restoreFocus, returnObservation, humanize });
1767
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1768
- }
1769
- catch (err) {
1770
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1771
- }
1772
- });
1773
- 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.', {
1774
- x: zod_1.z.number().describe('Absolute x (virtual-screen logical pixels).'),
1775
- y: zod_1.z.number().describe('Absolute y.'),
1776
- 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`.'),
1777
- 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.'),
1778
- 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.'),
1779
- }, async ({ x, y, expected, tolerance, confirm }) => {
1780
- try {
1781
- const res = await client.automationPixelColor({ x, y, expected, tolerance, confirm });
1782
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1783
- }
1784
- catch (err) {
1785
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1786
- }
1787
- });
1788
- 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.', {
1789
- x: zod_1.z.number().optional().describe('Absolute x (virtual-screen logical pixels). Pass EITHER x+y OR label/automationId/role+name.'),
1790
- y: zod_1.z.number().optional().describe('Absolute y.'),
1791
- label: zod_1.z.string().optional().describe('Visible text to hover over (OCR-resolved).'),
1792
- automationId: zod_1.z.string().optional().describe('AX AutomationId — most reliable locator.'),
1793
- role: zod_1.z.string().optional().describe('AX role (pair with name=).'),
1794
- name: zod_1.z.string().optional().describe('AX accessible name (pair with role=).'),
1795
- caseSensitive: zod_1.z.boolean().optional().describe('Default false — case-insensitive label/role-name match.'),
1796
- 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.'),
1797
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1798
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1799
- processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision target.'),
1800
- hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1801
- restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the hover.'),
1802
- 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.'),
1803
- 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.'),
1804
- }, async ({ x, y, label, automationId, role, name, caseSensitive, dwellMs, confirm, window, processName, hwnd, restoreFocus, returnObservation, humanize }) => {
1805
- try {
1806
- const res = await client.automationHover({ x, y, label, automationId, role, name, caseSensitive, dwellMs, confirm, window, processName, hwnd, restoreFocus, returnObservation, humanize });
1807
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1808
- }
1809
- catch (err) {
1810
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1811
- }
1812
- });
1813
- 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).', {
1814
- x: zod_1.z.number().describe('Right-click X (virtual-screen logical pixels).'),
1815
- y: zod_1.z.number().describe('Right-click Y.'),
1816
- 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.'),
1817
- caseSensitive: zod_1.z.boolean().optional().describe('Default false — menuItemText match is case-insensitive.'),
1818
- 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.'),
1819
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1820
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Required when targeting a non-foreground window.'),
1821
- processName: zod_1.z.string().optional().describe('Exact process executable name.'),
1822
- hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list).'),
1823
- restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the menu item is clicked.'),
1824
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-click PNG.'),
1825
- }, async ({ x, y, menuItemText, caseSensitive, timeoutMs, confirm, window, processName, hwnd, restoreFocus, returnObservation }) => {
1826
- try {
1827
- const res = await client.automationContextMenuSelect({ x, y, menuItemText, caseSensitive, timeoutMs, confirm, window, processName, hwnd, restoreFocus, returnObservation });
1828
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1829
- }
1830
- catch (err) {
1831
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1832
- }
1833
- });
1834
- 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.', {
1835
- 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.'),
1836
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt'),
1837
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1838
- processName: zod_1.z.string().optional().describe('Exact process executable name.'),
1839
- hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1840
- restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after scroll.'),
1841
- 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).'),
1842
- 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.'),
1843
- 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.'),
1844
- 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.'),
1845
- anchorY: zod_1.z.number().optional().describe('Physical screen Y for the anchor. See anchorX.'),
1846
- 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.'),
1847
- returnObservation: returnObservationSchema.optional().describe('Default "screenshot" — auto-returns post-scroll PNG. "full" adds OCR + AX textElements. "none" suppresses.'),
1848
- }, async ({ amount, confirm, window, processName, hwnd, restoreFocus, method, unit, axis, anchorX, anchorY, recalibrate, returnObservation }) => {
1849
- try {
1850
- const res = await client.automationScroll({ amount, confirm, window, processName, hwnd, restoreFocus, method, unit, axis, anchorX, anchorY, recalibrate, returnObservation });
1851
- return { content: buildWriteActionContent(res.data), isError: !res.data.ok };
1852
- }
1853
- catch (err) {
1854
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1855
- }
1856
- });
1857
- 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.', {
1858
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). When omitted, dumps the foreground window / full screen.'),
1859
- processName: zod_1.z.string().optional().describe('Exact process executable name. Highest-precision target.'),
1860
- hwnd: zod_1.z.string().optional().describe('Direct window handle from superbased_window_list.'),
1861
- 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.'),
1862
- includeScreenshot: zod_1.z.boolean().optional().describe('Default true — emit PNG as an MCP image content block.'),
1863
- includeOcr: zod_1.z.boolean().optional().describe('Default true — run Tesseract OCR and include words + lines with coordinates.'),
1864
- 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.'),
1865
- 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.'),
1866
- ocrMinConfidence: zod_1.z.number().optional().describe('Default 30 (0-100). Raise to filter low-confidence OCR noise.'),
1867
- }, async ({ window, processName, hwnd, background, includeScreenshot, includeOcr, includeAxTree, ocrScaleFactor, ocrMinConfidence }) => {
1868
- try {
1869
- const res = await client.automationUiDump({ window, processName, hwnd, background, includeScreenshot, includeOcr, includeAxTree, ocrScaleFactor, ocrMinConfidence });
1870
- const data = res.data;
1871
- const content = [
1872
- { type: 'text', text: formatResponse({
1873
- ok: data.ok,
1874
- error: data.error,
1875
- window: data.window,
1876
- screenshot: data.screenshot ? { width: data.screenshot.width, height: data.screenshot.height, mimeType: data.screenshot.mimeType } : undefined,
1877
- textElementCount: data.textElements?.length ?? 0,
1878
- textElements: data.textElements,
1879
- axTree: data.axTree ? { available: data.axTree.available, error: data.axTree.error, nodeCount: data.axTree.nodeCount } : undefined,
1880
- timings: data.timings,
1881
- backgroundMode: data.backgroundMode,
1882
- capturePathUsed: data.capturePathUsed,
1883
- dpiScale: data.dpiScale,
1884
- diagnostic: data.diagnostic,
1885
- }) },
1886
- ];
1887
- if (data.screenshot?.imageBase64) {
1888
- content.push({ type: 'image', data: data.screenshot.imageBase64, mimeType: 'image/png' });
1889
- }
1890
- return { content, isError: !data.ok };
1891
- }
1892
- catch (err) {
1893
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1894
- }
1895
- });
1896
- 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.', {
1897
- targetText: zod_1.z.string().describe('Text to scroll to. Substring match by default (see matchMode).'),
1898
- direction: zod_1.z.enum(['down', 'up']).optional().describe('Scroll direction. Default "down".'),
1899
- 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.'),
1900
- matchMode: zod_1.z.enum(['exact', 'substring']).optional().describe('Default "substring" (element text INCLUDES target). "exact" requires whole-element match.'),
1901
- caseSensitive: zod_1.z.boolean().optional().describe('Default false.'),
1902
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt. ONE confirm covers the whole loop.'),
1903
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Applied ONCE at loop start.'),
1904
- processName: zod_1.z.string().optional().describe('Exact process executable name (highest precision).'),
1905
- hwnd: zod_1.z.string().optional().describe('Direct window handle from superbased_window_list.'),
1906
- restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the entire loop completes.'),
1907
- 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.'),
1908
- 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.'),
1909
- }, async ({ targetText, direction, maxPages, matchMode, caseSensitive, confirm, window, processName, hwnd, restoreFocus, returnObservation, ocrScaleFactor }) => {
1910
- try {
1911
- const res = await client.automationScrollTo({ targetText, direction, maxPages, matchMode, caseSensitive, confirm, window, processName, hwnd, restoreFocus, returnObservation, ocrScaleFactor });
1912
- const data = res.data;
1913
- // Emit image content block (the final observation) + text with full JSON
1914
- // (with imageBase64 stripped — image goes separately).
1915
- const obs = data.observation;
1916
- const textProjection = {
1917
- ok: data.ok,
1918
- error: data.error,
1919
- found: data.found,
1920
- pagesScrolled: data.pagesScrolled,
1921
- atEnd: data.atEnd,
1922
- match: data.match,
1923
- matches: data.matches,
1924
- method: data.method,
1925
- confidence: data.confidence,
1926
- details: data.details,
1927
- observation: obs ? { width: obs.width, height: obs.height, mimeType: obs.mimeType, backgroundMode: obs.backgroundMode, dpiScale: obs.dpiScale, textElementCount: obs.textElements?.length ?? 0 } : undefined,
1928
- };
1929
- const content = [
1930
- { type: 'text', text: formatResponse(textProjection) },
1931
- ];
1932
- if (obs?.imageBase64) {
1933
- content.push({ type: 'image', data: obs.imageBase64, mimeType: obs.mimeType });
1934
- }
1935
- return { content, isError: !data.ok };
1936
- }
1937
- catch (err) {
1938
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1939
- }
1940
- });
1941
- 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).', {
1942
- 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.'),
1943
- anchorY: zod_1.z.number().describe('Physical screen Y for the anchor. See anchorX.'),
1944
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher).'),
1945
- processName: zod_1.z.string().optional().describe('Exact process executable name (highest precision).'),
1946
- hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
1947
- direction: zod_1.z.enum(['down', 'up']).optional().describe('Scroll direction. Default "down".'),
1948
- 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.'),
1949
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt. ONE confirm covers the whole loop.'),
1950
- restoreFocus: zod_1.z.boolean().optional().describe('Default true — restore previous foreground after the entire capture loop completes.'),
1951
- 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.'),
1952
- 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.'),
1953
- 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.'),
1954
- }, async ({ anchorX, anchorY, window, processName, hwnd, direction, maxPages, confirm, restoreFocus, recalibrate, stopOnAtEnd, settleMs }) => {
1955
- try {
1956
- const res = await client.automationScrollCapture({ anchorX, anchorY, window, processName, hwnd, direction, maxPages, confirm, restoreFocus, recalibrate, stopOnAtEnd, settleMs });
1957
- const data = res.data;
1958
- // Emit each captured frame as an MCP image content block. Text
1959
- // block carries metadata + scrolledPx per frame (stripped of the
1960
- // base64 duplicates).
1961
- const frames = data.frames ?? [];
1962
- 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 }));
1963
- const textProjection = {
1964
- ok: data.ok,
1965
- error: data.error,
1966
- framesCaptured: data.framesCaptured,
1967
- pagesScrolled: data.pagesScrolled,
1968
- atEnd: data.atEnd,
1969
- atEndReason: data.atEndReason,
1970
- calibration: data.calibration,
1971
- calibrationFramesPath: data.calibrationFramesPath,
1972
- dpiScale: data.dpiScale,
1973
- sessionDir: data.sessionDir,
1974
- frames: framesMeta,
1975
- details: data.details,
1976
- };
1977
- const content = [
1978
- { type: 'text', text: formatResponse(textProjection) },
1979
- ];
1980
- for (const f of frames) {
1981
- if (f.imageBase64) {
1982
- content.push({ type: 'image', data: f.imageBase64, mimeType: 'image/png' });
1983
- }
1984
- }
1985
- return { content, isError: !data.ok };
1986
- }
1987
- catch (err) {
1988
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
1989
- }
1990
- });
1991
- 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.', {
1992
- steps: zod_1.z.array(zod_1.z.discriminatedUnion('action', [
1993
- zod_1.z.object({
1994
- action: zod_1.z.literal('click'),
1995
- x: zod_1.z.number().describe('Absolute x px'),
1996
- y: zod_1.z.number().describe('Absolute y px'),
1997
- button: zod_1.z.enum(['left', 'right', 'middle']).optional(),
1998
- doubleClick: zod_1.z.boolean().optional(),
1999
- 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.'),
2000
- }),
2001
- zod_1.z.object({
2002
- action: zod_1.z.literal('type'),
2003
- text: zod_1.z.string().describe('Literal characters to type (no special-key interpretation — use hotkey for {Enter}/{Tab}/etc)'),
2004
- returnObservation: returnObservationSchema.optional().describe('Default "none" in sequences.'),
2005
- }),
2006
- zod_1.z.object({
2007
- action: zod_1.z.literal('hotkey'),
2008
- combo: zod_1.z.string().describe('Combo like "Ctrl+S", "Enter", "Cmd+A"'),
2009
- returnObservation: returnObservationSchema.optional().describe('Default "none" in sequences.'),
2010
- }),
2011
- zod_1.z.object({
2012
- action: zod_1.z.literal('scroll'),
2013
- amount: zod_1.z.number().describe('Scroll amount. Interpreted per `unit` (default ticks = wheel ticks).'),
2014
- 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.'),
2015
- 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.'),
2016
- returnObservation: returnObservationSchema.optional().describe('Default "none" in sequences.'),
2017
- }),
2018
- zod_1.z.object({
2019
- action: zod_1.z.literal('screenshot'),
2020
- 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)'),
2021
- }),
2022
- zod_1.z.object({
2023
- action: zod_1.z.literal('wait'),
2024
- ms: zod_1.z.number().describe('Delay in ms (0-60000). Useful between steps that trigger UI animations'),
2025
- }),
2026
- zod_1.z.object({
2027
- action: zod_1.z.literal('move'),
2028
- x: zod_1.z.number(),
2029
- y: zod_1.z.number(),
2030
- }).describe('Mouse move only (no click) — useful to position cursor before a scroll, or to hover over a tooltip target'),
2031
- ])).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.'),
2032
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). Applied ONCE at sequence start. Subsequent activation not re-triggered mid-sequence.'),
2033
- processName: zod_1.z.string().optional().describe('Exact process executable name (highest precision).'),
2034
- hwnd: zod_1.z.string().optional().describe('Direct window handle from superbased_window_list. Bypasses scoring entirely.'),
2035
- 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.'),
2036
- confirm: zod_1.z.boolean().optional().describe('Required unless user has disabled the safety prompt. ONE confirm covers all steps.'),
2037
- 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).'),
2038
- }, async ({ steps, window, processName, hwnd, restoreFocus, confirm, stopOnError }) => {
2039
- try {
2040
- const res = await client.automationSequence({ steps, window, processName, hwnd, restoreFocus, confirm, stopOnError });
2041
- const data = res.data;
2042
- const imageBlocks = (data.results || [])
2043
- .filter((r) => typeof r.imageBase64 === 'string' && r.imageBase64.length > 0)
2044
- .map((r) => ({ type: 'image', data: r.imageBase64, mimeType: 'image/png' }));
2045
- // Text summary first; image blocks follow in step order.
2046
- return {
2047
- content: [
2048
- { type: 'text', text: formatResponse(data) },
2049
- ...imageBlocks,
2050
- ],
2051
- isError: !data.ok,
2052
- };
2053
- }
2054
- catch (err) {
2055
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
2056
- }
2057
- });
2058
- 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).', {
2059
- window: zod_1.z.string().optional().describe('Window-title needle (scored matcher). When combined with processName, used to disambiguate among same-process windows.'),
2060
- processName: zod_1.z.string().optional().describe('Exact process executable name (e.g. "Notepad", "Notepad.exe").'),
2061
- hwnd: zod_1.z.string().optional().describe('Direct window handle (from superbased_window_list). Bypasses scoring entirely.'),
2062
- }, async ({ window, processName, hwnd }) => {
2063
- try {
2064
- const res = await client.automationFocusWindow({ window, processName, hwnd });
2065
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
2066
- }
2067
- catch (err) {
2068
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
2069
- }
2070
- });
2071
- server.tool('superbased_mouse_position', 'Read the current cursor position (no input is generated). Read-only — no safety gate.', {}, async () => {
2072
- try {
2073
- const res = await client.automationMousePosition();
2074
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
2075
- }
2076
- catch (err) {
2077
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
2078
- }
2079
- });
2080
- 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.', {
2081
- condition: zod_1.z.union([
2082
- zod_1.z.object({ type: zod_1.z.literal('text'), value: zod_1.z.string(), caseSensitive: zod_1.z.boolean().optional() }),
2083
- 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() }),
2084
- zod_1.z.object({ type: zod_1.z.literal('idle'), ms: zod_1.z.number() }),
2085
- 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() }),
2086
- ]).describe('Condition to poll.'),
2087
- timeoutMs: zod_1.z.number().describe('Max wait duration (required, >0).'),
2088
- intervalMs: zod_1.z.number().optional().describe('Polling interval in ms (default 250).'),
2089
- }, async ({ condition, timeoutMs, intervalMs }) => {
2090
- try {
2091
- const res = await client.automationWaitFor({ condition, timeoutMs, intervalMs });
2092
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
2093
- }
2094
- catch (err) {
2095
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
2096
- }
2097
- });
2098
- server.tool('superbased_wait', 'Pause execution for a fixed duration (0–60000 ms). Useful between automation steps that need time for UI animations.', {
2099
- ms: zod_1.z.number().describe('Milliseconds to wait (clamped to 0–60000)'),
2100
- }, async ({ ms }) => {
2101
- try {
2102
- const res = await client.automationWait({ ms });
2103
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
2104
- }
2105
- catch (err) {
2106
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
2107
- }
2108
- });
2109
- 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.', {
2110
- label: zod_1.z.string().describe('Visible text on the UI element (button label, link text, etc.)'),
2111
- caseSensitive: zod_1.z.boolean().optional().describe('Match label case-sensitively (default: false)'),
2112
- }, async ({ label, caseSensitive }) => {
2113
- try {
2114
- const res = await client.automationLocate({ label, caseSensitive });
2115
- return { content: [{ type: 'text', text: formatResponse(res.data) }], isError: !res.data.ok };
2116
- }
2117
- catch (err) {
2118
- return { content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }], isError: true };
2119
- }
2120
- });
2121
- // ── Resources ──
2122
- server.resource('superbased-status', 'superbased://status', async () => {
2123
- try {
2124
- const res = await client.health();
2125
- return { contents: [{ uri: 'superbased://status', mimeType: 'application/json', text: formatResponse(res.data) }] };
2126
- }
2127
- catch {
2128
- return { contents: [{ uri: 'superbased://status', mimeType: 'text/plain', text: 'SuperBased is not running' }] };
2129
- }
2130
- });
2131
- server.resource('superbased-settings', 'superbased://settings', async () => {
2132
- try {
2133
- const res = await client.getSettings();
2134
- return { contents: [{ uri: 'superbased://settings', mimeType: 'application/json', text: formatResponse(res.data) }] };
2135
- }
2136
- catch {
2137
- return { contents: [{ uri: 'superbased://settings', mimeType: 'text/plain', text: 'Cannot read settings — SuperBased may not be running' }] };
2138
- }
2139
- });
2140
- server.resource('superbased-presets', 'superbased://presets', async () => {
2141
- try {
2142
- const res = await client.getPresets();
2143
- return { contents: [{ uri: 'superbased://presets', mimeType: 'application/json', text: formatResponse(res.data) }] };
2144
- }
2145
- catch {
2146
- return { contents: [{ uri: 'superbased://presets', mimeType: 'text/plain', text: 'Cannot read presets — SuperBased may not be running' }] };
2147
- }
2148
- });
2149
- server.resource('superbased-recent-captures', 'superbased://captures/recent', async () => {
2150
- try {
2151
- const res = await client.getCaptures(10);
2152
- return { contents: [{ uri: 'superbased://captures/recent', mimeType: 'application/json', text: formatResponse(res.data) }] };
2153
- }
2154
- catch {
2155
- return { contents: [{ uri: 'superbased://captures/recent', mimeType: 'text/plain', text: 'Cannot read captures — SuperBased may not be running' }] };
2156
- }
2157
- });
2158
- // ── Expanded Resources ──
2159
- server.resource('superbased-auth', 'superbased://auth', async () => {
2160
- try {
2161
- const res = await client.authStatus();
2162
- return { contents: [{ uri: 'superbased://auth', mimeType: 'application/json', text: formatResponse(res.data) }] };
2163
- }
2164
- catch {
2165
- return { contents: [{ uri: 'superbased://auth', mimeType: 'text/plain', text: 'Cannot read auth state' }] };
2166
- }
2167
- });
2168
- server.resource('superbased-license', 'superbased://license', async () => {
2169
- try {
2170
- const res = await client.licenseInfo();
2171
- return { contents: [{ uri: 'superbased://license', mimeType: 'application/json', text: formatResponse(res.data) }] };
2172
- }
2173
- catch {
2174
- return { contents: [{ uri: 'superbased://license', mimeType: 'text/plain', text: 'Cannot read license state' }] };
2175
- }
2176
- });
2177
- server.resource('superbased-recording', 'superbased://recording', async () => {
2178
- try {
2179
- const res = await client.recordingStatus();
2180
- return { contents: [{ uri: 'superbased://recording', mimeType: 'application/json', text: formatResponse(res.data) }] };
2181
- }
2182
- catch {
2183
- return { contents: [{ uri: 'superbased://recording', mimeType: 'text/plain', text: 'Cannot read recording state' }] };
2184
- }
2185
- });
2186
- server.resource('superbased-recording-monitor', 'superbased://recording/monitor', async () => {
2187
- try {
2188
- const res = await client.recordingMonitorStatus();
2189
- return { contents: [{ uri: 'superbased://recording/monitor', mimeType: 'application/json', text: formatResponse(res.data) }] };
2190
- }
2191
- catch {
2192
- return { contents: [{ uri: 'superbased://recording/monitor', mimeType: 'text/plain', text: 'Cannot read monitor state — SuperBased may not be running or no monitor session active' }] };
2193
- }
2194
- });
2195
- server.resource('superbased-analytics', 'superbased://analytics/summary', async () => {
2196
- try {
2197
- const res = await client.analyticsSummary();
2198
- return { contents: [{ uri: 'superbased://analytics/summary', mimeType: 'application/json', text: formatResponse(res.data) }] };
2199
- }
2200
- catch {
2201
- return { contents: [{ uri: 'superbased://analytics/summary', mimeType: 'text/plain', text: 'Cannot read analytics' }] };
2202
- }
2203
- });
2204
- server.resource('superbased-ai-usage', 'superbased://ai/usage', async () => {
2205
- try {
2206
- const res = await client.aiUsage();
2207
- return { contents: [{ uri: 'superbased://ai/usage', mimeType: 'application/json', text: formatResponse(res.data) }] };
2208
- }
2209
- catch {
2210
- return { contents: [{ uri: 'superbased://ai/usage', mimeType: 'text/plain', text: 'Cannot read AI usage' }] };
2211
- }
2212
- });
2213
- // ── Watcher Resources (Phase 3 — subscribable event streams) ──
2214
- server.resource('superbased-watcher-clipboard', 'superbased://watchers/clipboard', {
2215
- description: 'Clipboard change events. Subscribe with resources/subscribe to receive notifications/resources/updated on every clipboard text change. Text-only for v1.',
2216
- }, async () => {
2217
- // Synchronous read returns the current subscriber count + poll interval.
2218
- try {
2219
- const res = await client.watcherStatus();
2220
- const entry = res.data.watchers.find((w) => w.uri === 'superbased://watchers/clipboard');
2221
- return {
2222
- contents: [{
2223
- uri: 'superbased://watchers/clipboard',
2224
- mimeType: 'application/json',
2225
- text: formatResponse({
2226
- description: 'Subscribe for clipboard-change notifications. Text-only.',
2227
- subscribers: entry?.subscribers ?? 0,
2228
- }),
2229
- }],
2230
- };
2231
- }
2232
- catch {
2233
- return { contents: [{ uri: 'superbased://watchers/clipboard', mimeType: 'text/plain', text: 'Cannot read watcher status' }] };
2234
- }
2235
- });
2236
- server.resource('superbased-watcher-active-window', 'superbased://watchers/active-window', {
2237
- description: 'Foreground-window change events. Subscribe to receive notifications when the active application or window title changes. Payload: { appName, windowTitle, source }.',
2238
- }, async () => {
2239
- try {
2240
- const res = await client.watcherStatus();
2241
- const entry = res.data.watchers.find((w) => w.uri === 'superbased://watchers/active-window');
2242
- return {
2243
- contents: [{
2244
- uri: 'superbased://watchers/active-window',
2245
- mimeType: 'application/json',
2246
- text: formatResponse({
2247
- description: 'Subscribe for foreground-window change notifications.',
2248
- subscribers: entry?.subscribers ?? 0,
2249
- }),
2250
- }],
2251
- };
2252
- }
2253
- catch {
2254
- return { contents: [{ uri: 'superbased://watchers/active-window', mimeType: 'text/plain', text: 'Cannot read watcher status' }] };
2255
- }
2256
- });
2257
- server.resource('superbased-watcher-screen-region-fullscreen', 'superbased://watchers/screen-region/fullscreen', {
2258
- 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.',
2259
- }, async () => {
2260
- try {
2261
- const res = await client.watcherStatus();
2262
- const entry = res.data.watchers.find((w) => w.uri === 'superbased://watchers/screen-region/fullscreen');
2263
- return {
2264
- contents: [{
2265
- uri: 'superbased://watchers/screen-region/fullscreen',
2266
- mimeType: 'application/json',
2267
- text: formatResponse({
2268
- description: 'Subscribe for fullscreen visual-change notifications.',
2269
- subscribers: entry?.subscribers ?? 0,
2270
- }),
2271
- }],
2272
- };
2273
- }
2274
- catch {
2275
- return { contents: [{ uri: 'superbased://watchers/screen-region/fullscreen', mimeType: 'text/plain', text: 'Cannot read watcher status' }] };
2276
- }
2277
- });
2278
- // File watcher is URI-templated — one subscription per filesystem path.
2279
- // Advertised via listResourceTemplates so clients can construct concrete URIs.
2280
- server.resource('superbased-watcher-file', new mcp_js_1.ResourceTemplate('superbased://watchers/file/{+path}', { list: undefined }), {
2281
- 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.',
2282
- }, async (uri) => {
2283
- try {
2284
- const res = await client.watcherStatus();
2285
- const entry = res.data.watchers.find((w) => w.uri === uri.toString());
2286
- return {
2287
- contents: [{
2288
- uri: uri.toString(),
2289
- mimeType: 'application/json',
2290
- text: formatResponse({
2291
- description: 'Subscribe for file-change notifications on this path.',
2292
- subscribers: entry?.subscribers ?? 0,
2293
- }),
2294
- }],
2295
- };
2296
- }
2297
- catch {
2298
- return { contents: [{ uri: uri.toString(), mimeType: 'text/plain', text: 'Cannot read watcher status' }] };
2299
- }
2300
- });
2301
- // ── Subscribe / Unsubscribe wiring ──
2302
- // Advertise subscribe capability. Must be done before transport connects.
2303
- server.server.registerCapabilities({ resources: { subscribe: true } });
2304
- const subscribedUris = new Set();
2305
- let closeSseStream = null;
2306
- function ensureSseOpen() {
2307
- if (closeSseStream)
2308
- return;
2309
- closeSseStream = client.openWatcherStream((event) => {
2310
- // Only forward to the client if we have an active subscription to this URI.
2311
- if (!subscribedUris.has(event.uri))
2312
- return;
2313
- void server.server.sendResourceUpdated({ uri: event.uri }).catch(() => {
2314
- // Transport may be in the middle of shutdown — swallow.
2315
- });
2316
- }, () => {
2317
- // SSE dropped. Null out so next subscribe reconnects. No aggressive retry —
2318
- // subscriptions are long-lived and the MCP client can reconnect the server
2319
- // if it wants a fresh stream.
2320
- closeSseStream = null;
2321
- });
2322
- }
2323
- server.server.setRequestHandler(types_js_1.SubscribeRequestSchema, async (request) => {
2324
- const uri = request.params.uri;
2325
- try {
2326
- await client.subscribeWatcher(uri);
2327
- }
2328
- catch (err) {
2329
- throw new Error(err instanceof Error ? err.message : String(err));
2330
- }
2331
- subscribedUris.add(uri);
2332
- ensureSseOpen();
2333
- return {};
2334
- });
2335
- server.server.setRequestHandler(types_js_1.UnsubscribeRequestSchema, async (request) => {
2336
- const uri = request.params.uri;
2337
- subscribedUris.delete(uri);
2338
- try {
2339
- await client.unsubscribeWatcher(uri);
2340
- }
2341
- catch {
2342
- // Server-side refcount will leak, but we've already dropped local state —
2343
- // api-server's `stopApiServer` shutdown hook handles final cleanup.
2344
- }
2345
- return {};
2346
- });
2347
- // On transport close, send unsubscribes for every URI we own so the api-server
2348
- // refcount decrements correctly. Without this, watchers would keep running
2349
- // after the MCP client disconnects.
2350
- const originalOnClose = server.server.onclose;
2351
- server.server.onclose = () => {
2352
- if (closeSseStream) {
2353
- try {
2354
- closeSseStream();
2355
- }
2356
- catch { /* ignore */ }
2357
- closeSseStream = null;
2358
- }
2359
- const uris = Array.from(subscribedUris);
2360
- subscribedUris.clear();
2361
- // Fire-and-forget — process may exit before these resolve, which is fine:
2362
- // api-server also calls registry.shutdown() on its own stop path.
2363
- for (const uri of uris) {
2364
- void client.unsubscribeWatcher(uri).catch(() => { });
2365
- }
2366
- if (originalOnClose) {
2367
- try {
2368
- originalOnClose();
2369
- }
2370
- catch { /* ignore */ }
2371
- }
2372
- };
2373
- // ── Phase 5.5: progressive-disclosure filter on tools/list ──
2374
- //
2375
- // If the user has opted into progressive disclosure, override the SDK's
2376
- // default ListTools handler to surface only the core-11 subset. Non-core
2377
- // tools remain registered with the server's call handler (they're callable
2378
- // by name from plugin slash commands); we only filter what's advertised
2379
- // via tools/list. See src/tool-categories.ts for the category map and
2380
- // `superbased_tools` registration above for the discovery dispatcher.
2381
- //
2382
- // Setting is read once at startup; flipping it requires an MCP server
2383
- // restart (marked `requiresRestart: true` in the schema). Documented.
2384
- //
2385
- // Read the setting directly from the shared settings file instead of
2386
- // importing from electron/core — mcp-server ships as a separate package
2387
- // and doesn't bundle electron modules. This matches the convention used
2388
- // elsewhere for cross-process config (e.g., paths.ts resolution).
2389
- try {
2390
- // eslint-disable-next-line @typescript-eslint/no-require-imports
2391
- const fs = require('fs');
2392
- // eslint-disable-next-line @typescript-eslint/no-require-imports
2393
- const pathMod = require('path');
2394
- // eslint-disable-next-line @typescript-eslint/no-require-imports
2395
- const os = require('os');
2396
- const settingsPath = process.env.SUPERBASED_DATA_DIR
2397
- ? pathMod.join(process.env.SUPERBASED_DATA_DIR, 'superbased-settings.json')
2398
- : pathMod.join(os.homedir(), '.superbased', 'superbased-settings.json');
2399
- let progressiveOn = false;
2400
- try {
2401
- if (fs.existsSync(settingsPath)) {
2402
- const raw = fs.readFileSync(settingsPath, 'utf-8');
2403
- const settings = JSON.parse(raw);
2404
- const pd = (settings.progressiveDisclosure ?? {});
2405
- progressiveOn = pd.enabled === true;
2406
- }
2407
- }
2408
- catch {
2409
- // Settings file unreadable or malformed — default to off.
2410
- }
2411
- if (progressiveOn) {
2412
- // eslint-disable-next-line @typescript-eslint/no-require-imports
2413
- const { CORE_TOOLS } = require('./tool-categories');
2414
- // eslint-disable-next-line @typescript-eslint/no-require-imports
2415
- const { ListToolsRequestSchema } = require('@modelcontextprotocol/sdk/types.js');
2416
- // eslint-disable-next-line @typescript-eslint/no-require-imports
2417
- const zodCompat = require('@modelcontextprotocol/sdk/server/zod-compat.js');
2418
- // eslint-disable-next-line @typescript-eslint/no-require-imports
2419
- const schemaCompat = require('@modelcontextprotocol/sdk/server/zod-json-schema-compat.js');
2420
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2421
- const registered = server._registeredTools;
2422
- server.server.setRequestHandler(ListToolsRequestSchema, async () => {
2423
- const tools = [];
2424
- for (const [name, tool] of Object.entries(registered)) {
2425
- if (tool.enabled === false)
2426
- continue;
2427
- if (!CORE_TOOLS.has(name))
2428
- continue;
2429
- const inputSchemaObj = tool.inputSchema ? zodCompat.normalizeObjectSchema(tool.inputSchema) : null;
2430
- const inputSchema = inputSchemaObj
2431
- ? schemaCompat.toJsonSchemaCompat(inputSchemaObj, { strictUnions: true, pipeStrategy: 'input' })
2432
- : { type: 'object' };
2433
- tools.push({
2434
- name,
2435
- title: tool.title,
2436
- description: tool.description,
2437
- inputSchema,
2438
- annotations: tool.annotations,
2439
- _meta: tool._meta,
2440
- });
2441
- }
2442
- return { tools };
2443
- });
2444
- }
2445
- }
2446
- catch (err) {
2447
- // If the override fails (SDK internals moved, etc.), degrade gracefully
2448
- // to the default full-list behaviour. Users hit the same token cost as
2449
- // before but nothing is broken.
2450
- console.error('[mcp] Progressive-disclosure override failed to install; falling back to full tools/list:', err);
2451
- }
2452
- return { startMonitorPoller, stopMonitorPoller };
2453
- }
2454
- /**
2455
- * Start the MCP server over stdio transport.
2456
- * Called from `superbased mcp` (unified mode) or standalone MCP server.
2457
- */
2458
- async function startMcpServer(port = 47592, projectDir) {
2459
- const client = new api_client_1.SuperBasedAPIClient(`http://127.0.0.1:${port}`);
2460
- const server = new mcp_js_1.McpServer({ name: 'superbased', version: '1.0.0' });
2461
- registerMcpTools(server, client, projectDir);
2462
- const transport = new stdio_js_1.StdioServerTransport();
2463
- await server.connect(transport);
2464
- }
2465
- /**
2466
- * Create an MCP HTTP handler for mounting on an existing HTTP server.
2467
- * Supports Streamable HTTP transport (POST/GET/DELETE /mcp) for clients
2468
- * like OpenAI Codex that connect via URL instead of stdio.
2469
- */
2470
- function createMcpHttpHandler(port = 47592, projectDir) {
2471
- const { StreamableHTTPServerTransport } = require('@modelcontextprotocol/sdk/server/streamableHttp.js');
2472
- const { randomUUID } = require('crypto');
2473
- // Session management: map session IDs to transports
2474
- const sessions = new Map();
2475
- async function handlePost(req, res, body) {
2476
- const sessionId = req.headers['mcp-session-id'];
2477
- try {
2478
- if (sessionId && sessions.has(sessionId)) {
2479
- // Existing session — reuse transport
2480
- const transport = sessions.get(sessionId);
2481
- await transport.handleRequest(req, res, body);
2482
- }
2483
- else if (!sessionId) {
2484
- // New initialization — create transport + server
2485
- const transport = new StreamableHTTPServerTransport({
2486
- sessionIdGenerator: () => randomUUID(),
2487
- onsessioninitialized: (newId) => {
2488
- sessions.set(newId, transport);
2489
- },
2490
- onsessionclosed: (closedId) => {
2491
- sessions.delete(closedId);
2492
- },
2493
- });
2494
- transport.onclose = () => {
2495
- const sid = transport.sessionId;
2496
- if (sid)
2497
- sessions.delete(sid);
2498
- };
2499
- const client = new api_client_1.SuperBasedAPIClient(`http://127.0.0.1:${port}`);
2500
- const server = new mcp_js_1.McpServer({ name: 'superbased', version: '1.0.0' });
2501
- registerMcpTools(server, client, projectDir);
2502
- await server.connect(transport);
2503
- await transport.handleRequest(req, res, body);
2504
- }
2505
- else {
2506
- // Session ID provided but not found
2507
- res.writeHead(404, { 'Content-Type': 'application/json' });
2508
- res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32000, message: 'Session not found' }, id: null }));
2509
- }
2510
- }
2511
- catch (err) {
2512
- if (!res.headersSent) {
2513
- res.writeHead(500, { 'Content-Type': 'application/json' });
2514
- res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error' }, id: null }));
2515
- }
2516
- }
2517
- }
2518
- async function handleGet(req, res) {
2519
- const sessionId = req.headers['mcp-session-id'];
2520
- if (!sessionId || !sessions.has(sessionId)) {
2521
- res.writeHead(400, { 'Content-Type': 'application/json' });
2522
- res.end(JSON.stringify({ error: 'Invalid or missing session ID' }));
2523
- return;
2524
- }
2525
- const transport = sessions.get(sessionId);
2526
- await transport.handleRequest(req, res);
2527
- }
2528
- async function handleDelete(req, res) {
2529
- const sessionId = req.headers['mcp-session-id'];
2530
- if (!sessionId || !sessions.has(sessionId)) {
2531
- res.writeHead(400, { 'Content-Type': 'application/json' });
2532
- res.end(JSON.stringify({ error: 'Invalid or missing session ID' }));
2533
- return;
2534
- }
2535
- const transport = sessions.get(sessionId);
2536
- await transport.handleRequest(req, res);
2537
- }
2538
- return { handlePost, handleGet, handleDelete };
2539
- }
2540
- // Auto-run when executed directly (node index.js)
2541
- async function main() {
2542
- const { port, projectDir } = parseArgs();
2543
- await startMcpServer(port, projectDir);
2544
- }
2545
- if (require.main === module) {
2546
- main().catch((err) => {
2547
- process.stderr.write(`MCP server error: ${err instanceof Error ? err.message : String(err)}\n`);
2548
- process.exit(1);
2549
- });
2550
- }