simplify3x-connect 0.0.0-stage → 0.28.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (363) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +117 -3
  3. package/dist/acText.d.ts +12 -0
  4. package/dist/acText.d.ts.map +1 -0
  5. package/dist/acText.js +44 -0
  6. package/dist/acText.js.map +1 -0
  7. package/dist/adapters/factory.d.ts +25 -0
  8. package/dist/adapters/factory.d.ts.map +1 -0
  9. package/dist/adapters/factory.js +55 -0
  10. package/dist/adapters/factory.js.map +1 -0
  11. package/dist/adapters/http.d.ts +62 -0
  12. package/dist/adapters/http.d.ts.map +1 -0
  13. package/dist/adapters/http.js +138 -0
  14. package/dist/adapters/http.js.map +1 -0
  15. package/dist/adapters/remoteMcp/adapter.d.ts +112 -0
  16. package/dist/adapters/remoteMcp/adapter.d.ts.map +1 -0
  17. package/dist/adapters/remoteMcp/adapter.js +259 -0
  18. package/dist/adapters/remoteMcp/adapter.js.map +1 -0
  19. package/dist/adapters/simplifyqa/adapter.d.ts +1390 -0
  20. package/dist/adapters/simplifyqa/adapter.d.ts.map +1 -0
  21. package/dist/adapters/simplifyqa/adapter.js +9126 -0
  22. package/dist/adapters/simplifyqa/adapter.js.map +1 -0
  23. package/dist/adapters/simplifyqa/apiFailureReason.d.ts +11 -0
  24. package/dist/adapters/simplifyqa/apiFailureReason.d.ts.map +1 -0
  25. package/dist/adapters/simplifyqa/apiFailureReason.js +35 -0
  26. package/dist/adapters/simplifyqa/apiFailureReason.js.map +1 -0
  27. package/dist/adapters/simplifyqa/desktopConditions.d.ts +50 -0
  28. package/dist/adapters/simplifyqa/desktopConditions.d.ts.map +1 -0
  29. package/dist/adapters/simplifyqa/desktopConditions.js +95 -0
  30. package/dist/adapters/simplifyqa/desktopConditions.js.map +1 -0
  31. package/dist/adapters/simplifyqa/executionFailures.d.ts +59 -0
  32. package/dist/adapters/simplifyqa/executionFailures.d.ts.map +1 -0
  33. package/dist/adapters/simplifyqa/executionFailures.js +641 -0
  34. package/dist/adapters/simplifyqa/executionFailures.js.map +1 -0
  35. package/dist/adapters/simplifyqa/failureCategory.d.ts +26 -0
  36. package/dist/adapters/simplifyqa/failureCategory.d.ts.map +1 -0
  37. package/dist/adapters/simplifyqa/failureCategory.js +208 -0
  38. package/dist/adapters/simplifyqa/failureCategory.js.map +1 -0
  39. package/dist/adapters/simplifyqa/failureReport.d.ts +50 -0
  40. package/dist/adapters/simplifyqa/failureReport.d.ts.map +1 -0
  41. package/dist/adapters/simplifyqa/failureReport.js +383 -0
  42. package/dist/adapters/simplifyqa/failureReport.js.map +1 -0
  43. package/dist/adapters/simplifyqa/failureTypes.d.ts +193 -0
  44. package/dist/adapters/simplifyqa/failureTypes.d.ts.map +1 -0
  45. package/dist/adapters/simplifyqa/failureTypes.js +8 -0
  46. package/dist/adapters/simplifyqa/failureTypes.js.map +1 -0
  47. package/dist/adapters/simplifyqa/flow.d.ts +58 -0
  48. package/dist/adapters/simplifyqa/flow.d.ts.map +1 -0
  49. package/dist/adapters/simplifyqa/flow.js +335 -0
  50. package/dist/adapters/simplifyqa/flow.js.map +1 -0
  51. package/dist/adapters/simplifyqa/functionMatch.d.ts +53 -0
  52. package/dist/adapters/simplifyqa/functionMatch.d.ts.map +1 -0
  53. package/dist/adapters/simplifyqa/functionMatch.js +110 -0
  54. package/dist/adapters/simplifyqa/functionMatch.js.map +1 -0
  55. package/dist/adapters/simplifyqa/heal/apply.d.ts +59 -0
  56. package/dist/adapters/simplifyqa/heal/apply.d.ts.map +1 -0
  57. package/dist/adapters/simplifyqa/heal/apply.js +213 -0
  58. package/dist/adapters/simplifyqa/heal/apply.js.map +1 -0
  59. package/dist/adapters/simplifyqa/heal/diagnose.d.ts +24 -0
  60. package/dist/adapters/simplifyqa/heal/diagnose.d.ts.map +1 -0
  61. package/dist/adapters/simplifyqa/heal/diagnose.js +211 -0
  62. package/dist/adapters/simplifyqa/heal/diagnose.js.map +1 -0
  63. package/dist/adapters/simplifyqa/heal/index.d.ts +37 -0
  64. package/dist/adapters/simplifyqa/heal/index.d.ts.map +1 -0
  65. package/dist/adapters/simplifyqa/heal/index.js +83 -0
  66. package/dist/adapters/simplifyqa/heal/index.js.map +1 -0
  67. package/dist/adapters/simplifyqa/heal/plan.d.ts +67 -0
  68. package/dist/adapters/simplifyqa/heal/plan.d.ts.map +1 -0
  69. package/dist/adapters/simplifyqa/heal/plan.js +338 -0
  70. package/dist/adapters/simplifyqa/heal/plan.js.map +1 -0
  71. package/dist/adapters/simplifyqa/heal/store.d.ts +10 -0
  72. package/dist/adapters/simplifyqa/heal/store.d.ts.map +1 -0
  73. package/dist/adapters/simplifyqa/heal/store.js +40 -0
  74. package/dist/adapters/simplifyqa/heal/store.js.map +1 -0
  75. package/dist/adapters/simplifyqa/mapLimit.d.ts +3 -0
  76. package/dist/adapters/simplifyqa/mapLimit.d.ts.map +1 -0
  77. package/dist/adapters/simplifyqa/mapLimit.js +14 -0
  78. package/dist/adapters/simplifyqa/mapLimit.js.map +1 -0
  79. package/dist/adapters/simplifyqa/mapper.d.ts +159 -0
  80. package/dist/adapters/simplifyqa/mapper.d.ts.map +1 -0
  81. package/dist/adapters/simplifyqa/mapper.js +1767 -0
  82. package/dist/adapters/simplifyqa/mapper.js.map +1 -0
  83. package/dist/adapters/simplifyqa/planTree.d.ts +31 -0
  84. package/dist/adapters/simplifyqa/planTree.d.ts.map +1 -0
  85. package/dist/adapters/simplifyqa/planTree.js +110 -0
  86. package/dist/adapters/simplifyqa/planTree.js.map +1 -0
  87. package/dist/adapters/simplifyqa/searchEngine.d.ts +254 -0
  88. package/dist/adapters/simplifyqa/searchEngine.d.ts.map +1 -0
  89. package/dist/adapters/simplifyqa/searchEngine.js +1248 -0
  90. package/dist/adapters/simplifyqa/searchEngine.js.map +1 -0
  91. package/dist/adapters/simplifyqa/searchRegistry.d.ts +117 -0
  92. package/dist/adapters/simplifyqa/searchRegistry.d.ts.map +1 -0
  93. package/dist/adapters/simplifyqa/searchRegistry.js +1664 -0
  94. package/dist/adapters/simplifyqa/searchRegistry.js.map +1 -0
  95. package/dist/adapters/simplifyqa/searchResolve.d.ts +84 -0
  96. package/dist/adapters/simplifyqa/searchResolve.d.ts.map +1 -0
  97. package/dist/adapters/simplifyqa/searchResolve.js +319 -0
  98. package/dist/adapters/simplifyqa/searchResolve.js.map +1 -0
  99. package/dist/adapters/simplifyqa/stepDiagnostics.d.ts +25 -0
  100. package/dist/adapters/simplifyqa/stepDiagnostics.d.ts.map +1 -0
  101. package/dist/adapters/simplifyqa/stepDiagnostics.js +89 -0
  102. package/dist/adapters/simplifyqa/stepDiagnostics.js.map +1 -0
  103. package/dist/adapters/simplifyqa/stepRules.d.ts +91 -0
  104. package/dist/adapters/simplifyqa/stepRules.d.ts.map +1 -0
  105. package/dist/adapters/simplifyqa/stepRules.js +228 -0
  106. package/dist/adapters/simplifyqa/stepRules.js.map +1 -0
  107. package/dist/adapters/types.d.ts +514 -0
  108. package/dist/adapters/types.d.ts.map +1 -0
  109. package/dist/adapters/types.js +2 -0
  110. package/dist/adapters/types.js.map +1 -0
  111. package/dist/adapters/walnut/actionTypes.d.ts +16 -0
  112. package/dist/adapters/walnut/actionTypes.d.ts.map +1 -0
  113. package/dist/adapters/walnut/actionTypes.js +178 -0
  114. package/dist/adapters/walnut/actionTypes.js.map +1 -0
  115. package/dist/adapters/walnut/adapter.d.ts +235 -0
  116. package/dist/adapters/walnut/adapter.d.ts.map +1 -0
  117. package/dist/adapters/walnut/adapter.js +1120 -0
  118. package/dist/adapters/walnut/adapter.js.map +1 -0
  119. package/dist/adapters/walnut/mapper.d.ts +55 -0
  120. package/dist/adapters/walnut/mapper.d.ts.map +1 -0
  121. package/dist/adapters/walnut/mapper.js +364 -0
  122. package/dist/adapters/walnut/mapper.js.map +1 -0
  123. package/dist/cli.d.ts +3 -0
  124. package/dist/cli.d.ts.map +1 -0
  125. package/dist/cli.js +38 -0
  126. package/dist/cli.js.map +1 -0
  127. package/dist/config.d.ts +109 -0
  128. package/dist/config.d.ts.map +1 -0
  129. package/dist/config.js +272 -0
  130. package/dist/config.js.map +1 -0
  131. package/dist/connection.d.ts +105 -0
  132. package/dist/connection.d.ts.map +1 -0
  133. package/dist/connection.js +255 -0
  134. package/dist/connection.js.map +1 -0
  135. package/dist/domain/heal.d.ts +163 -0
  136. package/dist/domain/heal.d.ts.map +1 -0
  137. package/dist/domain/heal.js +55 -0
  138. package/dist/domain/heal.js.map +1 -0
  139. package/dist/domain/types.d.ts +1328 -0
  140. package/dist/domain/types.d.ts.map +1 -0
  141. package/dist/domain/types.js +8 -0
  142. package/dist/domain/types.js.map +1 -0
  143. package/dist/domain/validate.d.ts +3 -0
  144. package/dist/domain/validate.d.ts.map +1 -0
  145. package/dist/domain/validate.js +67 -0
  146. package/dist/domain/validate.js.map +1 -0
  147. package/dist/drafts/apiPatch.d.ts +9 -0
  148. package/dist/drafts/apiPatch.d.ts.map +1 -0
  149. package/dist/drafts/apiPatch.js +27 -0
  150. package/dist/drafts/apiPatch.js.map +1 -0
  151. package/dist/drafts/bulk.d.ts +24 -0
  152. package/dist/drafts/bulk.d.ts.map +1 -0
  153. package/dist/drafts/bulk.js +44 -0
  154. package/dist/drafts/bulk.js.map +1 -0
  155. package/dist/drafts/duplicate.d.ts +12 -0
  156. package/dist/drafts/duplicate.d.ts.map +1 -0
  157. package/dist/drafts/duplicate.js +59 -0
  158. package/dist/drafts/duplicate.js.map +1 -0
  159. package/dist/drafts/store.d.ts +91 -0
  160. package/dist/drafts/store.d.ts.map +1 -0
  161. package/dist/drafts/store.js +244 -0
  162. package/dist/drafts/store.js.map +1 -0
  163. package/dist/gateway.d.ts +37 -0
  164. package/dist/gateway.d.ts.map +1 -0
  165. package/dist/gateway.js +71 -0
  166. package/dist/gateway.js.map +1 -0
  167. package/dist/httpMain.d.ts +3 -0
  168. package/dist/httpMain.d.ts.map +1 -0
  169. package/dist/httpMain.js +20 -0
  170. package/dist/httpMain.js.map +1 -0
  171. package/dist/index.d.ts +3 -0
  172. package/dist/index.d.ts.map +1 -0
  173. package/dist/index.js +46 -0
  174. package/dist/index.js.map +1 -0
  175. package/dist/initAgents.d.ts +2 -0
  176. package/dist/initAgents.d.ts.map +1 -0
  177. package/dist/initAgents.js +508 -0
  178. package/dist/initAgents.js.map +1 -0
  179. package/dist/log.d.ts +17 -0
  180. package/dist/log.d.ts.map +1 -0
  181. package/dist/log.js +49 -0
  182. package/dist/log.js.map +1 -0
  183. package/dist/mcpResult.d.ts +39 -0
  184. package/dist/mcpResult.d.ts.map +1 -0
  185. package/dist/mcpResult.js +19 -0
  186. package/dist/mcpResult.js.map +1 -0
  187. package/dist/mount.d.ts +33 -0
  188. package/dist/mount.d.ts.map +1 -0
  189. package/dist/mount.js +213 -0
  190. package/dist/mount.js.map +1 -0
  191. package/dist/paramTokens.d.ts +18 -0
  192. package/dist/paramTokens.d.ts.map +1 -0
  193. package/dist/paramTokens.js +50 -0
  194. package/dist/paramTokens.js.map +1 -0
  195. package/dist/projectStore.d.ts +5 -0
  196. package/dist/projectStore.d.ts.map +1 -0
  197. package/dist/projectStore.js +60 -0
  198. package/dist/projectStore.js.map +1 -0
  199. package/dist/requestConnection.d.ts +22 -0
  200. package/dist/requestConnection.d.ts.map +1 -0
  201. package/dist/requestConnection.js +50 -0
  202. package/dist/requestConnection.js.map +1 -0
  203. package/dist/serve.d.ts +10 -0
  204. package/dist/serve.d.ts.map +1 -0
  205. package/dist/serve.js +37 -0
  206. package/dist/serve.js.map +1 -0
  207. package/dist/server.d.ts +41 -0
  208. package/dist/server.d.ts.map +1 -0
  209. package/dist/server.js +370 -0
  210. package/dist/server.js.map +1 -0
  211. package/dist/tools/actionCatalog.d.ts +24 -0
  212. package/dist/tools/actionCatalog.d.ts.map +1 -0
  213. package/dist/tools/actionCatalog.js +56 -0
  214. package/dist/tools/actionCatalog.js.map +1 -0
  215. package/dist/tools/attachment.tools.d.ts +15 -0
  216. package/dist/tools/attachment.tools.d.ts.map +1 -0
  217. package/dist/tools/attachment.tools.js +104 -0
  218. package/dist/tools/attachment.tools.js.map +1 -0
  219. package/dist/tools/backlog.tools.d.ts +13 -0
  220. package/dist/tools/backlog.tools.d.ts.map +1 -0
  221. package/dist/tools/backlog.tools.js +690 -0
  222. package/dist/tools/backlog.tools.js.map +1 -0
  223. package/dist/tools/connection.tools.d.ts +16 -0
  224. package/dist/tools/connection.tools.d.ts.map +1 -0
  225. package/dist/tools/connection.tools.js +120 -0
  226. package/dist/tools/connection.tools.js.map +1 -0
  227. package/dist/tools/defects.tools.d.ts +7 -0
  228. package/dist/tools/defects.tools.d.ts.map +1 -0
  229. package/dist/tools/defects.tools.js +108 -0
  230. package/dist/tools/defects.tools.js.map +1 -0
  231. package/dist/tools/discovery.tools.d.ts +23 -0
  232. package/dist/tools/discovery.tools.d.ts.map +1 -0
  233. package/dist/tools/discovery.tools.js +1746 -0
  234. package/dist/tools/discovery.tools.js.map +1 -0
  235. package/dist/tools/executionPlan.tools.d.ts +14 -0
  236. package/dist/tools/executionPlan.tools.d.ts.map +1 -0
  237. package/dist/tools/executionPlan.tools.js +184 -0
  238. package/dist/tools/executionPlan.tools.js.map +1 -0
  239. package/dist/tools/failure.tools.d.ts +14 -0
  240. package/dist/tools/failure.tools.d.ts.map +1 -0
  241. package/dist/tools/failure.tools.js +65 -0
  242. package/dist/tools/failure.tools.js.map +1 -0
  243. package/dist/tools/formulas.tools.d.ts +7 -0
  244. package/dist/tools/formulas.tools.d.ts.map +1 -0
  245. package/dist/tools/formulas.tools.js +84 -0
  246. package/dist/tools/formulas.tools.js.map +1 -0
  247. package/dist/tools/functionReuse.d.ts +77 -0
  248. package/dist/tools/functionReuse.d.ts.map +1 -0
  249. package/dist/tools/functionReuse.js +384 -0
  250. package/dist/tools/functionReuse.js.map +1 -0
  251. package/dist/tools/gapAnalysis.tools.d.ts +31 -0
  252. package/dist/tools/gapAnalysis.tools.d.ts.map +1 -0
  253. package/dist/tools/gapAnalysis.tools.js +287 -0
  254. package/dist/tools/gapAnalysis.tools.js.map +1 -0
  255. package/dist/tools/heal.tools.d.ts +20 -0
  256. package/dist/tools/heal.tools.d.ts.map +1 -0
  257. package/dist/tools/heal.tools.js +268 -0
  258. package/dist/tools/heal.tools.js.map +1 -0
  259. package/dist/tools/impactAnalysis.tools.d.ts +17 -0
  260. package/dist/tools/impactAnalysis.tools.d.ts.map +1 -0
  261. package/dist/tools/impactAnalysis.tools.js +352 -0
  262. package/dist/tools/impactAnalysis.tools.js.map +1 -0
  263. package/dist/tools/markdown.d.ts +13 -0
  264. package/dist/tools/markdown.d.ts.map +1 -0
  265. package/dist/tools/markdown.js +145 -0
  266. package/dist/tools/markdown.js.map +1 -0
  267. package/dist/tools/objects.tools.d.ts +7 -0
  268. package/dist/tools/objects.tools.d.ts.map +1 -0
  269. package/dist/tools/objects.tools.js +458 -0
  270. package/dist/tools/objects.tools.js.map +1 -0
  271. package/dist/tools/pipeline.tools.d.ts +11 -0
  272. package/dist/tools/pipeline.tools.d.ts.map +1 -0
  273. package/dist/tools/pipeline.tools.js +100 -0
  274. package/dist/tools/pipeline.tools.js.map +1 -0
  275. package/dist/tools/preference.tools.d.ts +15 -0
  276. package/dist/tools/preference.tools.d.ts.map +1 -0
  277. package/dist/tools/preference.tools.js +114 -0
  278. package/dist/tools/preference.tools.js.map +1 -0
  279. package/dist/tools/privileges.tools.d.ts +65 -0
  280. package/dist/tools/privileges.tools.d.ts.map +1 -0
  281. package/dist/tools/privileges.tools.js +186 -0
  282. package/dist/tools/privileges.tools.js.map +1 -0
  283. package/dist/tools/project.tools.d.ts +13 -0
  284. package/dist/tools/project.tools.d.ts.map +1 -0
  285. package/dist/tools/project.tools.js +199 -0
  286. package/dist/tools/project.tools.js.map +1 -0
  287. package/dist/tools/query.tools.d.ts +23 -0
  288. package/dist/tools/query.tools.d.ts.map +1 -0
  289. package/dist/tools/query.tools.js +368 -0
  290. package/dist/tools/query.tools.js.map +1 -0
  291. package/dist/tools/recording.tools.d.ts +58 -0
  292. package/dist/tools/recording.tools.d.ts.map +1 -0
  293. package/dist/tools/recording.tools.js +1050 -0
  294. package/dist/tools/recording.tools.js.map +1 -0
  295. package/dist/tools/recordingNames.d.ts +3 -0
  296. package/dist/tools/recordingNames.d.ts.map +1 -0
  297. package/dist/tools/recordingNames.js +16 -0
  298. package/dist/tools/recordingNames.js.map +1 -0
  299. package/dist/tools/report.tools.d.ts +12 -0
  300. package/dist/tools/report.tools.d.ts.map +1 -0
  301. package/dist/tools/report.tools.js +104 -0
  302. package/dist/tools/report.tools.js.map +1 -0
  303. package/dist/tools/run.tools.d.ts +25 -0
  304. package/dist/tools/run.tools.d.ts.map +1 -0
  305. package/dist/tools/run.tools.js +1295 -0
  306. package/dist/tools/run.tools.js.map +1 -0
  307. package/dist/tools/schemas.d.ts +860 -0
  308. package/dist/tools/schemas.d.ts.map +1 -0
  309. package/dist/tools/schemas.js +220 -0
  310. package/dist/tools/schemas.js.map +1 -0
  311. package/dist/tools/storySync.tools.d.ts +167 -0
  312. package/dist/tools/storySync.tools.d.ts.map +1 -0
  313. package/dist/tools/storySync.tools.js +678 -0
  314. package/dist/tools/storySync.tools.js.map +1 -0
  315. package/dist/tools/suiteManage.tools.d.ts +14 -0
  316. package/dist/tools/suiteManage.tools.d.ts.map +1 -0
  317. package/dist/tools/suiteManage.tools.js +112 -0
  318. package/dist/tools/suiteManage.tools.js.map +1 -0
  319. package/dist/tools/tasks.tools.d.ts +7 -0
  320. package/dist/tools/tasks.tools.d.ts.map +1 -0
  321. package/dist/tools/tasks.tools.js +101 -0
  322. package/dist/tools/tasks.tools.js.map +1 -0
  323. package/dist/tools/tcEditPublisher.d.ts +29 -0
  324. package/dist/tools/tcEditPublisher.d.ts.map +1 -0
  325. package/dist/tools/tcEditPublisher.js +61 -0
  326. package/dist/tools/tcEditPublisher.js.map +1 -0
  327. package/dist/tools/testCaseLint.d.ts +5 -0
  328. package/dist/tools/testCaseLint.d.ts.map +1 -0
  329. package/dist/tools/testCaseLint.js +112 -0
  330. package/dist/tools/testCaseLint.js.map +1 -0
  331. package/dist/tools/testPlan.tools.d.ts +12 -0
  332. package/dist/tools/testPlan.tools.d.ts.map +1 -0
  333. package/dist/tools/testPlan.tools.js +104 -0
  334. package/dist/tools/testPlan.tools.js.map +1 -0
  335. package/dist/tools/testcase.tools.d.ts +86 -0
  336. package/dist/tools/testcase.tools.d.ts.map +1 -0
  337. package/dist/tools/testcase.tools.js +1591 -0
  338. package/dist/tools/testcase.tools.js.map +1 -0
  339. package/dist/tools/testdata.tools.d.ts +7 -0
  340. package/dist/tools/testdata.tools.d.ts.map +1 -0
  341. package/dist/tools/testdata.tools.js +636 -0
  342. package/dist/tools/testdata.tools.js.map +1 -0
  343. package/dist/tools/xlsx.d.ts +8 -0
  344. package/dist/tools/xlsx.d.ts.map +1 -0
  345. package/dist/tools/xlsx.js +113 -0
  346. package/dist/tools/xlsx.js.map +1 -0
  347. package/dist/vendor/actionSignatures.d.ts +117 -0
  348. package/dist/vendor/actionSignatures.d.ts.map +1 -0
  349. package/dist/vendor/actionSignatures.js +420 -0
  350. package/dist/vendor/actionSignatures.js.map +1 -0
  351. package/dist/vendor/logger.d.ts +43 -0
  352. package/dist/vendor/logger.d.ts.map +1 -0
  353. package/dist/vendor/logger.js +184 -0
  354. package/dist/vendor/logger.js.map +1 -0
  355. package/dist/version.d.ts +10 -0
  356. package/dist/version.d.ts.map +1 -0
  357. package/dist/version.js +10 -0
  358. package/dist/version.js.map +1 -0
  359. package/dist/versionName.d.ts +21 -0
  360. package/dist/versionName.d.ts.map +1 -0
  361. package/dist/versionName.js +48 -0
  362. package/dist/versionName.js.map +1 -0
  363. package/package.json +62 -4
@@ -0,0 +1,1295 @@
1
+ import { z } from 'zod';
2
+ import { log } from '../log.js';
3
+ import { ok, err } from '../mcpResult.js';
4
+ import { SCHEDULE_TYPES } from '../domain/types.js';
5
+ const NOT_CONNECTED = 'Not connected to a product. Use qa_connect({ url, token, projectId }) first — running a test needs a live backend connection.';
6
+ const lastRun = new Map();
7
+ function summarizeLastRun(c) {
8
+ const parts = [];
9
+ if (c.when)
10
+ parts.push(`when=${c.when}`);
11
+ if (c.mode)
12
+ parts.push(`mode=${c.mode}`);
13
+ if (c.releaseId !== undefined)
14
+ parts.push(`release=${c.releaseId || '(none)'}`);
15
+ if (c.sprintId !== undefined)
16
+ parts.push(`sprint=${c.sprintId || '(none)'}`);
17
+ if (c.environment)
18
+ parts.push(`env=${c.environment}`);
19
+ if (c.browser)
20
+ parts.push(`browser=${c.browser}`);
21
+ if (c.agentId)
22
+ parts.push(`agent=${c.agentId}`);
23
+ if (c.cloudRunnerId)
24
+ parts.push(`runner=${c.cloudRunnerId}`);
25
+ return parts.join(', ');
26
+ }
27
+ function describeError(e) {
28
+ return e instanceof Error ? e.message : String(e);
29
+ }
30
+ function runnerLine(r) {
31
+ const host = r.os ? ` · ${r.os}` : '';
32
+ return `- ${r.online ? '🟢' : '⚪'} ${r.name}${host} \`${r.id}\`${r.status ? ` (${r.status})` : ''}`;
33
+ }
34
+ function localAgentLine(a) {
35
+ // Show the machine hostname next to the owner (like the product UI) so the user can tell apart
36
+ // several agents owned by the same person; the credential_id in backticks is for the tool call.
37
+ const host = a.host && a.host !== a.name ? ` · ${a.host}` : '';
38
+ return `- ${a.online ? '🟢' : '⚪'} ${a.name ?? a.id}${host} \`${a.id}\`${a.status ? ` (${a.status})` : ''}`;
39
+ }
40
+ function mobileDeviceLine(d) {
41
+ // `active` here is the last-known connection flag from the SQA DB (stale by design). Show it as
42
+ // a hint, not a gate — a device the user just plugged in may still read `active:false` here.
43
+ const dot = d.active ? '🟢' : '⚪';
44
+ const label = d.displayName || d.name;
45
+ const os = d.osVersion ? ` · ${d.platform.toLowerCase()} ${d.osVersion}` : ` · ${d.platform.toLowerCase()}`;
46
+ const status = d.status ? ` (${d.status})` : '';
47
+ return `- ${dot} ${label}${os} \`${d.id}\`${status}`;
48
+ }
49
+ /** One line per schedule for management listings — what it runs, cadence, where + pinned agent,
50
+ * browser, next run, status; the credential-free id in backticks is what the management tools take. */
51
+ function scheduleLine(s) {
52
+ const where = s.executionTarget === 'cloud_runner' ? 'cloud' : 'local';
53
+ const agent = s.agent ? ` → ${s.agent}` : '';
54
+ const br = s.browser ? ` · ${s.browser}` : '';
55
+ const next = s.nextRunAt ? ` · next ${s.nextRunAt}` : s.scheduledFor ? ` · at ${s.scheduledFor}` : '';
56
+ const paused = s.active === false ? ' [paused]' : '';
57
+ return `- ${s.target} — ${s.scheduleType}, ${where}${agent}${br}${next} · **${s.status}**${paused} \`${s.id}\``;
58
+ }
59
+ const SCHEDULE_TYPE_DESC = "SCHEDULE STEP — REQUIRED for when:'schedule'; ASK the user explicitly, never assume. The " +
60
+ "UI's Recurrence choices: 'once', 'every_5_minutes', 'hourly', 'daily', 'weekly', 'monthly'. " +
61
+ "Anything but 'once' also needs endDate. ('weekdays' = weekly Mon–Fri, MCP shortcut — don't offer it.)";
62
+ const END_DATE_DESC = "SCHEDULE STEP — ISO end date; REQUIRED when scheduleType is anything but 'once'. ASK the user.";
63
+ /** The scheduler form's Recurrence dropdown, in the UI's order — what the user is asked to pick from. */
64
+ const RECURRENCE_CHOICES = "Once (once) · Every 5 Minutes (every_5_minutes) · Hourly (hourly) · Daily (daily) · Weekly (weekly) · Monthly (monthly)";
65
+ /** The schedule questions the UI forces (start time, recurrence, then end date for a repeating one).
66
+ * Returns the refusal to send, or null when everything was given. Never defaults the recurrence to
67
+ * "once" — a silent default is how a schedule got created without the user ever being asked. */
68
+ export function missingScheduleFields(tool, scheduledFor, scheduleType, endDate) {
69
+ const missing = [];
70
+ if (!scheduledFor)
71
+ missing.push("`scheduledFor` — when the first (or only) run starts, as an ISO datetime (e.g. '2026-08-20T09:00:00Z'), plus the timezone");
72
+ if (!scheduleType)
73
+ missing.push(`\`scheduleType\` — how often it repeats. Offer EXACTLY the UI's choices, in this order: ${RECURRENCE_CHOICES}`);
74
+ if (scheduleType && scheduleType !== 'once' && !endDate)
75
+ missing.push("`endDate` — when the repetition stops (ISO date); required for every recurrence except Once");
76
+ if (!missing.length)
77
+ return null;
78
+ return (`ASK the user explicitly before creating the schedule — do not assume or default any of these:\n` +
79
+ missing.map((m, i) => ` ${i + 1}. ${m}`).join('\n') +
80
+ `\nThen call ${tool} again with when:'schedule' and the answers.` +
81
+ (!scheduleType ? ' If they choose anything but Once, also ask for the end date.' : ''));
82
+ }
83
+ /** A schedule fires detached from any live session, so a LOCAL schedule must target a specific
84
+ * agent — there is no "your online agent" at fire time. Build the "pick an agent" message, offering
85
+ * ALL agents (online AND offline): a scheduled run can target an agent that is offline right now,
86
+ * because it runs when it fires — this mirrors the product's scheduler picker. */
87
+ async function localScheduleNeedsAgent(adapter) {
88
+ let list = '';
89
+ if (adapter.listLocalAgents) {
90
+ try {
91
+ const agents = await adapter.listLocalAgents();
92
+ list = agents.length
93
+ ? '\n\nAgents (a scheduled run can target an offline one — it runs when it fires):\n' +
94
+ agents.map(localAgentLine).join('\n')
95
+ : '\n\nNo local agents are registered to this project.';
96
+ }
97
+ catch { /* best-effort listing — the core message still stands */ }
98
+ }
99
+ return ('A LOCAL schedule runs detached from any live session, so it must target a specific agent. ' +
100
+ 'Call again with `agentId` set to a credential_id from local_agents.' + list);
101
+ }
102
+ /** A run-NOW to a specific LOCAL agent cannot target an offline one (mirrors the product UI, which
103
+ * offers only ONLINE agents for an immediate run). Returns an error message when the picked agent is
104
+ * known-offline, else null. Roster errors are swallowed — the backend still validates at reserve. */
105
+ async function localAgentOfflineForNow(adapter, agentId) {
106
+ if (!adapter.listLocalAgents)
107
+ return null;
108
+ try {
109
+ const agents = await adapter.listLocalAgents();
110
+ const picked = agents.find((a) => a.id === agentId);
111
+ // If the picked agent physically belongs to this machine (hostname / MAC / IP matched), the
112
+ // adapter's DB-flag override in listLocalAgents already set `online: true`. Never refuse a
113
+ // run-now for our OWN machine — the DB flag is stale by design (7s cron in the executions
114
+ // service that we cannot touch).
115
+ if (picked?.isThisMachine)
116
+ return null;
117
+ if (picked && !picked.online) {
118
+ const online = agents.filter((a) => a.online);
119
+ return (`Agent \`${agentId}\`${picked.name ? ` (${picked.name})` : ''} is offline — a run-now needs an ONLINE agent. ` +
120
+ (online.length
121
+ ? 'Online now:\n' + online.map(localAgentLine).join('\n')
122
+ : 'No local agents are online right now — schedule it instead, or bring an agent online.'));
123
+ }
124
+ }
125
+ catch { /* roster unavailable — let the backend validate at reserve */ }
126
+ return null;
127
+ }
128
+ /** Human summary of a run's status. For a SUITE run `children` carries the per-test-case rollup and
129
+ * `progress` counts TEST CASES; a single test-case run has neither (progress counts steps). */
130
+ export function statusText(s) {
131
+ const unit = s.children ? 'test cases' : 'steps';
132
+ const prog = s.progress ? ` · ${s.progress.done}/${s.progress.total} ${unit}` : '';
133
+ const when = s.startedAt ? ` · started ${s.startedAt}${s.endedAt ? ` · ended ${s.endedAt}` : ''}` : '';
134
+ const link = s.reportUrl ? `\n${s.reportUrl}` : '';
135
+ const icon = (state) => state === 'passed' ? '✅'
136
+ : state === 'failed' ? '❌'
137
+ : state === 'running' ? '⏳'
138
+ : state === 'skipped' ? '⏭️'
139
+ : state === 'notExecuted' ? '➖'
140
+ : state === 'stopped' ? '⏹️'
141
+ : state === 'error' ? '⚠️'
142
+ : '•';
143
+ // Per-state tally across children (suite runs only) — EVERY state SQA actually reports gets its
144
+ // own bucket (skipped/notExecuted/error included, not folded into another), so the sum below is
145
+ // guaranteed to equal `total` by construction (every child has exactly one state). Kept concise —
146
+ // only non-zero buckets, in a stable order so the header reads the same every poll.
147
+ const isProvisional = s.state === 'running' || s.state === 'queued';
148
+ const tally = s.children?.length
149
+ ? (() => {
150
+ const order = ['passed', 'failed', 'skipped', 'notExecuted', 'running', 'queued', 'stopped', 'error'];
151
+ const counts = new Map();
152
+ for (const c of s.children)
153
+ counts.set(c.state, (counts.get(c.state) ?? 0) + 1);
154
+ const parts = order.filter((k) => counts.get(k)).map((k) => `${counts.get(k)} ${k}`);
155
+ // One row per SUITE MEMBER (test case), never per iteration — counts below are per test
156
+ // case, stated explicitly since a member with multiple testdata iterations still counts once.
157
+ const label = isProvisional ? ' (provisional — run still in progress)' : '';
158
+ return parts.length ? ` · ${parts.join(', ')} [per test case]${label}` : '';
159
+ })()
160
+ : '';
161
+ const CHILD_CAP = 100;
162
+ const total = s.children?.length ?? 0;
163
+ const shown = s.children?.slice(0, CHILD_CAP) ?? [];
164
+ const kids = shown.length
165
+ ? '\n\n' + shown.map((c) => `- ${icon(c.state)} ${c.id}${c.title ? ` — ${c.title}` : ''} (${c.state})`).join('\n') +
166
+ (total > CHILD_CAP ? `\n… and ${total - CHILD_CAP} more (${total} total)` : '') +
167
+ (total > 0 ? '\n\nTo see WHY a specific one passed/failed, call run_status again with the same runId ' +
168
+ 'plus `tcId` set to one of the ids above.' : '')
169
+ : '';
170
+ // First 5 non-blank lines of the raw error string — the previous single-line slice usually
171
+ // showed a "[ERROR] session …" log prefix instead of the actual exception. Enough context for
172
+ // the LLM to name the failure ("NoSuchElement on #foo") without dumping a full stack.
173
+ const errBlock = (raw) => {
174
+ if (!raw)
175
+ return '';
176
+ const lines = raw.split('\n').map((l) => l.trim()).filter((l) => l.length > 0).slice(0, 5);
177
+ return lines.map((l) => ` ${l}`).join('\n');
178
+ };
179
+ const stepIcon = (st) => st === 'passed' ? '✅' : st === 'failed' ? '❌' : st === 'skipped' ? '⏭️' : '•';
180
+ // A failed step the executor reported NO reason for (a plugin that returned false without logging) — say so,
181
+ // instead of listing it bare, so the caller knows to look in the agent log rather than assume there is nothing.
182
+ const NO_REASON = ' (no error text was reported for this step — check the agent log for this run)';
183
+ const steps = s.stepResults?.length
184
+ ? '\n\n' + s.stepResults.map((st) => {
185
+ const desc = st.description?.trim() || '(no description)';
186
+ const err = errBlock(st.error) || (st.status === 'failed' ? NO_REASON : '');
187
+ const warn = st.warning ? `\n ⚠️ ${st.warning}` : '';
188
+ return `${stepIcon(st.status)} step ${st.n}: ${desc} (${st.status})${err ? '\n' + err : ''}${warn}`;
189
+ }).join('\n')
190
+ : '';
191
+ // Failed-step summary: hoist FAILED rows to the top so the LLM sees "which step, why" without
192
+ // scanning the full list. Only fires when the run itself is failed AND at least one step row is
193
+ // failed (a run can be marked FAILED before any step logs, in which case the reportUrl is the
194
+ // only lead). Multi-step failures are all listed — cascading failures often clarify the root.
195
+ const failedSteps = (s.stepResults ?? []).filter((st) => st.status === 'failed');
196
+ const failedSummary = s.state === 'failed' && failedSteps.length
197
+ ? '\n\n**Failed at:**\n' + failedSteps.map((st) => {
198
+ const desc = st.description?.trim() || '(no description)';
199
+ const err = errBlock(st.error) || NO_REASON;
200
+ return `- step ${st.n}: ${desc}${err ? '\n' + err : ''}`;
201
+ }).join('\n')
202
+ : '';
203
+ // Steps that passed but carry a warning (no API response, empty read, unresolved ${param}) — hoisted so a green run
204
+ // is not mistaken for a clean one.
205
+ const warnedSteps = (s.stepResults ?? []).filter((st) => st.warning);
206
+ const warnSummary = warnedSteps.length
207
+ ? `\n\n**⚠️ ${warnedSteps.length} step(s) need attention:**\n` +
208
+ warnedSteps.map((st) => `- step ${st.n}: ${st.warning}`).join('\n')
209
+ : '';
210
+ const stateLabel = s.state === 'passed' && warnedSteps.length ? `passed, but ${warnedSteps.length} step(s) need attention` : s.state;
211
+ return `Run ${s.runId} · **${stateLabel}**${prog}${when}${tally}${link}${failedSummary}${warnSummary}${kids}${steps}`;
212
+ }
213
+ /** Compact per-run bullet list for `run_history`. Matches the icon vocabulary `statusText` uses so
214
+ * the two outputs feel like one surface. Duration only shows when both timestamps are present
215
+ * (running/queued rows will read as `-> (running)` without a `(53s)` suffix). */
216
+ function renderRunHistory(type, entityId, runs) {
217
+ const stateIcon = (st) => st === 'passed' ? '✅'
218
+ : st === 'failed' ? '❌'
219
+ : st === 'running' ? '⏳'
220
+ : st === 'skipped' ? '⏭️'
221
+ : st === 'notExecuted' ? '➖'
222
+ : st === 'stopped' ? '⏹️'
223
+ : st === 'error' ? '⚠️'
224
+ : '•';
225
+ const durationOf = (r) => {
226
+ if (!r.startedAt || !r.endedAt)
227
+ return '';
228
+ const start = Date.parse(r.startedAt);
229
+ const end = Date.parse(r.endedAt);
230
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start)
231
+ return '';
232
+ const secs = Math.round((end - start) / 1000);
233
+ if (secs < 60)
234
+ return ` (${secs}s)`;
235
+ const m = Math.floor(secs / 60);
236
+ const s = secs % 60;
237
+ return ` (${m}m ${s.toString().padStart(2, '0')}s)`;
238
+ };
239
+ const when = (r) => {
240
+ if (r.startedAt && r.endedAt)
241
+ return ` · ${r.startedAt} → ${r.endedAt}${durationOf(r)}`;
242
+ if (r.startedAt)
243
+ return ` · started ${r.startedAt}`;
244
+ return '';
245
+ };
246
+ const tally = (r) => {
247
+ if (type !== 'SUITE' || r.totalTestCases === undefined)
248
+ return '';
249
+ const parts = [`${r.passed ?? 0}✅`];
250
+ parts.push(`${r.failed ?? 0}❌`);
251
+ parts.push(`${r.skipped ?? 0}⏭`);
252
+ if ((r.notExecuted ?? 0) > 0)
253
+ parts.push(`${r.notExecuted}➖`);
254
+ return ` · ${parts.join('/')} of ${r.totalTestCases}`;
255
+ };
256
+ const label = type === 'SUITE' ? 'suite' : 'test case';
257
+ const header = `Recent executions of ${label} ${entityId} (${runs.length} shown):\n`;
258
+ const lines = runs.map((r) => `- ${stateIcon(r.state)} ${r.runId} · ${r.state}${tally(r)}${when(r)}`);
259
+ const hint = type === 'SUITE'
260
+ ? '\n\nCall run_status({ runId: "<id>" }) for the per-test-case rollup, then again with tcId for a child\'s steps.'
261
+ : '\n\nCall run_status({ runId: "<id>" }) for step-level detail on any one.';
262
+ return header + '\n' + lines.join('\n') + hint;
263
+ }
264
+ export function registerRunTools(server, deps) {
265
+ server.registerTool('cloud_runners', {
266
+ title: 'List cloud runners (and which are online)',
267
+ description: 'List the cloud runner VMs registered to the connected project and which are online. Use this ' +
268
+ 'to show the user the cloud options, or to pick a specific runner id for tc_run. Requires a live connection.',
269
+ inputSchema: {},
270
+ annotations: { readOnlyHint: true },
271
+ }, async () => {
272
+ const adapter = deps.getAdapter();
273
+ if (!adapter)
274
+ return err(NOT_CONNECTED);
275
+ if (!adapter.listCloudRunners)
276
+ return err('This product has no cloud runners.');
277
+ try {
278
+ const runners = await adapter.listCloudRunners();
279
+ const online = runners.filter((r) => r.online);
280
+ if (!runners.length)
281
+ return ok('No cloud runners are registered to this project.', { runners: [] });
282
+ const text = `${runners.length} cloud runner${runners.length === 1 ? '' : 's'} · ${online.length} online:\n\n` +
283
+ runners.map(runnerLine).join('\n');
284
+ return ok(text, { runners, online: online.length });
285
+ }
286
+ catch (e) {
287
+ return err(describeError(e));
288
+ }
289
+ });
290
+ server.registerTool('local_agents', {
291
+ title: "List THIS machine's local agent(s)",
292
+ description: "List the LOCAL agent(s) registered from THIS machine — the desktop agent running on the box " +
293
+ "this MCP is on. Use for a LOCAL tc_run / suite_run. There is exactly one desktop agent per " +
294
+ "machine, so this is 0 or 1 row: empty means no agent is registered from this box (start the " +
295
+ "SimplifyQA desktop agent, or use mode:'remote' to dispatch to a teammate's). Use `remote_agents` " +
296
+ "for the other registered machines. Requires a live connection.",
297
+ inputSchema: {},
298
+ annotations: { readOnlyHint: true },
299
+ }, async () => {
300
+ const adapter = deps.getAdapter();
301
+ if (!adapter)
302
+ return err(NOT_CONNECTED);
303
+ if (!adapter.listLocalAgents)
304
+ return err('This product has no local agents to list.');
305
+ try {
306
+ const all = await adapter.listLocalAgents();
307
+ const agents = all.filter((a) => a.isThisMachine);
308
+ if (!agents.length) {
309
+ return ok("No local agent is registered from this machine. Start the SimplifyQA desktop agent on " +
310
+ "this box, or use remote_agents + mode:'remote' to run on a teammate's machine.", { agents: [] });
311
+ }
312
+ const online = agents.filter((a) => a.online);
313
+ const text = `${agents.length} local agent${agents.length === 1 ? '' : 's'} on this machine · ${online.length} online:\n\n` +
314
+ agents.map(localAgentLine).join('\n');
315
+ return ok(text, { agents, online: online.length });
316
+ }
317
+ catch (e) {
318
+ return err(describeError(e));
319
+ }
320
+ });
321
+ server.registerTool('remote_agents', {
322
+ title: 'List REMOTE agents (other registered machines)',
323
+ description: "List the LOCAL agents registered on OTHER machines (teammates' boxes) — the pool a REMOTE " +
324
+ "run dispatches to. Use to pick an `agentId` for a REMOTE tc_run / suite_run. Excludes this " +
325
+ "machine's own agent (that's `local_agents`). REMOTE dispatches to a specific teammate's " +
326
+ "registered desktop agent through the SimplifyQA queue; the picked agent's browsers / adb " +
327
+ "devices are what actually execute. Requires a live connection.",
328
+ inputSchema: {},
329
+ annotations: { readOnlyHint: true },
330
+ }, async () => {
331
+ const adapter = deps.getAdapter();
332
+ if (!adapter)
333
+ return err(NOT_CONNECTED);
334
+ if (!adapter.listLocalAgents)
335
+ return err('This product has no local agents to list.');
336
+ try {
337
+ const all = await adapter.listLocalAgents();
338
+ const agents = all.filter((a) => !a.isThisMachine);
339
+ if (!agents.length)
340
+ return ok('No other machines are registered as agents for this customer.', { agents: [] });
341
+ const online = agents.filter((a) => a.online);
342
+ const text = `${agents.length} remote agent${agents.length === 1 ? '' : 's'} · ${online.length} online:\n\n` +
343
+ agents.map(localAgentLine).join('\n');
344
+ return ok(text, { agents, online: online.length });
345
+ }
346
+ catch (e) {
347
+ return err(describeError(e));
348
+ }
349
+ });
350
+ server.registerTool('mobile_list_devices', {
351
+ title: 'List mobile devices (Android or iOS)',
352
+ description: "List MOBILE devices available to the project — union of the LOCAL roster (real devices + " +
353
+ "emulators/simulators registered via the desktop agent, from `/tm/mobileDevices/search`) " +
354
+ "and the CLOUD roster (whichever farm the project has integrated: LambdaTest / " +
355
+ "BrowserStack / SauceLabs / SimplifyQA Device Farm — the first non-empty one wins, " +
356
+ "matching the UI's single-provider-per-project model). Use before `tc_run` for an ANDROID " +
357
+ "or IOS test case to pick a `deviceId` (and read `deviceType` + `cloudDeviceType` off the " +
358
+ "same row). The `active` flag on local rows is last-known: stale by design (the SQA " +
359
+ "backend writes it when the desktop agent connects/disconnects, and a 7s-stale cron flips " +
360
+ "it back); a device the user just plugged in may still read `active:false` here. Cloud " +
361
+ "rows don't carry `active` — cloud farms are always assumed reachable. Requires a live " +
362
+ "connection.",
363
+ inputSchema: {
364
+ platform: z.enum(['android', 'ios']).describe("Which mobile platform to list devices for."),
365
+ },
366
+ annotations: { readOnlyHint: true },
367
+ }, async ({ platform }) => {
368
+ const adapter = deps.getAdapter();
369
+ if (!adapter)
370
+ return err(NOT_CONNECTED);
371
+ if (!adapter.listMobileDevices)
372
+ return err('This product has no mobile device roster to list.');
373
+ try {
374
+ const devices = await adapter.listMobileDevices(platform.toUpperCase());
375
+ if (!devices.length) {
376
+ return ok(`No ${platform.toUpperCase()} devices are registered to this project. Connect a device ` +
377
+ `via the SimplifyQA desktop agent, then try again.`, { devices: [] });
378
+ }
379
+ // Group by deviceType so the client can present the same tabs the UI does (Real / Emulator
380
+ // / Simulator / Cloud Device). Cloud rows come from the configured farm (LT / BS / SL / SQA
381
+ // Device Farm); the row's `cloudDeviceType` names which one — pass it back on `tc_run`.
382
+ const groups = {};
383
+ for (const d of devices) {
384
+ if (!groups[d.deviceType])
385
+ groups[d.deviceType] = [];
386
+ groups[d.deviceType].push(d);
387
+ }
388
+ const active = devices.filter((d) => d.active).length;
389
+ const sections = Object.entries(groups)
390
+ .map(([type, rows]) => `**${type}** (${rows.length})\n${rows.map(mobileDeviceLine).join('\n')}`)
391
+ .join('\n\n');
392
+ const text = `${devices.length} ${platform.toUpperCase()} device${devices.length === 1 ? '' : 's'} · ${active} active:\n\n` +
393
+ sections;
394
+ return ok(text, { devices, active });
395
+ }
396
+ catch (e) {
397
+ return err(describeError(e));
398
+ }
399
+ });
400
+ server.registerTool('tc_run', {
401
+ title: 'Run a test case (local / remote / cloud; now or scheduled)',
402
+ description: "★ ORDER OF QUESTIONS (STRICT — applies whether you ask one at a time OR bundle several into a " +
403
+ "single message): when → mode → release → sprint → version → environment → browser/device → " +
404
+ "schedule fields → agent. Ask in THIS order, always — never schema-declaration order, never " +
405
+ "refusal-arrival order, never a 'natural UI' order (release first is WRONG). Skip a step only " +
406
+ "when the flag below says it's skippable (sprint when release='', version when TC has one " +
407
+ "version, browser vs. device by TC type). ★\n\n" +
408
+ "Execute ONE existing test case in the connected product. ASK the user for EVERY field the " +
409
+ "Execute dialog asks — never assume — in this DEPENDENCY ORDER: (0) if a previous run in this " +
410
+ "session left a config for the project, the tool refuses first asking `reuseConfig` (true=merge " +
411
+ "remembered mode/release/sprint/env/browser/agent, false=start fresh); (1) `when` " +
412
+ "immediate/schedule, (2) `mode` local/remote/cloud, (3) `releaseId` (from list_releases; pass " +
413
+ "'' to skip — no release), (4) `sprintId` (from list_sprints; skipped entirely when " +
414
+ "releaseId=''), (5) `versionId` (from tc_get's `versions[]`; pass '' for current), (6) " +
415
+ "`environment` (from tc_list_environments), (7) FOR WEB TCs: `browser`; FOR ANDROID/IOS TCs: " +
416
+ "`deviceType` + `deviceId` (via `mobile_list_devices`), (8) for a schedule the start time + " +
417
+ "recurrence (ASK — Once / Every 5 Minutes / Hourly / Daily / Weekly / Monthly, never default) + end date + timezone, (9) THEN offer the eligible agent/runner and pass the pick. IF YOU " +
418
+ "BATCH SEVERAL REFUSED FIELDS INTO ONE AskUserQuestion, ORDER the questions EXACTLY as above " +
419
+ "(when → mode → release → sprint → version → environment → browser/device → schedule fields " +
420
+ "→ agent) — never in schema order or refusal order. `mode` decides WHERE it runs:\n" +
421
+ " • 'local' — THIS machine's desktop agent (its own browser). Call `local_agents` (0 or 1 row per box). " +
422
+ "For when:'immediate' the tool first probes the desktop agent (:4040) and refuses cleanly if it's not up. " +
423
+ "Omit `agentId` to auto-pick this machine's agent (or pass it explicitly — must be this machine's row). " +
424
+ "For when:'schedule' `agentId` is REQUIRED.\n" +
425
+ " • 'remote' — ANOTHER registered machine's desktop agent (a teammate's box). Call `remote_agents` and " +
426
+ "OFFER the list; `agentId` is REQUIRED (no auto-pick across boxes). For when:'immediate' only ONLINE " +
427
+ "remote agents are eligible; for when:'schedule' ANY remote agent works (it runs when it fires).\n" +
428
+ " • 'cloud' — an online cloud runner VM (ONLINE-only whether now or scheduled). Pass `cloudRunnerId` " +
429
+ 'from cloud_runners; for a schedule omit it to let the backend auto-pick a live VM at fire time.\n' +
430
+ 'For cloud, if no runner is online it reports that there are no active cloud runners (nothing is run).\n' +
431
+ 'NOTE: MANUAL test cases cannot be run or scheduled by an agent — the backend rejects them.',
432
+ inputSchema: {
433
+ tcId: z.string().describe('The test case id (or business key) to run.'),
434
+ reuseConfig: z.boolean().optional().describe("Set only when the tool refused asking about REUSE. true = merge the previous run's mode/release/sprint/browser/agent/runner into any unset field; the ENVIRONMENT is never merged — it is asked on every run; false = ignore prior config and walk the full cascade. Omit on a first run."),
435
+ when: z.enum(['immediate', 'schedule']).optional().describe("STEP 1 — when to run. REQUIRED, ASK the user if unstated (the tool refuses when omitted). 'immediate' dispatches now; 'schedule' creates a schedule (needs scheduledFor)."),
436
+ mode: z.enum(['local', 'remote', 'cloud']).optional().describe("STEP 2 — where to run. REQUIRED, ASK the user if unstated."),
437
+ releaseId: z.string().optional().describe("STEP 3 — tag the run with a RELEASE (from list_releases). Optional in the UI; pass '' after asking to skip. The tool refuses when undefined so the user is asked."),
438
+ sprintId: z.string().optional().describe("STEP 4 — tag the run with a SPRINT (from list_sprints, scoped to release). Only asked when releaseId is non-empty; skipped entirely when releaseId=''. Pass '' after asking to skip."),
439
+ versionId: z.string().optional().describe("STEP 5 — override the TC's currently-selected VERSION for this run (an id or name from the TC's `versions[]`). Pass '' to accept the TC's current version."),
440
+ environment: z.string().optional().describe('STEP 6 — environment key (from tc_list_environments). ASK the user on EVERY run; the UI marks this required. Never inherited from a previous run — reuseConfig does not fill it.'),
441
+ browser: z.string().optional().describe("STEP 7 (WEB TCs) — browser, default 'chromium' (bundled + isolated). Others: 'chrome'/'msedge' (installed channel), 'firefox', 'webkit'. NOTE: a schedule accepts only chromium/msedge/firefox/webkit."),
442
+ deviceId: z.string().optional().describe("STEP 7 (ANDROID/IOS TCs) — the target device id. LOCAL: adb serial or emulator name. CLOUD: the marketplace device name. Enumerate with `mobile_list_devices`."),
443
+ deviceName: z.string().optional().describe("STEP 7 (ANDROID/IOS TCs) — the human-readable device name (e.g. 'Oppo-Cph2375-Ab1fe936', 'Pixel 7'). Read off the matching row's `displayName` (preferred) or `name` field from `mobile_list_devices`. Shown in the execution report. Auto-resolved from the device roster if omitted."),
444
+ deviceType: z.enum(['real_device', 'emulator', 'simulator', 'cloud_device', 'cloud_emulator', 'cloud_simulator']).optional().describe("STEP 7 (ANDROID/IOS TCs) — the KIND of device the picked `deviceId` is (read off the matching row from `mobile_list_devices`)."),
445
+ cloudDeviceType: z.enum(['lambda_test', 'browser_stack', 'sauce_labs', 'simplify_qa_device_form']).optional().describe("REQUIRED when `deviceType` is cloud_* — which cloud farm the device came from (read off the matching row's `cloudDeviceType`)."),
446
+ osVersion: z.string().optional().describe("Optional OS version to stamp on the wire platform object for ANDROID/IOS — read off the matching row from `mobile_list_devices`."),
447
+ devices: z.array(z.object({
448
+ deviceId: z.string().describe("Device id (adb serial / emulator name for LOCAL; marketplace device name for CLOUD)."),
449
+ deviceName: z.string().optional().describe("Human-readable device name from mobile_list_devices."),
450
+ deviceType: z.enum(['real_device', 'emulator', 'simulator', 'cloud_device', 'cloud_emulator', 'cloud_simulator']).optional().describe("Kind of device (read off the matching row from mobile_list_devices)."),
451
+ cloudDeviceType: z.enum(['lambda_test', 'browser_stack', 'sauce_labs', 'simplify_qa_device_form']).optional().describe("Cloud farm (required when deviceType is cloud_*)."),
452
+ osVersion: z.string().optional().describe("OS version from mobile_list_devices."),
453
+ })).optional().describe("STEP 7 (ANDROID/IOS TCs) — for PARALLEL execution on MULTIPLE devices. Pass an array of device specs to create ONE execution with one run per device (parallel). When provided, the single-device fields (deviceId, deviceName, deviceType, cloudDeviceType, osVersion) are ignored."),
454
+ agentId: z.string().optional().describe("STEP 9 — for local: a credential_id from `local_agents` (must be THIS machine's row; omit to auto-pick). For remote: REQUIRED — a credential_id from `remote_agents`. when:'immediate' → the picked agent must be ONLINE; when:'schedule' → offline OK and `agentId` is REQUIRED for both local and remote."),
455
+ cloudRunnerId: z.string().optional().describe("STEP 9 (cloud) — a specific ONLINE runner id (from cloud_runners). For when:'schedule' omit to auto-pick a live VM at fire time."),
456
+ headless: z.boolean().optional().describe('Headless. Defaults: cloud=true, local=false. (Immediate runs only.)'),
457
+ scheduledFor: z.string().optional().describe("STEP 8 — REQUIRED for when:'schedule'; ISO datetime of the first/only run (e.g. '2026-08-20T09:00:00Z')."),
458
+ scheduleType: z.enum(SCHEDULE_TYPES).optional().describe(SCHEDULE_TYPE_DESC),
459
+ endDate: z.string().optional().describe(END_DATE_DESC),
460
+ timezone: z.string().optional().describe("IANA timezone for a schedule (e.g. 'Asia/Kolkata'). Default 'UTC'."),
461
+ },
462
+ annotations: { readOnlyHint: false },
463
+ }, async ({ tcId, reuseConfig, when, mode, agentId, environment, browser, headless, cloudRunnerId, deviceId, deviceName: deviceNameArg, deviceType, cloudDeviceType, osVersion, devices, scheduledFor, scheduleType, endDate, timezone, releaseId, sprintId, versionId }) => {
464
+ let deviceName = deviceNameArg;
465
+ const adapter = deps.getAdapter();
466
+ if (!adapter)
467
+ return err(NOT_CONNECTED);
468
+ // STEP 0 — reuse-last-config prompt. Fires only when the caller wired getProjectId AND there
469
+ // is a remembered config for that project AND the caller has not answered yet (undefined).
470
+ // Merging when `reuseConfig: true` fills only fields left unset by this call — the user can
471
+ // still override any single field explicitly. TC-specific fields (versionId, deviceId,
472
+ // schedule cadence) are never remembered — they belong to the run, not the environment.
473
+ const projectId = deps.getProjectId?.() ?? null;
474
+ const remembered = projectId ? lastRun.get(projectId) : undefined;
475
+ if (remembered && reuseConfig === undefined) {
476
+ return err(`Previous run in this project used: ${summarizeLastRun(remembered)}. ` +
477
+ 'ASK the user whether to reuse it — call tc_run again with `reuseConfig: true` to merge ' +
478
+ 'those defaults, or `reuseConfig: false` to start fresh and be asked each field.');
479
+ }
480
+ if (reuseConfig === true && remembered) {
481
+ if (when === undefined)
482
+ when = remembered.when;
483
+ if (mode === undefined)
484
+ mode = remembered.mode;
485
+ if (releaseId === undefined)
486
+ releaseId = remembered.releaseId;
487
+ if (sprintId === undefined)
488
+ sprintId = remembered.sprintId;
489
+ // `environment` is deliberately NOT merged: it selects which test-data set the run uses
490
+ // (general / UAT / …) and must be asked on EVERY run, even when the rest is reused.
491
+ if (browser === undefined)
492
+ browser = remembered.browser;
493
+ if (agentId === undefined)
494
+ agentId = remembered.agentId;
495
+ if (cloudRunnerId === undefined)
496
+ cloudRunnerId = remembered.cloudRunnerId;
497
+ }
498
+ // STEP 1 — when. Decides schedule vs immediate; gates the schedule fields and the agent
499
+ // online-check downstream, so ask before anything else.
500
+ if (!when) {
501
+ return err("Specify WHEN to run: call tc_run again with when: 'immediate' (run now) or when: 'schedule' " +
502
+ '(create a schedule). If the user has not said, ask them first — never assume.');
503
+ }
504
+ // STEP 2 — mode. Decides the agent/runner pool and constrains the browser set for a schedule.
505
+ if (!mode) {
506
+ return err("Specify where to run: call tc_run again with mode: 'local', 'remote', or 'cloud'. " +
507
+ "If the user has not said which, ASK them first — local runs on THIS machine's agent, " +
508
+ "remote runs on a teammate's registered agent, cloud runs on an online cloud runner VM.");
509
+ }
510
+ // STEP 3 — release. Optional in the UI; the tool asks anyway (pass '' to skip).
511
+ if (releaseId === undefined) {
512
+ return err("ASK the user which RELEASE this run belongs to (from list_releases), then call tc_run " +
513
+ "again with releaseId. If the user wants no release, pass releaseId: '' (empty string).");
514
+ }
515
+ // STEP 4 — sprint. Only asked when a release was picked; when release is skipped, sprint is
516
+ // skipped entirely (sprints scope to a release in the UI).
517
+ if (releaseId !== '' && sprintId === undefined) {
518
+ return err("ASK the user which SPRINT this run belongs to (from list_sprints, filtered by releaseId), " +
519
+ "then call tc_run again with sprintId. If the user wants no sprint, pass sprintId: '' (empty string).");
520
+ }
521
+ if (releaseId === '')
522
+ sprintId = '';
523
+ // STEP 5 — version. Needs the TC's tcType and version list, so pre-fetch once here.
524
+ let preview;
525
+ try {
526
+ preview = await adapter.getTestCase(tcId);
527
+ }
528
+ catch (e) {
529
+ return err(describeError(e));
530
+ }
531
+ const tcType = (preview.technologyType ?? 'WEB').toUpperCase();
532
+ const isMobile = tcType === 'ANDROID' || tcType === 'IOS';
533
+ if (versionId === undefined) {
534
+ const vs = preview.versions ?? [];
535
+ if (vs.length > 1) {
536
+ const listing = vs
537
+ .map((v) => ` • \`${v.id}\` — **${v.name}**${v.isCurrent ? ' (current)' : ''}`)
538
+ .join('\n');
539
+ return err(`Test case ${preview.id ?? tcId} has ${vs.length} versions — ASK the user which ` +
540
+ `one to run, then call tc_run again with versionId (pass the version id OR its ` +
541
+ `name — either resolves). Pass versionId: '' to accept the TC's current ` +
542
+ `version.\n\n${listing}`);
543
+ }
544
+ versionId = '';
545
+ }
546
+ // STEP 6 — environment.
547
+ if (!environment) {
548
+ return err('ASK the user which ENVIRONMENT to run against (from tc_list_environments), then call ' +
549
+ 'tc_run again with environment set to the chosen env key. Required — the UI marks this ' +
550
+ 'field with a red asterisk.');
551
+ }
552
+ // STEP 7 (web only) — browser. Mobile branch handled after mode-dependent cloud/agent
553
+ // resolution, since the device roster is filtered by where it will run. API / DB /
554
+ // MAINFRAME / SAP / DESKTOP test cases have no browser/platform pick — asking for one blocks
555
+ // those runs (and pushes callers into a local fallback), so gate strictly on WEB.
556
+ if ((tcType === 'WEB' || tcType === 'WEB_DEPRECATED') && !browser) {
557
+ return err("ASK the user which BROWSER to run in (chromium / chrome / msedge / firefox / webkit), " +
558
+ 'then call tc_run again with browser set. Required — the UI marks this field with a ' +
559
+ 'red asterisk.');
560
+ }
561
+ let resolvedRunner;
562
+ if (mode === 'cloud') {
563
+ if (!adapter.listCloudRunners)
564
+ return err('This product has no cloud runners; run with mode: "local".');
565
+ let runners;
566
+ try {
567
+ runners = await adapter.listCloudRunners();
568
+ }
569
+ catch (e) {
570
+ return err(describeError(e));
571
+ }
572
+ // Cloud is ONLINE-only whether now or scheduled (a schedule pin to an offline VM is rejected).
573
+ const online = runners.filter((r) => r.online);
574
+ if (!online.length) {
575
+ return err('Currently there are no active cloud runners in your project.');
576
+ }
577
+ if (cloudRunnerId) {
578
+ resolvedRunner = online.find((r) => r.id === cloudRunnerId);
579
+ if (!resolvedRunner) {
580
+ return err(`Cloud runner "${cloudRunnerId}" is not online. Online now:\n` + online.map(runnerLine).join('\n'));
581
+ }
582
+ }
583
+ else if (when === 'immediate') {
584
+ resolvedRunner = online[0]; // run-now with no pick → auto-pick the first online runner
585
+ }
586
+ // when:'schedule' with no cloudRunnerId → leave unpinned; the backend auto-picks a live VM at fire time.
587
+ }
588
+ // LOCAL/REMOTE run-NOW to a specific agent must be online (can't dispatch to an offline agent).
589
+ // The SCHEDULE branch below allows an offline agent since it runs when it fires. REMOTE also
590
+ // REQUIRES an explicit agentId at all times — auto-pick across teammate boxes is unsafe.
591
+ if (mode === 'remote' && !agentId) {
592
+ return err("REMOTE runs need an explicit agentId. Call remote_agents to see the teammate machines, " +
593
+ "then pass one as agentId (must be an ONLINE row for when:'immediate').");
594
+ }
595
+ if ((mode === 'local' || mode === 'remote') && when === 'immediate' && agentId) {
596
+ const offlineMsg = await localAgentOfflineForNow(adapter, agentId);
597
+ if (offlineMsg)
598
+ return err(offlineMsg);
599
+ }
600
+ // Mobile refuse cascade — asked AFTER mode/when so the client can filter the device list by
601
+ // where it's going to run. Order mirrors the UI: pick the KIND of device (Real / Emulator /
602
+ // Cloud …), then the specific device off the matching tab. Cloud tabs show even in LOCAL
603
+ // mode (see device-dropdown.component.html:104-111) — LOCAL orchestrator can drive a cloud
604
+ // device via Appium.
605
+ const isMultiDevice = isMobile && devices && devices.length > 1;
606
+ if (isMobile && !isMultiDevice) {
607
+ if (!deviceType) {
608
+ const platform = tcType.toLowerCase();
609
+ const localKinds = platform === 'ios' ? "'real_device', 'simulator'" : "'real_device', 'emulator'";
610
+ return err(`ASK the user which DEVICE TYPE this ${tcType} run should use: ${localKinds}, or ` +
611
+ `'cloud_device' / 'cloud_emulator' / 'cloud_simulator' for a farm device. Then call ` +
612
+ `tc_run again with deviceType set. (Also call mobile_list_devices({ platform: '${platform}' }) ` +
613
+ `to show the available devices grouped by kind — the user picks a device and passes ` +
614
+ `\`id\` as deviceId, its \`deviceType\`, and — for cloud rows — its \`cloudDeviceType\`.)`);
615
+ }
616
+ const isCloudPick = deviceType.startsWith('cloud_');
617
+ if (isCloudPick && !cloudDeviceType) {
618
+ const platform = tcType.toLowerCase();
619
+ return err(`Cloud device picks need \`cloudDeviceType\` — which farm the device came from. Call ` +
620
+ `mobile_list_devices({ platform: '${platform}' }); the matching row's \`cloudDeviceType\` ` +
621
+ `is one of 'lambda_test' / 'browser_stack' / 'sauce_labs' / 'simplify_qa_device_form'. ` +
622
+ `Pass it alongside deviceType and deviceId.`);
623
+ }
624
+ if (!deviceId) {
625
+ const platform = tcType.toLowerCase();
626
+ return err(`ASK the user which DEVICE to run on. Call mobile_list_devices({ platform: '${platform}' }) ` +
627
+ `and offer the rows whose deviceType matches '${deviceType}' — the user picks one; pass its ` +
628
+ `\`id\` as deviceId (and optionally its \`osVersion\`) to tc_run.`);
629
+ }
630
+ // Always resolve the best device display name for the execution report. Even when the
631
+ // model already provided deviceName (from the `name` field), the `displayName` from the
632
+ // device roster is richer (Manufacturer-Model-Serial, e.g. "Oppo-Cph2375-Ab1fe936").
633
+ // Best-effort — a failed lookup keeps whatever the model provided (or falls back to deviceId).
634
+ if (deviceId && adapter.listMobileDevices) {
635
+ try {
636
+ const deviceRoster = await adapter.listMobileDevices(tcType.toUpperCase());
637
+ const match = deviceRoster.find((d) => d.id === deviceId);
638
+ log(`[mcp][tc_run] device resolve: deviceId=${deviceId} match=${match ? `id=${match.id} name=${match.name} displayName=${match.displayName ?? '(none)'}` : '(no match)'} provided=${deviceName ?? '(none)'}`);
639
+ if (match) {
640
+ const resolved = match.displayName || (match.name !== match.id ? match.name : undefined);
641
+ if (resolved)
642
+ deviceName = resolved;
643
+ log(`[mcp][tc_run] device resolve: resolved=${resolved ?? '(none)'} final deviceName=${deviceName ?? '(none)'}`);
644
+ }
645
+ }
646
+ catch (e) {
647
+ log(`[mcp][tc_run] device resolve failed: ${e}`);
648
+ }
649
+ }
650
+ }
651
+ else if (isMultiDevice) {
652
+ // Multi-device parallel: validate each device entry has at least a deviceId
653
+ for (const dev of devices) {
654
+ if (!dev.deviceId) {
655
+ return err('Each entry in `devices` must have a `deviceId`.');
656
+ }
657
+ }
658
+ // Best-effort resolve display names for each device from the roster
659
+ if (adapter.listMobileDevices) {
660
+ try {
661
+ const deviceRoster = await adapter.listMobileDevices(tcType.toUpperCase());
662
+ for (const dev of devices) {
663
+ const match = deviceRoster.find((d) => d.id === dev.deviceId);
664
+ if (match && !dev.deviceName) {
665
+ dev.deviceName = match.displayName || (match.name !== match.id ? match.name : undefined);
666
+ }
667
+ }
668
+ }
669
+ catch (e) {
670
+ log(`[mcp][tc_run] multi-device roster resolve failed: ${e}`);
671
+ }
672
+ }
673
+ }
674
+ if (when === 'schedule') {
675
+ if (!adapter.createSchedule)
676
+ return err('This product does not support scheduling runs.');
677
+ const askSchedule = missingScheduleFields('tc_run', scheduledFor, scheduleType, endDate);
678
+ if (askSchedule || !scheduledFor)
679
+ return err(askSchedule ?? 'scheduledFor is required.');
680
+ // A schedule fires detached from any live session — a LOCAL or REMOTE schedule must pin a
681
+ // specific agent (mode:'remote' already fenced above, so this catches LOCAL).
682
+ if (mode === 'local' && !agentId)
683
+ return err(await localScheduleNeedsAgent(adapter));
684
+ // Cloud: pin the runner's CREDENTIAL only when the user explicitly picked one; otherwise leave
685
+ // it unpinned so the backend auto-picks a live VM at fire time (don't freeze today's online[0]).
686
+ const pinnedRunner = mode === 'cloud' && cloudRunnerId ? resolvedRunner : undefined;
687
+ const schedOpts = {
688
+ mode,
689
+ scheduledFor,
690
+ ...((mode === 'local' || mode === 'remote') && agentId ? { agentId } : {}),
691
+ ...(pinnedRunner?.credentialId ? { cloudRunnerCredentialId: pinnedRunner.credentialId } : {}),
692
+ ...(browser !== undefined ? { browser } : {}),
693
+ ...(environment !== undefined ? { environmentId: environment } : {}),
694
+ ...(releaseId ? { releaseId } : {}),
695
+ ...(sprintId ? { sprintId } : {}),
696
+ ...(scheduleType !== undefined ? { scheduleType } : {}),
697
+ ...(endDate !== undefined ? { endDate } : {}),
698
+ ...(timezone !== undefined ? { timezone } : {}),
699
+ };
700
+ try {
701
+ const sched = await adapter.createSchedule({ tcId }, schedOpts);
702
+ const next = sched.nextRunAt ? ` · first run ${sched.nextRunAt}` : '';
703
+ const where = mode === 'cloud'
704
+ ? (pinnedRunner ? `cloud runner **${pinnedRunner.name}**` : 'cloud (auto-pick a live VM at run time)')
705
+ : `agent \`${agentId}\``;
706
+ if (projectId)
707
+ lastRun.set(projectId, { when, mode, releaseId, sprintId, browser, agentId, cloudRunnerId });
708
+ return ok(`Scheduled ${tcId} (${scheduleType ?? 'once'}, ${mode}) for ${scheduledFor}${next} → ${where}. Schedule id \`${sched.id}\`.`, { schedule: sched, mode, when: 'schedule', ...(pinnedRunner ? { runner: pinnedRunner } : {}) });
709
+ }
710
+ catch (e) {
711
+ return err(describeError(e));
712
+ }
713
+ }
714
+ const opts = {
715
+ mode,
716
+ ...((mode === 'local' || mode === 'remote') && agentId ? { agentId } : {}),
717
+ ...(environment !== undefined ? { environment } : {}),
718
+ ...(browser !== undefined ? { browser } : {}),
719
+ ...(headless !== undefined ? { headless } : {}),
720
+ ...(resolvedRunner ? { cloudRunnerId: resolvedRunner.id } : {}),
721
+ ...(mode === 'cloud' && resolvedRunner?.cloudType ? { cloudType: resolvedRunner.cloudType } : {}),
722
+ // Multi-device parallel: pass devices array and force parallel strategy
723
+ ...(isMultiDevice ? {
724
+ devices: devices.map((d) => ({
725
+ deviceId: d.deviceId,
726
+ ...(d.deviceName ? { deviceName: d.deviceName } : {}),
727
+ ...(d.deviceType ? { deviceType: d.deviceType.toUpperCase() } : {}),
728
+ ...(d.cloudDeviceType ? { cloudDeviceType: d.cloudDeviceType.toUpperCase() } : {}),
729
+ ...(d.osVersion ? { osVersion: d.osVersion } : {}),
730
+ })),
731
+ strategy: 'parallel',
732
+ } : {
733
+ ...(deviceId !== undefined ? { deviceId } : {}),
734
+ ...(deviceName !== undefined ? { deviceName } : {}),
735
+ ...(deviceType !== undefined ? { deviceType: deviceType.toUpperCase() } : {}),
736
+ ...(cloudDeviceType !== undefined ? { cloudDeviceType: cloudDeviceType.toUpperCase() } : {}),
737
+ ...(osVersion !== undefined ? { osVersion } : {}),
738
+ }),
739
+ ...(releaseId ? { releaseId } : {}),
740
+ ...(sprintId ? { sprintId } : {}),
741
+ ...(versionId ? { versionId } : {}),
742
+ };
743
+ try {
744
+ const run = await adapter.startRun({ tcId }, opts);
745
+ const where = mode === 'cloud'
746
+ ? `on cloud runner ${resolvedRunner ? `**${resolvedRunner.name}**` : ''}`
747
+ : mode === 'remote'
748
+ ? `on remote agent \`${agentId}\``
749
+ : `locally${agentId ? ` on agent \`${agentId}\`` : ' on your online agent'}`;
750
+ if (projectId)
751
+ lastRun.set(projectId, { when, mode, releaseId, sprintId, browser, agentId, cloudRunnerId: resolvedRunner?.id ?? cloudRunnerId });
752
+ const deviceCount = isMultiDevice ? ` across ${devices.length} devices (parallel)` : '';
753
+ return ok(`Started ${tcId} ${where}${deviceCount}. Run id \`${run.runId}\` — poll run_status({ runId: "${run.runId}" }) for progress.` +
754
+ (run.reportUrl ? `
755
+ Report: ${run.reportUrl} (use this link as-is; do not build a report URL yourself)` : ''), { run, mode, ...(resolvedRunner ? { runner: resolvedRunner } : {}) });
756
+ }
757
+ catch (e) {
758
+ return err(describeError(e));
759
+ }
760
+ });
761
+ server.registerTool('suite_run', {
762
+ title: 'Run a test suite (local / remote / cloud; now or scheduled)',
763
+ description: "★ ORDER OF QUESTIONS (STRICT — applies whether you ask one at a time OR bundle several into a " +
764
+ "single message): when → mode → strategy (serial/parallel, IMMEDIATE runs) → release → sprint " +
765
+ "→ environment → schedule fields → agent. Ask " +
766
+ "in THIS order, always — never schema-declaration order, never refusal-arrival order, never " +
767
+ "a 'natural UI' order (release first is WRONG). Skip sprint when release=''. Suites do NOT " +
768
+ "ask version / browser / device — each TC in the suite carries its own. ★\n\n" +
769
+ 'Execute an existing test SUITE — all its member test cases, in order — in the connected product. ' +
770
+ "ASK the user for EVERY field the UI's Execute-suite dialog asks — never assume — in this " +
771
+ "DEPENDENCY ORDER: (0) if a previous run in this session left a config for the project, the tool " +
772
+ "refuses first asking `reuseConfig` (true=merge remembered mode/release/sprint/agent (the ENVIRONMENT is always asked), " +
773
+ "false=start fresh); (1) `when` immediate/schedule, (2) `mode` local/remote/cloud, (3) " +
774
+ "`strategy` SERIAL/PARALLEL — the UI's PARALLEL/SERIAL radio, shown for LOCAL, REMOTE and CLOUD " +
775
+ "alike (ask it for an immediate run), (4) `releaseId` (from list_releases; pass '' to skip), " +
776
+ "(5) `sprintId` (from list_sprints; skipped " +
777
+ "entirely when releaseId=''), (6) `environment` (from tc_list_environments), (7) for a schedule " +
778
+ "the start time + recurrence (ASK — Once / Every 5 Minutes / Hourly / Daily / Weekly / Monthly, never default) + end date + timezone, (8) THEN offer the eligible agent/runner. IF YOU " +
779
+ "BATCH SEVERAL REFUSED FIELDS INTO ONE AskUserQuestion, ORDER the questions EXACTLY as above " +
780
+ "(when → mode → strategy → release → sprint → environment → schedule fields → agent) — never in schema " +
781
+ "order or refusal order. UNLIKE " +
782
+ "`tc_run`, a suite does NOT ask for `versionId` or `browser` — each TC in the suite carries its " +
783
+ "own pinned version + execution platform (that's what the suite editor picks per row). " +
784
+ '★ RECOMMEND PARALLEL when the suite has more than one test case that can run independently ' +
785
+ '(they dispatch concurrently — much faster); recommend SERIAL when the cases must run in order or ' +
786
+ 'share state (create → verify → delete, one shared login, a single local browser profile). The UI ' +
787
+ 'preselects SERIAL — say WHY you suggest parallel.\n' +
788
+ '`mode` decides WHERE it runs:\n' +
789
+ " • 'local' — THIS machine's desktop agent. Runs SERIAL or PARALLEL exactly as asked (parallel " +
790
+ "dispatches each TC as its own child execution). Call `local_agents` (0 or 1 row). For " +
791
+ "when:'immediate' the tool probes :4040 and refuses if the desktop agent is down. Omit `agentId` to " +
792
+ "auto-pick this machine's agent; for when:'schedule' `agentId` is REQUIRED.\n" +
793
+ " • 'remote' — ANOTHER registered machine's desktop agent, SERIAL or PARALLEL as asked. " +
794
+ "Call `remote_agents`; " +
795
+ "`agentId` is REQUIRED (no auto-pick). when:'immediate' → ONLINE only; when:'schedule' → offline OK.\n" +
796
+ " • 'cloud' — online cloud runner VM(s) (ONLINE-only whether now or scheduled). Pass `cloudRunnerId` " +
797
+ 'from cloud_runners; for a schedule omit it to auto-pick a live VM at fire time.\n' +
798
+ 'For cloud, if no runner is online it reports that there are no active cloud runners (nothing is run).\n' +
799
+ 'NOTE: manual suites go through the same dispatch — the backend stores them as an execution (no agent picks them up until steps are marked from the UI).',
800
+ inputSchema: {
801
+ suiteId: z.string().describe('The suite id to run (from suite_list / suite_get).'),
802
+ reuseConfig: z.boolean().optional().describe("Set only when the tool refused asking about REUSE. true = merge the previous run's mode/release/sprint/browser/agent/runner into any unset field; the ENVIRONMENT is never merged — it is asked on every run; false = ignore prior config. Omit on a first run."),
803
+ when: z.enum(['immediate', 'schedule']).optional().describe("STEP 1 — when to run. REQUIRED, ASK the user if unstated."),
804
+ mode: z.enum(['local', 'remote', 'cloud']).optional().describe('STEP 2 — where to run. REQUIRED, ASK the user if unstated.'),
805
+ releaseId: z.string().optional().describe("STEP 4 — release from list_releases. ASK the user; pass '' to skip (no release / no sprint asked)."),
806
+ sprintId: z.string().optional().describe("STEP 5 — sprint from list_sprints (scoped to release). Only asked when releaseId is non-empty; skipped when releaseId=''. Pass '' to skip."),
807
+ environment: z.string().optional().describe('STEP 6 — environment key (from tc_list_environments). ASK the user on EVERY suite run; the UI marks this required for a suite. Never inherited from a previous run — reuseConfig does not fill it.'),
808
+ browser: z.string().optional().describe("Optional at the SUITE level — each TC in the suite has its own execution platform (that's the suite-editor pick per row). Provide only to OVERRIDE for every WEB TC. Values: 'chromium' (default), 'chrome'/'msedge', 'firefox', 'webkit'. NOTE: a schedule accepts only chromium/msedge/firefox/webkit."),
809
+ headless: z.boolean().optional().describe('Headless. Defaults: cloud=true, local=false. (Immediate runs only.)'),
810
+ agentId: z.string().optional().describe("STEP 8 — for local: a credential_id from `local_agents` (this machine only; omit to auto-pick). For remote: REQUIRED — a credential_id from `remote_agents`. when:'immediate' → picked agent must be ONLINE; when:'schedule' → offline OK, agentId REQUIRED for both local and remote."),
811
+ cloudRunnerId: z.string().optional().describe("STEP 8 (cloud) — a specific ONLINE runner id (from cloud_runners). For when:'schedule' omit to auto-pick a live VM at fire time."),
812
+ strategy: z.enum(['serial', 'parallel']).optional().describe("STEP 3 (immediate runs) — SERIAL or PARALLEL across the suite's test cases: the same choice the " +
813
+ "UI's Execute-suite dialog shows as a PARALLEL/SERIAL radio, and it applies to LOCAL, REMOTE and " +
814
+ "CLOUD alike. ASK the user. RECOMMEND 'parallel' when the suite has several independent test cases " +
815
+ "(they run concurrently — much faster); recommend 'serial' when order or shared state matters. The " +
816
+ "wire defaults to SERIAL, which is why it must be asked rather than assumed."),
817
+ maxConcurrent: z.number().int().positive().optional().describe('Cloud parallel only — maps to globalConfiguration.MAXIMUM_CONTAINER_COUNT on the wire.'),
818
+ terminateOnFailure: z.boolean().optional().describe('Stop dispatching remaining test cases after the first failure. Maps to globalConfiguration.TERMINATE_ON_FAIL on the wire.'),
819
+ scheduledFor: z.string().optional().describe("STEP 6 — REQUIRED for when:'schedule'; ISO datetime of the first/only run (e.g. '2026-08-20T09:00:00Z')."),
820
+ scheduleType: z.enum(SCHEDULE_TYPES).optional().describe(SCHEDULE_TYPE_DESC),
821
+ endDate: z.string().optional().describe(END_DATE_DESC),
822
+ timezone: z.string().optional().describe("IANA timezone for a schedule (e.g. 'Asia/Kolkata'). Default 'UTC'."),
823
+ },
824
+ annotations: { readOnlyHint: false },
825
+ }, async ({ suiteId, reuseConfig, releaseId, sprintId, mode, agentId, environment, browser, headless, cloudRunnerId, strategy, maxConcurrent, terminateOnFailure, when, scheduledFor, scheduleType, endDate, timezone }) => {
826
+ const adapter = deps.getAdapter();
827
+ if (!adapter)
828
+ return err(NOT_CONNECTED);
829
+ // STEP 0 — reuse-last-config prompt. Same shape as tc_run: fires only when the caller wired
830
+ // getProjectId AND there is a remembered config AND the user hasn't answered yet. Merges the
831
+ // environment-level fields (mode/release/sprint/env/browser/agent/runner) into any left unset.
832
+ const projectId = deps.getProjectId?.() ?? null;
833
+ const remembered = projectId ? lastRun.get(projectId) : undefined;
834
+ if (remembered && reuseConfig === undefined) {
835
+ return err(`Previous run in this project used: ${summarizeLastRun(remembered)}. ` +
836
+ 'ASK the user whether to reuse it — call suite_run again with `reuseConfig: true` to merge ' +
837
+ 'those defaults, or `reuseConfig: false` to start fresh.');
838
+ }
839
+ if (reuseConfig === true && remembered) {
840
+ if (when === undefined)
841
+ when = remembered.when;
842
+ if (mode === undefined)
843
+ mode = remembered.mode;
844
+ if (releaseId === undefined)
845
+ releaseId = remembered.releaseId;
846
+ if (sprintId === undefined)
847
+ sprintId = remembered.sprintId;
848
+ // `environment` is deliberately NOT merged: it selects which test-data set the run uses
849
+ // (general / UAT / …) and must be asked on EVERY run, even when the rest is reused.
850
+ if (browser === undefined)
851
+ browser = remembered.browser;
852
+ if (agentId === undefined)
853
+ agentId = remembered.agentId;
854
+ if (cloudRunnerId === undefined)
855
+ cloudRunnerId = remembered.cloudRunnerId;
856
+ }
857
+ // STEP 1 — when.
858
+ if (!when) {
859
+ return err("Specify WHEN to run: call suite_run again with when: 'immediate' (run now) or when: 'schedule' " +
860
+ '(create a schedule). If the user has not said, ask them first — never assume.');
861
+ }
862
+ // STEP 2 — mode.
863
+ if (!mode) {
864
+ return err("Specify where to run: call suite_run again with mode: 'local', 'remote', or 'cloud'. " +
865
+ "If the user has not said which, ASK them first — local runs on THIS machine's agent, " +
866
+ "remote runs on a teammate's registered agent, cloud runs on online cloud runner VM(s).");
867
+ }
868
+ // STEP 3 — serial vs parallel (the UI's PARALLEL/SERIAL radio). The wire defaults to SERIAL, so an
869
+ // unasked strategy silently hides the faster option on every suite run.
870
+ if (when === 'immediate' && !strategy) {
871
+ return err('ASK the user whether this suite should run SERIAL or PARALLEL — the PARALLEL/SERIAL radio the ' +
872
+ "UI's Execute-suite dialog shows above Release (it applies to local, remote and cloud). RECOMMEND " +
873
+ 'PARALLEL when the suite has more than one independent test case (they dispatch concurrently and ' +
874
+ 'finish much sooner); recommend SERIAL when the cases must run in order or share state. Then call ' +
875
+ "suite_run again with strategy: 'serial' or 'parallel'.");
876
+ }
877
+ // STEP 4 — release. Unified with tc_run: pass '' to skip (matches the UI's optional field).
878
+ if (releaseId === undefined) {
879
+ return err("ASK the user which RELEASE this suite run belongs to (from list_releases), then call " +
880
+ "suite_run again with releaseId. If the user wants no release, pass releaseId: '' (empty string).");
881
+ }
882
+ // STEP 4 — sprint. Only asked when release is non-empty.
883
+ if (releaseId !== '' && sprintId === undefined) {
884
+ return err("ASK the user which SPRINT this suite run belongs to (from list_sprints, filtered by " +
885
+ "releaseId), then call suite_run again with sprintId. If the user wants no sprint, pass " +
886
+ "sprintId: '' (empty string).");
887
+ }
888
+ if (releaseId === '')
889
+ sprintId = '';
890
+ // STEP 5 — environment.
891
+ if (!environment) {
892
+ return err('ASK the user which ENVIRONMENT to run against (from tc_list_environments), then call ' +
893
+ 'suite_run again with environment set to the chosen env key. Required — the UI marks this ' +
894
+ 'field with a red asterisk for a suite.');
895
+ }
896
+ let resolvedRunner;
897
+ if (mode === 'cloud') {
898
+ if (!adapter.listCloudRunners)
899
+ return err('This product has no cloud runners; run with mode: "local".');
900
+ let runners;
901
+ try {
902
+ runners = await adapter.listCloudRunners();
903
+ }
904
+ catch (e) {
905
+ return err(describeError(e));
906
+ }
907
+ // Cloud is ONLINE-only whether now or scheduled (a schedule pin to an offline VM is rejected).
908
+ const online = runners.filter((r) => r.online);
909
+ if (!online.length) {
910
+ return err('Currently there are no active cloud runners in your project.');
911
+ }
912
+ if (cloudRunnerId) {
913
+ resolvedRunner = online.find((r) => r.id === cloudRunnerId);
914
+ if (!resolvedRunner) {
915
+ return err(`Cloud runner "${cloudRunnerId}" is not online. Online now:\n` + online.map(runnerLine).join('\n'));
916
+ }
917
+ }
918
+ else if (when === 'immediate') {
919
+ resolvedRunner = online[0]; // run-now with no pick → auto-pick the first online runner
920
+ }
921
+ // when:'schedule' with no cloudRunnerId → leave unpinned; the backend auto-picks a live VM at fire time.
922
+ }
923
+ // LOCAL/REMOTE run-NOW to a specific agent must be online. SCHEDULE branch below allows offline.
924
+ // REMOTE always requires an explicit agentId (auto-pick across teammate boxes is unsafe).
925
+ if (mode === 'remote' && !agentId) {
926
+ return err("REMOTE runs need an explicit agentId. Call remote_agents to see the teammate machines, " +
927
+ "then pass one as agentId (must be an ONLINE row for when:'immediate').");
928
+ }
929
+ if ((mode === 'local' || mode === 'remote') && when === 'immediate' && agentId) {
930
+ const offlineMsg = await localAgentOfflineForNow(adapter, agentId);
931
+ if (offlineMsg)
932
+ return err(offlineMsg);
933
+ }
934
+ if (when === 'schedule') {
935
+ if (!adapter.createSchedule)
936
+ return err('This product does not support scheduling runs.');
937
+ const askSchedule = missingScheduleFields('suite_run', scheduledFor, scheduleType, endDate);
938
+ if (askSchedule || !scheduledFor) {
939
+ return err((askSchedule ?? 'scheduledFor is required.') +
940
+ " NOTE: strategy/maxConcurrent/terminateOnFailure are immediate-run only — a schedule uses the suite's own settings.");
941
+ }
942
+ // A schedule fires detached from any live session — LOCAL and REMOTE schedules must pin a
943
+ // specific agent. REMOTE was already fenced above; this catches LOCAL.
944
+ if (mode === 'local' && !agentId)
945
+ return err(await localScheduleNeedsAgent(adapter));
946
+ // Cloud: pin the runner's CREDENTIAL only when the user explicitly picked one; otherwise leave
947
+ // it unpinned so the backend auto-picks a live VM at fire time (don't freeze today's online[0]).
948
+ const pinnedRunner = mode === 'cloud' && cloudRunnerId ? resolvedRunner : undefined;
949
+ const schedOpts = {
950
+ mode,
951
+ scheduledFor,
952
+ ...((mode === 'local' || mode === 'remote') && agentId ? { agentId } : {}),
953
+ ...(pinnedRunner?.credentialId ? { cloudRunnerCredentialId: pinnedRunner.credentialId } : {}),
954
+ ...(browser !== undefined ? { browser } : {}),
955
+ ...(environment !== undefined ? { environmentId: environment } : {}),
956
+ ...(releaseId ? { releaseId } : {}),
957
+ ...(sprintId ? { sprintId } : {}),
958
+ ...(scheduleType !== undefined ? { scheduleType } : {}),
959
+ ...(endDate !== undefined ? { endDate } : {}),
960
+ ...(timezone !== undefined ? { timezone } : {}),
961
+ };
962
+ try {
963
+ const sched = await adapter.createSchedule({ suiteId }, schedOpts);
964
+ const next = sched.nextRunAt ? ` · first run ${sched.nextRunAt}` : '';
965
+ const where = mode === 'cloud'
966
+ ? (pinnedRunner ? `cloud runner **${pinnedRunner.name}**` : 'cloud (auto-pick a live VM at run time)')
967
+ : `agent \`${agentId}\``;
968
+ if (projectId)
969
+ lastRun.set(projectId, { when, mode, releaseId, sprintId, browser, agentId, cloudRunnerId });
970
+ return ok(`Scheduled suite ${suiteId} (${scheduleType ?? 'once'}, ${mode}) for ${scheduledFor}${next} → ${where}. Schedule id \`${sched.id}\`.`, { schedule: sched, mode, when: 'schedule', ...(pinnedRunner ? { runner: pinnedRunner } : {}) });
971
+ }
972
+ catch (e) {
973
+ return err(describeError(e));
974
+ }
975
+ }
976
+ const opts = {
977
+ mode,
978
+ ...((mode === 'local' || mode === 'remote') && agentId ? { agentId } : {}),
979
+ ...(environment !== undefined ? { environment } : {}),
980
+ ...(browser !== undefined ? { browser } : {}),
981
+ ...(headless !== undefined ? { headless } : {}),
982
+ ...(resolvedRunner ? { cloudRunnerId: resolvedRunner.id } : {}),
983
+ ...(mode === 'cloud' && resolvedRunner?.cloudType ? { cloudType: resolvedRunner.cloudType } : {}),
984
+ ...(releaseId ? { releaseId } : {}),
985
+ ...(sprintId ? { sprintId } : {}),
986
+ ...(strategy !== undefined ? { strategy } : {}),
987
+ ...(maxConcurrent !== undefined ? { maxConcurrent } : {}),
988
+ ...(terminateOnFailure !== undefined ? { terminateOnFailure } : {}),
989
+ };
990
+ try {
991
+ const run = await adapter.startRun({ suiteId }, opts);
992
+ const where = mode === 'cloud'
993
+ ? `on cloud runner ${resolvedRunner ? `**${resolvedRunner.name}**` : ''}`
994
+ : mode === 'remote'
995
+ ? `on remote agent \`${agentId}\``
996
+ : `locally${agentId ? ` on agent \`${agentId}\`` : ' on your online agent'}`;
997
+ if (projectId)
998
+ lastRun.set(projectId, { when, mode, releaseId, sprintId, browser, agentId, cloudRunnerId: resolvedRunner?.id ?? cloudRunnerId });
999
+ return ok(`Started suite ${suiteId} ${where}. Run id \`${run.runId}\` — poll run_status({ runId: "${run.runId}" }) for progress.` +
1000
+ (run.reportUrl ? `
1001
+ Report: ${run.reportUrl} (use this link as-is; do not build a report URL yourself)` : ''), { run, mode, ...(resolvedRunner ? { runner: resolvedRunner } : {}) });
1002
+ }
1003
+ catch (e) {
1004
+ return err(describeError(e));
1005
+ }
1006
+ });
1007
+ server.registerTool('run_status', {
1008
+ title: 'Get a run status',
1009
+ description: 'Read the status of a run — state (queued/running/passed/failed/skipped/notExecuted/stopped/' +
1010
+ 'error), progress, per-test-case rollup for a SUITE run (capped at 100 shown, ONE ROW PER ' +
1011
+ 'TEST CASE — not per iteration), and a link. Every state SQA reports is its own bucket in the ' +
1012
+ 'per-state tally (skipped and notExecuted are real, distinct outcomes — never counted as ' +
1013
+ 'passed or folded into queued). While the run is still queued/running, the tally is labelled ' +
1014
+ 'provisional. Pass EITHER `runId` (from tc_run / suite_run) or `suiteId` (from suite_list) to ' +
1015
+ 'read that suite\'s LATEST execution.\n\n' +
1016
+ 'The suite rollup only says pass/fail/etc per test case, never WHY — to get one child\'s own ' +
1017
+ 'step-level detail (which step failed, the error), call again with the SAME `runId`/`suiteId` ' +
1018
+ 'plus `tcId` set to one of the ids shown in the rollup. Requires a live connection.',
1019
+ inputSchema: {
1020
+ runId: z.string().optional().describe('The run id returned by tc_run or suite_run.'),
1021
+ suiteId: z.string().optional().describe('A suite id (from suite_list) — resolves to the suite\'s latest execution.'),
1022
+ tcId: z.string().optional().describe('Drill into ONE child test case\'s step-level results within a SUITE run — its id from the ' +
1023
+ 'rollup shown by a prior run_status call (without `tcId`). Ignored / refused for a single-TC run.'),
1024
+ },
1025
+ annotations: { readOnlyHint: true },
1026
+ }, async ({ runId, suiteId, tcId }) => {
1027
+ const adapter = deps.getAdapter();
1028
+ if (!adapter)
1029
+ return err(NOT_CONNECTED);
1030
+ if ((runId && suiteId) || (!runId && !suiteId)) {
1031
+ return err('Pass exactly one of `runId` or `suiteId`.');
1032
+ }
1033
+ try {
1034
+ let effectiveRunId = runId;
1035
+ if (suiteId) {
1036
+ if (!adapter.getLatestSuiteRun)
1037
+ return err('This product does not support latest-suite-run lookup — pass `runId` instead.');
1038
+ const latest = await adapter.getLatestSuiteRun(suiteId);
1039
+ if (!latest)
1040
+ return ok(`Suite ${suiteId} has no executions yet.`);
1041
+ effectiveRunId = latest;
1042
+ }
1043
+ const status = await adapter.getRun(effectiveRunId);
1044
+ if (tcId === undefined) {
1045
+ return ok(statusText(status), { run: status });
1046
+ }
1047
+ if (!status.children) {
1048
+ return err(`Run ${effectiveRunId} is not a suite run (or has no per-test-case rollup yet) — \`tcId\` doesn't apply here.`);
1049
+ }
1050
+ if (!adapter.getSuiteChildRun) {
1051
+ return err('This product does not support drilling into one test case\'s result within a suite run.');
1052
+ }
1053
+ const child = status.children.find((c) => c.id === tcId || c.testcaseId === tcId);
1054
+ if (!child) {
1055
+ const options = status.children.map((c) => `\`${c.id}\`${c.title ? ` — ${c.title}` : ''} (${c.state})`).join('\n');
1056
+ return err(`"${tcId}" is not one of the test cases in this suite run. Available:\n${options}`);
1057
+ }
1058
+ if (!child.testcaseId) {
1059
+ return err(`Test case ${child.id} in this suite run has no resolvable testcaseId — cannot fetch its step-level detail.`);
1060
+ }
1061
+ const childStatus = await adapter.getSuiteChildRun(effectiveRunId, {
1062
+ testcaseId: child.testcaseId,
1063
+ ...(child.versionId ? { versionId: child.versionId } : {}),
1064
+ ...(child.stepId ? { stepId: child.stepId } : {}),
1065
+ });
1066
+ return ok(`${child.id}${child.title ? ` — ${child.title}` : ''} within suite run ${effectiveRunId}:\n\n${statusText(childStatus)}`, { run: childStatus });
1067
+ }
1068
+ catch (e) {
1069
+ return err(describeError(e));
1070
+ }
1071
+ });
1072
+ server.registerTool('run_history', {
1073
+ title: 'Recent execution history for a suite or test case',
1074
+ description: 'Return the top-N most recent STANDALONE executions of a suite or test case (newest first), ' +
1075
+ 'as a scoreboard — runId, state, timing, reportUrl, plus a per-test-case tally for SUITE ' +
1076
+ 'runs (passed/failed/skipped of total). No step-level detail; use `run_status({ runId })` ' +
1077
+ 'on any row to drill in. Pass EXACTLY one of `suiteId` or `tcId`. `limit` defaults to 5, ' +
1078
+ 'capped at 20. Suite-child TC rows are excluded from a `tcId` query, so a test case that ' +
1079
+ 'only runs inside suites returns empty. Requires a live connection.',
1080
+ inputSchema: {
1081
+ suiteId: z.string().optional().describe('A suite id (from suite_list) — returns the suite\'s recent executions.'),
1082
+ tcId: z.string().optional().describe('A test case id — returns the TC\'s recent STANDALONE executions.'),
1083
+ limit: z.number().int().min(1).max(20).optional().describe('How many recent runs to return (default 5, max 20).'),
1084
+ },
1085
+ annotations: { readOnlyHint: true },
1086
+ }, async ({ suiteId, tcId, limit }) => {
1087
+ const adapter = deps.getAdapter();
1088
+ if (!adapter)
1089
+ return err(NOT_CONNECTED);
1090
+ if ((suiteId && tcId) || (!suiteId && !tcId)) {
1091
+ return err('Pass exactly one of `suiteId` or `tcId`.');
1092
+ }
1093
+ if (!adapter.listRecentRuns) {
1094
+ return err('This product does not support run-history lookup.');
1095
+ }
1096
+ const type = suiteId ? 'SUITE' : 'TC';
1097
+ const entityId = (suiteId ?? tcId);
1098
+ const n = Math.min(Math.max(limit ?? 5, 1), 20);
1099
+ try {
1100
+ const runs = await adapter.listRecentRuns(type, entityId, n);
1101
+ if (!runs.length) {
1102
+ const label = type === 'SUITE' ? 'suite' : 'test case';
1103
+ return ok(`No executions found for ${label} ${entityId}.`, { runs: [] });
1104
+ }
1105
+ const text = renderRunHistory(type, entityId, runs);
1106
+ return ok(text, { runs });
1107
+ }
1108
+ catch (e) {
1109
+ return err(describeError(e));
1110
+ }
1111
+ });
1112
+ server.registerTool('run_stop', {
1113
+ title: 'Stop a run',
1114
+ description: 'Signal a running execution to stop, and poll briefly for the terminal state so the reply ' +
1115
+ "reflects reality (not a fire-and-forget). Pass EXACTLY one of: `runId` (from tc_run / " +
1116
+ "suite_run), `suiteId` (stops the suite's LATEST execution), or `tcId` (stops the TC's " +
1117
+ 'LATEST standalone execution — suite-child rows are excluded). Requires a live connection.',
1118
+ inputSchema: {
1119
+ runId: z.string().optional().describe('The run id (from tc_run / suite_run).'),
1120
+ suiteId: z.string().optional().describe("A suite id (from suite_list) — stops the suite's latest execution."),
1121
+ tcId: z.string().optional().describe("A test case id — stops the TC's latest STANDALONE execution."),
1122
+ },
1123
+ annotations: { readOnlyHint: false },
1124
+ }, async ({ runId, suiteId, tcId }) => {
1125
+ const adapter = deps.getAdapter();
1126
+ if (!adapter)
1127
+ return err(NOT_CONNECTED);
1128
+ if ([runId, suiteId, tcId].filter((v) => v !== undefined && v !== '').length !== 1) {
1129
+ return err('Pass exactly one of `runId`, `suiteId`, or `tcId`.');
1130
+ }
1131
+ try {
1132
+ let effectiveRunId = runId;
1133
+ if (suiteId) {
1134
+ if (!adapter.getLatestSuiteRun)
1135
+ return err('This product does not support latest-suite-run lookup — pass `runId` instead.');
1136
+ const latest = await adapter.getLatestSuiteRun(suiteId);
1137
+ if (!latest)
1138
+ return err(`Suite ${suiteId} has no executions to stop.`);
1139
+ effectiveRunId = latest;
1140
+ }
1141
+ else if (tcId) {
1142
+ if (!adapter.getLatestTestcaseRun)
1143
+ return err('This product does not support latest-testcase-run lookup — pass `runId` instead.');
1144
+ const latest = await adapter.getLatestTestcaseRun(tcId);
1145
+ if (!latest)
1146
+ return err(`Test case ${tcId} has no executions to stop.`);
1147
+ effectiveRunId = latest;
1148
+ }
1149
+ await adapter.stopRun(effectiveRunId);
1150
+ // Confirm — the backend accepts the stop async, so getRun is the source of truth. Poll a few
1151
+ // times so the reply reports the actual state instead of lying "requested" and moving on.
1152
+ // ponytail: fixed 3×1.5s poll, upgrade to configurable/backoff if teams hit slow stop paths.
1153
+ const TERMINAL = new Set(['stopped', 'passed', 'failed', 'error', 'skipped', 'notExecuted']);
1154
+ for (let i = 0; i < 3; i++) {
1155
+ await new Promise((r) => setTimeout(r, 1500));
1156
+ const s = await adapter.getRun(effectiveRunId);
1157
+ if (TERMINAL.has(s.state))
1158
+ return ok(`Run ${effectiveRunId} is now **${s.state}**.`, { run: s });
1159
+ }
1160
+ return ok(`Stop request sent for run ${effectiveRunId}. State is still queued/running — poll ` +
1161
+ `run_status({ runId: "${effectiveRunId}" }) to confirm.`);
1162
+ }
1163
+ catch (e) {
1164
+ return err(describeError(e));
1165
+ }
1166
+ });
1167
+ server.registerTool('schedule_list', {
1168
+ title: 'List schedules',
1169
+ description: 'List the scheduled runs in the connected project — each with WHAT it runs (test case / suite), ' +
1170
+ 'its cadence, next run time, status (scheduled / running / paused / cancelled), where it runs + the ' +
1171
+ 'pinned agent, and its browser. Use this to find a schedule to edit, pause/resume, cancel, or delete. ' +
1172
+ 'Requires a live connection.',
1173
+ inputSchema: {},
1174
+ annotations: { readOnlyHint: true },
1175
+ }, async () => {
1176
+ const adapter = deps.getAdapter();
1177
+ if (!adapter)
1178
+ return err(NOT_CONNECTED);
1179
+ if (!adapter.listSchedules)
1180
+ return err('This product does not support listing schedules.');
1181
+ try {
1182
+ const schedules = await adapter.listSchedules();
1183
+ if (!schedules.length)
1184
+ return ok('No schedules in this project.', { schedules: [] });
1185
+ const text = `${schedules.length} schedule${schedules.length === 1 ? '' : 's'}:\n\n` +
1186
+ schedules.map(scheduleLine).join('\n');
1187
+ return ok(text, { schedules });
1188
+ }
1189
+ catch (e) {
1190
+ return err(describeError(e));
1191
+ }
1192
+ });
1193
+ server.registerTool('schedule_update', {
1194
+ title: 'Edit a schedule',
1195
+ description: "Change a schedule's time / recurrence / end date / timezone / browser / environment, or RE-PIN its " +
1196
+ 'agent. Pass `scheduleId` (from schedule_list) and ONLY the fields to change. To re-pin: ' +
1197
+ "mode:'local' + `agentId` (from local_agents), or mode:'cloud' + a runner's `cloudRunnerCredentialId` " +
1198
+ '(the `credentialId` from cloud_runners). Requires a live connection.',
1199
+ inputSchema: {
1200
+ scheduleId: z.string().describe('The schedule id (from schedule_list).'),
1201
+ scheduledFor: z.string().optional().describe('New start / next-run ISO datetime.'),
1202
+ scheduleType: z.enum(SCHEDULE_TYPES).optional().describe('New recurrence (same choices as the UI: once, every_5_minutes, hourly, daily, weekly, monthly). Anything but once needs an endDate.'),
1203
+ endDate: z.string().optional().describe('New ISO end date (for recurring schedules).'),
1204
+ timezone: z.string().optional().describe("New IANA timezone (e.g. 'Asia/Kolkata')."),
1205
+ browser: z.enum(['chromium', 'msedge', 'firefox', 'webkit']).optional().describe('New browser (schedules accept chromium/msedge/firefox/webkit, not chrome).'),
1206
+ environment: z.string().optional().describe('New environment id (Mongo id).'),
1207
+ mode: z.enum(['local', 'cloud']).optional().describe('Re-pin target: pair with agentId (local) or cloudRunnerCredentialId (cloud).'),
1208
+ agentId: z.string().optional().describe('Local re-pin: an agent credential_id from local_agents.'),
1209
+ cloudRunnerCredentialId: z.string().optional().describe("Cloud re-pin: a runner's credentialId from cloud_runners."),
1210
+ },
1211
+ annotations: { readOnlyHint: false },
1212
+ }, async ({ scheduleId, scheduledFor, scheduleType, endDate, timezone, browser, environment, mode, agentId, cloudRunnerCredentialId }) => {
1213
+ const adapter = deps.getAdapter();
1214
+ if (!adapter)
1215
+ return err(NOT_CONNECTED);
1216
+ if (!adapter.updateSchedule)
1217
+ return err('This product does not support editing schedules.');
1218
+ const changes = {
1219
+ ...(scheduledFor !== undefined ? { scheduledFor } : {}),
1220
+ ...(scheduleType !== undefined ? { scheduleType } : {}),
1221
+ ...(endDate !== undefined ? { endDate } : {}),
1222
+ ...(timezone !== undefined ? { timezone } : {}),
1223
+ ...(browser !== undefined ? { browser } : {}),
1224
+ ...(environment !== undefined ? { environmentId: environment } : {}),
1225
+ ...(mode !== undefined ? { mode } : {}),
1226
+ ...(agentId !== undefined ? { agentId } : {}),
1227
+ ...(cloudRunnerCredentialId !== undefined ? { cloudRunnerCredentialId } : {}),
1228
+ };
1229
+ if (Object.keys(changes).length === 0) {
1230
+ return err('Nothing to change — pass at least one field to edit (e.g. scheduledFor, scheduleType, browser, or a re-pin via mode + agentId/cloudRunnerCredentialId).');
1231
+ }
1232
+ try {
1233
+ const ref = await adapter.updateSchedule(scheduleId, changes);
1234
+ return ok(`Updated schedule \`${ref.id}\`${ref.nextRunAt ? ` · next run ${ref.nextRunAt}` : ''}.`, { schedule: ref });
1235
+ }
1236
+ catch (e) {
1237
+ return err(describeError(e));
1238
+ }
1239
+ });
1240
+ server.registerTool('schedule_control', {
1241
+ title: 'Pause / resume / cancel a schedule',
1242
+ description: "Change a schedule's state: `pause` (stop it firing but keep it — reversible with `resume`), " +
1243
+ '`resume` (re-enable a paused schedule), or `cancel` (stop its pending / live run). To remove a ' +
1244
+ 'schedule entirely, use schedule_delete instead. Requires a live connection.',
1245
+ inputSchema: {
1246
+ scheduleId: z.string().describe('The schedule id (from schedule_list).'),
1247
+ action: z.enum(['pause', 'resume', 'cancel']).describe('pause / resume / cancel.'),
1248
+ },
1249
+ annotations: { readOnlyHint: false },
1250
+ }, async ({ scheduleId, action }) => {
1251
+ const adapter = deps.getAdapter();
1252
+ if (!adapter)
1253
+ return err(NOT_CONNECTED);
1254
+ if (!adapter.controlSchedule)
1255
+ return err('This product does not support pausing / resuming / cancelling schedules.');
1256
+ try {
1257
+ const ref = await adapter.controlSchedule(scheduleId, action);
1258
+ const verb = action === 'pause' ? 'Paused' : action === 'resume' ? 'Resumed' : 'Cancelled';
1259
+ return ok(`${verb} schedule \`${ref.id}\`${ref.status ? ` · status ${ref.status}` : ''}.`, { schedule: ref });
1260
+ }
1261
+ catch (e) {
1262
+ return err(describeError(e));
1263
+ }
1264
+ });
1265
+ server.registerTool('schedule_delete', {
1266
+ title: 'Delete a schedule',
1267
+ description: 'Permanently DELETE a schedule (and tear down any run it currently owns). This cannot be undone — ' +
1268
+ 'to only stop it temporarily use schedule_control (pause / cancel). CONFIRM with the user before ' +
1269
+ 'deleting. Requires a live connection.',
1270
+ inputSchema: {
1271
+ scheduleId: z.string().describe('The schedule id (from schedule_list).'),
1272
+ confirm: z.boolean().optional().describe('SimplifyQA: the first call only previews; pass true on the SECOND call, after the user explicitly said to delete.'),
1273
+ },
1274
+ annotations: { readOnlyHint: false, destructiveHint: true },
1275
+ }, async ({ scheduleId, confirm }) => {
1276
+ const adapter = deps.getAdapter();
1277
+ if (!adapter)
1278
+ return err(NOT_CONNECTED);
1279
+ if (!adapter.deleteSchedule)
1280
+ return err('This product does not support deleting schedules.');
1281
+ try {
1282
+ if (adapter.scheduleDeletePreview && confirm !== true) {
1283
+ const p = await adapter.scheduleDeletePreview(scheduleId);
1284
+ return ok(`About to delete schedule ${p.code ?? p.id}${p.name ? ` (${p.name})` : ''}, which runs ${p.target}. This cannot be undone. ` +
1285
+ 'Show this to the user; call again with confirm:true only after they explicitly say to delete.', { preview: p });
1286
+ }
1287
+ await adapter.deleteSchedule(scheduleId);
1288
+ return ok(`Deleted schedule \`${scheduleId}\`.`);
1289
+ }
1290
+ catch (e) {
1291
+ return err(describeError(e));
1292
+ }
1293
+ });
1294
+ }
1295
+ //# sourceMappingURL=run.tools.js.map