dp-worker 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (933) hide show
  1. package/builtin-skills/sourcepool.md +228 -0
  2. package/builtin-skills/x.md +263 -0
  3. package/config.example.json +37 -0
  4. package/dist/agent/agent-types.d.ts +44 -0
  5. package/dist/agent/agent-types.js +23 -0
  6. package/dist/agent/agent-types.js.map +1 -0
  7. package/dist/agent/agent.d.ts +162 -0
  8. package/dist/agent/agent.js +670 -0
  9. package/dist/agent/agent.js.map +1 -0
  10. package/dist/agent/browser-lock.d.ts +36 -0
  11. package/dist/agent/browser-lock.js +46 -0
  12. package/dist/agent/browser-lock.js.map +1 -0
  13. package/dist/agent/chat-engine.d.ts +87 -0
  14. package/dist/agent/chat-engine.js +588 -0
  15. package/dist/agent/chat-engine.js.map +1 -0
  16. package/dist/agent/chrome-watchdog.d.ts +74 -0
  17. package/dist/agent/chrome-watchdog.js +136 -0
  18. package/dist/agent/chrome-watchdog.js.map +1 -0
  19. package/dist/agent/context.d.ts +148 -0
  20. package/dist/agent/context.js +521 -0
  21. package/dist/agent/context.js.map +1 -0
  22. package/dist/agent/duration.d.ts +2 -0
  23. package/dist/agent/duration.js +15 -0
  24. package/dist/agent/duration.js.map +1 -0
  25. package/dist/agent/executors/attachment-executor.d.ts +19 -0
  26. package/dist/agent/executors/attachment-executor.js +136 -0
  27. package/dist/agent/executors/attachment-executor.js.map +1 -0
  28. package/dist/agent/executors/memory-executor.d.ts +2 -0
  29. package/dist/agent/executors/memory-executor.js +13 -0
  30. package/dist/agent/executors/memory-executor.js.map +1 -0
  31. package/dist/agent/executors/org-executor.d.ts +8 -0
  32. package/dist/agent/executors/org-executor.js +47 -0
  33. package/dist/agent/executors/org-executor.js.map +1 -0
  34. package/dist/agent/executors/scheduler-executor.d.ts +21 -0
  35. package/dist/agent/executors/scheduler-executor.js +75 -0
  36. package/dist/agent/executors/scheduler-executor.js.map +1 -0
  37. package/dist/agent/executors/skill-executor.d.ts +10 -0
  38. package/dist/agent/executors/skill-executor.js +178 -0
  39. package/dist/agent/executors/skill-executor.js.map +1 -0
  40. package/dist/agent/executors/store-executor.d.ts +2 -0
  41. package/dist/agent/executors/store-executor.js +42 -0
  42. package/dist/agent/executors/store-executor.js.map +1 -0
  43. package/dist/agent/executors/web-fetch-executor.d.ts +17 -0
  44. package/dist/agent/executors/web-fetch-executor.js +164 -0
  45. package/dist/agent/executors/web-fetch-executor.js.map +1 -0
  46. package/dist/agent/frontend-multiplexer.d.ts +38 -0
  47. package/dist/agent/frontend-multiplexer.js +67 -0
  48. package/dist/agent/frontend-multiplexer.js.map +1 -0
  49. package/dist/agent/image-generator.d.ts +35 -0
  50. package/dist/agent/image-generator.js +266 -0
  51. package/dist/agent/image-generator.js.map +1 -0
  52. package/dist/agent/image-postprocess.d.ts +25 -0
  53. package/dist/agent/image-postprocess.js +82 -0
  54. package/dist/agent/image-postprocess.js.map +1 -0
  55. package/dist/agent/memory.d.ts +55 -0
  56. package/dist/agent/memory.js +401 -0
  57. package/dist/agent/memory.js.map +1 -0
  58. package/dist/agent/org-manager.d.ts +70 -0
  59. package/dist/agent/org-manager.js +280 -0
  60. package/dist/agent/org-manager.js.map +1 -0
  61. package/dist/agent/scheduler.d.ts +51 -0
  62. package/dist/agent/scheduler.js +302 -0
  63. package/dist/agent/scheduler.js.map +1 -0
  64. package/dist/agent/skill-generator.d.ts +116 -0
  65. package/dist/agent/skill-generator.js +704 -0
  66. package/dist/agent/skill-generator.js.map +1 -0
  67. package/dist/agent/storage-policy.d.ts +55 -0
  68. package/dist/agent/storage-policy.js +406 -0
  69. package/dist/agent/storage-policy.js.map +1 -0
  70. package/dist/agent/store.d.ts +58 -0
  71. package/dist/agent/store.js +309 -0
  72. package/dist/agent/store.js.map +1 -0
  73. package/dist/agent/task-runner.d.ts +34 -0
  74. package/dist/agent/task-runner.js +705 -0
  75. package/dist/agent/task-runner.js.map +1 -0
  76. package/dist/agent/tool-loop-detection.d.ts +60 -0
  77. package/dist/agent/tool-loop-detection.js +233 -0
  78. package/dist/agent/tool-loop-detection.js.map +1 -0
  79. package/dist/agent/tool-runner.d.ts +37 -0
  80. package/dist/agent/tool-runner.js +72 -0
  81. package/dist/agent/tool-runner.js.map +1 -0
  82. package/dist/browser/actions.d.ts +217 -0
  83. package/dist/browser/actions.js +3097 -0
  84. package/dist/browser/actions.js.map +1 -0
  85. package/dist/browser/builtin-page-cleanups.d.ts +19 -0
  86. package/dist/browser/builtin-page-cleanups.js +111 -0
  87. package/dist/browser/builtin-page-cleanups.js.map +1 -0
  88. package/dist/browser/chrome-process.d.ts +55 -0
  89. package/dist/browser/chrome-process.js +288 -0
  90. package/dist/browser/chrome-process.js.map +1 -0
  91. package/dist/browser/dispatch.d.ts +32 -0
  92. package/dist/browser/dispatch.js +582 -0
  93. package/dist/browser/dispatch.js.map +1 -0
  94. package/dist/browser/dom-helpers.d.ts +68 -0
  95. package/dist/browser/dom-helpers.js +477 -0
  96. package/dist/browser/dom-helpers.js.map +1 -0
  97. package/dist/browser/expect.d.ts +66 -0
  98. package/dist/browser/expect.js +314 -0
  99. package/dist/browser/expect.js.map +1 -0
  100. package/dist/browser/humanize.d.ts +56 -0
  101. package/dist/browser/humanize.js +216 -0
  102. package/dist/browser/humanize.js.map +1 -0
  103. package/dist/browser/locator-resolver.d.ts +88 -0
  104. package/dist/browser/locator-resolver.js +302 -0
  105. package/dist/browser/locator-resolver.js.map +1 -0
  106. package/dist/browser/manager.d.ts +95 -0
  107. package/dist/browser/manager.js +389 -0
  108. package/dist/browser/manager.js.map +1 -0
  109. package/dist/browser/script-runner.d.ts +117 -0
  110. package/dist/browser/script-runner.js +305 -0
  111. package/dist/browser/script-runner.js.map +1 -0
  112. package/dist/browser/selectors.d.ts +41 -0
  113. package/dist/browser/selectors.js +165 -0
  114. package/dist/browser/selectors.js.map +1 -0
  115. package/dist/browser/snapshot.d.ts +129 -0
  116. package/dist/browser/snapshot.js +504 -0
  117. package/dist/browser/snapshot.js.map +1 -0
  118. package/dist/browser/workspace-lock.d.ts +37 -0
  119. package/dist/browser/workspace-lock.js +286 -0
  120. package/dist/browser/workspace-lock.js.map +1 -0
  121. package/dist/center/center-client.d.ts +124 -0
  122. package/dist/center/center-client.js +316 -0
  123. package/dist/center/center-client.js.map +1 -0
  124. package/dist/center/center-frontend.d.ts +92 -0
  125. package/dist/center/center-frontend.js +459 -0
  126. package/dist/center/center-frontend.js.map +1 -0
  127. package/dist/center/session-sync.d.ts +85 -0
  128. package/dist/center/session-sync.js +345 -0
  129. package/dist/center/session-sync.js.map +1 -0
  130. package/dist/config/center-config.d.ts +60 -0
  131. package/dist/config/center-config.js +92 -0
  132. package/dist/config/center-config.js.map +1 -0
  133. package/dist/config/types.d.ts +93 -0
  134. package/dist/config/types.js +136 -0
  135. package/dist/config/types.js.map +1 -0
  136. package/dist/index.d.ts +2 -0
  137. package/dist/index.js +395 -0
  138. package/dist/index.js.map +1 -0
  139. package/dist/llm/client.d.ts +24 -0
  140. package/dist/llm/client.js +696 -0
  141. package/dist/llm/client.js.map +1 -0
  142. package/dist/llm/message-optimizer.d.ts +50 -0
  143. package/dist/llm/message-optimizer.js +337 -0
  144. package/dist/llm/message-optimizer.js.map +1 -0
  145. package/dist/llm/tools.d.ts +37 -0
  146. package/dist/llm/tools.js +895 -0
  147. package/dist/llm/tools.js.map +1 -0
  148. package/dist/llm/types.d.ts +96 -0
  149. package/dist/llm/types.js +2 -0
  150. package/dist/llm/types.js.map +1 -0
  151. package/dist/logging/logger.d.ts +17 -0
  152. package/dist/logging/logger.js +54 -0
  153. package/dist/logging/logger.js.map +1 -0
  154. package/dist/scripts/migrate-history-to-store.d.ts +2 -0
  155. package/dist/scripts/migrate-history-to-store.js +250 -0
  156. package/dist/scripts/migrate-history-to-store.js.map +1 -0
  157. package/dist/telegram/bot.d.ts +28 -0
  158. package/dist/telegram/bot.js +546 -0
  159. package/dist/telegram/bot.js.map +1 -0
  160. package/dist/tui/tui.d.ts +12 -0
  161. package/dist/tui/tui.js +177 -0
  162. package/dist/tui/tui.js.map +1 -0
  163. package/dist/utils/safe-slice.d.ts +25 -0
  164. package/dist/utils/safe-slice.js +43 -0
  165. package/dist/utils/safe-slice.js.map +1 -0
  166. package/node_modules/dp-shared/dist/admin-broadcast.d.ts +26 -0
  167. package/node_modules/dp-shared/dist/admin-broadcast.d.ts.map +1 -0
  168. package/node_modules/dp-shared/dist/admin-broadcast.js +7 -0
  169. package/node_modules/dp-shared/dist/admin-broadcast.js.map +1 -0
  170. package/node_modules/dp-shared/dist/audit-contracts.d.ts +41 -0
  171. package/node_modules/dp-shared/dist/audit-contracts.d.ts.map +1 -0
  172. package/node_modules/dp-shared/dist/audit-contracts.js +30 -0
  173. package/node_modules/dp-shared/dist/audit-contracts.js.map +1 -0
  174. package/node_modules/dp-shared/dist/configs-contracts.d.ts +187 -0
  175. package/node_modules/dp-shared/dist/configs-contracts.d.ts.map +1 -0
  176. package/node_modules/dp-shared/dist/configs-contracts.js +165 -0
  177. package/node_modules/dp-shared/dist/configs-contracts.js.map +1 -0
  178. package/node_modules/dp-shared/dist/db-rows.d.ts +293 -0
  179. package/node_modules/dp-shared/dist/db-rows.d.ts.map +1 -0
  180. package/node_modules/dp-shared/dist/db-rows.js +222 -0
  181. package/node_modules/dp-shared/dist/db-rows.js.map +1 -0
  182. package/node_modules/dp-shared/dist/deploy-contracts.d.ts +34 -0
  183. package/node_modules/dp-shared/dist/deploy-contracts.d.ts.map +1 -0
  184. package/node_modules/dp-shared/dist/deploy-contracts.js +32 -0
  185. package/node_modules/dp-shared/dist/deploy-contracts.js.map +1 -0
  186. package/node_modules/dp-shared/dist/domain.d.ts +144 -0
  187. package/node_modules/dp-shared/dist/domain.d.ts.map +1 -0
  188. package/node_modules/dp-shared/dist/domain.js +81 -0
  189. package/node_modules/dp-shared/dist/domain.js.map +1 -0
  190. package/node_modules/dp-shared/dist/identities.d.ts +35 -0
  191. package/node_modules/dp-shared/dist/identities.d.ts.map +1 -0
  192. package/node_modules/dp-shared/dist/identities.js +27 -0
  193. package/node_modules/dp-shared/dist/identities.js.map +1 -0
  194. package/node_modules/dp-shared/dist/index.d.ts +24 -0
  195. package/node_modules/dp-shared/dist/index.d.ts.map +1 -0
  196. package/node_modules/dp-shared/dist/index.js +24 -0
  197. package/node_modules/dp-shared/dist/index.js.map +1 -0
  198. package/node_modules/dp-shared/dist/rest-contracts.d.ts +459 -0
  199. package/node_modules/dp-shared/dist/rest-contracts.d.ts.map +1 -0
  200. package/node_modules/dp-shared/dist/rest-contracts.js +318 -0
  201. package/node_modules/dp-shared/dist/rest-contracts.js.map +1 -0
  202. package/node_modules/dp-shared/dist/task-history-contracts.d.ts +210 -0
  203. package/node_modules/dp-shared/dist/task-history-contracts.d.ts.map +1 -0
  204. package/node_modules/dp-shared/dist/task-history-contracts.js +99 -0
  205. package/node_modules/dp-shared/dist/task-history-contracts.js.map +1 -0
  206. package/node_modules/dp-shared/dist/worker-detail-contracts.d.ts +212 -0
  207. package/node_modules/dp-shared/dist/worker-detail-contracts.d.ts.map +1 -0
  208. package/node_modules/dp-shared/dist/worker-detail-contracts.js +193 -0
  209. package/node_modules/dp-shared/dist/worker-detail-contracts.js.map +1 -0
  210. package/node_modules/dp-shared/dist/ws-protocol.d.ts +839 -0
  211. package/node_modules/dp-shared/dist/ws-protocol.d.ts.map +1 -0
  212. package/node_modules/dp-shared/dist/ws-protocol.js +264 -0
  213. package/node_modules/dp-shared/dist/ws-protocol.js.map +1 -0
  214. package/node_modules/dp-shared/package.json +31 -0
  215. package/node_modules/zod/LICENSE +21 -0
  216. package/node_modules/zod/README.md +191 -0
  217. package/node_modules/zod/index.cjs +33 -0
  218. package/node_modules/zod/index.d.cts +4 -0
  219. package/node_modules/zod/index.d.ts +4 -0
  220. package/node_modules/zod/index.js +4 -0
  221. package/node_modules/zod/locales/index.cjs +17 -0
  222. package/node_modules/zod/locales/index.d.cts +1 -0
  223. package/node_modules/zod/locales/index.d.ts +1 -0
  224. package/node_modules/zod/locales/index.js +1 -0
  225. package/node_modules/zod/locales/package.json +7 -0
  226. package/node_modules/zod/mini/index.cjs +32 -0
  227. package/node_modules/zod/mini/index.d.cts +3 -0
  228. package/node_modules/zod/mini/index.d.ts +3 -0
  229. package/node_modules/zod/mini/index.js +3 -0
  230. package/node_modules/zod/mini/package.json +7 -0
  231. package/node_modules/zod/package.json +135 -0
  232. package/node_modules/zod/src/index.ts +4 -0
  233. package/node_modules/zod/src/locales/index.ts +1 -0
  234. package/node_modules/zod/src/mini/index.ts +3 -0
  235. package/node_modules/zod/src/v3/ZodError.ts +330 -0
  236. package/node_modules/zod/src/v3/benchmarks/datetime.ts +58 -0
  237. package/node_modules/zod/src/v3/benchmarks/discriminatedUnion.ts +80 -0
  238. package/node_modules/zod/src/v3/benchmarks/index.ts +59 -0
  239. package/node_modules/zod/src/v3/benchmarks/ipv4.ts +57 -0
  240. package/node_modules/zod/src/v3/benchmarks/object.ts +69 -0
  241. package/node_modules/zod/src/v3/benchmarks/primitives.ts +162 -0
  242. package/node_modules/zod/src/v3/benchmarks/realworld.ts +63 -0
  243. package/node_modules/zod/src/v3/benchmarks/string.ts +55 -0
  244. package/node_modules/zod/src/v3/benchmarks/union.ts +80 -0
  245. package/node_modules/zod/src/v3/errors.ts +13 -0
  246. package/node_modules/zod/src/v3/external.ts +6 -0
  247. package/node_modules/zod/src/v3/helpers/enumUtil.ts +17 -0
  248. package/node_modules/zod/src/v3/helpers/errorUtil.ts +8 -0
  249. package/node_modules/zod/src/v3/helpers/parseUtil.ts +176 -0
  250. package/node_modules/zod/src/v3/helpers/partialUtil.ts +34 -0
  251. package/node_modules/zod/src/v3/helpers/typeAliases.ts +2 -0
  252. package/node_modules/zod/src/v3/helpers/util.ts +224 -0
  253. package/node_modules/zod/src/v3/index.ts +4 -0
  254. package/node_modules/zod/src/v3/locales/en.ts +124 -0
  255. package/node_modules/zod/src/v3/standard-schema.ts +113 -0
  256. package/node_modules/zod/src/v3/tests/Mocker.ts +54 -0
  257. package/node_modules/zod/src/v3/tests/all-errors.test.ts +157 -0
  258. package/node_modules/zod/src/v3/tests/anyunknown.test.ts +28 -0
  259. package/node_modules/zod/src/v3/tests/array.test.ts +71 -0
  260. package/node_modules/zod/src/v3/tests/async-parsing.test.ts +388 -0
  261. package/node_modules/zod/src/v3/tests/async-refinements.test.ts +46 -0
  262. package/node_modules/zod/src/v3/tests/base.test.ts +29 -0
  263. package/node_modules/zod/src/v3/tests/bigint.test.ts +55 -0
  264. package/node_modules/zod/src/v3/tests/branded.test.ts +53 -0
  265. package/node_modules/zod/src/v3/tests/catch.test.ts +220 -0
  266. package/node_modules/zod/src/v3/tests/coerce.test.ts +133 -0
  267. package/node_modules/zod/src/v3/tests/complex.test.ts +70 -0
  268. package/node_modules/zod/src/v3/tests/custom.test.ts +31 -0
  269. package/node_modules/zod/src/v3/tests/date.test.ts +32 -0
  270. package/node_modules/zod/src/v3/tests/deepmasking.test.ts +186 -0
  271. package/node_modules/zod/src/v3/tests/default.test.ts +112 -0
  272. package/node_modules/zod/src/v3/tests/description.test.ts +33 -0
  273. package/node_modules/zod/src/v3/tests/discriminated-unions.test.ts +315 -0
  274. package/node_modules/zod/src/v3/tests/enum.test.ts +80 -0
  275. package/node_modules/zod/src/v3/tests/error.test.ts +551 -0
  276. package/node_modules/zod/src/v3/tests/firstparty.test.ts +87 -0
  277. package/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts +21 -0
  278. package/node_modules/zod/src/v3/tests/function.test.ts +261 -0
  279. package/node_modules/zod/src/v3/tests/generics.test.ts +48 -0
  280. package/node_modules/zod/src/v3/tests/instanceof.test.ts +37 -0
  281. package/node_modules/zod/src/v3/tests/intersection.test.ts +110 -0
  282. package/node_modules/zod/src/v3/tests/language-server.source.ts +76 -0
  283. package/node_modules/zod/src/v3/tests/language-server.test.ts +207 -0
  284. package/node_modules/zod/src/v3/tests/literal.test.ts +36 -0
  285. package/node_modules/zod/src/v3/tests/map.test.ts +110 -0
  286. package/node_modules/zod/src/v3/tests/masking.test.ts +4 -0
  287. package/node_modules/zod/src/v3/tests/mocker.test.ts +19 -0
  288. package/node_modules/zod/src/v3/tests/nan.test.ts +24 -0
  289. package/node_modules/zod/src/v3/tests/nativeEnum.test.ts +87 -0
  290. package/node_modules/zod/src/v3/tests/nullable.test.ts +42 -0
  291. package/node_modules/zod/src/v3/tests/number.test.ts +176 -0
  292. package/node_modules/zod/src/v3/tests/object-augmentation.test.ts +29 -0
  293. package/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts +29 -0
  294. package/node_modules/zod/src/v3/tests/object.test.ts +434 -0
  295. package/node_modules/zod/src/v3/tests/optional.test.ts +42 -0
  296. package/node_modules/zod/src/v3/tests/parseUtil.test.ts +23 -0
  297. package/node_modules/zod/src/v3/tests/parser.test.ts +41 -0
  298. package/node_modules/zod/src/v3/tests/partials.test.ts +243 -0
  299. package/node_modules/zod/src/v3/tests/pickomit.test.ts +111 -0
  300. package/node_modules/zod/src/v3/tests/pipeline.test.ts +29 -0
  301. package/node_modules/zod/src/v3/tests/preprocess.test.ts +186 -0
  302. package/node_modules/zod/src/v3/tests/primitive.test.ts +440 -0
  303. package/node_modules/zod/src/v3/tests/promise.test.ts +90 -0
  304. package/node_modules/zod/src/v3/tests/readonly.test.ts +194 -0
  305. package/node_modules/zod/src/v3/tests/record.test.ts +171 -0
  306. package/node_modules/zod/src/v3/tests/recursive.test.ts +197 -0
  307. package/node_modules/zod/src/v3/tests/refine.test.ts +313 -0
  308. package/node_modules/zod/src/v3/tests/safeparse.test.ts +27 -0
  309. package/node_modules/zod/src/v3/tests/set.test.ts +142 -0
  310. package/node_modules/zod/src/v3/tests/standard-schema.test.ts +83 -0
  311. package/node_modules/zod/src/v3/tests/string.test.ts +916 -0
  312. package/node_modules/zod/src/v3/tests/transformer.test.ts +233 -0
  313. package/node_modules/zod/src/v3/tests/tuple.test.ts +90 -0
  314. package/node_modules/zod/src/v3/tests/unions.test.ts +57 -0
  315. package/node_modules/zod/src/v3/tests/validations.test.ts +133 -0
  316. package/node_modules/zod/src/v3/tests/void.test.ts +15 -0
  317. package/node_modules/zod/src/v3/types.ts +5138 -0
  318. package/node_modules/zod/src/v4/classic/checks.ts +32 -0
  319. package/node_modules/zod/src/v4/classic/coerce.ts +27 -0
  320. package/node_modules/zod/src/v4/classic/compat.ts +70 -0
  321. package/node_modules/zod/src/v4/classic/errors.ts +82 -0
  322. package/node_modules/zod/src/v4/classic/external.ts +52 -0
  323. package/node_modules/zod/src/v4/classic/from-json-schema.ts +659 -0
  324. package/node_modules/zod/src/v4/classic/index.ts +5 -0
  325. package/node_modules/zod/src/v4/classic/iso.ts +90 -0
  326. package/node_modules/zod/src/v4/classic/parse.ts +82 -0
  327. package/node_modules/zod/src/v4/classic/schemas.ts +2672 -0
  328. package/node_modules/zod/src/v4/classic/tests/anyunknown.test.ts +26 -0
  329. package/node_modules/zod/src/v4/classic/tests/apply.test.ts +59 -0
  330. package/node_modules/zod/src/v4/classic/tests/array.test.ts +264 -0
  331. package/node_modules/zod/src/v4/classic/tests/assignability.test.ts +216 -0
  332. package/node_modules/zod/src/v4/classic/tests/async-parsing.test.ts +381 -0
  333. package/node_modules/zod/src/v4/classic/tests/async-refinements.test.ts +68 -0
  334. package/node_modules/zod/src/v4/classic/tests/base.test.ts +7 -0
  335. package/node_modules/zod/src/v4/classic/tests/bigint.test.ts +54 -0
  336. package/node_modules/zod/src/v4/classic/tests/brand.test.ts +106 -0
  337. package/node_modules/zod/src/v4/classic/tests/catch.test.ts +326 -0
  338. package/node_modules/zod/src/v4/classic/tests/coalesce.test.ts +20 -0
  339. package/node_modules/zod/src/v4/classic/tests/codec-examples.test.ts +573 -0
  340. package/node_modules/zod/src/v4/classic/tests/codec.test.ts +703 -0
  341. package/node_modules/zod/src/v4/classic/tests/coerce.test.ts +160 -0
  342. package/node_modules/zod/src/v4/classic/tests/continuability.test.ts +374 -0
  343. package/node_modules/zod/src/v4/classic/tests/custom.test.ts +40 -0
  344. package/node_modules/zod/src/v4/classic/tests/date.test.ts +62 -0
  345. package/node_modules/zod/src/v4/classic/tests/datetime.test.ts +302 -0
  346. package/node_modules/zod/src/v4/classic/tests/default.test.ts +409 -0
  347. package/node_modules/zod/src/v4/classic/tests/describe-meta-checks.test.ts +27 -0
  348. package/node_modules/zod/src/v4/classic/tests/description.test.ts +32 -0
  349. package/node_modules/zod/src/v4/classic/tests/detached-methods.test.ts +197 -0
  350. package/node_modules/zod/src/v4/classic/tests/discriminated-unions.test.ts +694 -0
  351. package/node_modules/zod/src/v4/classic/tests/enum.test.ts +285 -0
  352. package/node_modules/zod/src/v4/classic/tests/error-utils.test.ts +807 -0
  353. package/node_modules/zod/src/v4/classic/tests/error.test.ts +711 -0
  354. package/node_modules/zod/src/v4/classic/tests/file.test.ts +96 -0
  355. package/node_modules/zod/src/v4/classic/tests/firstparty.test.ts +179 -0
  356. package/node_modules/zod/src/v4/classic/tests/fix-json-issue.test.ts +26 -0
  357. package/node_modules/zod/src/v4/classic/tests/from-json-schema.test.ts +895 -0
  358. package/node_modules/zod/src/v4/classic/tests/function.test.ts +360 -0
  359. package/node_modules/zod/src/v4/classic/tests/generics.test.ts +72 -0
  360. package/node_modules/zod/src/v4/classic/tests/global-config.test.ts +39 -0
  361. package/node_modules/zod/src/v4/classic/tests/hash.test.ts +68 -0
  362. package/node_modules/zod/src/v4/classic/tests/index.test.ts +939 -0
  363. package/node_modules/zod/src/v4/classic/tests/instanceof.test.ts +60 -0
  364. package/node_modules/zod/src/v4/classic/tests/intersection.test.ts +198 -0
  365. package/node_modules/zod/src/v4/classic/tests/jitless-allows-eval.test.ts +46 -0
  366. package/node_modules/zod/src/v4/classic/tests/json.test.ts +109 -0
  367. package/node_modules/zod/src/v4/classic/tests/lazy.test.ts +227 -0
  368. package/node_modules/zod/src/v4/classic/tests/literal.test.ts +117 -0
  369. package/node_modules/zod/src/v4/classic/tests/locales_ka.test.ts +29 -0
  370. package/node_modules/zod/src/v4/classic/tests/locales_ro.test.ts +24 -0
  371. package/node_modules/zod/src/v4/classic/tests/map.test.ts +330 -0
  372. package/node_modules/zod/src/v4/classic/tests/nan.test.ts +21 -0
  373. package/node_modules/zod/src/v4/classic/tests/nested-refine.test.ts +168 -0
  374. package/node_modules/zod/src/v4/classic/tests/nonoptional.test.ts +101 -0
  375. package/node_modules/zod/src/v4/classic/tests/nullable.test.ts +22 -0
  376. package/node_modules/zod/src/v4/classic/tests/number.test.ts +325 -0
  377. package/node_modules/zod/src/v4/classic/tests/object.test.ts +717 -0
  378. package/node_modules/zod/src/v4/classic/tests/optional.test.ts +333 -0
  379. package/node_modules/zod/src/v4/classic/tests/partial.test.ts +450 -0
  380. package/node_modules/zod/src/v4/classic/tests/pickomit.test.ts +211 -0
  381. package/node_modules/zod/src/v4/classic/tests/pipe.test.ts +101 -0
  382. package/node_modules/zod/src/v4/classic/tests/prefault.test.ts +74 -0
  383. package/node_modules/zod/src/v4/classic/tests/preprocess-types.test.ts +26 -0
  384. package/node_modules/zod/src/v4/classic/tests/preprocess.test.ts +351 -0
  385. package/node_modules/zod/src/v4/classic/tests/primitive.test.ts +175 -0
  386. package/node_modules/zod/src/v4/classic/tests/promise.test.ts +81 -0
  387. package/node_modules/zod/src/v4/classic/tests/prototypes.test.ts +23 -0
  388. package/node_modules/zod/src/v4/classic/tests/readonly.test.ts +252 -0
  389. package/node_modules/zod/src/v4/classic/tests/record.test.ts +717 -0
  390. package/node_modules/zod/src/v4/classic/tests/recursive-types.test.ts +631 -0
  391. package/node_modules/zod/src/v4/classic/tests/refine.test.ts +633 -0
  392. package/node_modules/zod/src/v4/classic/tests/registries.test.ts +243 -0
  393. package/node_modules/zod/src/v4/classic/tests/set.test.ts +181 -0
  394. package/node_modules/zod/src/v4/classic/tests/standard-schema.test.ts +134 -0
  395. package/node_modules/zod/src/v4/classic/tests/string-formats.test.ts +125 -0
  396. package/node_modules/zod/src/v4/classic/tests/string.test.ts +1224 -0
  397. package/node_modules/zod/src/v4/classic/tests/stringbool.test.ts +106 -0
  398. package/node_modules/zod/src/v4/classic/tests/template-literal.test.ts +771 -0
  399. package/node_modules/zod/src/v4/classic/tests/to-json-schema-methods.test.ts +438 -0
  400. package/node_modules/zod/src/v4/classic/tests/to-json-schema.test.ts +3125 -0
  401. package/node_modules/zod/src/v4/classic/tests/transform.test.ts +378 -0
  402. package/node_modules/zod/src/v4/classic/tests/tuple.test.ts +496 -0
  403. package/node_modules/zod/src/v4/classic/tests/union.test.ts +273 -0
  404. package/node_modules/zod/src/v4/classic/tests/url.test.ts +13 -0
  405. package/node_modules/zod/src/v4/classic/tests/validations.test.ts +283 -0
  406. package/node_modules/zod/src/v4/classic/tests/void.test.ts +12 -0
  407. package/node_modules/zod/src/v4/core/api.ts +1823 -0
  408. package/node_modules/zod/src/v4/core/checks.ts +1293 -0
  409. package/node_modules/zod/src/v4/core/config.ts +15 -0
  410. package/node_modules/zod/src/v4/core/core.ts +153 -0
  411. package/node_modules/zod/src/v4/core/doc.ts +44 -0
  412. package/node_modules/zod/src/v4/core/errors.ts +455 -0
  413. package/node_modules/zod/src/v4/core/index.ts +16 -0
  414. package/node_modules/zod/src/v4/core/json-schema-generator.ts +126 -0
  415. package/node_modules/zod/src/v4/core/json-schema-processors.ts +666 -0
  416. package/node_modules/zod/src/v4/core/json-schema.ts +147 -0
  417. package/node_modules/zod/src/v4/core/parse.ts +195 -0
  418. package/node_modules/zod/src/v4/core/regexes.ts +190 -0
  419. package/node_modules/zod/src/v4/core/registries.ts +105 -0
  420. package/node_modules/zod/src/v4/core/schemas.ts +4730 -0
  421. package/node_modules/zod/src/v4/core/standard-schema.ts +159 -0
  422. package/node_modules/zod/src/v4/core/tests/extend.test.ts +59 -0
  423. package/node_modules/zod/src/v4/core/tests/index.test.ts +46 -0
  424. package/node_modules/zod/src/v4/core/tests/locales/be.test.ts +124 -0
  425. package/node_modules/zod/src/v4/core/tests/locales/el.test.ts +215 -0
  426. package/node_modules/zod/src/v4/core/tests/locales/en.test.ts +22 -0
  427. package/node_modules/zod/src/v4/core/tests/locales/es.test.ts +181 -0
  428. package/node_modules/zod/src/v4/core/tests/locales/fr.test.ts +72 -0
  429. package/node_modules/zod/src/v4/core/tests/locales/he.test.ts +379 -0
  430. package/node_modules/zod/src/v4/core/tests/locales/hr.test.ts +163 -0
  431. package/node_modules/zod/src/v4/core/tests/locales/nl.test.ts +46 -0
  432. package/node_modules/zod/src/v4/core/tests/locales/ru.test.ts +128 -0
  433. package/node_modules/zod/src/v4/core/tests/locales/tr.test.ts +69 -0
  434. package/node_modules/zod/src/v4/core/tests/locales/uz.test.ts +105 -0
  435. package/node_modules/zod/src/v4/core/tests/record-constructor.test.ts +125 -0
  436. package/node_modules/zod/src/v4/core/tests/recursive-tuples.test.ts +45 -0
  437. package/node_modules/zod/src/v4/core/to-json-schema.ts +622 -0
  438. package/node_modules/zod/src/v4/core/util.ts +983 -0
  439. package/node_modules/zod/src/v4/core/versions.ts +5 -0
  440. package/node_modules/zod/src/v4/core/zsf.ts +323 -0
  441. package/node_modules/zod/src/v4/index.ts +4 -0
  442. package/node_modules/zod/src/v4/locales/ar.ts +115 -0
  443. package/node_modules/zod/src/v4/locales/az.ts +111 -0
  444. package/node_modules/zod/src/v4/locales/be.ts +176 -0
  445. package/node_modules/zod/src/v4/locales/bg.ts +128 -0
  446. package/node_modules/zod/src/v4/locales/ca.ts +116 -0
  447. package/node_modules/zod/src/v4/locales/cs.ts +118 -0
  448. package/node_modules/zod/src/v4/locales/da.ts +123 -0
  449. package/node_modules/zod/src/v4/locales/de.ts +116 -0
  450. package/node_modules/zod/src/v4/locales/el.ts +121 -0
  451. package/node_modules/zod/src/v4/locales/en.ts +123 -0
  452. package/node_modules/zod/src/v4/locales/eo.ts +118 -0
  453. package/node_modules/zod/src/v4/locales/es.ts +141 -0
  454. package/node_modules/zod/src/v4/locales/fa.ts +126 -0
  455. package/node_modules/zod/src/v4/locales/fi.ts +121 -0
  456. package/node_modules/zod/src/v4/locales/fr-CA.ts +116 -0
  457. package/node_modules/zod/src/v4/locales/fr.ts +132 -0
  458. package/node_modules/zod/src/v4/locales/he.ts +246 -0
  459. package/node_modules/zod/src/v4/locales/hr.ts +131 -0
  460. package/node_modules/zod/src/v4/locales/hu.ts +117 -0
  461. package/node_modules/zod/src/v4/locales/hy.ts +164 -0
  462. package/node_modules/zod/src/v4/locales/id.ts +115 -0
  463. package/node_modules/zod/src/v4/locales/index.ts +52 -0
  464. package/node_modules/zod/src/v4/locales/is.ts +119 -0
  465. package/node_modules/zod/src/v4/locales/it.ts +116 -0
  466. package/node_modules/zod/src/v4/locales/ja.ts +114 -0
  467. package/node_modules/zod/src/v4/locales/ka.ts +123 -0
  468. package/node_modules/zod/src/v4/locales/kh.ts +7 -0
  469. package/node_modules/zod/src/v4/locales/km.ts +119 -0
  470. package/node_modules/zod/src/v4/locales/ko.ts +121 -0
  471. package/node_modules/zod/src/v4/locales/lt.ts +239 -0
  472. package/node_modules/zod/src/v4/locales/mk.ts +118 -0
  473. package/node_modules/zod/src/v4/locales/ms.ts +115 -0
  474. package/node_modules/zod/src/v4/locales/nl.ts +121 -0
  475. package/node_modules/zod/src/v4/locales/no.ts +116 -0
  476. package/node_modules/zod/src/v4/locales/ota.ts +117 -0
  477. package/node_modules/zod/src/v4/locales/pl.ts +118 -0
  478. package/node_modules/zod/src/v4/locales/ps.ts +126 -0
  479. package/node_modules/zod/src/v4/locales/pt.ts +116 -0
  480. package/node_modules/zod/src/v4/locales/ro.ts +129 -0
  481. package/node_modules/zod/src/v4/locales/ru.ts +176 -0
  482. package/node_modules/zod/src/v4/locales/sl.ts +118 -0
  483. package/node_modules/zod/src/v4/locales/sv.ts +119 -0
  484. package/node_modules/zod/src/v4/locales/ta.ts +118 -0
  485. package/node_modules/zod/src/v4/locales/th.ts +119 -0
  486. package/node_modules/zod/src/v4/locales/tr.ts +111 -0
  487. package/node_modules/zod/src/v4/locales/ua.ts +7 -0
  488. package/node_modules/zod/src/v4/locales/uk.ts +117 -0
  489. package/node_modules/zod/src/v4/locales/ur.ts +119 -0
  490. package/node_modules/zod/src/v4/locales/uz.ts +117 -0
  491. package/node_modules/zod/src/v4/locales/vi.ts +117 -0
  492. package/node_modules/zod/src/v4/locales/yo.ts +124 -0
  493. package/node_modules/zod/src/v4/locales/zh-CN.ts +116 -0
  494. package/node_modules/zod/src/v4/locales/zh-TW.ts +115 -0
  495. package/node_modules/zod/src/v4/mini/checks.ts +32 -0
  496. package/node_modules/zod/src/v4/mini/coerce.ts +27 -0
  497. package/node_modules/zod/src/v4/mini/external.ts +41 -0
  498. package/node_modules/zod/src/v4/mini/index.ts +3 -0
  499. package/node_modules/zod/src/v4/mini/iso.ts +66 -0
  500. package/node_modules/zod/src/v4/mini/parse.ts +14 -0
  501. package/node_modules/zod/src/v4/mini/schemas.ts +1947 -0
  502. package/node_modules/zod/src/v4/mini/tests/apply.test.ts +24 -0
  503. package/node_modules/zod/src/v4/mini/tests/assignability.test.ts +129 -0
  504. package/node_modules/zod/src/v4/mini/tests/brand.test.ts +94 -0
  505. package/node_modules/zod/src/v4/mini/tests/checks.test.ts +144 -0
  506. package/node_modules/zod/src/v4/mini/tests/codec.test.ts +548 -0
  507. package/node_modules/zod/src/v4/mini/tests/computed.test.ts +36 -0
  508. package/node_modules/zod/src/v4/mini/tests/error.test.ts +22 -0
  509. package/node_modules/zod/src/v4/mini/tests/functions.test.ts +5 -0
  510. package/node_modules/zod/src/v4/mini/tests/index.test.ts +993 -0
  511. package/node_modules/zod/src/v4/mini/tests/number.test.ts +95 -0
  512. package/node_modules/zod/src/v4/mini/tests/object.test.ts +227 -0
  513. package/node_modules/zod/src/v4/mini/tests/prototypes.test.ts +43 -0
  514. package/node_modules/zod/src/v4/mini/tests/recursive-types.test.ts +325 -0
  515. package/node_modules/zod/src/v4/mini/tests/standard-schema.test.ts +50 -0
  516. package/node_modules/zod/src/v4/mini/tests/string.test.ts +352 -0
  517. package/node_modules/zod/src/v4-mini/index.ts +3 -0
  518. package/node_modules/zod/v3/ZodError.cjs +138 -0
  519. package/node_modules/zod/v3/ZodError.d.cts +164 -0
  520. package/node_modules/zod/v3/ZodError.d.ts +164 -0
  521. package/node_modules/zod/v3/ZodError.js +133 -0
  522. package/node_modules/zod/v3/errors.cjs +17 -0
  523. package/node_modules/zod/v3/errors.d.cts +5 -0
  524. package/node_modules/zod/v3/errors.d.ts +5 -0
  525. package/node_modules/zod/v3/errors.js +9 -0
  526. package/node_modules/zod/v3/external.cjs +22 -0
  527. package/node_modules/zod/v3/external.d.cts +6 -0
  528. package/node_modules/zod/v3/external.d.ts +6 -0
  529. package/node_modules/zod/v3/external.js +6 -0
  530. package/node_modules/zod/v3/helpers/enumUtil.cjs +2 -0
  531. package/node_modules/zod/v3/helpers/enumUtil.d.cts +8 -0
  532. package/node_modules/zod/v3/helpers/enumUtil.d.ts +8 -0
  533. package/node_modules/zod/v3/helpers/enumUtil.js +1 -0
  534. package/node_modules/zod/v3/helpers/errorUtil.cjs +9 -0
  535. package/node_modules/zod/v3/helpers/errorUtil.d.cts +9 -0
  536. package/node_modules/zod/v3/helpers/errorUtil.d.ts +9 -0
  537. package/node_modules/zod/v3/helpers/errorUtil.js +6 -0
  538. package/node_modules/zod/v3/helpers/parseUtil.cjs +124 -0
  539. package/node_modules/zod/v3/helpers/parseUtil.d.cts +78 -0
  540. package/node_modules/zod/v3/helpers/parseUtil.d.ts +78 -0
  541. package/node_modules/zod/v3/helpers/parseUtil.js +109 -0
  542. package/node_modules/zod/v3/helpers/partialUtil.cjs +2 -0
  543. package/node_modules/zod/v3/helpers/partialUtil.d.cts +8 -0
  544. package/node_modules/zod/v3/helpers/partialUtil.d.ts +8 -0
  545. package/node_modules/zod/v3/helpers/partialUtil.js +1 -0
  546. package/node_modules/zod/v3/helpers/typeAliases.cjs +2 -0
  547. package/node_modules/zod/v3/helpers/typeAliases.d.cts +2 -0
  548. package/node_modules/zod/v3/helpers/typeAliases.d.ts +2 -0
  549. package/node_modules/zod/v3/helpers/typeAliases.js +1 -0
  550. package/node_modules/zod/v3/helpers/util.cjs +137 -0
  551. package/node_modules/zod/v3/helpers/util.d.cts +85 -0
  552. package/node_modules/zod/v3/helpers/util.d.ts +85 -0
  553. package/node_modules/zod/v3/helpers/util.js +133 -0
  554. package/node_modules/zod/v3/index.cjs +33 -0
  555. package/node_modules/zod/v3/index.d.cts +4 -0
  556. package/node_modules/zod/v3/index.d.ts +4 -0
  557. package/node_modules/zod/v3/index.js +4 -0
  558. package/node_modules/zod/v3/locales/en.cjs +112 -0
  559. package/node_modules/zod/v3/locales/en.d.cts +3 -0
  560. package/node_modules/zod/v3/locales/en.d.ts +3 -0
  561. package/node_modules/zod/v3/locales/en.js +109 -0
  562. package/node_modules/zod/v3/package.json +7 -0
  563. package/node_modules/zod/v3/standard-schema.cjs +2 -0
  564. package/node_modules/zod/v3/standard-schema.d.cts +102 -0
  565. package/node_modules/zod/v3/standard-schema.d.ts +102 -0
  566. package/node_modules/zod/v3/standard-schema.js +1 -0
  567. package/node_modules/zod/v3/types.cjs +3777 -0
  568. package/node_modules/zod/v3/types.d.cts +1034 -0
  569. package/node_modules/zod/v3/types.d.ts +1034 -0
  570. package/node_modules/zod/v3/types.js +3695 -0
  571. package/node_modules/zod/v4/classic/checks.cjs +33 -0
  572. package/node_modules/zod/v4/classic/checks.d.cts +1 -0
  573. package/node_modules/zod/v4/classic/checks.d.ts +1 -0
  574. package/node_modules/zod/v4/classic/checks.js +1 -0
  575. package/node_modules/zod/v4/classic/coerce.cjs +47 -0
  576. package/node_modules/zod/v4/classic/coerce.d.cts +17 -0
  577. package/node_modules/zod/v4/classic/coerce.d.ts +17 -0
  578. package/node_modules/zod/v4/classic/coerce.js +17 -0
  579. package/node_modules/zod/v4/classic/compat.cjs +61 -0
  580. package/node_modules/zod/v4/classic/compat.d.cts +50 -0
  581. package/node_modules/zod/v4/classic/compat.d.ts +50 -0
  582. package/node_modules/zod/v4/classic/compat.js +31 -0
  583. package/node_modules/zod/v4/classic/errors.cjs +74 -0
  584. package/node_modules/zod/v4/classic/errors.d.cts +30 -0
  585. package/node_modules/zod/v4/classic/errors.d.ts +30 -0
  586. package/node_modules/zod/v4/classic/errors.js +48 -0
  587. package/node_modules/zod/v4/classic/external.cjs +73 -0
  588. package/node_modules/zod/v4/classic/external.d.cts +16 -0
  589. package/node_modules/zod/v4/classic/external.d.ts +16 -0
  590. package/node_modules/zod/v4/classic/external.js +20 -0
  591. package/node_modules/zod/v4/classic/from-json-schema.cjs +625 -0
  592. package/node_modules/zod/v4/classic/from-json-schema.d.cts +12 -0
  593. package/node_modules/zod/v4/classic/from-json-schema.d.ts +12 -0
  594. package/node_modules/zod/v4/classic/from-json-schema.js +599 -0
  595. package/node_modules/zod/v4/classic/index.cjs +33 -0
  596. package/node_modules/zod/v4/classic/index.d.cts +4 -0
  597. package/node_modules/zod/v4/classic/index.d.ts +4 -0
  598. package/node_modules/zod/v4/classic/index.js +4 -0
  599. package/node_modules/zod/v4/classic/iso.cjs +60 -0
  600. package/node_modules/zod/v4/classic/iso.d.cts +22 -0
  601. package/node_modules/zod/v4/classic/iso.d.ts +22 -0
  602. package/node_modules/zod/v4/classic/iso.js +30 -0
  603. package/node_modules/zod/v4/classic/package.json +7 -0
  604. package/node_modules/zod/v4/classic/parse.cjs +41 -0
  605. package/node_modules/zod/v4/classic/parse.d.cts +31 -0
  606. package/node_modules/zod/v4/classic/parse.d.ts +31 -0
  607. package/node_modules/zod/v4/classic/parse.js +15 -0
  608. package/node_modules/zod/v4/classic/schemas.cjs +1511 -0
  609. package/node_modules/zod/v4/classic/schemas.d.cts +767 -0
  610. package/node_modules/zod/v4/classic/schemas.d.ts +767 -0
  611. package/node_modules/zod/v4/classic/schemas.js +1395 -0
  612. package/node_modules/zod/v4/core/api.cjs +1227 -0
  613. package/node_modules/zod/v4/core/api.d.cts +325 -0
  614. package/node_modules/zod/v4/core/api.d.ts +325 -0
  615. package/node_modules/zod/v4/core/api.js +1087 -0
  616. package/node_modules/zod/v4/core/checks.cjs +601 -0
  617. package/node_modules/zod/v4/core/checks.d.cts +278 -0
  618. package/node_modules/zod/v4/core/checks.d.ts +278 -0
  619. package/node_modules/zod/v4/core/checks.js +575 -0
  620. package/node_modules/zod/v4/core/core.cjs +85 -0
  621. package/node_modules/zod/v4/core/core.d.cts +70 -0
  622. package/node_modules/zod/v4/core/core.d.ts +70 -0
  623. package/node_modules/zod/v4/core/core.js +78 -0
  624. package/node_modules/zod/v4/core/doc.cjs +39 -0
  625. package/node_modules/zod/v4/core/doc.d.cts +14 -0
  626. package/node_modules/zod/v4/core/doc.d.ts +14 -0
  627. package/node_modules/zod/v4/core/doc.js +35 -0
  628. package/node_modules/zod/v4/core/errors.cjs +216 -0
  629. package/node_modules/zod/v4/core/errors.d.cts +221 -0
  630. package/node_modules/zod/v4/core/errors.d.ts +221 -0
  631. package/node_modules/zod/v4/core/errors.js +185 -0
  632. package/node_modules/zod/v4/core/index.cjs +47 -0
  633. package/node_modules/zod/v4/core/index.d.cts +16 -0
  634. package/node_modules/zod/v4/core/index.d.ts +16 -0
  635. package/node_modules/zod/v4/core/index.js +16 -0
  636. package/node_modules/zod/v4/core/json-schema-generator.cjs +99 -0
  637. package/node_modules/zod/v4/core/json-schema-generator.d.cts +65 -0
  638. package/node_modules/zod/v4/core/json-schema-generator.d.ts +65 -0
  639. package/node_modules/zod/v4/core/json-schema-generator.js +95 -0
  640. package/node_modules/zod/v4/core/json-schema-processors.cjs +644 -0
  641. package/node_modules/zod/v4/core/json-schema-processors.d.cts +49 -0
  642. package/node_modules/zod/v4/core/json-schema-processors.d.ts +49 -0
  643. package/node_modules/zod/v4/core/json-schema-processors.js +601 -0
  644. package/node_modules/zod/v4/core/json-schema.cjs +2 -0
  645. package/node_modules/zod/v4/core/json-schema.d.cts +88 -0
  646. package/node_modules/zod/v4/core/json-schema.d.ts +88 -0
  647. package/node_modules/zod/v4/core/json-schema.js +1 -0
  648. package/node_modules/zod/v4/core/package.json +7 -0
  649. package/node_modules/zod/v4/core/parse.cjs +131 -0
  650. package/node_modules/zod/v4/core/parse.d.cts +49 -0
  651. package/node_modules/zod/v4/core/parse.d.ts +49 -0
  652. package/node_modules/zod/v4/core/parse.js +93 -0
  653. package/node_modules/zod/v4/core/regexes.cjs +172 -0
  654. package/node_modules/zod/v4/core/regexes.d.cts +85 -0
  655. package/node_modules/zod/v4/core/regexes.d.ts +85 -0
  656. package/node_modules/zod/v4/core/regexes.js +139 -0
  657. package/node_modules/zod/v4/core/registries.cjs +56 -0
  658. package/node_modules/zod/v4/core/registries.d.cts +35 -0
  659. package/node_modules/zod/v4/core/registries.d.ts +35 -0
  660. package/node_modules/zod/v4/core/registries.js +51 -0
  661. package/node_modules/zod/v4/core/schemas.cjs +2270 -0
  662. package/node_modules/zod/v4/core/schemas.d.cts +1184 -0
  663. package/node_modules/zod/v4/core/schemas.d.ts +1184 -0
  664. package/node_modules/zod/v4/core/schemas.js +2239 -0
  665. package/node_modules/zod/v4/core/standard-schema.cjs +2 -0
  666. package/node_modules/zod/v4/core/standard-schema.d.cts +126 -0
  667. package/node_modules/zod/v4/core/standard-schema.d.ts +126 -0
  668. package/node_modules/zod/v4/core/standard-schema.js +1 -0
  669. package/node_modules/zod/v4/core/to-json-schema.cjs +457 -0
  670. package/node_modules/zod/v4/core/to-json-schema.d.cts +114 -0
  671. package/node_modules/zod/v4/core/to-json-schema.d.ts +114 -0
  672. package/node_modules/zod/v4/core/to-json-schema.js +448 -0
  673. package/node_modules/zod/v4/core/util.cjs +734 -0
  674. package/node_modules/zod/v4/core/util.d.cts +200 -0
  675. package/node_modules/zod/v4/core/util.d.ts +200 -0
  676. package/node_modules/zod/v4/core/util.js +674 -0
  677. package/node_modules/zod/v4/core/versions.cjs +8 -0
  678. package/node_modules/zod/v4/core/versions.d.cts +5 -0
  679. package/node_modules/zod/v4/core/versions.d.ts +5 -0
  680. package/node_modules/zod/v4/core/versions.js +5 -0
  681. package/node_modules/zod/v4/index.cjs +22 -0
  682. package/node_modules/zod/v4/index.d.cts +3 -0
  683. package/node_modules/zod/v4/index.d.ts +3 -0
  684. package/node_modules/zod/v4/index.js +3 -0
  685. package/node_modules/zod/v4/locales/ar.cjs +133 -0
  686. package/node_modules/zod/v4/locales/ar.d.cts +5 -0
  687. package/node_modules/zod/v4/locales/ar.d.ts +4 -0
  688. package/node_modules/zod/v4/locales/ar.js +106 -0
  689. package/node_modules/zod/v4/locales/az.cjs +132 -0
  690. package/node_modules/zod/v4/locales/az.d.cts +5 -0
  691. package/node_modules/zod/v4/locales/az.d.ts +4 -0
  692. package/node_modules/zod/v4/locales/az.js +105 -0
  693. package/node_modules/zod/v4/locales/be.cjs +183 -0
  694. package/node_modules/zod/v4/locales/be.d.cts +5 -0
  695. package/node_modules/zod/v4/locales/be.d.ts +4 -0
  696. package/node_modules/zod/v4/locales/be.js +156 -0
  697. package/node_modules/zod/v4/locales/bg.cjs +147 -0
  698. package/node_modules/zod/v4/locales/bg.d.cts +5 -0
  699. package/node_modules/zod/v4/locales/bg.d.ts +4 -0
  700. package/node_modules/zod/v4/locales/bg.js +120 -0
  701. package/node_modules/zod/v4/locales/ca.cjs +134 -0
  702. package/node_modules/zod/v4/locales/ca.d.cts +5 -0
  703. package/node_modules/zod/v4/locales/ca.d.ts +4 -0
  704. package/node_modules/zod/v4/locales/ca.js +107 -0
  705. package/node_modules/zod/v4/locales/cs.cjs +138 -0
  706. package/node_modules/zod/v4/locales/cs.d.cts +5 -0
  707. package/node_modules/zod/v4/locales/cs.d.ts +4 -0
  708. package/node_modules/zod/v4/locales/cs.js +111 -0
  709. package/node_modules/zod/v4/locales/da.cjs +142 -0
  710. package/node_modules/zod/v4/locales/da.d.cts +5 -0
  711. package/node_modules/zod/v4/locales/da.d.ts +4 -0
  712. package/node_modules/zod/v4/locales/da.js +115 -0
  713. package/node_modules/zod/v4/locales/de.cjs +135 -0
  714. package/node_modules/zod/v4/locales/de.d.cts +5 -0
  715. package/node_modules/zod/v4/locales/de.d.ts +4 -0
  716. package/node_modules/zod/v4/locales/de.js +108 -0
  717. package/node_modules/zod/v4/locales/el.cjs +136 -0
  718. package/node_modules/zod/v4/locales/el.d.cts +5 -0
  719. package/node_modules/zod/v4/locales/el.d.ts +4 -0
  720. package/node_modules/zod/v4/locales/el.js +109 -0
  721. package/node_modules/zod/v4/locales/en.cjs +140 -0
  722. package/node_modules/zod/v4/locales/en.d.cts +5 -0
  723. package/node_modules/zod/v4/locales/en.d.ts +4 -0
  724. package/node_modules/zod/v4/locales/en.js +113 -0
  725. package/node_modules/zod/v4/locales/eo.cjs +136 -0
  726. package/node_modules/zod/v4/locales/eo.d.cts +5 -0
  727. package/node_modules/zod/v4/locales/eo.d.ts +4 -0
  728. package/node_modules/zod/v4/locales/eo.js +109 -0
  729. package/node_modules/zod/v4/locales/es.cjs +159 -0
  730. package/node_modules/zod/v4/locales/es.d.cts +5 -0
  731. package/node_modules/zod/v4/locales/es.d.ts +4 -0
  732. package/node_modules/zod/v4/locales/es.js +132 -0
  733. package/node_modules/zod/v4/locales/fa.cjs +141 -0
  734. package/node_modules/zod/v4/locales/fa.d.cts +5 -0
  735. package/node_modules/zod/v4/locales/fa.d.ts +4 -0
  736. package/node_modules/zod/v4/locales/fa.js +114 -0
  737. package/node_modules/zod/v4/locales/fi.cjs +139 -0
  738. package/node_modules/zod/v4/locales/fi.d.cts +5 -0
  739. package/node_modules/zod/v4/locales/fi.d.ts +4 -0
  740. package/node_modules/zod/v4/locales/fi.js +112 -0
  741. package/node_modules/zod/v4/locales/fr-CA.cjs +134 -0
  742. package/node_modules/zod/v4/locales/fr-CA.d.cts +5 -0
  743. package/node_modules/zod/v4/locales/fr-CA.d.ts +4 -0
  744. package/node_modules/zod/v4/locales/fr-CA.js +107 -0
  745. package/node_modules/zod/v4/locales/fr.cjs +152 -0
  746. package/node_modules/zod/v4/locales/fr.d.cts +5 -0
  747. package/node_modules/zod/v4/locales/fr.d.ts +4 -0
  748. package/node_modules/zod/v4/locales/fr.js +125 -0
  749. package/node_modules/zod/v4/locales/he.cjs +241 -0
  750. package/node_modules/zod/v4/locales/he.d.cts +5 -0
  751. package/node_modules/zod/v4/locales/he.d.ts +4 -0
  752. package/node_modules/zod/v4/locales/he.js +214 -0
  753. package/node_modules/zod/v4/locales/hr.cjs +149 -0
  754. package/node_modules/zod/v4/locales/hr.d.cts +5 -0
  755. package/node_modules/zod/v4/locales/hr.d.ts +4 -0
  756. package/node_modules/zod/v4/locales/hr.js +122 -0
  757. package/node_modules/zod/v4/locales/hu.cjs +135 -0
  758. package/node_modules/zod/v4/locales/hu.d.cts +5 -0
  759. package/node_modules/zod/v4/locales/hu.d.ts +4 -0
  760. package/node_modules/zod/v4/locales/hu.js +108 -0
  761. package/node_modules/zod/v4/locales/hy.cjs +174 -0
  762. package/node_modules/zod/v4/locales/hy.d.cts +5 -0
  763. package/node_modules/zod/v4/locales/hy.d.ts +4 -0
  764. package/node_modules/zod/v4/locales/hy.js +147 -0
  765. package/node_modules/zod/v4/locales/id.cjs +133 -0
  766. package/node_modules/zod/v4/locales/id.d.cts +5 -0
  767. package/node_modules/zod/v4/locales/id.d.ts +4 -0
  768. package/node_modules/zod/v4/locales/id.js +106 -0
  769. package/node_modules/zod/v4/locales/index.cjs +111 -0
  770. package/node_modules/zod/v4/locales/index.d.cts +52 -0
  771. package/node_modules/zod/v4/locales/index.d.ts +52 -0
  772. package/node_modules/zod/v4/locales/index.js +52 -0
  773. package/node_modules/zod/v4/locales/is.cjs +136 -0
  774. package/node_modules/zod/v4/locales/is.d.cts +5 -0
  775. package/node_modules/zod/v4/locales/is.d.ts +4 -0
  776. package/node_modules/zod/v4/locales/is.js +109 -0
  777. package/node_modules/zod/v4/locales/it.cjs +135 -0
  778. package/node_modules/zod/v4/locales/it.d.cts +5 -0
  779. package/node_modules/zod/v4/locales/it.d.ts +4 -0
  780. package/node_modules/zod/v4/locales/it.js +108 -0
  781. package/node_modules/zod/v4/locales/ja.cjs +134 -0
  782. package/node_modules/zod/v4/locales/ja.d.cts +5 -0
  783. package/node_modules/zod/v4/locales/ja.d.ts +4 -0
  784. package/node_modules/zod/v4/locales/ja.js +107 -0
  785. package/node_modules/zod/v4/locales/ka.cjs +139 -0
  786. package/node_modules/zod/v4/locales/ka.d.cts +5 -0
  787. package/node_modules/zod/v4/locales/ka.d.ts +4 -0
  788. package/node_modules/zod/v4/locales/ka.js +112 -0
  789. package/node_modules/zod/v4/locales/kh.cjs +12 -0
  790. package/node_modules/zod/v4/locales/kh.d.cts +5 -0
  791. package/node_modules/zod/v4/locales/kh.d.ts +5 -0
  792. package/node_modules/zod/v4/locales/kh.js +5 -0
  793. package/node_modules/zod/v4/locales/km.cjs +137 -0
  794. package/node_modules/zod/v4/locales/km.d.cts +5 -0
  795. package/node_modules/zod/v4/locales/km.d.ts +4 -0
  796. package/node_modules/zod/v4/locales/km.js +110 -0
  797. package/node_modules/zod/v4/locales/ko.cjs +138 -0
  798. package/node_modules/zod/v4/locales/ko.d.cts +5 -0
  799. package/node_modules/zod/v4/locales/ko.d.ts +4 -0
  800. package/node_modules/zod/v4/locales/ko.js +111 -0
  801. package/node_modules/zod/v4/locales/lt.cjs +230 -0
  802. package/node_modules/zod/v4/locales/lt.d.cts +5 -0
  803. package/node_modules/zod/v4/locales/lt.d.ts +4 -0
  804. package/node_modules/zod/v4/locales/lt.js +203 -0
  805. package/node_modules/zod/v4/locales/mk.cjs +136 -0
  806. package/node_modules/zod/v4/locales/mk.d.cts +5 -0
  807. package/node_modules/zod/v4/locales/mk.d.ts +4 -0
  808. package/node_modules/zod/v4/locales/mk.js +109 -0
  809. package/node_modules/zod/v4/locales/ms.cjs +134 -0
  810. package/node_modules/zod/v4/locales/ms.d.cts +5 -0
  811. package/node_modules/zod/v4/locales/ms.d.ts +4 -0
  812. package/node_modules/zod/v4/locales/ms.js +107 -0
  813. package/node_modules/zod/v4/locales/nl.cjs +137 -0
  814. package/node_modules/zod/v4/locales/nl.d.cts +5 -0
  815. package/node_modules/zod/v4/locales/nl.d.ts +4 -0
  816. package/node_modules/zod/v4/locales/nl.js +110 -0
  817. package/node_modules/zod/v4/locales/no.cjs +135 -0
  818. package/node_modules/zod/v4/locales/no.d.cts +5 -0
  819. package/node_modules/zod/v4/locales/no.d.ts +4 -0
  820. package/node_modules/zod/v4/locales/no.js +108 -0
  821. package/node_modules/zod/v4/locales/ota.cjs +136 -0
  822. package/node_modules/zod/v4/locales/ota.d.cts +5 -0
  823. package/node_modules/zod/v4/locales/ota.d.ts +4 -0
  824. package/node_modules/zod/v4/locales/ota.js +109 -0
  825. package/node_modules/zod/v4/locales/package.json +7 -0
  826. package/node_modules/zod/v4/locales/pl.cjs +136 -0
  827. package/node_modules/zod/v4/locales/pl.d.cts +5 -0
  828. package/node_modules/zod/v4/locales/pl.d.ts +4 -0
  829. package/node_modules/zod/v4/locales/pl.js +109 -0
  830. package/node_modules/zod/v4/locales/ps.cjs +141 -0
  831. package/node_modules/zod/v4/locales/ps.d.cts +5 -0
  832. package/node_modules/zod/v4/locales/ps.d.ts +4 -0
  833. package/node_modules/zod/v4/locales/ps.js +114 -0
  834. package/node_modules/zod/v4/locales/pt.cjs +135 -0
  835. package/node_modules/zod/v4/locales/pt.d.cts +5 -0
  836. package/node_modules/zod/v4/locales/pt.d.ts +4 -0
  837. package/node_modules/zod/v4/locales/pt.js +108 -0
  838. package/node_modules/zod/v4/locales/ro.cjs +146 -0
  839. package/node_modules/zod/v4/locales/ro.d.cts +5 -0
  840. package/node_modules/zod/v4/locales/ro.d.ts +4 -0
  841. package/node_modules/zod/v4/locales/ro.js +119 -0
  842. package/node_modules/zod/v4/locales/ru.cjs +183 -0
  843. package/node_modules/zod/v4/locales/ru.d.cts +5 -0
  844. package/node_modules/zod/v4/locales/ru.d.ts +4 -0
  845. package/node_modules/zod/v4/locales/ru.js +156 -0
  846. package/node_modules/zod/v4/locales/sl.cjs +136 -0
  847. package/node_modules/zod/v4/locales/sl.d.cts +5 -0
  848. package/node_modules/zod/v4/locales/sl.d.ts +4 -0
  849. package/node_modules/zod/v4/locales/sl.js +109 -0
  850. package/node_modules/zod/v4/locales/sv.cjs +137 -0
  851. package/node_modules/zod/v4/locales/sv.d.cts +5 -0
  852. package/node_modules/zod/v4/locales/sv.d.ts +4 -0
  853. package/node_modules/zod/v4/locales/sv.js +110 -0
  854. package/node_modules/zod/v4/locales/ta.cjs +137 -0
  855. package/node_modules/zod/v4/locales/ta.d.cts +5 -0
  856. package/node_modules/zod/v4/locales/ta.d.ts +4 -0
  857. package/node_modules/zod/v4/locales/ta.js +110 -0
  858. package/node_modules/zod/v4/locales/th.cjs +137 -0
  859. package/node_modules/zod/v4/locales/th.d.cts +5 -0
  860. package/node_modules/zod/v4/locales/th.d.ts +4 -0
  861. package/node_modules/zod/v4/locales/th.js +110 -0
  862. package/node_modules/zod/v4/locales/tr.cjs +132 -0
  863. package/node_modules/zod/v4/locales/tr.d.cts +5 -0
  864. package/node_modules/zod/v4/locales/tr.d.ts +4 -0
  865. package/node_modules/zod/v4/locales/tr.js +105 -0
  866. package/node_modules/zod/v4/locales/ua.cjs +12 -0
  867. package/node_modules/zod/v4/locales/ua.d.cts +5 -0
  868. package/node_modules/zod/v4/locales/ua.d.ts +5 -0
  869. package/node_modules/zod/v4/locales/ua.js +5 -0
  870. package/node_modules/zod/v4/locales/uk.cjs +135 -0
  871. package/node_modules/zod/v4/locales/uk.d.cts +5 -0
  872. package/node_modules/zod/v4/locales/uk.d.ts +4 -0
  873. package/node_modules/zod/v4/locales/uk.js +108 -0
  874. package/node_modules/zod/v4/locales/ur.cjs +137 -0
  875. package/node_modules/zod/v4/locales/ur.d.cts +5 -0
  876. package/node_modules/zod/v4/locales/ur.d.ts +4 -0
  877. package/node_modules/zod/v4/locales/ur.js +110 -0
  878. package/node_modules/zod/v4/locales/uz.cjs +137 -0
  879. package/node_modules/zod/v4/locales/uz.d.cts +5 -0
  880. package/node_modules/zod/v4/locales/uz.d.ts +4 -0
  881. package/node_modules/zod/v4/locales/uz.js +110 -0
  882. package/node_modules/zod/v4/locales/vi.cjs +135 -0
  883. package/node_modules/zod/v4/locales/vi.d.cts +5 -0
  884. package/node_modules/zod/v4/locales/vi.d.ts +4 -0
  885. package/node_modules/zod/v4/locales/vi.js +108 -0
  886. package/node_modules/zod/v4/locales/yo.cjs +134 -0
  887. package/node_modules/zod/v4/locales/yo.d.cts +5 -0
  888. package/node_modules/zod/v4/locales/yo.d.ts +4 -0
  889. package/node_modules/zod/v4/locales/yo.js +107 -0
  890. package/node_modules/zod/v4/locales/zh-CN.cjs +136 -0
  891. package/node_modules/zod/v4/locales/zh-CN.d.cts +5 -0
  892. package/node_modules/zod/v4/locales/zh-CN.d.ts +4 -0
  893. package/node_modules/zod/v4/locales/zh-CN.js +109 -0
  894. package/node_modules/zod/v4/locales/zh-TW.cjs +134 -0
  895. package/node_modules/zod/v4/locales/zh-TW.d.cts +5 -0
  896. package/node_modules/zod/v4/locales/zh-TW.d.ts +4 -0
  897. package/node_modules/zod/v4/locales/zh-TW.js +107 -0
  898. package/node_modules/zod/v4/mini/checks.cjs +34 -0
  899. package/node_modules/zod/v4/mini/checks.d.cts +1 -0
  900. package/node_modules/zod/v4/mini/checks.d.ts +1 -0
  901. package/node_modules/zod/v4/mini/checks.js +1 -0
  902. package/node_modules/zod/v4/mini/coerce.cjs +52 -0
  903. package/node_modules/zod/v4/mini/coerce.d.cts +7 -0
  904. package/node_modules/zod/v4/mini/coerce.d.ts +7 -0
  905. package/node_modules/zod/v4/mini/coerce.js +22 -0
  906. package/node_modules/zod/v4/mini/external.cjs +63 -0
  907. package/node_modules/zod/v4/mini/external.d.cts +13 -0
  908. package/node_modules/zod/v4/mini/external.d.ts +13 -0
  909. package/node_modules/zod/v4/mini/external.js +14 -0
  910. package/node_modules/zod/v4/mini/index.cjs +32 -0
  911. package/node_modules/zod/v4/mini/index.d.cts +3 -0
  912. package/node_modules/zod/v4/mini/index.d.ts +3 -0
  913. package/node_modules/zod/v4/mini/index.js +3 -0
  914. package/node_modules/zod/v4/mini/iso.cjs +64 -0
  915. package/node_modules/zod/v4/mini/iso.d.cts +22 -0
  916. package/node_modules/zod/v4/mini/iso.d.ts +22 -0
  917. package/node_modules/zod/v4/mini/iso.js +34 -0
  918. package/node_modules/zod/v4/mini/package.json +7 -0
  919. package/node_modules/zod/v4/mini/parse.cjs +16 -0
  920. package/node_modules/zod/v4/mini/parse.d.cts +1 -0
  921. package/node_modules/zod/v4/mini/parse.d.ts +1 -0
  922. package/node_modules/zod/v4/mini/parse.js +1 -0
  923. package/node_modules/zod/v4/mini/schemas.cjs +1083 -0
  924. package/node_modules/zod/v4/mini/schemas.d.cts +445 -0
  925. package/node_modules/zod/v4/mini/schemas.d.ts +445 -0
  926. package/node_modules/zod/v4/mini/schemas.js +961 -0
  927. package/node_modules/zod/v4/package.json +7 -0
  928. package/node_modules/zod/v4-mini/index.cjs +32 -0
  929. package/node_modules/zod/v4-mini/index.d.cts +3 -0
  930. package/node_modules/zod/v4-mini/index.d.ts +3 -0
  931. package/node_modules/zod/v4-mini/index.js +3 -0
  932. package/node_modules/zod/v4-mini/package.json +7 -0
  933. package/package.json +69 -0
@@ -0,0 +1,3097 @@
1
+ import { takeSnapshot, getElementRef, resetRefs, } from "./snapshot.js";
2
+ import { pasteText, humanType, humanMove, humanDrag, } from "./humanize.js";
3
+ import { normalizeSelector } from "./selectors.js";
4
+ import { preflightEvaluateScript, wrapEvaluateScript } from "./dom-helpers.js";
5
+ import { safeSliceHead, safeSliceTail } from "../utils/safe-slice.js";
6
+ import { resolveSelector, locateRefWithRecovery, looksDestructive, refNotFoundMessage, } from "./locator-resolver.js";
7
+ import { cleanupRunHandled, runBuiltinPageCleanups, } from "./builtin-page-cleanups.js";
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import crypto from "node:crypto";
11
+ const DEFAULT_ACTION_DELAY = { min: 800, max: 3000 };
12
+ const MAX_CONSOLE_MESSAGES = 1000;
13
+ // Track which pages already have a console listener
14
+ const trackedPages = new WeakSet();
15
+ // Per-page console buffer
16
+ const consoleBuffers = new WeakMap();
17
+ function ensureConsoleCapture(page) {
18
+ if (trackedPages.has(page))
19
+ return;
20
+ trackedPages.add(page);
21
+ const buffer = [];
22
+ consoleBuffers.set(page, buffer);
23
+ page.on("console", (msg) => {
24
+ buffer.push({
25
+ type: msg.type(),
26
+ text: msg.text(),
27
+ timestamp: new Date().toISOString(),
28
+ });
29
+ if (buffer.length > MAX_CONSOLE_MESSAGES) {
30
+ buffer.shift();
31
+ }
32
+ });
33
+ // Uncaught exceptions (React reconciliation crashes etc.) come through
34
+ // pageerror, not console. Capture them in the same buffer so the
35
+ // type-action failure dump can surface them.
36
+ page.on("pageerror", (err) => {
37
+ buffer.push({
38
+ type: "pageerror",
39
+ text: err.message,
40
+ timestamp: new Date().toISOString(),
41
+ });
42
+ if (buffer.length > MAX_CONSOLE_MESSAGES) {
43
+ buffer.shift();
44
+ }
45
+ });
46
+ }
47
+ /**
48
+ * Recent console / pageerror messages, newest last. For failure diagnostics.
49
+ */
50
+ function recentConsoleEntries(page, n) {
51
+ const buf = consoleBuffers.get(page);
52
+ if (!buf || buf.length === 0)
53
+ return [];
54
+ return buf.slice(-n);
55
+ }
56
+ // refNotFoundMessage moved to ./locator-resolver.
57
+ /**
58
+ * Tag we stamp on the editable element we ultimately focus, so the
59
+ * post-insertion verifier can read the same node back without depending on
60
+ * `document.activeElement` (which loses focus when the verifier itself
61
+ * does anything that ticks the event loop). Cleared on snapshot reset.
62
+ */
63
+ const EDIT_TARGET_ATTR = "data-dipclaw-edit-target";
64
+ /**
65
+ * After clicking the resolved locator to focus it, make sure we actually
66
+ * landed on an editable node. If not, search the original locator's subtree
67
+ * for a single editable descendant and focus that instead.
68
+ *
69
+ * Stamps `EDIT_TARGET_ATTR` on whatever we end up focusing so the verifier
70
+ * can read the same node back regardless of subsequent focus changes
71
+ * (clicking outside the editor for any reason, snapshot taking focus, etc.).
72
+ */
73
+ async function ensureEditableTarget(page, locator) {
74
+ const result = await locator.first().evaluate((root, attr) => {
75
+ // Arrow form (not `function describe()`) is intentional: tsx/esbuild
76
+ // wraps named function declarations with __name() to preserve
77
+ // Function.name. When this body is serialized for Playwright
78
+ // evaluate, the page context has no __name binding and the whole
79
+ // call throws ReferenceError. Same goes for the other inline
80
+ // helpers below — keep them all as const arrows.
81
+ const describe = (node) => {
82
+ const tag = node.tagName.toLowerCase();
83
+ const role = node.getAttribute("role");
84
+ const editable = node.isContentEditable;
85
+ return `<${tag}${role ? ` role=${role}` : ""}${editable ? " editable" : ""}>`;
86
+ };
87
+ const isEditable = (node) => {
88
+ const tag = node.tagName.toLowerCase();
89
+ if (tag === "input") {
90
+ const t = node.type.toLowerCase();
91
+ return ![
92
+ "button",
93
+ "submit",
94
+ "reset",
95
+ "checkbox",
96
+ "radio",
97
+ "file",
98
+ "image",
99
+ "hidden",
100
+ "range",
101
+ "color",
102
+ ].includes(t);
103
+ }
104
+ if (tag === "textarea")
105
+ return true;
106
+ if (node.isContentEditable)
107
+ return true;
108
+ if (node.getAttribute("role") === "textbox")
109
+ return true;
110
+ return false;
111
+ };
112
+ const isRich = (node) => {
113
+ if (node.isContentEditable)
114
+ return true;
115
+ const tag = node.tagName.toLowerCase();
116
+ if (tag === "input" || tag === "textarea")
117
+ return false;
118
+ if (node.matches('[data-lexical-editor],.ProseMirror,.tiptap,[contenteditable="true"]')) {
119
+ return true;
120
+ }
121
+ return false;
122
+ };
123
+ const root_ = root;
124
+ // Clear any stale stamp on the document — only one edit target at a time.
125
+ document
126
+ .querySelectorAll(`[${attr}]`)
127
+ .forEach((n) => n.removeAttribute(attr));
128
+ let target = null;
129
+ let diag = describe(root_);
130
+ if (isEditable(root_)) {
131
+ target = root_;
132
+ }
133
+ else {
134
+ // Look for editable descendants. Strict policy: only pick one when
135
+ // there's EXACTLY one match. Multiple matches are ambiguous —
136
+ // typing into the wrong field (e.g. a generic <body> selector
137
+ // landing on the page's search box) is a worse failure mode than
138
+ // returning an error. Caller is told which descendants we found
139
+ // so the LLM can pick a more precise selector and retry.
140
+ const candidates = Array.from(root_.querySelectorAll("*")).filter((n) => isEditable(n));
141
+ if (candidates.length === 1) {
142
+ target = candidates[0];
143
+ diag = `${describe(root_)} → descendant ${describe(target)}`;
144
+ }
145
+ else if (candidates.length > 1) {
146
+ const top = candidates.slice(0, 5).map((n) => describe(n));
147
+ return {
148
+ ok: false,
149
+ message: `resolved target ${describe(root_)} contains ${candidates.length} ` +
150
+ `editable descendants — refusing to guess which one to type into. ` +
151
+ `Found: ${top.join(", ")}${candidates.length > 5 ? ", ..." : ""}. ` +
152
+ `Pass a more specific selector/ref pointing at the editable directly.`,
153
+ diagnostic: describe(root_),
154
+ };
155
+ }
156
+ }
157
+ if (!target) {
158
+ // Last resort: maybe a click already shifted focus into an editor
159
+ // sibling/portal (Lexical spawns the editable in a portal, etc.).
160
+ const active = document.activeElement;
161
+ if (active && active !== document.body && isEditable(active)) {
162
+ target = active;
163
+ diag = `${describe(root_)} → activeElement ${describe(active)}`;
164
+ }
165
+ }
166
+ if (!target) {
167
+ return {
168
+ ok: false,
169
+ message: `resolved target ${describe(root_)} is not editable and contains no editable descendant`,
170
+ diagnostic: describe(root_),
171
+ };
172
+ }
173
+ target.setAttribute(attr, "1");
174
+ // Focus the editable. A second focus() is a no-op on the host page
175
+ // when it's already focused; cheap insurance for the wrapper case.
176
+ try {
177
+ target.focus({ preventScroll: false });
178
+ }
179
+ catch {
180
+ // Some elements (e.g. non-tabbable contenteditable hosts) reject
181
+ // focus() — Playwright's click already pointed the user at it,
182
+ // which produces a real focus event. Ignore.
183
+ }
184
+ return {
185
+ ok: true,
186
+ isRichEditor: isRich(target),
187
+ diagnostic: diag,
188
+ };
189
+ }, EDIT_TARGET_ATTR);
190
+ if (!result.ok) {
191
+ return { ok: false, message: result.message, diagnostic: result.diagnostic };
192
+ }
193
+ return {
194
+ ok: true,
195
+ handleSelector: `[${EDIT_TARGET_ATTR}="1"]`,
196
+ isRichEditor: result.isRichEditor === true,
197
+ diagnostic: result.diagnostic,
198
+ };
199
+ }
200
+ async function insertText(page, method, text) {
201
+ if (method === "paste") {
202
+ await pasteText(page, text);
203
+ }
204
+ else {
205
+ await humanType(page, text);
206
+ }
207
+ }
208
+ /**
209
+ * Empty the editable's contents reliably across plain inputs and
210
+ * framework-controlled rich editors.
211
+ *
212
+ * Plain <input>/<textarea>: write "" through the prototype's native value
213
+ * setter (same React-tracker bypass `pasteText` uses) and emit input+change.
214
+ * No keystroke needed.
215
+ *
216
+ * Rich editor (contenteditable / Draft.js / Lexical / ProseMirror): focus
217
+ * the editable, then press Cmd+A + Delete via real CDP keystrokes. Cmd+A
218
+ * dispatches keydown to the editor's own keybinding handler, which
219
+ * synchronously sets the editor's INTERNAL selection state to "all
220
+ * blocks". The follow-up Delete then reads that selection and deletes
221
+ * everything through the framework's standard input pipeline.
222
+ *
223
+ * Why not Selection API: an earlier implementation set
224
+ * `window.getSelection()` via `selectNodeContents()` then pressed Delete.
225
+ * That fails on Draft.js because Draft.js maintains its OWN SelectionState
226
+ * (decoupled from window.getSelection()), only synced via the async
227
+ * `selectionchange` event. By the time Delete's `beforeinput` reaches
228
+ * Draft.js, the internal SelectionState is still the pre-clear caret
229
+ * position, so Delete only removes one character (or nothing). The next
230
+ * paste then appends to the stale content, producing "duplicated" in
231
+ * the verifier. Cmd+A goes through the editor's keydown handler
232
+ * synchronously and updates the internal selection correctly.
233
+ *
234
+ * Caller must ensure blocking modal overlays are closed so the Cmd+A
235
+ * keystroke reaches the editor instead of being trapped by a dialog.
236
+ */
237
+ async function forceClear(page, handleSelector) {
238
+ await runBuiltinPageCleanups(page, "before-edit");
239
+ const handled = await page.evaluate((sel) => {
240
+ const el = document.querySelector(sel);
241
+ if (!el)
242
+ return false;
243
+ try {
244
+ el.focus({ preventScroll: false });
245
+ }
246
+ catch {
247
+ // Non-tabbable contenteditable: ignore, the caller's click already
248
+ // focused it.
249
+ }
250
+ const tag = el.tagName;
251
+ if (tag === "INPUT" || tag === "TEXTAREA") {
252
+ const input = el;
253
+ const proto = tag === "INPUT"
254
+ ? HTMLInputElement.prototype
255
+ : HTMLTextAreaElement.prototype;
256
+ const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
257
+ if (setter) {
258
+ setter.call(input, "");
259
+ }
260
+ else {
261
+ input.value = "";
262
+ }
263
+ input.dispatchEvent(new InputEvent("input", {
264
+ bubbles: true,
265
+ inputType: "deleteContentBackward",
266
+ }));
267
+ input.dispatchEvent(new Event("change", { bubbles: true }));
268
+ return true;
269
+ }
270
+ return false;
271
+ }, handleSelector);
272
+ if (handled)
273
+ return;
274
+ const mod = process.platform === "darwin" ? "Meta" : "Control";
275
+ await page.keyboard.press(`${mod}+a`);
276
+ // Small gap so the editor's keybinding has committed select-all into its
277
+ // internal selection state before Delete reads it.
278
+ await new Promise((r) => setTimeout(r, 30));
279
+ await page.keyboard.press("Delete");
280
+ // Let the framework's reducer + React commit actually remove the content
281
+ // from the DOM before the next insert runs on top of it.
282
+ await new Promise((r) => setTimeout(r, 100));
283
+ }
284
+ async function dumpEditorDiagnostics(page, handleSelector, expectedText) {
285
+ return await page.evaluate(({ sel, expected }) => {
286
+ const all = document.querySelectorAll(sel);
287
+ const el = all[0];
288
+ // Inline mirror of normalizeForCompare. Use \u escapes (not literal
289
+ // chars) so TS source parser doesn't trip on U+2028/U+2029 which
290
+ // are line terminators in ECMAScript syntax even inside a string.
291
+ const norm = (s) => s
292
+ .normalize("NFC")
293
+ .replace(/[\u200B-\u200D\uFEFF]/g, "")
294
+ .replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g, " ")
295
+ .replace(/[\u2028\u2029]/g, "\n")
296
+ .replace(/\r\n?/g, "\n")
297
+ .replace(/[ \t]+/g, " ")
298
+ .replace(/[ \t]*\n[ \t]*/g, "\n")
299
+ .replace(/\n{3,}/g, "\n\n")
300
+ .trim();
301
+ if (!el) {
302
+ return {
303
+ readSelector: sel,
304
+ resolvedTag: "(missing)",
305
+ resolvedClass: "",
306
+ resolvedRole: null,
307
+ isContentEditable: false,
308
+ fullInnerText: "",
309
+ innerTextLength: 0,
310
+ outerHtmlSnippet: "",
311
+ outerHtmlLength: 0,
312
+ matchOffsets: [],
313
+ blockCount: 0,
314
+ multipleMatches: false,
315
+ };
316
+ }
317
+ const innerText = el.innerText ?? "";
318
+ const innerTextNorm = norm(innerText);
319
+ const expectedNorm = norm(expected);
320
+ const offsets = [];
321
+ if (expectedNorm.length > 0) {
322
+ let from = 0;
323
+ while (true) {
324
+ const i = innerTextNorm.indexOf(expectedNorm, from);
325
+ if (i === -1)
326
+ break;
327
+ offsets.push(i);
328
+ if (offsets.length >= 5)
329
+ break;
330
+ from = i + expectedNorm.length;
331
+ }
332
+ }
333
+ const html = el.outerHTML ?? "";
334
+ return {
335
+ readSelector: sel,
336
+ resolvedTag: el.tagName.toLowerCase(),
337
+ resolvedClass: el.className || "",
338
+ resolvedRole: el.getAttribute("role"),
339
+ isContentEditable: el.isContentEditable,
340
+ fullInnerText: innerText,
341
+ innerTextLength: innerText.length,
342
+ outerHtmlSnippet: html.slice(0, 1500),
343
+ outerHtmlLength: html.length,
344
+ matchOffsets: offsets,
345
+ blockCount: el.querySelectorAll("[data-block='true']").length,
346
+ multipleMatches: all.length > 1,
347
+ };
348
+ }, { sel: handleSelector, expected: expectedText });
349
+ }
350
+ /**
351
+ * Normalize text for comparison. Deliberately narrow: only changes that the
352
+ * browser/site reliably normalizes regardless of content. Smart quotes,
353
+ * em-dashes, ellipses are content-meaningful and intentionally preserved
354
+ * — if the user typed them, the verifier should detect when they got
355
+ * dropped, not silently paper over the difference.
356
+ */
357
+ export function normalizeForCompare(s) {
358
+ return s
359
+ .normalize("NFC")
360
+ // zero-width: ZWSP, ZWNJ, ZWJ, BOM
361
+ .replace(/[\u200B-\u200D\uFEFF]/g, "")
362
+ // non-breaking & exotic spaces → regular space.
363
+ // NBSP, EN/EM-class spaces (2000-200A), narrow NBSP, medium math space, ideographic space.
364
+ .replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g, " ")
365
+ // line separator (2028) / paragraph separator (2029) → LF.
366
+ .replace(/[\u2028\u2029]/g, "\n")
367
+ // CRLF / CR → LF
368
+ .replace(/\r\n?/g, "\n")
369
+ // collapse runs of horizontal whitespace
370
+ .replace(/[ \t]+/g, " ")
371
+ // trim per-line horizontal whitespace
372
+ .replace(/[ \t]*\n[ \t]*/g, "\n")
373
+ // collapse 3+ blank lines to 2
374
+ .replace(/\n{3,}/g, "\n\n")
375
+ .trim();
376
+ }
377
+ const URL_REGEX = /\bhttps?:\/\/[^\s<>'"`)\]}]+/gi;
378
+ // Trailing punctuation that almost certainly isn't part of the URL itself
379
+ // (a sentence break that ran into the URL). Stripped post-match because
380
+ // putting these in the URL regex's exclusion class would also exclude them
381
+ // mid-URL where they're valid (paths, queries).
382
+ const URL_TRAILING_TRIM = /[,.;:!?]+$/;
383
+ export function extractUrls(s) {
384
+ const out = s.match(URL_REGEX);
385
+ if (!out)
386
+ return [];
387
+ return Array.from(new Set(out.map((u) => u.replace(URL_TRAILING_TRIM, ""))));
388
+ }
389
+ export function urlKey(u) {
390
+ try {
391
+ const url = new URL(u);
392
+ return {
393
+ host: url.host.toLowerCase().replace(/^www\./, ""),
394
+ pathKey: url.pathname.replace(/\/+$/, ""),
395
+ raw: u,
396
+ };
397
+ }
398
+ catch {
399
+ return null;
400
+ }
401
+ }
402
+ /**
403
+ * Read the editable's current value and any anchor hrefs inside it (rich
404
+ * editors only). Returned as raw strings; normalization is the caller's job.
405
+ */
406
+ async function readEditable(page, handleSelector) {
407
+ return page.locator(handleSelector).first().evaluate((el) => {
408
+ if (el instanceof HTMLInputElement ||
409
+ el instanceof HTMLTextAreaElement) {
410
+ return { value: el.value, anchors: [] };
411
+ }
412
+ const he = el;
413
+ const value = he.innerText ?? he.textContent ?? "";
414
+ const anchors = Array.from(he.querySelectorAll("a[href]"))
415
+ .map((a) => a.href)
416
+ .filter((h) => !!h);
417
+ return { value, anchors };
418
+ });
419
+ }
420
+ /**
421
+ * One-shot evaluation of expected vs actual. Pure function over the
422
+ * already-read snapshot (no DOM access), so the polling loop can iterate
423
+ * cheaply.
424
+ */
425
+ export function evaluateMatch(expectedText, expectedUrls, value, anchorHrefs) {
426
+ const expectedTextOnly = normalizeForCompare(expectedText.replace(URL_REGEX, " ")).trim();
427
+ const valueNorm = normalizeForCompare(value);
428
+ // Body check. Empty expected body (text was all URLs) → skip body check.
429
+ let bodyOk = true;
430
+ let missingChunks;
431
+ if (expectedTextOnly.length > 0) {
432
+ bodyOk = valueNorm.includes(expectedTextOnly);
433
+ if (!bodyOk) {
434
+ // Diagnostic: split expected into newline-paragraphs and call out
435
+ // which ones aren't present.
436
+ const chunks = expectedTextOnly
437
+ .split(/\n\n+/)
438
+ .map((c) => c.trim())
439
+ .filter((c) => c.length > 0);
440
+ missingChunks = chunks.filter((c) => !valueNorm.includes(c));
441
+ if (missingChunks.length === 0) {
442
+ // Whole thing missing but every paragraph matches individually:
443
+ // ordering or interleaving issue. Report whole expected as missing.
444
+ missingChunks = [expectedTextOnly];
445
+ }
446
+ }
447
+ }
448
+ // Duplicate detection: same expected body appears 2+ times. Common when
449
+ // clear failed and retry stacked content on top of the previous attempt.
450
+ // Only meaningful when body is present and non-trivial.
451
+ if (bodyOk && expectedTextOnly.length >= 8) {
452
+ const first = valueNorm.indexOf(expectedTextOnly);
453
+ const second = valueNorm.indexOf(expectedTextOnly, first + expectedTextOnly.length);
454
+ if (second !== -1) {
455
+ return {
456
+ ok: false,
457
+ status: "duplicated",
458
+ lastValue: value,
459
+ };
460
+ }
461
+ }
462
+ if (!bodyOk) {
463
+ return {
464
+ ok: false,
465
+ status: "missing_text",
466
+ lastValue: value,
467
+ missingChunks,
468
+ expectedUrls: expectedUrls.map((u) => u.raw),
469
+ };
470
+ }
471
+ // URL check (best-effort).
472
+ if (expectedUrls.length === 0) {
473
+ return { ok: true, status: "ok", lastValue: value };
474
+ }
475
+ const anchorKeys = anchorHrefs
476
+ .map(urlKey)
477
+ .filter((k) => k !== null);
478
+ const foundUrls = [];
479
+ const missingUrls = [];
480
+ for (const expected of expectedUrls) {
481
+ // Match path 1: URL appears literally in the editable's text (often
482
+ // true before async link-card rewrite, or in plain textareas).
483
+ if (valueNorm.includes(expected.raw)) {
484
+ foundUrls.push(expected.raw);
485
+ continue;
486
+ }
487
+ // Match path 2: an <a href> inside the editable has the same
488
+ // host + path (ignoring scheme, www, trailing slash, query, fragment).
489
+ // Deliberately NOT special-casing any shortener (t.co / bit.ly / lnkd.in
490
+ // etc.) — host-level rewrite is exactly the case we report as a
491
+ // best-effort uncertainty rather than silently treating as success.
492
+ const hit = anchorKeys.some((a) => a.host === expected.host && a.pathKey === expected.pathKey);
493
+ if (hit) {
494
+ foundUrls.push(expected.raw);
495
+ continue;
496
+ }
497
+ missingUrls.push(expected.raw);
498
+ }
499
+ if (missingUrls.length === 0) {
500
+ return {
501
+ ok: true,
502
+ status: "ok",
503
+ lastValue: value,
504
+ expectedUrls: expectedUrls.map((u) => u.raw),
505
+ foundUrls,
506
+ };
507
+ }
508
+ // URL-only insert (no non-URL body to anchor on): the URL is the entire
509
+ // signal, so a missing URL is a hard failure, not a warning. Body-with-URL
510
+ // can soft-pass on URL-not-visible because we still confirmed body landed,
511
+ // but here there is no body — empty editable + missing URL means nothing
512
+ // landed.
513
+ if (expectedTextOnly.length === 0) {
514
+ return {
515
+ ok: false,
516
+ status: "missing_text",
517
+ lastValue: value,
518
+ missingChunks: missingUrls,
519
+ expectedUrls: expectedUrls.map((u) => u.raw),
520
+ foundUrls,
521
+ missingUrls,
522
+ };
523
+ }
524
+ return {
525
+ ok: true,
526
+ status: "ok_url_warning",
527
+ lastValue: value,
528
+ expectedUrls: expectedUrls.map((u) => u.raw),
529
+ foundUrls,
530
+ missingUrls,
531
+ };
532
+ }
533
+ /**
534
+ * Verify text landed in the editable. Bounded-poll wrapper around
535
+ * {@link evaluateMatch}: rich editors (Lexical/ProseMirror/Tiptap, link-card
536
+ * rewriters, SPAs that re-render on input) often need a few hundred ms
537
+ * before the DOM settles. Poll, exit as soon as we see a definitive
538
+ * outcome, return the most-informative result on timeout.
539
+ *
540
+ * Definitive (early-exit) outcomes:
541
+ * - status="ok" — clean match, no reason to wait
542
+ * - status="duplicated" — extra polling won't unduplicate
543
+ *
544
+ * Non-definitive (keep polling within deadline):
545
+ * - status="missing_text" — body may still be rendering
546
+ * - status="ok_url_warning" — link card may still be materializing
547
+ */
548
+ async function verifyInsertedText(handleSelector, page, text, opts = {}) {
549
+ if (!handleSelector || text === "") {
550
+ return { ok: true, status: "ok", lastValue: "" };
551
+ }
552
+ const expectedUrls = extractUrls(text)
553
+ .map(urlKey)
554
+ .filter((k) => k !== null);
555
+ // Microtask flush before first read. Draft.js / Lexical / ProseMirror
556
+ // all commit EditorState changes via React's reducer pipeline, which is
557
+ // asynchronous — execCommand('insertText') / a real keystroke synchronously
558
+ // fires beforeinput, but the DOM doesn't reflect the change until React's
559
+ // next commit phase (typically tens of ms; can stretch to hundreds when
560
+ // the page is busy closing a modal / animating). Reading the DOM at
561
+ // t≈0 causes a false-negative loop that triggers the alt-method fallback
562
+ // on top of content that DID land — that's the duplicated-text bug we
563
+ // see in production logs. 100ms is short enough not to slow the success
564
+ // path meaningfully, long enough to cover normal React commits.
565
+ await new Promise((r) => setTimeout(r, 100));
566
+ const deadline = Date.now() + (opts.timeoutMs ?? 800);
567
+ let last = {
568
+ ok: false,
569
+ status: "error",
570
+ lastValue: "",
571
+ message: "verifier did not run",
572
+ };
573
+ while (true) {
574
+ try {
575
+ const { value, anchors } = await readEditable(page, handleSelector);
576
+ const result = evaluateMatch(text, expectedUrls, value, anchors);
577
+ last = result;
578
+ if (result.status === "ok" || result.status === "duplicated") {
579
+ return result;
580
+ }
581
+ }
582
+ catch (err) {
583
+ last = {
584
+ ok: false,
585
+ status: "error",
586
+ lastValue: "",
587
+ message: err instanceof Error ? err.message : String(err),
588
+ };
589
+ }
590
+ if (Date.now() >= deadline)
591
+ return last;
592
+ await new Promise((r) => setTimeout(r, 100));
593
+ }
594
+ }
595
+ function summarizeVerifyForError(v) {
596
+ const preview = v.lastValue
597
+ ? JSON.stringify(v.lastValue.length > 200
598
+ ? v.lastValue.slice(0, 200) + "…"
599
+ : v.lastValue)
600
+ : '""';
601
+ switch (v.status) {
602
+ case "missing_text": {
603
+ const miss = v.missingChunks?.length
604
+ ? ` Missing: ${v.missingChunks.map((c) => JSON.stringify(c.slice(0, 80))).join(", ")}.`
605
+ : "";
606
+ return `insertion not visible after settle.${miss} Last seen: ${preview}.`;
607
+ }
608
+ case "duplicated":
609
+ return `text appears more than once (clear/retry stacked content). Last seen: ${preview}.`;
610
+ case "error":
611
+ return `verifier error: ${v.message ?? "unknown"}. Last seen: ${preview}.`;
612
+ case "ok_url_warning":
613
+ // Not a hard fail — caller decides how to surface. Kept for symmetry.
614
+ return `body matched but URL(s) not visible in editable: ${v.missingUrls?.join(", ") ?? ""}. Last seen: ${preview}.`;
615
+ case "ok":
616
+ return `ok. Last seen: ${preview}.`;
617
+ }
618
+ }
619
+ /**
620
+ * Pre-flight check for a ref-backed locator. Our in-memory ref map can still
621
+ * return a hit (role+name pair) after the underlying DOM node is gone
622
+ * (e.g. click triggered SPA nav, React replaced the node on focus). Playwright
623
+ * surfaces the mismatch as a generic "Timeout exceeded" after 5s, which is
624
+ * slow and uninformative — so we check accessibility-tree presence first and
625
+ * return the lifecycle message immediately when the node is missing.
626
+ */
627
+ async function resolveRefOrError(locator, ref, label = "element", selectorParam = "selector") {
628
+ try {
629
+ if ((await locator.count()) === 0) {
630
+ return refNotFoundMessage(ref, label, selectorParam);
631
+ }
632
+ }
633
+ catch {
634
+ return refNotFoundMessage(ref, label, selectorParam);
635
+ }
636
+ return null;
637
+ }
638
+ /* -------------------------------------------------------------------------- */
639
+ /* Generic safe click helpers */
640
+ /* -------------------------------------------------------------------------- */
641
+ const CLICK_TARGET_ATTR = "data-dipclaw-click-target";
642
+ function anyCleanupHandled(runs) {
643
+ return runs.some(cleanupRunHandled);
644
+ }
645
+ function makeClickStamp() {
646
+ return `dipclaw-${Date.now().toString(36)}-${Math.random()
647
+ .toString(36)
648
+ .slice(2)}`;
649
+ }
650
+ function clickStampSelector(stamp) {
651
+ return `[${CLICK_TARGET_ATTR}=${JSON.stringify(stamp)}]`;
652
+ }
653
+ function describeHitTarget(probe) {
654
+ const tag = probe.hitTag ?? "(none)";
655
+ const testid = probe.hitTestid ? ` data-testid=${JSON.stringify(probe.hitTestid)}` : "";
656
+ const cls = probe.hitClass && probe.hitClass.length <= 80
657
+ ? ` class=${JSON.stringify(probe.hitClass)}`
658
+ : "";
659
+ return `<${tag}${testid}${cls}>`;
660
+ }
661
+ function describeClickEventTarget(probe) {
662
+ const tag = probe.clickTargetTag ?? "(none)";
663
+ const role = probe.clickTargetRole
664
+ ? ` role=${JSON.stringify(probe.clickTargetRole)}`
665
+ : "";
666
+ const aria = probe.clickTargetAriaLabel
667
+ ? ` aria-label=${JSON.stringify(probe.clickTargetAriaLabel)}`
668
+ : "";
669
+ return `<${tag}${role}${aria}>`;
670
+ }
671
+ async function stampClickTarget(locator, stamp) {
672
+ await locator.first().evaluate((el, args) => {
673
+ document
674
+ .querySelectorAll(`[${args.attr}]`)
675
+ .forEach((n) => n.removeAttribute(args.attr));
676
+ el.setAttribute(args.attr, args.stamp);
677
+ }, { attr: CLICK_TARGET_ATTR, stamp });
678
+ }
679
+ async function clearClickTargetStamps(page) {
680
+ await page
681
+ .evaluate((attr) => {
682
+ document
683
+ .querySelectorAll(`[${attr}]`)
684
+ .forEach((n) => n.removeAttribute(attr));
685
+ }, CLICK_TARGET_ATTR)
686
+ .catch(() => { });
687
+ }
688
+ async function probeClickTarget(page, selector) {
689
+ return await page.evaluate((sel) => {
690
+ const el = document.querySelector(sel);
691
+ if (!el)
692
+ return { found: false, reason: "not-found" };
693
+ const he = el;
694
+ if (!document.body.contains(he)) {
695
+ return { found: false, reason: "detached" };
696
+ }
697
+ if ("disabled" in he && he.disabled) {
698
+ return { found: false, reason: "disabled" };
699
+ }
700
+ if (he.getAttribute("aria-disabled") === "true") {
701
+ return { found: false, reason: "disabled" };
702
+ }
703
+ const r = he.getBoundingClientRect();
704
+ if (r.width === 0 || r.height === 0) {
705
+ return { found: false, reason: "zero-size" };
706
+ }
707
+ if (r.bottom <= 0 ||
708
+ r.right <= 0 ||
709
+ r.top >= window.innerHeight ||
710
+ r.left >= window.innerWidth) {
711
+ return { found: false, reason: "off-screen" };
712
+ }
713
+ const x = r.left + r.width * (0.4 + Math.random() * 0.2);
714
+ const y = r.top + r.height * (0.4 + Math.random() * 0.2);
715
+ const hit = document.elementFromPoint(x, y);
716
+ const onTarget = !!hit && (hit === he || he.contains(hit));
717
+ return {
718
+ found: true,
719
+ x,
720
+ y,
721
+ onTarget,
722
+ hitTag: hit?.tagName.toLowerCase() ?? "(none)",
723
+ hitClass: typeof hit?.className === "string" ? hit.className : "",
724
+ hitTestid: hit?.getAttribute?.("data-testid") ?? null,
725
+ targetTag: he.tagName.toLowerCase(),
726
+ targetRole: he.getAttribute("role"),
727
+ targetAriaLabel: he.getAttribute("aria-label"),
728
+ };
729
+ }, selector);
730
+ }
731
+ async function installClickEventProbe(page, selector, probeId) {
732
+ await page.evaluate(({ sel, id }) => {
733
+ const target = document.querySelector(sel);
734
+ const w = window;
735
+ w.__dipclawClickProbes ??= {};
736
+ const state = {
737
+ pointerdownOnTarget: false,
738
+ pointerupOnTarget: false,
739
+ clickOnTarget: false,
740
+ trustedClickOnTarget: false,
741
+ };
742
+ const controller = new AbortController();
743
+ document.addEventListener("pointerdown", (event) => {
744
+ state.pointerdownOnTarget ||=
745
+ !!target && event.composedPath().includes(target);
746
+ }, { capture: true, signal: controller.signal });
747
+ document.addEventListener("pointerup", (event) => {
748
+ state.pointerupOnTarget ||=
749
+ !!target && event.composedPath().includes(target);
750
+ }, { capture: true, signal: controller.signal });
751
+ document.addEventListener("click", (event) => {
752
+ const onTarget = !!target && event.composedPath().includes(target);
753
+ state.clickOnTarget ||= onTarget;
754
+ state.trustedClickOnTarget ||= onTarget && event.isTrusted;
755
+ const el = event.target;
756
+ state.clickTargetTag = el?.tagName.toLowerCase();
757
+ state.clickTargetRole = el?.getAttribute?.("role") ?? null;
758
+ state.clickTargetAriaLabel = el?.getAttribute?.("aria-label") ?? null;
759
+ }, { capture: true, signal: controller.signal });
760
+ w.__dipclawClickProbes[id] = {
761
+ state,
762
+ controller,
763
+ };
764
+ }, { sel: selector, id: probeId });
765
+ }
766
+ async function readAndClearClickEventProbe(page, probeId) {
767
+ return await page.evaluate((id) => {
768
+ const w = window;
769
+ const probe = w.__dipclawClickProbes?.[id];
770
+ if (!probe)
771
+ return undefined;
772
+ probe.controller?.abort();
773
+ delete w.__dipclawClickProbes?.[id];
774
+ return probe.state;
775
+ }, probeId);
776
+ }
777
+ async function installHoverEventProbe(page, selector, probeId) {
778
+ await page.evaluate(({ sel, id }) => {
779
+ const target = document.querySelector(sel);
780
+ const w = window;
781
+ w.__dipclawHoverProbes ??= {};
782
+ const state = {
783
+ pointeroverOnTarget: false,
784
+ pointerenterOnTarget: false,
785
+ mouseoverOnTarget: false,
786
+ mouseenterOnTarget: false,
787
+ mousemoveOnTarget: false,
788
+ };
789
+ const controller = new AbortController();
790
+ const mark = (key) => (event) => {
791
+ state[key] ||= !!target && event.composedPath().includes(target);
792
+ };
793
+ document.addEventListener("pointerover", mark("pointeroverOnTarget"), {
794
+ capture: true,
795
+ signal: controller.signal,
796
+ });
797
+ // pointerenter doesn't bubble; listen at target if present, else skip.
798
+ // We still listen on document with capture for the rare browsers that
799
+ // dispatch it that way; main read still works because we check
800
+ // composedPath, which on a non-bubbling event contains only the target.
801
+ document.addEventListener("pointerenter", mark("pointerenterOnTarget"), {
802
+ capture: true,
803
+ signal: controller.signal,
804
+ });
805
+ document.addEventListener("mouseover", mark("mouseoverOnTarget"), {
806
+ capture: true,
807
+ signal: controller.signal,
808
+ });
809
+ document.addEventListener("mouseenter", mark("mouseenterOnTarget"), {
810
+ capture: true,
811
+ signal: controller.signal,
812
+ });
813
+ document.addEventListener("mousemove", mark("mousemoveOnTarget"), {
814
+ capture: true,
815
+ signal: controller.signal,
816
+ });
817
+ w.__dipclawHoverProbes[id] = { state, controller };
818
+ }, { sel: selector, id: probeId });
819
+ }
820
+ async function readAndClearHoverEventProbe(page, probeId) {
821
+ return await page.evaluate((id) => {
822
+ const w = window;
823
+ const probe = w.__dipclawHoverProbes?.[id];
824
+ if (!probe)
825
+ return undefined;
826
+ probe.controller?.abort();
827
+ delete w.__dipclawHoverProbes?.[id];
828
+ return probe.state;
829
+ }, probeId);
830
+ }
831
+ function hoverEventReachedTarget(probe) {
832
+ // Any of these means React-style hover handlers had a chance to fire.
833
+ // mouseover is the one React relies on for synthetic onMouseEnter.
834
+ return (probe.mouseoverOnTarget ||
835
+ probe.mouseenterOnTarget ||
836
+ probe.pointeroverOnTarget ||
837
+ probe.pointerenterOnTarget);
838
+ }
839
+ async function evaluateDomHover(page, selector) {
840
+ return await page.evaluate((sel) => {
841
+ const el = document.querySelector(sel);
842
+ if (!el)
843
+ return { ok: false, reason: "not-found" };
844
+ if (!document.body.contains(el))
845
+ return { ok: false, reason: "detached" };
846
+ const style = window.getComputedStyle(el);
847
+ if (style.display === "none" || style.visibility === "hidden") {
848
+ return { ok: false, reason: "not-visible" };
849
+ }
850
+ const rect = el.getBoundingClientRect();
851
+ const cx = rect.left + rect.width / 2;
852
+ const cy = rect.top + rect.height / 2;
853
+ const mk = (type, Ctor, extra = {}) => new Ctor(type, {
854
+ bubbles: type !== "mouseenter" && type !== "pointerenter",
855
+ cancelable: true,
856
+ view: window,
857
+ clientX: cx,
858
+ clientY: cy,
859
+ button: 0,
860
+ ...extra,
861
+ });
862
+ // Order mirrors what a real mouse traversal would dispatch:
863
+ // pointerover → pointerenter → mouseover → mouseenter → mousemove.
864
+ // React onMouseEnter delegates from native `mouseover`, so this triggers
865
+ // X.com's hover-card fetch the same way a physical hover would.
866
+ el.dispatchEvent(mk("pointerover", PointerEvent, { pointerType: "mouse" }));
867
+ el.dispatchEvent(mk("pointerenter", PointerEvent, { pointerType: "mouse" }));
868
+ el.dispatchEvent(mk("mouseover", MouseEvent));
869
+ el.dispatchEvent(mk("mouseenter", MouseEvent));
870
+ el.dispatchEvent(mk("mousemove", MouseEvent));
871
+ return { ok: true };
872
+ }, selector);
873
+ }
874
+ async function installKeyEventProbe(page, probeId) {
875
+ await page.evaluate((id) => {
876
+ const w = window;
877
+ w.__dipclawKeyProbes ??= {};
878
+ const state = {
879
+ keydownFired: false,
880
+ keyupFired: false,
881
+ };
882
+ const controller = new AbortController();
883
+ // "any keydown during the window" is a sufficient signal that CDP
884
+ // delivered the key to the renderer — modifier combos like "Control+A"
885
+ // produce multiple keydowns, so don't try to match a specific key here.
886
+ document.addEventListener("keydown", (e) => {
887
+ if (!state.keydownFired) {
888
+ state.keydownFired = true;
889
+ state.keydownKey = e.key;
890
+ const el = e.target;
891
+ state.keydownTargetTag = el?.tagName?.toLowerCase();
892
+ }
893
+ }, { capture: true, signal: controller.signal });
894
+ document.addEventListener("keyup", () => {
895
+ state.keyupFired = true;
896
+ }, { capture: true, signal: controller.signal });
897
+ w.__dipclawKeyProbes[id] = { state, controller };
898
+ }, probeId);
899
+ }
900
+ async function readAndClearKeyEventProbe(page, probeId) {
901
+ return await page.evaluate((id) => {
902
+ const w = window;
903
+ const probe = w.__dipclawKeyProbes?.[id];
904
+ if (!probe)
905
+ return undefined;
906
+ probe.controller?.abort();
907
+ delete w.__dipclawKeyProbes?.[id];
908
+ return probe.state;
909
+ }, probeId);
910
+ }
911
+ async function evaluateDomKey(page, key) {
912
+ return await page.evaluate((k) => {
913
+ // Modifier combos like "Control+A" rely on real key state (event.ctrlKey,
914
+ // etc.) — JS dispatch can't reproduce the state machine, so reject.
915
+ if (k.includes("+")) {
916
+ return { ok: false, reason: "modifier-combo-not-supported" };
917
+ }
918
+ // Synthetic KeyboardEvent has isTrusted=false, so browsers skip the
919
+ // NATIVE default action (focus traversal, caret movement, char delete,
920
+ // page scroll, dialog close). JS keydown listeners DO fire, so the
921
+ // fallback only helps for keys whose effect is handler-driven in the
922
+ // common case. Refusing keys outside this list makes the caller see an
923
+ // honest failure instead of a silent "press succeeded but nothing
924
+ // happened" cascade.
925
+ //
926
+ // Handler-driven (fallback usable):
927
+ // - Enter — most apps listen; we additionally replicate native
928
+ // implicit form-submit below for text inputs.
929
+ // - Escape — universally handled by JS for modal/popover close.
930
+ // - Arrow* — primary use case is menu / typeahead / listbox nav,
931
+ // which is handler-driven; pure caret movement is lost.
932
+ //
933
+ // Native-only (fallback refused):
934
+ // - Tab, Backspace, Delete, Space, Home, End, PageUp, PageDown.
935
+ // Each needs the native action (focus move, edit, scroll, caret)
936
+ // that synthetic events can't perform.
937
+ const KNOWN = {
938
+ Enter: { code: "Enter", keyCode: 13 },
939
+ Escape: { code: "Escape", keyCode: 27 },
940
+ Tab: { code: "Tab", keyCode: 9 },
941
+ ArrowUp: { code: "ArrowUp", keyCode: 38 },
942
+ ArrowDown: { code: "ArrowDown", keyCode: 40 },
943
+ ArrowLeft: { code: "ArrowLeft", keyCode: 37 },
944
+ ArrowRight: { code: "ArrowRight", keyCode: 39 },
945
+ Backspace: { code: "Backspace", keyCode: 8 },
946
+ Delete: { code: "Delete", keyCode: 46 },
947
+ Space: { code: "Space", keyCode: 32 },
948
+ Home: { code: "Home", keyCode: 36 },
949
+ End: { code: "End", keyCode: 35 },
950
+ PageUp: { code: "PageUp", keyCode: 33 },
951
+ PageDown: { code: "PageDown", keyCode: 34 },
952
+ };
953
+ const HANDLER_DRIVEN = new Set([
954
+ "Enter",
955
+ "Escape",
956
+ "ArrowUp",
957
+ "ArrowDown",
958
+ "ArrowLeft",
959
+ "ArrowRight",
960
+ ]);
961
+ const meta = KNOWN[k];
962
+ if (!meta) {
963
+ // Printable characters would need a US-layout map for `code`; skip
964
+ // until a real caller needs them — paste/keyboard typing handles text.
965
+ return { ok: false, reason: `key-not-supported: ${k}` };
966
+ }
967
+ if (!HANDLER_DRIVEN.has(k)) {
968
+ return { ok: false, reason: `key-requires-native-action: ${k}` };
969
+ }
970
+ const target = document.activeElement ?? document.body;
971
+ if (!target)
972
+ return { ok: false, reason: "no-active-element" };
973
+ const init = {
974
+ key: k,
975
+ code: meta.code,
976
+ keyCode: meta.keyCode,
977
+ which: meta.keyCode,
978
+ bubbles: true,
979
+ cancelable: true,
980
+ composed: true,
981
+ };
982
+ const keydown = new KeyboardEvent("keydown", init);
983
+ target.dispatchEvent(keydown);
984
+ // Real Enter has native semantics that synthetic keydown alone doesn't
985
+ // reproduce — replicate them manually so the fallback doesn't silently
986
+ // succeed without activating the target:
987
+ //
988
+ // 1. Text-like <input> in a form → implicit form submission.
989
+ // 2. Focused <button> or <a> → activation (fires click / navigation).
990
+ // element.click() dispatches a click event that React onClick and
991
+ // browser link navigation both respond to, even with isTrusted=false.
992
+ //
993
+ // Excludes <textarea> (Enter = newline). Submit-type inputs that happen
994
+ // to have focus are handled via the button branch.
995
+ if (k === "Enter" && !keydown.defaultPrevented) {
996
+ const IMPLICIT_SUBMIT_TYPES = new Set([
997
+ "text", "search", "url", "tel", "email", "password", "number",
998
+ "date", "datetime-local", "month", "week", "time",
999
+ ]);
1000
+ const tag = target.tagName;
1001
+ if (tag === "INPUT") {
1002
+ const ae = target;
1003
+ const type = (ae.type || "text").toLowerCase();
1004
+ if (IMPLICIT_SUBMIT_TYPES.has(type) && ae.form) {
1005
+ const form = ae.form;
1006
+ if (typeof form.requestSubmit === "function") {
1007
+ try {
1008
+ form.requestSubmit();
1009
+ }
1010
+ catch {
1011
+ // Form may be invalid (constraint validation); ignore.
1012
+ }
1013
+ }
1014
+ }
1015
+ else if ((type === "submit" || type === "button" || type === "image") &&
1016
+ !ae.disabled) {
1017
+ // Focused submit/button-style input behaves like a button on Enter.
1018
+ ae.click();
1019
+ }
1020
+ }
1021
+ else if (tag === "BUTTON" || tag === "A") {
1022
+ const ae = target;
1023
+ const disabled = "disabled" in ae && ae.disabled;
1024
+ if (!disabled) {
1025
+ ae.click();
1026
+ }
1027
+ }
1028
+ }
1029
+ target.dispatchEvent(new KeyboardEvent("keyup", init));
1030
+ return { ok: true };
1031
+ }, key);
1032
+ }
1033
+ async function evaluateDomClick(page, selector) {
1034
+ return await page.evaluate((sel) => {
1035
+ const el = document.querySelector(sel);
1036
+ if (!el)
1037
+ return { ok: false, reason: "not-found" };
1038
+ if (!document.body.contains(el))
1039
+ return { ok: false, reason: "detached" };
1040
+ const style = window.getComputedStyle(el);
1041
+ if (style.display === "none" || style.visibility === "hidden") {
1042
+ return { ok: false, reason: "not-visible" };
1043
+ }
1044
+ if ("disabled" in el && el.disabled) {
1045
+ return { ok: false, reason: "disabled" };
1046
+ }
1047
+ if (el.getAttribute("aria-disabled") === "true") {
1048
+ return { ok: false, reason: "disabled" };
1049
+ }
1050
+ el.click();
1051
+ return { ok: true };
1052
+ }, selector);
1053
+ }
1054
+ /**
1055
+ * Send a single key with keyboard → dom fallback. No logging, no delay —
1056
+ * callers (pressKey, type's submit) wrap with their own logging and
1057
+ * inter-action throttle. Returns a structured result so callers can decide
1058
+ * what to do (e.g. type folds the result into its existing log entry rather
1059
+ * than emitting a second one).
1060
+ *
1061
+ * Same shape as dispatchSafeClick: physical attempt first, probe the
1062
+ * renderer for actual delivery, fall back to JS dispatch on event-miss.
1063
+ */
1064
+ async function dispatchSafeKeyPress(page, key) {
1065
+ let probeId = makeClickStamp();
1066
+ await installKeyEventProbe(page, probeId);
1067
+ let physicalError;
1068
+ try {
1069
+ await page.keyboard.press(key);
1070
+ }
1071
+ catch (err) {
1072
+ physicalError = err instanceof Error ? err.message : String(err);
1073
+ }
1074
+ const eventProbe = await readAndClearKeyEventProbe(page, probeId).catch(() => undefined);
1075
+ probeId = undefined;
1076
+ let fallbackUsed = false;
1077
+ let dispatchedVia = "keyboard";
1078
+ let fallbackError;
1079
+ // "Needs fallback" means the physical attempt cannot be relied on:
1080
+ // either it threw, or the in-page probe never saw a keydown (CDP synthetic
1081
+ // input was dropped). If needsFallback is true and the DOM fallback didn't
1082
+ // succeed, the press did NOT happen — callers must see ok:false.
1083
+ const needsFallback = !!physicalError || (!!eventProbe && !eventProbe.keydownFired);
1084
+ if (needsFallback) {
1085
+ const dom = await evaluateDomKey(page, key);
1086
+ if (dom.ok) {
1087
+ fallbackUsed = true;
1088
+ dispatchedVia = "dom";
1089
+ }
1090
+ else {
1091
+ fallbackError = dom.reason;
1092
+ }
1093
+ }
1094
+ return {
1095
+ ok: !needsFallback || fallbackUsed,
1096
+ dispatchedVia,
1097
+ fallbackUsed,
1098
+ eventProbe,
1099
+ fallbackError,
1100
+ physicalError,
1101
+ };
1102
+ }
1103
+ async function withKeyboardModifiers(page, modifiers, fn) {
1104
+ const keys = modifiers ?? [];
1105
+ for (const key of keys)
1106
+ await page.keyboard.down(key);
1107
+ try {
1108
+ return await fn();
1109
+ }
1110
+ finally {
1111
+ for (const key of keys.slice().reverse()) {
1112
+ await page.keyboard.up(key).catch(() => { });
1113
+ }
1114
+ }
1115
+ }
1116
+ async function dispatchSafeClick(page, locator, opts) {
1117
+ const dispatch = opts.dispatch ?? "mouse";
1118
+ let probe;
1119
+ let eventProbe;
1120
+ let probeId;
1121
+ try {
1122
+ let stamp = makeClickStamp();
1123
+ await stampClickTarget(locator, stamp);
1124
+ let targetSelector = clickStampSelector(stamp);
1125
+ if (dispatch === "dom") {
1126
+ if (opts.button && opts.button !== "left") {
1127
+ return {
1128
+ ok: false,
1129
+ dispatchedVia: "dom",
1130
+ message: 'dispatch="dom" supports only left-button single clicks',
1131
+ fallbackReason: "unsupported-button",
1132
+ };
1133
+ }
1134
+ if (opts.modifiers?.length) {
1135
+ return {
1136
+ ok: false,
1137
+ dispatchedVia: "dom",
1138
+ message: 'dispatch="dom" does not support modifier-clicks',
1139
+ fallbackReason: "unsupported-modifiers",
1140
+ };
1141
+ }
1142
+ const dom = await evaluateDomClick(page, targetSelector);
1143
+ if (!dom.ok) {
1144
+ return {
1145
+ ok: false,
1146
+ dispatchedVia: "dom",
1147
+ message: `dom click target not actionable: ${dom.reason ?? "unknown"}`,
1148
+ fallbackReason: dom.reason,
1149
+ };
1150
+ }
1151
+ return { ok: true, dispatchedVia: "dom" };
1152
+ }
1153
+ const clickOnce = async () => {
1154
+ probe = await probeClickTarget(page, targetSelector);
1155
+ if (!probe.found) {
1156
+ return {
1157
+ ok: false,
1158
+ dispatchedVia: "mouse",
1159
+ probe,
1160
+ message: `click target not actionable: ${probe.reason ?? "unknown"}`,
1161
+ };
1162
+ }
1163
+ if (!probe.onTarget) {
1164
+ return {
1165
+ ok: false,
1166
+ dispatchedVia: "mouse",
1167
+ probe,
1168
+ message: `target is not receiving pointer events; hit ${describeHitTarget(probe)} instead`,
1169
+ };
1170
+ }
1171
+ probeId = makeClickStamp();
1172
+ await installClickEventProbe(page, targetSelector, probeId);
1173
+ try {
1174
+ await withKeyboardModifiers(page, opts.modifiers, () => page.mouse.click(probe.x, probe.y, {
1175
+ delay: Math.random() * 20,
1176
+ button: opts.button ?? "left",
1177
+ }));
1178
+ }
1179
+ finally {
1180
+ eventProbe = await readAndClearClickEventProbe(page, probeId).catch(() => undefined);
1181
+ probeId = undefined;
1182
+ }
1183
+ if (eventProbe && !eventProbe.clickOnTarget) {
1184
+ return {
1185
+ ok: false,
1186
+ dispatchedVia: "mouse",
1187
+ probe,
1188
+ eventProbe,
1189
+ fallbackReason: "event-miss",
1190
+ message: `click event did not reach target; event landed on ${describeClickEventTarget(eventProbe)}`,
1191
+ };
1192
+ }
1193
+ return { ok: true, dispatchedVia: "mouse", probe, eventProbe };
1194
+ };
1195
+ const first = await clickOnce();
1196
+ if (first.ok || first.fallbackReason !== "event-miss") {
1197
+ return first;
1198
+ }
1199
+ // The coordinate hit-test said "target", but the real click event did
1200
+ // not include the stamped element in its composedPath. This happens when
1201
+ // X/React re-renders between measurement and dispatch. Re-resolve the
1202
+ // original locator, stamp the fresh element, wait for its box to settle,
1203
+ // then make exactly one more physical mouse attempt.
1204
+ stamp = makeClickStamp();
1205
+ await stampClickTarget(locator, stamp);
1206
+ targetSelector = clickStampSelector(stamp);
1207
+ const stable = await waitForLocatorStable(page, targetSelector, 150, 1500);
1208
+ if (!stable) {
1209
+ return {
1210
+ ok: false,
1211
+ dispatchedVia: "mouse",
1212
+ probe,
1213
+ eventProbe,
1214
+ fallbackReason: "event-miss",
1215
+ message: "click event did not reach target; fresh target bounding box did not stabilize for retry",
1216
+ };
1217
+ }
1218
+ const second = await clickOnce();
1219
+ if (second.ok || second.fallbackReason !== "event-miss") {
1220
+ return second;
1221
+ }
1222
+ return {
1223
+ ...second,
1224
+ message: `click event did not reach target after retry; event landed on ${second.eventProbe
1225
+ ? describeClickEventTarget(second.eventProbe)
1226
+ : "(unknown)"}`,
1227
+ };
1228
+ }
1229
+ catch (err) {
1230
+ if (probeId && !eventProbe) {
1231
+ eventProbe = await readAndClearClickEventProbe(page, probeId).catch(() => undefined);
1232
+ }
1233
+ return {
1234
+ ok: false,
1235
+ dispatchedVia: dispatch,
1236
+ probe,
1237
+ eventProbe,
1238
+ message: err instanceof Error ? err.message : String(err),
1239
+ };
1240
+ }
1241
+ finally {
1242
+ await clearClickTargetStamps(page);
1243
+ }
1244
+ }
1245
+ /* -------------------------------------------------------------------------- */
1246
+ /* Polling helpers for `wait` */
1247
+ /* -------------------------------------------------------------------------- */
1248
+ async function waitForCondition(timeoutMs, pred) {
1249
+ const deadline = Date.now() + timeoutMs;
1250
+ while (Date.now() < deadline) {
1251
+ if (await pred())
1252
+ return;
1253
+ await new Promise((r) => setTimeout(r, 100));
1254
+ }
1255
+ // Final check at the boundary, then fail.
1256
+ if (await pred())
1257
+ return;
1258
+ throw new Error(`condition not met within ${timeoutMs}ms`);
1259
+ }
1260
+ /**
1261
+ * Wait until `selector`'s bounding box has been stable (same x,y,width,height)
1262
+ * for `stableMs` consecutive milliseconds. Used to let pending CSS/layout
1263
+ * animations settle so a subsequent click lands where the user expects.
1264
+ *
1265
+ * Returns false on timeout (caller decides whether that's an error). Uses
1266
+ * `boundingBox` polling — cheap, no MutationObserver, no race with React.
1267
+ */
1268
+ async function waitForLocatorStable(page, selector, stableMs, timeoutMs) {
1269
+ const deadline = Date.now() + timeoutMs;
1270
+ let lastBox = null;
1271
+ let stableSince = Date.now();
1272
+ while (Date.now() < deadline) {
1273
+ let box = null;
1274
+ try {
1275
+ box = (await page.locator(selector).first().boundingBox()) ?? null;
1276
+ }
1277
+ catch {
1278
+ box = null;
1279
+ }
1280
+ if (box &&
1281
+ lastBox &&
1282
+ box.x === lastBox.x &&
1283
+ box.y === lastBox.y &&
1284
+ box.width === lastBox.width &&
1285
+ box.height === lastBox.height) {
1286
+ if (Date.now() - stableSince >= stableMs)
1287
+ return true;
1288
+ }
1289
+ else {
1290
+ lastBox = box;
1291
+ stableSince = Date.now();
1292
+ }
1293
+ await new Promise((r) => setTimeout(r, 50));
1294
+ }
1295
+ return false;
1296
+ }
1297
+ /**
1298
+ * Wait until the page's DOM has had no mutations for `quietMs` consecutive
1299
+ * milliseconds (or until `timeoutMs` runs out). Implemented as a single
1300
+ * MutationObserver in the page that resets a timer on each batch — much
1301
+ * cheaper than polling document hashes from outside.
1302
+ */
1303
+ async function waitForDomQuiet(page, quietMs, timeoutMs) {
1304
+ return await page.evaluate(async ({ quietMs, timeoutMs }) => new Promise((resolve) => {
1305
+ let lastMutation = Date.now();
1306
+ const observer = new MutationObserver(() => {
1307
+ lastMutation = Date.now();
1308
+ });
1309
+ observer.observe(document.body, {
1310
+ childList: true,
1311
+ subtree: true,
1312
+ attributes: true,
1313
+ characterData: true,
1314
+ });
1315
+ const start = Date.now();
1316
+ const tick = setInterval(() => {
1317
+ const now = Date.now();
1318
+ if (now - lastMutation >= quietMs) {
1319
+ observer.disconnect();
1320
+ clearInterval(tick);
1321
+ resolve(true);
1322
+ return;
1323
+ }
1324
+ if (now - start >= timeoutMs) {
1325
+ observer.disconnect();
1326
+ clearInterval(tick);
1327
+ resolve(false);
1328
+ }
1329
+ }, Math.min(50, quietMs));
1330
+ }), { quietMs, timeoutMs });
1331
+ }
1332
+ const NAV_PRIMARY_TIMEOUT_MS = 60_000;
1333
+ const NAV_RECOVERY_TIMEOUT_MS = 15_000;
1334
+ /**
1335
+ * Single-step navigation with one bounded retry on timeout.
1336
+ *
1337
+ * Production logs showed page.goto timeouts on X status URLs killing
1338
+ * otherwise-recoverable tasks. The page often loads enough of the app
1339
+ * shell to be usable (URL committed, body has the target content) before
1340
+ * `domcontentloaded` resolves — the issue is that XHR/streaming keeps the
1341
+ * load-state machine spinning even after the user-visible page is done.
1342
+ *
1343
+ * Strategy:
1344
+ * 1. Try `domcontentloaded`, full timeout. If it succeeds, we're done.
1345
+ * 2. On timeout, probe the current page: did URL change? Is title set?
1346
+ * Is there visible content? If yes, treat as `recovered` and return.
1347
+ * 3. Otherwise, one quick retry with `commit` (Playwright resolves as
1348
+ * soon as the navigation request commits — no DOM-content wait at
1349
+ * all). If that succeeds, return as recovered with note.
1350
+ * 4. If everything fails, return a structured error including current
1351
+ * URL/title so the LLM can decide whether to retry, fall back to a
1352
+ * different URL, or give up.
1353
+ */
1354
+ async function navigateWithRecovery(page, url) {
1355
+ // Snapshot the URL we were on BEFORE the goto. If recovery later sees
1356
+ // the same URL, no commit happened and we shouldn't lie about success.
1357
+ // Catches: target = root + redirect to same-origin page (root special
1358
+ // case used to mask this) and target with query against an old page on
1359
+ // the same path.
1360
+ const beforeUrl = page.url();
1361
+ let firstError = null;
1362
+ try {
1363
+ await page.goto(url, {
1364
+ waitUntil: "domcontentloaded",
1365
+ timeout: NAV_PRIMARY_TIMEOUT_MS,
1366
+ });
1367
+ return {
1368
+ ok: true,
1369
+ recovered: false,
1370
+ text: `Navigated to ${url}`,
1371
+ attempt: 1,
1372
+ finalUrl: page.url(),
1373
+ };
1374
+ }
1375
+ catch (err) {
1376
+ firstError = err instanceof Error ? err.message : String(err);
1377
+ }
1378
+ // Probe whether the page actually loaded enough to be usable AND that
1379
+ // the URL actually committed to the target. Without the URL check, a
1380
+ // goto-timeout that fires before commit leaves page.url() pointing at
1381
+ // the previous page — and the old page is "usable" by every other
1382
+ // measure (title, body content), so we'd lie about navigation success.
1383
+ const usable = await isPageUsable(page, url, beforeUrl);
1384
+ if (usable.ok) {
1385
+ return {
1386
+ ok: true,
1387
+ recovered: true,
1388
+ text: `Navigated to ${url} [nav recovered: timed out but page is usable] ` +
1389
+ `final url: ${usable.url}, title: ${JSON.stringify(usable.title)}`,
1390
+ attempt: 1,
1391
+ finalUrl: usable.url,
1392
+ };
1393
+ }
1394
+ // Lightweight retry: `commit` returns as soon as the response has been
1395
+ // received, before any DOM events fire. Combined with a short timeout,
1396
+ // this gets us past sites that hang on `domcontentloaded` due to
1397
+ // long-poll XHR or streaming responses.
1398
+ try {
1399
+ await page.goto(url, {
1400
+ waitUntil: "commit",
1401
+ timeout: NAV_RECOVERY_TIMEOUT_MS,
1402
+ });
1403
+ const after = await isPageUsable(page, url, beforeUrl);
1404
+ if (!after.ok) {
1405
+ // commit succeeded according to Playwright but the URL still doesn't
1406
+ // match — extremely rare, but possible if the site immediately
1407
+ // redirected somewhere unrelated. Treat it as a recovery failure.
1408
+ return {
1409
+ ok: false,
1410
+ recovered: false,
1411
+ text: `Error navigating to ${url}: first attempt timed out (${firstError}); ` +
1412
+ `commit retry succeeded but page state is unexpected: ${after.reason}. ` +
1413
+ `Final url: ${after.url}.`,
1414
+ attempt: 2,
1415
+ finalUrl: after.url,
1416
+ };
1417
+ }
1418
+ return {
1419
+ ok: true,
1420
+ recovered: true,
1421
+ text: `Navigated to ${url} [nav recovered: retry with waitUntil=commit succeeded] ` +
1422
+ `final url: ${after.url}, title: ${JSON.stringify(after.title)}`,
1423
+ attempt: 2,
1424
+ finalUrl: after.url,
1425
+ };
1426
+ }
1427
+ catch (err) {
1428
+ const retryError = err instanceof Error ? err.message : String(err);
1429
+ return {
1430
+ ok: false,
1431
+ recovered: false,
1432
+ text: `Error navigating to ${url}: first attempt timed out (${firstError}); ` +
1433
+ `recovery attempt also failed (${retryError}). ` +
1434
+ `Current url: ${page.url()}. ` +
1435
+ `Suggestion: try a fresh tab (browser.open) or a more specific URL.`,
1436
+ attempt: 2,
1437
+ finalUrl: page.url(),
1438
+ };
1439
+ }
1440
+ }
1441
+ /**
1442
+ * A page is "usable for the requested target" if all three hold:
1443
+ * 1. URL is not about:blank/empty (page did navigate)
1444
+ * 2. Title or body content is present (page actually rendered something)
1445
+ * 3. The current URL matches the target by origin AND pathname prefix
1446
+ * (rules out the case where goto timed out before commit and we're
1447
+ * still on the previous page)
1448
+ *
1449
+ * (3) is the bit Fix #3 adds — without it, the previous "title or body
1450
+ * exists" check could greenlight any page in the browser, since the old
1451
+ * page necessarily has both.
1452
+ */
1453
+ async function isPageUsable(page, targetUrl, beforeUrl) {
1454
+ const url = page.url();
1455
+ if (!url || url === "about:blank") {
1456
+ return { ok: false, url, title: "", reason: "no navigation committed" };
1457
+ }
1458
+ if (!urlMatchesTarget(url, targetUrl, beforeUrl)) {
1459
+ // Distinguish "URL didn't change at all" (no commit) from "URL changed
1460
+ // but landed on the wrong place" — the LLM can decide differently.
1461
+ const reason = beforeUrl && url === beforeUrl
1462
+ ? `goto did not commit (still on ${url})`
1463
+ : `current url ${url} does not match target ${targetUrl}`;
1464
+ return { ok: false, url, title: "", reason };
1465
+ }
1466
+ let title = "";
1467
+ try {
1468
+ title = await page.title();
1469
+ }
1470
+ catch {
1471
+ return { ok: false, url, title: "", reason: "page closed or detached" };
1472
+ }
1473
+ if (title)
1474
+ return { ok: true, url, title };
1475
+ try {
1476
+ const hasBody = await page.evaluate(() => {
1477
+ return (document.body != null &&
1478
+ document.body.children.length > 0 &&
1479
+ (document.body.innerText ?? "").trim().length > 0);
1480
+ });
1481
+ return hasBody
1482
+ ? { ok: true, url, title }
1483
+ : { ok: false, url, title, reason: "page body is empty" };
1484
+ }
1485
+ catch {
1486
+ return { ok: false, url, title, reason: "page body inaccessible" };
1487
+ }
1488
+ }
1489
+ /**
1490
+ * URL match check for nav recovery. Conservative — must satisfy ALL of:
1491
+ *
1492
+ * 1. Same origin (protocol + host + port).
1493
+ * 2. (When `beforeUrl` is provided) the URL must have CHANGED from
1494
+ * beforeUrl. If they're identical the goto never committed, no real
1495
+ * navigation happened, and the page is whatever was there before —
1496
+ * regardless of how nice the title and body look.
1497
+ * 3. Pathname equals target's, OR extends it (target "/foo" → current
1498
+ * "/foo/bar"). Going SHORTER (target "/profile/me" → current
1499
+ * "/login") is rejected — the redirect-to-login case.
1500
+ * Special case: target pathname "/" (origin-only) accepts any path,
1501
+ * because sites routinely redirect their root URL to /home, /login,
1502
+ * /dashboard etc.
1503
+ * 4. (When target has a query string) every target query parameter must
1504
+ * be present in current with the same value. Extra params on current
1505
+ * are allowed (utm_*, tracking suffixes). This catches "goto
1506
+ * /search?q=new timed out before commit and we're still on
1507
+ * /search?q=old" — same path, different query, definitely not the
1508
+ * page the caller asked for.
1509
+ *
1510
+ * Hash differences are ignored — they don't constitute a navigation.
1511
+ *
1512
+ * Note on edge case: if the caller navigates to the SAME url they're
1513
+ * already on and goto times out, recovery will fail (rule 2). That's
1514
+ * intentional — we genuinely can't tell whether the page reloaded or not,
1515
+ * so reporting "navigation succeeded" would be a guess.
1516
+ */
1517
+ export function urlMatchesTarget(current, target, beforeUrl) {
1518
+ let c, t;
1519
+ try {
1520
+ c = new URL(current);
1521
+ t = new URL(target);
1522
+ }
1523
+ catch {
1524
+ return false;
1525
+ }
1526
+ if (c.origin !== t.origin)
1527
+ return false;
1528
+ // Same-URL guard: if we never moved, no commit happened. Compare on
1529
+ // origin+pathname+search — hash never counts as a navigation.
1530
+ if (beforeUrl) {
1531
+ try {
1532
+ const b = new URL(beforeUrl);
1533
+ const cKey = c.origin + (c.pathname || "/") + (c.search || "");
1534
+ const bKey = b.origin + (b.pathname || "/") + (b.search || "");
1535
+ if (cKey === bKey)
1536
+ return false;
1537
+ }
1538
+ catch {
1539
+ // Malformed beforeUrl — skip the guard.
1540
+ }
1541
+ }
1542
+ // Query subset: every target param must be present on current.
1543
+ if (t.search) {
1544
+ for (const [key, value] of t.searchParams) {
1545
+ if (c.searchParams.get(key) !== value)
1546
+ return false;
1547
+ }
1548
+ }
1549
+ // Path check.
1550
+ const cp = c.pathname.replace(/\/+$/, "") || "/";
1551
+ const tp = t.pathname.replace(/\/+$/, "") || "/";
1552
+ if (tp === "/")
1553
+ return true;
1554
+ if (cp === tp)
1555
+ return true;
1556
+ return cp.startsWith(tp + "/");
1557
+ }
1558
+ // --- Main class ---
1559
+ export class BrowserActions {
1560
+ browser;
1561
+ logger = null;
1562
+ actionDelay;
1563
+ lastActionTime = 0;
1564
+ dialogArmId = 0;
1565
+ uploadArmId = 0;
1566
+ attachmentsDir = null;
1567
+ constructor(browser, actionDelay, attachmentsDir) {
1568
+ this.browser = browser;
1569
+ this.actionDelay = actionDelay ?? DEFAULT_ACTION_DELAY;
1570
+ this.attachmentsDir = attachmentsDir ?? null;
1571
+ }
1572
+ /**
1573
+ * Auto-inject a random delay between consecutive browser actions
1574
+ * to simulate human pacing. Skips if enough time has already passed.
1575
+ */
1576
+ async interActionDelay() {
1577
+ if (this.actionDelay.max <= 0)
1578
+ return;
1579
+ const elapsed = Date.now() - this.lastActionTime;
1580
+ const target = this.actionDelay.min +
1581
+ Math.random() * (this.actionDelay.max - this.actionDelay.min);
1582
+ const remaining = target - elapsed;
1583
+ if (remaining > 0) {
1584
+ await new Promise((r) => setTimeout(r, remaining));
1585
+ }
1586
+ this.lastActionTime = Date.now();
1587
+ }
1588
+ /** Expose the active page for direct Playwright locator usage (e.g. CSS selectors in skill replay) */
1589
+ async getPage() {
1590
+ return this.browser.getActivePage();
1591
+ }
1592
+ setLogger(logger) {
1593
+ this.logger = logger;
1594
+ }
1595
+ clearLogger(logger) {
1596
+ if (this.logger === logger) {
1597
+ this.logger = null;
1598
+ }
1599
+ }
1600
+ // =====================
1601
+ // Top-level actions
1602
+ // =====================
1603
+ async navigate(url) {
1604
+ await this.interActionDelay();
1605
+ const page = await this.browser.getActivePage();
1606
+ // New URL → old accessibility tree is gone. Invalidate refs first so we
1607
+ // never report a recovery-based hit on the previous page mid-navigation.
1608
+ resetRefs();
1609
+ const navResult = await navigateWithRecovery(page, url);
1610
+ this.logger?.log("navigate", {
1611
+ url,
1612
+ ...(navResult.attempt > 1 ? { attempts: navResult.attempt } : {}),
1613
+ ...(navResult.recovered ? { recovered: true } : {}),
1614
+ finalUrl: navResult.finalUrl,
1615
+ });
1616
+ return navResult.text;
1617
+ }
1618
+ async snapshot(modeOrOptions) {
1619
+ const page = await this.browser.getActivePage();
1620
+ ensureConsoleCapture(page);
1621
+ // Wait for DOM content rather than network idle — SPAs with long-poll or
1622
+ // streaming can keep the network "busy" forever even
1623
+ // when the UI is fully usable. domcontentloaded is good enough as a
1624
+ // pre-snapshot barrier; if the LLM needs more, it should explicitly use
1625
+ // wait{selectorVisible|domQuietMs|locatorStableMs}.
1626
+ await page
1627
+ .waitForLoadState("domcontentloaded", { timeout: 5000 })
1628
+ .catch(() => { });
1629
+ const result = await takeSnapshot(page, modeOrOptions);
1630
+ const url = page.url();
1631
+ const title = await page.title();
1632
+ const opts = typeof modeOrOptions === "string"
1633
+ ? { mode: modeOrOptions }
1634
+ : modeOrOptions ?? {};
1635
+ this.logger?.log("snapshot", {
1636
+ url,
1637
+ title,
1638
+ mode: opts.mode ?? "full",
1639
+ selector: opts.selector,
1640
+ elements: result.elementRefs.size,
1641
+ });
1642
+ return `Page: ${title}\nURL: ${url}\n\n${result.text}`;
1643
+ }
1644
+ async screenshot(opts) {
1645
+ const page = await this.browser.getActivePage();
1646
+ // saveAs extension, if recognized, overrides `type` so the bytes on disk
1647
+ // match the filename the user sees. Unknown/missing extensions fall back
1648
+ // to `type` (default jpeg) and the extension is normalized accordingly.
1649
+ const saveAsExt = typeof opts?.saveAs === "string"
1650
+ ? path.extname(opts.saveAs.trim()).toLowerCase()
1651
+ : "";
1652
+ const imgType = saveAsExt === ".png"
1653
+ ? "png"
1654
+ : saveAsExt === ".jpg" || saveAsExt === ".jpeg"
1655
+ ? "jpeg"
1656
+ : opts?.type ?? "jpeg";
1657
+ const quality = imgType === "jpeg" ? { quality: 75 } : {};
1658
+ try {
1659
+ let buffer;
1660
+ if (opts?.ref) {
1661
+ const r = await locateRefWithRecovery(page, opts.ref, {
1662
+ destructive: false,
1663
+ label: "element",
1664
+ selectorParam: "element",
1665
+ });
1666
+ if (!r.ok) {
1667
+ this.logger?.log("screenshot", { ...opts, error: r.message }, false);
1668
+ return { base64: "", text: r.message };
1669
+ }
1670
+ buffer = await r.locator.screenshot({ type: imgType, ...quality });
1671
+ }
1672
+ else if (opts?.element) {
1673
+ const r = resolveSelector(page, opts.element, "element");
1674
+ if (!r.ok) {
1675
+ this.logger?.log("screenshot", { ...opts, error: r.error }, false);
1676
+ return { base64: "", text: r.error };
1677
+ }
1678
+ buffer = await r.locator.screenshot({ type: imgType, ...quality });
1679
+ }
1680
+ else {
1681
+ buffer = await page.screenshot({
1682
+ fullPage: opts?.fullPage ?? false,
1683
+ type: imgType,
1684
+ ...quality,
1685
+ });
1686
+ }
1687
+ const base64 = buffer.toString("base64");
1688
+ let savedAs;
1689
+ const wantSave = opts?.save === true || typeof opts?.saveAs === "string";
1690
+ if (wantSave) {
1691
+ if (!this.attachmentsDir) {
1692
+ this.logger?.log("screenshot", { ...opts, warning: "no attachments dir configured; save skipped" });
1693
+ }
1694
+ else {
1695
+ fs.mkdirSync(this.attachmentsDir, { recursive: true });
1696
+ const ext = imgType === "jpeg" ? ".jpg" : ".png";
1697
+ let filename;
1698
+ if (typeof opts?.saveAs === "string" && opts.saveAs.trim()) {
1699
+ const safe = path
1700
+ .basename(opts.saveAs.trim())
1701
+ .replace(/[^a-zA-Z0-9._-]/g, "_")
1702
+ .slice(0, 80) || "screenshot";
1703
+ const rawExt = path.extname(safe).toLowerCase();
1704
+ // Force the filename's extension to match the actual encoded bytes.
1705
+ // imgType was already reconciled with saveAsExt above, so .png/.jpg/
1706
+ // .jpeg on saveAs are already consistent and get preserved here.
1707
+ const isMatchingExt = (imgType === "png" && rawExt === ".png") ||
1708
+ (imgType === "jpeg" && (rawExt === ".jpg" || rawExt === ".jpeg"));
1709
+ const stem = rawExt ? safe.slice(0, -rawExt.length) : safe;
1710
+ filename = isMatchingExt ? safe : `${stem || "screenshot"}${ext}`;
1711
+ // Ensure unique to avoid clobbering a prior attachment
1712
+ if (fs.existsSync(path.join(this.attachmentsDir, filename))) {
1713
+ const base = path.basename(filename, path.extname(filename));
1714
+ filename = `${base}-${Date.now()}${path.extname(filename)}`;
1715
+ }
1716
+ }
1717
+ else {
1718
+ filename = `screenshot-${Date.now()}-${crypto.randomBytes(4).toString("hex")}${ext}`;
1719
+ }
1720
+ fs.writeFileSync(path.join(this.attachmentsDir, filename), buffer);
1721
+ savedAs = filename;
1722
+ }
1723
+ }
1724
+ this.logger?.log("screenshot", { ...opts, size: buffer.length, savedAs });
1725
+ const sizeNote = `Screenshot taken (${buffer.length} bytes, ${imgType})`;
1726
+ const text = savedAs
1727
+ ? `${sizeNote}. Saved as attachments/${savedAs} — pass this filename to attachment.send to deliver it.`
1728
+ : sizeNote;
1729
+ return { base64, text, savedAs };
1730
+ }
1731
+ catch (err) {
1732
+ const msg = err instanceof Error ? err.message : String(err);
1733
+ this.logger?.log("screenshot", { ...opts, error: msg }, false);
1734
+ return { base64: "", text: `Error taking screenshot: ${msg}` };
1735
+ }
1736
+ }
1737
+ async console(level) {
1738
+ const page = await this.browser.getActivePage();
1739
+ ensureConsoleCapture(page);
1740
+ const buffer = consoleBuffers.get(page) ?? [];
1741
+ const levelPriority = {
1742
+ debug: 0,
1743
+ log: 1,
1744
+ info: 1,
1745
+ warning: 2,
1746
+ error: 3,
1747
+ };
1748
+ let filtered = buffer;
1749
+ if (level) {
1750
+ const minPriority = levelPriority[level] ?? 0;
1751
+ filtered = buffer.filter((e) => (levelPriority[e.type] ?? 0) >= minPriority);
1752
+ }
1753
+ if (filtered.length === 0) {
1754
+ return "(no console messages)";
1755
+ }
1756
+ const text = filtered
1757
+ .map((e) => `[${e.type}] ${e.timestamp} ${e.text}`)
1758
+ .join("\n");
1759
+ // Cap output (UTF-16 boundary-safe — see safe-slice.ts)
1760
+ const MAX_CONSOLE_OUTPUT = 16_000;
1761
+ if (text.length > MAX_CONSOLE_OUTPUT) {
1762
+ const cut = safeSliceHead(text, MAX_CONSOLE_OUTPUT);
1763
+ return cut + `\n[...truncated ${text.length - cut.length} chars]`;
1764
+ }
1765
+ this.logger?.log("console", { level, count: filtered.length });
1766
+ return text;
1767
+ }
1768
+ async dialog(accept, promptText, timeoutMs) {
1769
+ const page = await this.browser.getActivePage();
1770
+ const armId = ++this.dialogArmId;
1771
+ const timeout = Math.min(timeoutMs ?? 30_000, 120_000);
1772
+ void page
1773
+ .waitForEvent("dialog", { timeout })
1774
+ .then(async (dialog) => {
1775
+ if (this.dialogArmId !== armId)
1776
+ return; // superseded
1777
+ if (accept) {
1778
+ await dialog.accept(promptText);
1779
+ }
1780
+ else {
1781
+ await dialog.dismiss();
1782
+ }
1783
+ })
1784
+ .catch(() => { }); // timeout is fine — dialog may never appear
1785
+ this.logger?.log("dialog", { accept, promptText });
1786
+ return `Dialog armed: will ${accept ? "accept" : "dismiss"} the next dialog`;
1787
+ }
1788
+ /**
1789
+ * Resolve a path the LLM passed to `upload` into an absolute filesystem
1790
+ * path. Playwright's setInputFiles/fileChooser.setFiles resolve relative
1791
+ * strings against process.cwd(), which isn't the workspace — so a bare
1792
+ * "attachments/foo.jpg" silently fails to upload. We normalize here:
1793
+ * 1. Absolute and exists → use as-is.
1794
+ * 2. Exists under workspace/attachments/ (with or without the
1795
+ * "attachments/" prefix) → resolve there.
1796
+ * 3. Exists relative to cwd → keep (preserves prior behavior).
1797
+ * 4. Otherwise → throw so the error reaches the LLM.
1798
+ */
1799
+ resolveUploadPath(input) {
1800
+ if (path.isAbsolute(input)) {
1801
+ if (fs.existsSync(input))
1802
+ return input;
1803
+ throw new Error(`upload path '${input}' does not exist (absolute path). Use a bare filename or "attachments/<name>" to pick up files the user uploaded.`);
1804
+ }
1805
+ if (this.attachmentsDir) {
1806
+ const stripped = input.replace(/^\.\/+/, "").replace(/^attachments\/+/, "");
1807
+ const resolvedAttach = path.resolve(this.attachmentsDir, stripped);
1808
+ const attachRoot = path.resolve(this.attachmentsDir);
1809
+ if ((resolvedAttach === attachRoot ||
1810
+ resolvedAttach.startsWith(attachRoot + path.sep)) &&
1811
+ fs.existsSync(resolvedAttach)) {
1812
+ return resolvedAttach;
1813
+ }
1814
+ }
1815
+ const resolvedCwd = path.resolve(input);
1816
+ if (fs.existsSync(resolvedCwd))
1817
+ return resolvedCwd;
1818
+ throw new Error(`upload path '${input}' not found. For user-uploaded files pass the filename as shown in the attachments/<name> preamble; for local files pass an absolute path.`);
1819
+ }
1820
+ async upload(paths, ref, timeoutMs, selector) {
1821
+ if (!Array.isArray(paths) || paths.length === 0) {
1822
+ return "Error: upload requires paths (non-empty array of file paths).";
1823
+ }
1824
+ let resolvedPaths;
1825
+ try {
1826
+ resolvedPaths = paths.map((p) => this.resolveUploadPath(p));
1827
+ }
1828
+ catch (err) {
1829
+ const msg = err instanceof Error ? err.message : String(err);
1830
+ this.logger?.log("upload", { paths, error: msg }, false);
1831
+ return `Error: ${msg}`;
1832
+ }
1833
+ await this.interActionDelay();
1834
+ const page = await this.browser.getActivePage();
1835
+ const timeout = Math.min(timeoutMs ?? 30_000, 120_000);
1836
+ if (ref) {
1837
+ // Direct mode: set files on the input element
1838
+ const r = await locateRefWithRecovery(page, ref, {
1839
+ destructive: false,
1840
+ label: "element",
1841
+ selectorParam: "selector",
1842
+ });
1843
+ if (!r.ok)
1844
+ return r.message;
1845
+ try {
1846
+ await r.locator.setInputFiles(resolvedPaths, { timeout: 10_000 });
1847
+ this.logger?.log("upload", {
1848
+ paths,
1849
+ resolvedPaths,
1850
+ ref,
1851
+ ...(r.recoveredVia ? { recoveredVia: r.recoveredVia } : {}),
1852
+ });
1853
+ return `Files uploaded to ${r.label} — ${resolvedPaths.join(", ")}`;
1854
+ }
1855
+ catch (err) {
1856
+ const msg = err instanceof Error ? err.message : String(err);
1857
+ return `Error uploading files: ${msg}`;
1858
+ }
1859
+ }
1860
+ if (selector) {
1861
+ // CSS-selector mode for skill replay: persist a stable selector
1862
+ // (e.g. input[type='file'] or [data-testid='upload']) and re-use
1863
+ // it on each run instead of an ephemeral ref. Same code path as
1864
+ // ref mode but skips the aria-ref recovery.
1865
+ const r = resolveSelector(page, selector);
1866
+ if (!r.ok) {
1867
+ this.logger?.log("upload", { paths, selector, error: r.error }, false);
1868
+ return r.error;
1869
+ }
1870
+ try {
1871
+ await r.locator.setInputFiles(resolvedPaths, { timeout: 10_000 });
1872
+ this.logger?.log("upload", {
1873
+ paths,
1874
+ resolvedPaths,
1875
+ selector: r.selector,
1876
+ });
1877
+ return `Files uploaded to ${r.selector} — ${resolvedPaths.join(", ")}`;
1878
+ }
1879
+ catch (err) {
1880
+ const msg = err instanceof Error ? err.message : String(err);
1881
+ return `Error uploading files: ${msg}`;
1882
+ }
1883
+ }
1884
+ // Armed mode: wait for next file chooser dialog. Capture errors from the
1885
+ // async callback so they surface on the NEXT upload call (the current call
1886
+ // can only report that the arm was set up — but if the callback fails,
1887
+ // we log it so the LLM isn't told "success" forever).
1888
+ const armId = ++this.uploadArmId;
1889
+ page
1890
+ .waitForEvent("filechooser", { timeout })
1891
+ .then(async (fileChooser) => {
1892
+ if (this.uploadArmId !== armId)
1893
+ return; // superseded
1894
+ try {
1895
+ await fileChooser.setFiles(resolvedPaths);
1896
+ }
1897
+ catch (err) {
1898
+ const msg = err instanceof Error ? err.message : String(err);
1899
+ this.logger?.log("upload", { paths, resolvedPaths, error: `setFiles failed: ${msg}` }, false);
1900
+ return;
1901
+ }
1902
+ // Dispatch events for reactivity
1903
+ try {
1904
+ const input = typeof fileChooser.element === "function"
1905
+ ? await Promise.resolve(fileChooser.element())
1906
+ : null;
1907
+ if (input) {
1908
+ await input.evaluate((el) => {
1909
+ el.dispatchEvent(new Event("input", { bubbles: true }));
1910
+ el.dispatchEvent(new Event("change", { bubbles: true }));
1911
+ });
1912
+ }
1913
+ }
1914
+ catch {
1915
+ // best-effort event dispatch
1916
+ }
1917
+ this.logger?.log("upload", { paths, resolvedPaths, delivered: true });
1918
+ })
1919
+ .catch((err) => {
1920
+ // Timeout or page closure — record so the user-facing log shows why.
1921
+ const msg = err instanceof Error ? err.message : String(err);
1922
+ if (!/Timeout/i.test(msg)) {
1923
+ this.logger?.log("upload", { paths, resolvedPaths, error: `filechooser: ${msg}` }, false);
1924
+ }
1925
+ });
1926
+ this.logger?.log("upload", { paths, resolvedPaths, armed: true });
1927
+ return `Upload armed: will set ${resolvedPaths.join(", ")} on next file chooser`;
1928
+ }
1929
+ // =====================
1930
+ // Interaction actions (act kinds)
1931
+ // =====================
1932
+ async click(ref, options, selector) {
1933
+ await this.interActionDelay();
1934
+ const page = await this.browser.getActivePage();
1935
+ ensureConsoleCapture(page);
1936
+ // Resolve locator: ref takes priority, then selector
1937
+ let locator;
1938
+ let label;
1939
+ let recoveredVia;
1940
+ let selectorUsed;
1941
+ let refUsed;
1942
+ if (ref) {
1943
+ const meta = getElementRef(ref);
1944
+ const destructive = meta ? looksDestructive(meta) : true;
1945
+ const r = await locateRefWithRecovery(page, ref, { destructive });
1946
+ if (!r.ok) {
1947
+ this.logger?.log("click", { ref, error: r.message }, false);
1948
+ return r.message;
1949
+ }
1950
+ locator = r.locator;
1951
+ label = r.label;
1952
+ recoveredVia = r.recoveredVia;
1953
+ selectorUsed = r.selectorUsed;
1954
+ refUsed = r.refUsed;
1955
+ }
1956
+ else if (selector != null) {
1957
+ const r = resolveSelector(page, selector);
1958
+ if (!r.ok) {
1959
+ this.logger?.log("click", { selector, error: r.error }, false);
1960
+ return r.error;
1961
+ }
1962
+ locator = r.locator;
1963
+ label = r.selector;
1964
+ selectorUsed = r.selector;
1965
+ }
1966
+ else {
1967
+ return "Error: click requires ref or selector.";
1968
+ }
1969
+ try {
1970
+ await locator.scrollIntoViewIfNeeded({ timeout: 5000 });
1971
+ // Human bezier mouse trail to a random point inside the target box.
1972
+ // Pure cosmetics for bot fingerprinting — boundingBox is best-effort,
1973
+ // and the actual click below is what carries correctness guarantees.
1974
+ const box = await locator.boundingBox();
1975
+ if (box) {
1976
+ await humanMove(page, box.x + box.width * (0.3 + Math.random() * 0.4), box.y + box.height * (0.3 + Math.random() * 0.4));
1977
+ }
1978
+ let safeClickResult;
1979
+ let eventMissCleanupRuns = [];
1980
+ if (options?.doubleClick) {
1981
+ if (options.dispatch === "dom") {
1982
+ const msg = 'dispatch="dom" does not support doubleClick';
1983
+ this.logger?.log("click", {
1984
+ ref,
1985
+ selector,
1986
+ label,
1987
+ dispatchedVia: "dom",
1988
+ error: msg,
1989
+ recentConsole: recentConsoleEntries(page, 10),
1990
+ }, false);
1991
+ return `Error clicking ${label}: ${msg}`;
1992
+ }
1993
+ await locator.dblclick({
1994
+ delay: Math.random() * 20,
1995
+ timeout: 5000,
1996
+ ...(options?.button ? { button: options.button } : {}),
1997
+ ...(options?.modifiers ? { modifiers: options.modifiers } : {}),
1998
+ });
1999
+ }
2000
+ else {
2001
+ safeClickResult = await dispatchSafeClick(page, locator, {
2002
+ selectorHint: selectorUsed ?? selector,
2003
+ label,
2004
+ button: options?.button,
2005
+ modifiers: options?.modifiers,
2006
+ dispatch: options?.dispatch ?? "mouse",
2007
+ purpose: "click",
2008
+ });
2009
+ if (!safeClickResult.ok &&
2010
+ safeClickResult.fallbackReason === "event-miss" &&
2011
+ (options?.dispatch ?? "mouse") === "mouse") {
2012
+ eventMissCleanupRuns = await runBuiltinPageCleanups(page, "after-click-event-miss");
2013
+ if (eventMissCleanupRuns.length > 0) {
2014
+ this.logger?.log("page_cleanup", {
2015
+ stage: "after-click-event-miss",
2016
+ runs: eventMissCleanupRuns,
2017
+ }, eventMissCleanupRuns.every((run) => run.ok));
2018
+ }
2019
+ if (anyCleanupHandled(eventMissCleanupRuns)) {
2020
+ safeClickResult = await dispatchSafeClick(page, locator, {
2021
+ selectorHint: selectorUsed ?? selector,
2022
+ label,
2023
+ button: options?.button,
2024
+ modifiers: options?.modifiers,
2025
+ dispatch: "mouse",
2026
+ purpose: "click",
2027
+ });
2028
+ }
2029
+ }
2030
+ if (!safeClickResult.ok) {
2031
+ const msg = safeClickResult.message ?? "click dispatch failed";
2032
+ this.logger?.log("click", {
2033
+ ref,
2034
+ selector,
2035
+ label,
2036
+ ...(selectorUsed ? { selectorUsed } : {}),
2037
+ ...(refUsed && refUsed !== ref ? { refUsed } : {}),
2038
+ ...(recoveredVia ? { recoveredVia } : {}),
2039
+ ...(options ?? {}),
2040
+ error: msg,
2041
+ dispatchedVia: safeClickResult.dispatchedVia,
2042
+ ...(safeClickResult.probe ? { probe: safeClickResult.probe } : {}),
2043
+ ...(safeClickResult.eventProbe
2044
+ ? { eventProbe: safeClickResult.eventProbe }
2045
+ : {}),
2046
+ ...(safeClickResult.fallbackReason
2047
+ ? { fallbackReason: safeClickResult.fallbackReason }
2048
+ : {}),
2049
+ ...(eventMissCleanupRuns.length > 0
2050
+ ? { eventMissCleanupRuns }
2051
+ : {}),
2052
+ recentConsole: recentConsoleEntries(page, 10),
2053
+ }, false);
2054
+ return `Error clicking ${label}: ${msg}`;
2055
+ }
2056
+ }
2057
+ this.logger?.log("click", {
2058
+ ref,
2059
+ selector,
2060
+ label,
2061
+ ...(selectorUsed ? { selectorUsed } : {}),
2062
+ ...(refUsed && refUsed !== ref ? { refUsed } : {}),
2063
+ ...(recoveredVia ? { recoveredVia } : {}),
2064
+ ...(options ?? {}),
2065
+ ...(safeClickResult?.dispatchedVia
2066
+ ? { dispatchedVia: safeClickResult.dispatchedVia }
2067
+ : {}),
2068
+ ...(safeClickResult?.probe ? { probe: safeClickResult.probe } : {}),
2069
+ ...(safeClickResult?.eventProbe
2070
+ ? { eventProbe: safeClickResult.eventProbe }
2071
+ : {}),
2072
+ ...(eventMissCleanupRuns.length > 0 ? { eventMissCleanupRuns } : {}),
2073
+ });
2074
+ return `Clicked ${label}${safeClickResult?.dispatchedVia === "dom" ? " [via dom dispatch]" : ""}`;
2075
+ }
2076
+ catch (err) {
2077
+ const msg = err instanceof Error ? err.message : String(err);
2078
+ this.logger?.log("click", {
2079
+ ref,
2080
+ selector,
2081
+ label,
2082
+ error: msg,
2083
+ recentConsole: recentConsoleEntries(page, 10),
2084
+ }, false);
2085
+ return `Error clicking ${label}: ${msg}`;
2086
+ }
2087
+ }
2088
+ async type(ref, text, clearOrOptions, selector) {
2089
+ await this.interActionDelay();
2090
+ const page = await this.browser.getActivePage();
2091
+ // Always-on console + pageerror capture for this page so the failure
2092
+ // log below can include recent JS errors (React reconciliation crashes
2093
+ // surface via pageerror, which the LLM never queries on its own).
2094
+ ensureConsoleCapture(page);
2095
+ // Resolve locator
2096
+ let locator;
2097
+ let label;
2098
+ if (ref) {
2099
+ const r = await locateRefWithRecovery(page, ref, { destructive: false });
2100
+ if (!r.ok) {
2101
+ this.logger?.log("type", { ref, text, error: r.message }, false);
2102
+ return r.message;
2103
+ }
2104
+ locator = r.locator;
2105
+ label = r.label;
2106
+ }
2107
+ else if (selector != null) {
2108
+ const r = resolveSelector(page, selector);
2109
+ if (!r.ok) {
2110
+ this.logger?.log("type", { selector, text, error: r.error }, false);
2111
+ return r.error;
2112
+ }
2113
+ locator = r.locator;
2114
+ label = r.selector;
2115
+ }
2116
+ else {
2117
+ return "Error: type requires ref or selector.";
2118
+ }
2119
+ // Normalize options
2120
+ let opts;
2121
+ if (typeof clearOrOptions === "boolean") {
2122
+ opts = { clear: clearOrOptions };
2123
+ }
2124
+ else {
2125
+ opts = clearOrOptions ?? {};
2126
+ }
2127
+ const clear = opts.clear ?? true;
2128
+ const explicitMethod = opts.method;
2129
+ try {
2130
+ const cleanup = await runBuiltinPageCleanups(page, "before-edit");
2131
+ if (cleanup.length > 0) {
2132
+ this.logger?.log("page_cleanup", {
2133
+ stage: "before-edit",
2134
+ runs: cleanup,
2135
+ }, cleanup.every((run) => run.ok));
2136
+ }
2137
+ await locator.scrollIntoViewIfNeeded({ timeout: 5000 });
2138
+ const box = await locator.boundingBox();
2139
+ // Human bezier mouse trail to the focus target. This is cosmetic:
2140
+ // dispatchSafeClick re-measures geometry and may click a nearby fresh
2141
+ // coordinate, which is what carries the focus/click correctness.
2142
+ if (box) {
2143
+ await humanMove(page, box.x + box.width * (0.3 + Math.random() * 0.4), box.y + box.height * (0.3 + Math.random() * 0.4));
2144
+ }
2145
+ let focusClick = await dispatchSafeClick(page, locator, {
2146
+ selectorHint: selector,
2147
+ label,
2148
+ button: "left",
2149
+ dispatch: "mouse",
2150
+ purpose: "type-focus",
2151
+ });
2152
+ let focusCleanupRuns = [];
2153
+ let focusRecoveredVia;
2154
+ let targetInfo;
2155
+ if (!focusClick.ok && focusClick.fallbackReason === "event-miss") {
2156
+ focusCleanupRuns = await runBuiltinPageCleanups(page, "after-click-event-miss");
2157
+ if (focusCleanupRuns.length > 0) {
2158
+ this.logger?.log("page_cleanup", {
2159
+ stage: "after-click-event-miss",
2160
+ runs: focusCleanupRuns,
2161
+ }, focusCleanupRuns.every((run) => run.ok));
2162
+ }
2163
+ if (anyCleanupHandled(focusCleanupRuns)) {
2164
+ const retriedFocusClick = await dispatchSafeClick(page, locator, {
2165
+ selectorHint: selector,
2166
+ label,
2167
+ button: "left",
2168
+ dispatch: "mouse",
2169
+ purpose: "type-focus",
2170
+ });
2171
+ if (retriedFocusClick.ok) {
2172
+ focusRecoveredVia = "cleanup-retry";
2173
+ }
2174
+ focusClick = retriedFocusClick;
2175
+ }
2176
+ }
2177
+ if (!focusClick.ok) {
2178
+ if (focusClick.fallbackReason === "event-miss") {
2179
+ const recoveredTarget = await ensureEditableTarget(page, locator);
2180
+ if (recoveredTarget.ok) {
2181
+ targetInfo = recoveredTarget;
2182
+ focusRecoveredVia = "dom-focus";
2183
+ }
2184
+ }
2185
+ }
2186
+ if (!focusClick.ok && !targetInfo?.ok) {
2187
+ const msg = focusClick.message ?? "focus click dispatch failed";
2188
+ this.logger?.log("type", {
2189
+ ref,
2190
+ selector,
2191
+ text,
2192
+ label,
2193
+ error: msg,
2194
+ dispatchedVia: focusClick.dispatchedVia,
2195
+ ...(focusClick.probe ? { probe: focusClick.probe } : {}),
2196
+ ...(focusClick.eventProbe ? { eventProbe: focusClick.eventProbe } : {}),
2197
+ ...(focusClick.fallbackReason
2198
+ ? { fallbackReason: focusClick.fallbackReason }
2199
+ : {}),
2200
+ ...(focusCleanupRuns.length > 0 ? { focusCleanupRuns } : {}),
2201
+ recentConsole: recentConsoleEntries(page, 10),
2202
+ }, false);
2203
+ return `Error typing into ${label}: failed to focus target: ${msg}`;
2204
+ }
2205
+ // Editable-target detection: production logs show 2 cases of the
2206
+ // selector resolving to a wrapper/link/body that can't accept text.
2207
+ // A successful click on such a node leaves activeElement unchanged
2208
+ // (or focuses a non-editable host), and humanType silently throws
2209
+ // its keystrokes into the void. Inspect what we actually focused
2210
+ // and, if it's not editable, walk the locator's subtree for a
2211
+ // single editable descendant before failing.
2212
+ targetInfo ??= await ensureEditableTarget(page, locator);
2213
+ if (!targetInfo.ok) {
2214
+ this.logger?.log("type", {
2215
+ ref,
2216
+ selector,
2217
+ text,
2218
+ label,
2219
+ error: targetInfo.message,
2220
+ ...(focusRecoveredVia ? { focusRecoveredVia } : {}),
2221
+ ...(focusCleanupRuns.length > 0 ? { focusCleanupRuns } : {}),
2222
+ }, false);
2223
+ return `Error typing into ${label}: ${targetInfo.message}`;
2224
+ }
2225
+ // Snapshot the editable's pre-action state. Only used in clear:false
2226
+ // (append) mode: lets us tell, between attempts, whether the first
2227
+ // insertion actually wrote anything. If it did, the field now holds
2228
+ // partial garbage on top of the user's draft, and fallback retry
2229
+ // would compound the corruption (we can't safely clear without
2230
+ // erasing the draft, and inserting again would produce
2231
+ // `garbageHello world`-style false success in the verifier).
2232
+ //
2233
+ // Both `value` and `anchors` are snapshotted: some editors (Notion
2234
+ // bookmark, LinkedIn share, custom rich editors) convert a URL paste
2235
+ // into an `<a href>` chip that contributes nothing to innerText,
2236
+ // so a value-only comparison would miss the partial write.
2237
+ let baselineValue = "";
2238
+ let baselineAnchorKey = "";
2239
+ if (!clear) {
2240
+ try {
2241
+ const snap = await readEditable(page, targetInfo.handleSelector);
2242
+ baselineValue = snap.value;
2243
+ baselineAnchorKey = snap.anchors.slice().sort().join("\u0001");
2244
+ }
2245
+ catch {
2246
+ // Read failure pre-insert is non-fatal — we just lose the ability
2247
+ // to detect partial corruption later. Keep going.
2248
+ }
2249
+ }
2250
+ if (clear) {
2251
+ await forceClear(page, targetInfo.handleSelector);
2252
+ }
2253
+ // Method selection: explicit > rich-editor auto-paste > keyboard.
2254
+ // Rich editors (Lexical/ProseMirror/Tiptap-style editors) drop
2255
+ // per-char keystrokes that aren't part of a paste/composition event.
2256
+ const method = explicitMethod ?? (targetInfo.isRichEditor ? "paste" : "keyboard");
2257
+ await insertText(page, method, text);
2258
+ // Read-back verification + recovery. `method` is a preference, not a
2259
+ // contract — by default we still attempt a one-shot retry when the
2260
+ // first attempt didn't land. The caller can pin behavior with
2261
+ // fallback:false (useful for diagnosing a specific method's failure
2262
+ // mode).
2263
+ //
2264
+ // Recovery branches on verifier status:
2265
+ //
2266
+ // duplicated → content already landed (often paste landed but
2267
+ // verifier missed React's commit window, OR the
2268
+ // prior clear silently no-op'd and we appended).
2269
+ // Switching to the alt method would type a THIRD
2270
+ // copy on top. Only safe move is forceClear +
2271
+ // retry with the SAME method.
2272
+ //
2273
+ // missing_text / error → content didn't land. Switch to alt method.
2274
+ // Production data shows this path does sometimes
2275
+ // save an otherwise-failed run.
2276
+ //
2277
+ // Rich-editor verifier gets a 2000ms window (vs 800ms for inputs)
2278
+ // because Draft.js / Lexical / ProseMirror commit through React's
2279
+ // reducer and can stall past 800ms when the page is busy closing a
2280
+ // modal or animating. Most successes still land in <200ms.
2281
+ const verifyTimeoutMs = targetInfo.isRichEditor ? 2000 : 800;
2282
+ const allowFallback = opts.fallback !== false;
2283
+ let verify = await verifyInsertedText(targetInfo.handleSelector, page, text, { timeoutMs: verifyTimeoutMs });
2284
+ let methodUsed = method;
2285
+ let fallbackUsed = false;
2286
+ // Same-method retry on duplicated. Only applicable with clear:true —
2287
+ // in append mode we can't safely reclear without destroying the
2288
+ // user's draft, and the partial-write detector below will surface
2289
+ // the failure to the caller instead.
2290
+ if (!verify.ok &&
2291
+ verify.status === "duplicated" &&
2292
+ allowFallback &&
2293
+ clear) {
2294
+ await forceClear(page, targetInfo.handleSelector);
2295
+ await insertText(page, method, text);
2296
+ verify = await verifyInsertedText(targetInfo.handleSelector, page, text, { timeoutMs: verifyTimeoutMs });
2297
+ // methodUsed unchanged; fallbackUsed stays false — this is the same
2298
+ // method, retried cleanly. Not a true alt-method fallback.
2299
+ }
2300
+ // Alt-method fallback. Only for genuine non-landing failures
2301
+ // (missing_text / error). Skip when status is still "duplicated"
2302
+ // after the same-method retry — switching method at that point would
2303
+ // stack a third copy on top of two.
2304
+ if (!verify.ok && verify.status !== "duplicated" && allowFallback) {
2305
+ const altMethod = method === "paste" ? "keyboard" : "paste";
2306
+ // Pre-retry safety check.
2307
+ //
2308
+ // clear:true → we own the field's content; forceClear and retry
2309
+ // with the alternate method. Clean.
2310
+ //
2311
+ // clear:false (append) → field contains the user's draft. We MUST
2312
+ // NOT forceClear (would destroy the draft). But we
2313
+ // also can't blindly retry: if the first attempt
2314
+ // partially wrote (e.g. rich editor accepted some
2315
+ // chars and dropped others), the field now holds
2316
+ // `<draft><partial garbage>`. Appending the full text
2317
+ // again would give `<draft><partial garbage><expected>`
2318
+ // — the verifier's substring check would pass, and
2319
+ // we'd return success on a corrupted field. So:
2320
+ // compare the current value to the baseline we
2321
+ // snapshotted. If it changed, partial write happened
2322
+ // — bail to the caller with a clear diagnostic. If
2323
+ // unchanged, the first attempt was a no-op and it's
2324
+ // safe to retry with the alternate method.
2325
+ if (clear) {
2326
+ await forceClear(page, targetInfo.handleSelector);
2327
+ }
2328
+ else {
2329
+ let currentValue = baselineValue;
2330
+ let currentAnchorKey = baselineAnchorKey;
2331
+ let readFailed = false;
2332
+ try {
2333
+ const snap = await readEditable(page, targetInfo.handleSelector);
2334
+ currentValue = snap.value;
2335
+ currentAnchorKey = snap.anchors.slice().sort().join("\u0001");
2336
+ }
2337
+ catch {
2338
+ // Read failure is treated as "we can not prove the field is
2339
+ // clean" - same as a partial-write case. Bail.
2340
+ readFailed = true;
2341
+ }
2342
+ const valueChanged = currentValue !== baselineValue;
2343
+ const anchorsChanged = currentAnchorKey !== baselineAnchorKey;
2344
+ if (readFailed || valueChanged || anchorsChanged) {
2345
+ const partialKind = readFailed
2346
+ ? "readback-failed"
2347
+ : valueChanged && anchorsChanged
2348
+ ? "value+anchor"
2349
+ : valueChanged
2350
+ ? "value"
2351
+ : "anchor";
2352
+ this.logger?.log("type", {
2353
+ ref,
2354
+ selector,
2355
+ text,
2356
+ label,
2357
+ method,
2358
+ clear,
2359
+ verifyStatus: verify.status,
2360
+ partialKind,
2361
+ error: "append-mode partial write detected; refusing to fallback to avoid corrupting the field",
2362
+ }, false);
2363
+ const detail = readFailed
2364
+ ? "post-attempt readback failed"
2365
+ : anchorsChanged && !valueChanged
2366
+ ? "first attempt added a link/anchor chip without visible text"
2367
+ : "first attempt partially wrote into the field";
2368
+ return (`Error typing into ${label}: ${detail} (clear:false / append mode); ` +
2369
+ `refusing automatic fallback because retrying with the alternate ` +
2370
+ `method would compound the corruption and could be reported as a ` +
2371
+ `false success. Inspect the editable, clean up manually, then call ` +
2372
+ `type again with the desired method. Resolved target: ${targetInfo.diagnostic}.`);
2373
+ }
2374
+ // First attempt was a no-op (editor dropped everything). Safe to
2375
+ // retry without clearing.
2376
+ }
2377
+ await insertText(page, altMethod, text);
2378
+ verify = await verifyInsertedText(targetInfo.handleSelector, page, text, { timeoutMs: verifyTimeoutMs });
2379
+ methodUsed = altMethod;
2380
+ fallbackUsed = true;
2381
+ }
2382
+ if (!verify.ok) {
2383
+ // Pull rich diagnostics so the failure log can disambiguate "true
2384
+ // double insert" / "stale + paste" / "verifier false positive" /
2385
+ // "React crash mid-render" without needing a live repro. Best-
2386
+ // effort — if the page is mid-navigation the read can throw.
2387
+ let diag;
2388
+ try {
2389
+ diag = await dumpEditorDiagnostics(page, targetInfo.handleSelector, text);
2390
+ }
2391
+ catch (err) {
2392
+ diag = { error: err instanceof Error ? err.message : String(err) };
2393
+ }
2394
+ const consoleTail = recentConsoleEntries(page, 8);
2395
+ // Anti-bypass guidance is critical: production traces show the LLM
2396
+ // rewriting user content (dropping URLs, shortening text) to make
2397
+ // the verifier pass. That's wrong — verifier failure is a tooling
2398
+ // signal, not a content signal. Spell this out in the error.
2399
+ this.logger?.log("type", {
2400
+ ref,
2401
+ selector,
2402
+ text,
2403
+ label,
2404
+ method,
2405
+ clear,
2406
+ ...(fallbackUsed ? { fallbackMethod: methodUsed } : {}),
2407
+ verifyStatus: verify.status,
2408
+ ...(verify.missingChunks
2409
+ ? { missingChunks: verify.missingChunks }
2410
+ : {}),
2411
+ ...(verify.message ? { error: verify.message } : {}),
2412
+ ...(focusRecoveredVia ? { focusRecoveredVia } : {}),
2413
+ ...(focusCleanupRuns.length > 0 ? { focusCleanupRuns } : {}),
2414
+ diag,
2415
+ ...(consoleTail.length ? { consoleTail } : {}),
2416
+ }, false);
2417
+ const attempts = fallbackUsed
2418
+ ? `both ${method} and ${methodUsed}`
2419
+ : `${method}`;
2420
+ return (`Error typing into ${label}: ${summarizeVerifyForError(verify)} ` +
2421
+ `Attempted: ${attempts}. Resolved target: ${targetInfo.diagnostic}. ` +
2422
+ `Do not work around this by deleting URLs, shortening text, or rewriting ` +
2423
+ `the user's content — this is an input/verifier issue, not a content ` +
2424
+ `issue. Take a fresh snapshot, try a more specific selector for the editable, ` +
2425
+ `or call type again (the verifier already polled and retried with the ` +
2426
+ `alternate method).`);
2427
+ }
2428
+ // Submit only after the text has been verified in the focused editable.
2429
+ // For SPA search boxes, pressing Enter can immediately navigate and move
2430
+ // focus to <body>; verifying after that creates false failures and can
2431
+ // trigger an unsafe alternate-method paste into the wrong element. The
2432
+ // dispatch-level `expect` block is responsible for post-submit state
2433
+ // such as URL/result changes.
2434
+ //
2435
+ // Routed through dispatchSafeKeyPress so this Enter shares the same
2436
+ // keyboard→dom fallback as actions.pressKey — without it, search-form
2437
+ // submits silently no-op whenever CDP synthetic-input is dropped (the
2438
+ // text lands, the URL never changes; observed often in production X.com
2439
+ // search flows).
2440
+ let submitResult;
2441
+ if (opts.submit) {
2442
+ submitResult = await dispatchSafeKeyPress(page, "Enter");
2443
+ }
2444
+ this.logger?.log("type", {
2445
+ ref,
2446
+ selector,
2447
+ text,
2448
+ clear,
2449
+ submit: opts.submit,
2450
+ method: methodUsed,
2451
+ fallbackUsed,
2452
+ verifyStatus: verify.status,
2453
+ ...(focusRecoveredVia ? { focusRecoveredVia } : {}),
2454
+ ...(focusCleanupRuns.length > 0 ? { focusCleanupRuns } : {}),
2455
+ ...(verify.missingUrls?.length
2456
+ ? { urlsNotVisible: verify.missingUrls }
2457
+ : {}),
2458
+ ...(submitResult
2459
+ ? {
2460
+ submitDispatchedVia: submitResult.dispatchedVia,
2461
+ ...(submitResult.fallbackUsed ? { submitFallbackUsed: true } : {}),
2462
+ ...(submitResult.eventProbe
2463
+ ? { submitEventProbe: submitResult.eventProbe }
2464
+ : {}),
2465
+ ...(submitResult.fallbackError
2466
+ ? { submitFallbackError: submitResult.fallbackError }
2467
+ : {}),
2468
+ ...(submitResult.physicalError
2469
+ ? { submitError: submitResult.physicalError }
2470
+ : {}),
2471
+ }
2472
+ : {}),
2473
+ label,
2474
+ }, submitResult ? submitResult.ok : true);
2475
+ const fallbackNote = fallbackUsed
2476
+ ? ` (fallback ${method}→${methodUsed})`
2477
+ : "";
2478
+ const submitNote = submitResult?.fallbackUsed
2479
+ ? " [submit via dom dispatch]"
2480
+ : "";
2481
+ // If submit Enter failed, return an Error-prefixed string so
2482
+ // dispatchBrowserActionDetailed's isFailureText catches it as a real
2483
+ // failure. Without the prefix, callers without an `expect` block would
2484
+ // see "Typed ..." and treat the whole action as successful even though
2485
+ // Enter never reached the page — the inline "[submit Enter failed]"
2486
+ // note alone is not enough because isFailureText only matches on
2487
+ // leading "Error[:\\s]" / "Wait timeout:" / "[verification failed]"
2488
+ // prefixes.
2489
+ if (submitResult && !submitResult.ok) {
2490
+ const reason = submitResult.physicalError ??
2491
+ (submitResult.fallbackError
2492
+ ? `physical input not delivered; dom fallback refused: ${submitResult.fallbackError}`
2493
+ : "physical input not delivered to renderer");
2494
+ return `Error typing into ${label}: text inserted (method=${methodUsed}${fallbackNote}) but submit Enter failed: ${reason}`;
2495
+ }
2496
+ // Surface the URL-not-visible warning to the caller. Body landed,
2497
+ // but at least one URL didn't show up as text or as a matching <a> —
2498
+ // the LLM should know this is best-effort (link card / shortener)
2499
+ // and NOT a reason to retype without the URL.
2500
+ const urlWarn = verify.status === "ok_url_warning" && verify.missingUrls?.length
2501
+ ? ` [url-not-visible: ${verify.missingUrls.join(", ")} — likely transformed into a link card or shortener; do not remove the URL]`
2502
+ : "";
2503
+ return `Typed "${text}" into ${label} [method=${methodUsed}${fallbackNote}]${urlWarn}${submitNote}`;
2504
+ }
2505
+ catch (err) {
2506
+ const msg = err instanceof Error ? err.message : String(err);
2507
+ this.logger?.log("type", { ref, selector, text, label, error: msg }, false);
2508
+ return `Error typing into ${label}: ${msg}`;
2509
+ }
2510
+ }
2511
+ async pressKey(key, delayMs) {
2512
+ await this.interActionDelay();
2513
+ const page = await this.browser.getActivePage();
2514
+ if (delayMs && delayMs > 0) {
2515
+ const clamped = Math.min(delayMs, 5000);
2516
+ await new Promise((r) => setTimeout(r, clamped));
2517
+ }
2518
+ const r = await dispatchSafeKeyPress(page, key);
2519
+ if (!r.ok) {
2520
+ // ok=false covers two cases: physical threw, OR probe shows the key
2521
+ // never reached the renderer AND evaluateDomKey refused it (modifier
2522
+ // combo, printable char outside KNOWN table, no active element).
2523
+ const reason = r.physicalError ??
2524
+ (r.fallbackError
2525
+ ? `physical input not delivered to renderer; dom fallback refused: ${r.fallbackError}`
2526
+ : "physical input not delivered to renderer");
2527
+ this.logger?.log("press", {
2528
+ key,
2529
+ delayMs,
2530
+ dispatchedVia: r.dispatchedVia,
2531
+ error: reason,
2532
+ ...(r.eventProbe ? { eventProbe: r.eventProbe } : {}),
2533
+ ...(r.fallbackError ? { fallbackError: r.fallbackError } : {}),
2534
+ }, false);
2535
+ return `Error pressing ${key}: ${reason}`;
2536
+ }
2537
+ this.logger?.log("press", {
2538
+ key,
2539
+ delayMs,
2540
+ dispatchedVia: r.dispatchedVia,
2541
+ ...(r.eventProbe ? { eventProbe: r.eventProbe } : {}),
2542
+ ...(r.fallbackUsed ? { fallbackUsed: true } : {}),
2543
+ ...(r.fallbackError && !r.fallbackUsed
2544
+ ? { fallbackError: r.fallbackError }
2545
+ : {}),
2546
+ });
2547
+ return `Pressed key: ${key}${r.fallbackUsed ? " (via dom dispatch)" : ""}`;
2548
+ }
2549
+ async hover(ref, selector) {
2550
+ await this.interActionDelay();
2551
+ const page = await this.browser.getActivePage();
2552
+ let locator;
2553
+ let label;
2554
+ if (ref) {
2555
+ const r = await locateRefWithRecovery(page, ref, { destructive: false });
2556
+ if (!r.ok) {
2557
+ this.logger?.log("hover", { ref, error: r.message }, false);
2558
+ return r.message;
2559
+ }
2560
+ locator = r.locator;
2561
+ label = r.label;
2562
+ }
2563
+ else if (selector != null) {
2564
+ const r = resolveSelector(page, selector);
2565
+ if (!r.ok) {
2566
+ this.logger?.log("hover", { selector, error: r.error }, false);
2567
+ return r.error;
2568
+ }
2569
+ locator = r.locator;
2570
+ label = r.selector;
2571
+ }
2572
+ else {
2573
+ return "Error: hover requires ref or selector.";
2574
+ }
2575
+ let probeId;
2576
+ let eventProbe;
2577
+ let fallbackUsed = false;
2578
+ let dispatchedVia = "mouse";
2579
+ try {
2580
+ await locator.scrollIntoViewIfNeeded({ timeout: 5000 });
2581
+ // Stamp the resolved element so the probe can match composedPath against
2582
+ // a specific node (same pattern dispatchSafeClick uses).
2583
+ const stamp = makeClickStamp();
2584
+ await stampClickTarget(locator, stamp);
2585
+ const stampSelector = clickStampSelector(stamp);
2586
+ probeId = makeClickStamp();
2587
+ await installHoverEventProbe(page, stampSelector, probeId);
2588
+ // Human mouse movement before hover
2589
+ const box = await locator.boundingBox();
2590
+ if (box) {
2591
+ await humanMove(page, box.x + box.width * (0.3 + Math.random() * 0.4), box.y + box.height * (0.3 + Math.random() * 0.4));
2592
+ }
2593
+ await locator.hover({ timeout: 5000 });
2594
+ eventProbe = await readAndClearHoverEventProbe(page, probeId).catch(() => undefined);
2595
+ probeId = undefined;
2596
+ // Same failure mode as click: Playwright reports hover ok, but no
2597
+ // pointer/mouse event reached the document. Fall back to JS-dispatched
2598
+ // hover events so React's onMouseEnter still fires (which is what
2599
+ // triggers X's hover-card fetch).
2600
+ //
2601
+ // Re-resolve and re-stamp the locator before the DOM dispatch — same
2602
+ // reason dispatchSafeClick re-stamps on event-miss: if React replaced
2603
+ // the element between the initial stamp and locator.hover(), the
2604
+ // original stamp is on a detached node and the original stampSelector
2605
+ // matches nothing. The physical hover may have actually succeeded on
2606
+ // the replacement; either way the DOM dispatch must target the live
2607
+ // node, not the detached one.
2608
+ if (eventProbe && !hoverEventReachedTarget(eventProbe)) {
2609
+ let fallbackSelector = stampSelector;
2610
+ try {
2611
+ const restamp = makeClickStamp();
2612
+ await stampClickTarget(locator, restamp);
2613
+ fallbackSelector = clickStampSelector(restamp);
2614
+ }
2615
+ catch {
2616
+ // Locator no longer resolves at all — fall through with the original
2617
+ // selector; evaluateDomHover will return not-found and we'll report
2618
+ // that as the fallback error.
2619
+ }
2620
+ const domHover = await evaluateDomHover(page, fallbackSelector);
2621
+ if (domHover.ok) {
2622
+ fallbackUsed = true;
2623
+ dispatchedVia = "dom";
2624
+ }
2625
+ else {
2626
+ this.logger?.log("hover", {
2627
+ ref,
2628
+ selector,
2629
+ label,
2630
+ dispatchedVia,
2631
+ eventProbe,
2632
+ fallbackReason: "event-miss",
2633
+ fallbackError: `dom dispatch failed: ${domHover.reason}`,
2634
+ }, false);
2635
+ return `Error hovering ${label}: physical mouse event did not reach target and dom-dispatch fallback failed (${domHover.reason})`;
2636
+ }
2637
+ }
2638
+ this.logger?.log("hover", {
2639
+ ref,
2640
+ selector,
2641
+ label,
2642
+ dispatchedVia,
2643
+ ...(eventProbe ? { eventProbe } : {}),
2644
+ ...(fallbackUsed ? { fallbackUsed: true } : {}),
2645
+ });
2646
+ return `Hovered ${label}${fallbackUsed ? " (via dom dispatch)" : ""}`;
2647
+ }
2648
+ catch (err) {
2649
+ const msg = err instanceof Error ? err.message : String(err);
2650
+ this.logger?.log("hover", {
2651
+ ref,
2652
+ selector,
2653
+ label,
2654
+ error: msg,
2655
+ ...(eventProbe ? { eventProbe } : {}),
2656
+ }, false);
2657
+ return `Error hovering ${label}: ${msg}`;
2658
+ }
2659
+ finally {
2660
+ if (probeId) {
2661
+ await readAndClearHoverEventProbe(page, probeId).catch(() => { });
2662
+ }
2663
+ }
2664
+ }
2665
+ async drag(startRef, endRef, startSelector, endSelector) {
2666
+ await this.interActionDelay();
2667
+ const page = await this.browser.getActivePage();
2668
+ let source;
2669
+ let target;
2670
+ let startLabel;
2671
+ let endLabel;
2672
+ if (startRef) {
2673
+ const r = await locateRefWithRecovery(page, startRef, {
2674
+ destructive: false,
2675
+ label: "start element",
2676
+ });
2677
+ if (!r.ok)
2678
+ return r.message;
2679
+ source = r.locator;
2680
+ startLabel = r.label;
2681
+ }
2682
+ else if (startSelector != null) {
2683
+ const r = resolveSelector(page, startSelector, "startSelector");
2684
+ if (!r.ok)
2685
+ return r.error;
2686
+ source = r.locator;
2687
+ startLabel = r.selector;
2688
+ }
2689
+ else {
2690
+ return "Error: drag requires startRef or startSelector.";
2691
+ }
2692
+ if (endRef) {
2693
+ const r = await locateRefWithRecovery(page, endRef, {
2694
+ destructive: false,
2695
+ label: "end element",
2696
+ });
2697
+ if (!r.ok)
2698
+ return r.message;
2699
+ target = r.locator;
2700
+ endLabel = r.label;
2701
+ }
2702
+ else if (endSelector != null) {
2703
+ const r = resolveSelector(page, endSelector, "endSelector");
2704
+ if (!r.ok)
2705
+ return r.error;
2706
+ target = r.locator;
2707
+ endLabel = r.selector;
2708
+ }
2709
+ else {
2710
+ return "Error: drag requires endRef or endSelector.";
2711
+ }
2712
+ try {
2713
+ await source.scrollIntoViewIfNeeded({ timeout: 5000 });
2714
+ const srcBox = await source.boundingBox();
2715
+ const tgtBox = await target.boundingBox();
2716
+ if (srcBox && tgtBox) {
2717
+ // Human drag: bezier to source, mousedown, bezier to target, mouseup
2718
+ await humanDrag(page, srcBox.x + srcBox.width * (0.3 + Math.random() * 0.4), srcBox.y + srcBox.height * (0.3 + Math.random() * 0.4), tgtBox.x + tgtBox.width * (0.3 + Math.random() * 0.4), tgtBox.y + tgtBox.height * (0.3 + Math.random() * 0.4));
2719
+ }
2720
+ else {
2721
+ // Fallback to Playwright native
2722
+ await source.dragTo(target, { timeout: 10_000 });
2723
+ }
2724
+ this.logger?.log("drag", { startRef, endRef, startSelector, endSelector });
2725
+ return `Dragged from ${startLabel} to ${endLabel}`;
2726
+ }
2727
+ catch (err) {
2728
+ const msg = err instanceof Error ? err.message : String(err);
2729
+ return `Error dragging: ${msg}`;
2730
+ }
2731
+ }
2732
+ async selectOption(ref, values, selector) {
2733
+ await this.interActionDelay();
2734
+ const page = await this.browser.getActivePage();
2735
+ const valArray = Array.isArray(values) ? values : [values];
2736
+ let locator;
2737
+ let label;
2738
+ if (ref) {
2739
+ const r = await locateRefWithRecovery(page, ref, { destructive: false });
2740
+ if (!r.ok)
2741
+ return r.message;
2742
+ locator = r.locator;
2743
+ label = r.label;
2744
+ }
2745
+ else if (selector != null) {
2746
+ const r = resolveSelector(page, selector);
2747
+ if (!r.ok)
2748
+ return r.error;
2749
+ locator = r.locator;
2750
+ label = r.selector;
2751
+ }
2752
+ else {
2753
+ return "Error: select requires ref or selector.";
2754
+ }
2755
+ try {
2756
+ await locator.selectOption(valArray, { timeout: 5000 });
2757
+ this.logger?.log("select", { ref, selector, values: valArray });
2758
+ return `Selected ${JSON.stringify(valArray)} in ${label}`;
2759
+ }
2760
+ catch (err) {
2761
+ const msg = err instanceof Error ? err.message : String(err);
2762
+ return `Error selecting option: ${msg}`;
2763
+ }
2764
+ }
2765
+ async fill(fields) {
2766
+ await this.interActionDelay();
2767
+ const page = await this.browser.getActivePage();
2768
+ const results = [];
2769
+ for (const field of fields) {
2770
+ const r = await locateRefWithRecovery(page, field.ref, {
2771
+ destructive: false,
2772
+ label: "element",
2773
+ selectorParam: null,
2774
+ });
2775
+ if (!r.ok) {
2776
+ return r.message + ` (failed at field ${results.length + 1})`;
2777
+ }
2778
+ try {
2779
+ if (field.type === "checkbox" || field.type === "radio") {
2780
+ const checked = field.value === "true" ||
2781
+ field.value === "1" ||
2782
+ field.value === "yes";
2783
+ await r.locator.setChecked(checked, { timeout: 5000 });
2784
+ }
2785
+ else {
2786
+ await r.locator.fill(field.value, { timeout: 5000 });
2787
+ }
2788
+ results.push(`${r.label} = "${field.value}"`);
2789
+ }
2790
+ catch (err) {
2791
+ const msg = err instanceof Error ? err.message : String(err);
2792
+ return `Error filling field ${field.ref}: ${msg}`;
2793
+ }
2794
+ }
2795
+ this.logger?.log("fill", { count: fields.length });
2796
+ return `Filled ${results.length} field(s):\n${results.join("\n")}`;
2797
+ }
2798
+ async resize(width, height) {
2799
+ const page = await this.browser.getActivePage();
2800
+ await page.setViewportSize({ width, height });
2801
+ this.logger?.log("resize", { width, height });
2802
+ return `Viewport resized to ${width}x${height}`;
2803
+ }
2804
+ async wait(opts) {
2805
+ const page = await this.browser.getActivePage();
2806
+ const timeout = opts.timeoutMs || 10000;
2807
+ try {
2808
+ // timeMs: simple delay (capped at 30s)
2809
+ if (opts.timeMs != null) {
2810
+ const ms = Math.min(Math.max(Math.round(opts.timeMs), 0), 30_000);
2811
+ await page.waitForTimeout(ms);
2812
+ this.logger?.log("wait", { timeMs: ms });
2813
+ return `Waited ${ms}ms`;
2814
+ }
2815
+ // --- UI-state-driven conditions (P1-2). These take priority over the
2816
+ // generic selector match below because they're more specific and the
2817
+ // typical SPA use case is "wait until X is visible/enabled/stable",
2818
+ // not "wait until X exists in the DOM" (which fires too early when
2819
+ // React mounts the node before it has content).
2820
+ if (opts.selectorVisible) {
2821
+ const norm = normalizeSelector(opts.selectorVisible);
2822
+ if (!norm.ok)
2823
+ return `Wait error: ${norm.error}`;
2824
+ await page.locator(norm.selector).first().waitFor({
2825
+ state: "visible",
2826
+ timeout,
2827
+ });
2828
+ this.logger?.log("wait", { selectorVisible: norm.selector });
2829
+ return `Selector visible: ${norm.selector}`;
2830
+ }
2831
+ if (opts.selectorHidden) {
2832
+ const norm = normalizeSelector(opts.selectorHidden);
2833
+ if (!norm.ok)
2834
+ return `Wait error: ${norm.error}`;
2835
+ await page.locator(norm.selector).first().waitFor({
2836
+ state: "hidden",
2837
+ timeout,
2838
+ });
2839
+ this.logger?.log("wait", { selectorHidden: norm.selector });
2840
+ return `Selector hidden: ${norm.selector}`;
2841
+ }
2842
+ if (opts.selectorEnabled) {
2843
+ const norm = normalizeSelector(opts.selectorEnabled);
2844
+ if (!norm.ok)
2845
+ return `Wait error: ${norm.error}`;
2846
+ await waitForCondition(timeout, async () => {
2847
+ try {
2848
+ return await page.locator(norm.selector).first().isEnabled();
2849
+ }
2850
+ catch {
2851
+ return false;
2852
+ }
2853
+ });
2854
+ this.logger?.log("wait", { selectorEnabled: norm.selector });
2855
+ return `Selector enabled: ${norm.selector}`;
2856
+ }
2857
+ if (opts.selectorDisabled) {
2858
+ const norm = normalizeSelector(opts.selectorDisabled);
2859
+ if (!norm.ok)
2860
+ return `Wait error: ${norm.error}`;
2861
+ await waitForCondition(timeout, async () => {
2862
+ try {
2863
+ return await page.locator(norm.selector).first().isDisabled();
2864
+ }
2865
+ catch {
2866
+ return false;
2867
+ }
2868
+ });
2869
+ this.logger?.log("wait", { selectorDisabled: norm.selector });
2870
+ return `Selector disabled: ${norm.selector}`;
2871
+ }
2872
+ if (opts.urlMatches) {
2873
+ let re;
2874
+ try {
2875
+ re = new RegExp(opts.urlMatches);
2876
+ }
2877
+ catch (err) {
2878
+ return `Wait error: invalid urlMatches regex (${err instanceof Error ? err.message : String(err)})`;
2879
+ }
2880
+ await waitForCondition(timeout, async () => re.test(page.url()));
2881
+ this.logger?.log("wait", { urlMatches: opts.urlMatches, url: page.url() });
2882
+ return `URL matched regex ${opts.urlMatches} → ${page.url()}`;
2883
+ }
2884
+ if (opts.textCountAtLeast) {
2885
+ const tcl = opts.textCountAtLeast;
2886
+ const norm = normalizeSelector(tcl.selector);
2887
+ if (!norm.ok)
2888
+ return `Wait error: ${norm.error}`;
2889
+ const want = Math.max(1, Math.floor(tcl.count));
2890
+ let lastSeen = 0;
2891
+ await waitForCondition(timeout, async () => {
2892
+ try {
2893
+ lastSeen = await page.locator(norm.selector).count();
2894
+ return lastSeen >= want;
2895
+ }
2896
+ catch {
2897
+ return false;
2898
+ }
2899
+ });
2900
+ this.logger?.log("wait", { textCountAtLeast: tcl, lastSeen });
2901
+ return `Selector ${norm.selector} count ≥ ${want} (saw ${lastSeen})`;
2902
+ }
2903
+ if (opts.locatorStableMs != null) {
2904
+ const sel = opts.selector ?? opts.selectorVisible;
2905
+ if (!sel) {
2906
+ return "Wait error: locatorStableMs requires `selector` or `selectorVisible`.";
2907
+ }
2908
+ const norm = normalizeSelector(sel);
2909
+ if (!norm.ok)
2910
+ return `Wait error: ${norm.error}`;
2911
+ const stable = Math.min(Math.max(opts.locatorStableMs, 50), 10_000);
2912
+ const ok = await waitForLocatorStable(page, norm.selector, stable, timeout);
2913
+ this.logger?.log("wait", { locatorStableMs: stable, selector: norm.selector });
2914
+ if (!ok)
2915
+ return `Wait timeout: locator ${norm.selector} did not stabilize within ${stable}ms`;
2916
+ return `Locator ${norm.selector} stable for ${stable}ms`;
2917
+ }
2918
+ if (opts.domQuietMs != null) {
2919
+ const quiet = Math.min(Math.max(opts.domQuietMs, 50), 10_000);
2920
+ const ok = await waitForDomQuiet(page, quiet, timeout);
2921
+ this.logger?.log("wait", { domQuietMs: quiet });
2922
+ if (!ok)
2923
+ return `Wait timeout: DOM did not stay quiet for ${quiet}ms`;
2924
+ return `DOM quiet for ${quiet}ms`;
2925
+ }
2926
+ // --- Original conditions kept for backward compat ---
2927
+ if (opts.selector) {
2928
+ const norm = normalizeSelector(opts.selector);
2929
+ if (!norm.ok) {
2930
+ this.logger?.log("wait", { selector: opts.selector, error: norm.error }, false);
2931
+ return `Wait error: ${norm.error}`;
2932
+ }
2933
+ await page.waitForSelector(norm.selector, { timeout });
2934
+ this.logger?.log("wait", { selector: norm.selector });
2935
+ return `Found element matching: ${norm.selector}`;
2936
+ }
2937
+ if (opts.text) {
2938
+ await page.getByText(opts.text).first().waitFor({ timeout });
2939
+ this.logger?.log("wait", { text: opts.text });
2940
+ return `Found text: "${opts.text}"`;
2941
+ }
2942
+ if (opts.textGone) {
2943
+ await page
2944
+ .getByText(opts.textGone)
2945
+ .first()
2946
+ .waitFor({ state: "hidden", timeout });
2947
+ this.logger?.log("wait", { textGone: opts.textGone });
2948
+ return `Text disappeared: "${opts.textGone}"`;
2949
+ }
2950
+ if (opts.url) {
2951
+ await page.waitForURL(opts.url, { timeout });
2952
+ this.logger?.log("wait", { url: opts.url });
2953
+ return `URL matched: ${opts.url}`;
2954
+ }
2955
+ if (opts.loadState) {
2956
+ await page.waitForLoadState(opts.loadState, { timeout });
2957
+ this.logger?.log("wait", { loadState: opts.loadState });
2958
+ return `Load state reached: ${opts.loadState}`;
2959
+ }
2960
+ if (opts.fn) {
2961
+ await page.waitForFunction(opts.fn, undefined, { timeout });
2962
+ this.logger?.log("wait", { fn: opts.fn });
2963
+ return `Function condition met`;
2964
+ }
2965
+ // Default: domcontentloaded — networkidle is unreliable on SPAs that
2966
+ // keep long-poll/streaming connections open even when the UI is idle.
2967
+ await page.waitForLoadState("domcontentloaded", { timeout });
2968
+ this.logger?.log("wait", { state: "domcontentloaded" });
2969
+ return "Page loaded (DOM content)";
2970
+ }
2971
+ catch (err) {
2972
+ const msg = err instanceof Error ? err.message : String(err);
2973
+ this.logger?.log("wait", { ...opts, error: msg }, false);
2974
+ return `Wait timeout: ${msg} (current url: ${page.url()}, title: ${JSON.stringify(await page.title().catch(() => ""))})`;
2975
+ }
2976
+ }
2977
+ async evaluate(script) {
2978
+ await this.interActionDelay();
2979
+ const page = await this.browser.getActivePage();
2980
+ // Cheap syntactic sanity check via `new Function` — no DOM, no round-trip.
2981
+ // Production logs showed 7 evaluate syntax errors that Playwright
2982
+ // surfaced as runtime "Unexpected token …" — same diagnostic the LLM
2983
+ // gets from the page, but minus the 50-300ms round trip and minus
2984
+ // anything ambiguous about whether the failure was parse or runtime.
2985
+ const preflight = preflightEvaluateScript(script);
2986
+ if (!preflight.ok) {
2987
+ this.logger?.log("evaluate", { script, error: `parse: ${preflight.message}` }, false);
2988
+ return (`Error: evaluate parse failure (caught before page execution): ${preflight.message}. ` +
2989
+ `Tip: for common patterns, prefer high-level act kinds: ` +
2990
+ `extractVisibleText, queryByText, findClickableNearText, extractLinks.`);
2991
+ }
2992
+ try {
2993
+ // Playwright's page.evaluate(string) treats the string as an expression
2994
+ // and does NOT auto-invoke function literals. Wrap so that:
2995
+ // "() => x" → invoked via ((...))()
2996
+ // "function(){}" → invoked via ((...))()
2997
+ // "document.title" → returned as-is
2998
+ // "window.scrollBy(0, 100)" → returned as-is, void 0 → 'ok'
2999
+ // The outer IIFE also normalizes undefined return (some Playwright 1.5x
3000
+ // versions throw "reading 'length'" when serializing undefined).
3001
+ const wrapped = wrapEvaluateScript(script);
3002
+ const result = await page.evaluate(wrapped);
3003
+ let resultStr = typeof result === "string" ? result : JSON.stringify(result, null, 2);
3004
+ // Cap evaluate result to prevent context blowout. safeSliceHead/Tail
3005
+ // guarantee we never split a surrogate pair at the cut, which would
3006
+ // otherwise be relayed back through the LLM request body as a lone
3007
+ // surrogate and trigger a 400 from the Anthropic API.
3008
+ const MAX_EVAL_RESULT = 16_000;
3009
+ if (resultStr.length > MAX_EVAL_RESULT) {
3010
+ const headLen = Math.floor(MAX_EVAL_RESULT * 0.7);
3011
+ const tailLen = Math.floor(MAX_EVAL_RESULT * 0.3);
3012
+ const head = safeSliceHead(resultStr, headLen);
3013
+ const tail = safeSliceTail(resultStr, tailLen);
3014
+ const trimmed = resultStr.length - head.length - tail.length;
3015
+ resultStr = `${head}\n\n[...truncated ${trimmed} chars...]\n\n${tail}`;
3016
+ }
3017
+ this.logger?.log("evaluate", { script, resultLength: resultStr.length });
3018
+ return resultStr || "(no return value)";
3019
+ }
3020
+ catch (err) {
3021
+ const msg = err instanceof Error ? err.message : String(err);
3022
+ this.logger?.log("evaluate", { script, error: msg }, false);
3023
+ return `Error: ${msg}`;
3024
+ }
3025
+ }
3026
+ // =====================
3027
+ // Tab management
3028
+ // =====================
3029
+ async openTab(url) {
3030
+ await this.interActionDelay();
3031
+ const page = await this.browser.newPage();
3032
+ // Active page switched + new DOM → prior refs are invalid.
3033
+ resetRefs();
3034
+ const navResult = await navigateWithRecovery(page, url);
3035
+ const title = await page.title().catch(() => "(no title)");
3036
+ this.logger?.log("open", {
3037
+ url,
3038
+ title,
3039
+ ...(navResult.attempt > 1 ? { attempts: navResult.attempt } : {}),
3040
+ ...(navResult.recovered ? { recovered: true } : {}),
3041
+ });
3042
+ if (!navResult.ok && !navResult.recovered) {
3043
+ return `${navResult.text} (tab ${title})`;
3044
+ }
3045
+ return `Opened new tab: ${title} — ${navResult.finalUrl}${navResult.recovered ? " [nav recovered]" : ""}`;
3046
+ }
3047
+ async listTabs() {
3048
+ const pages = await this.browser.getPages();
3049
+ const tabs = await Promise.all(pages.map(async (p, i) => {
3050
+ const title = await p.title();
3051
+ return `[${i}] ${title} - ${p.url()}`;
3052
+ }));
3053
+ return tabs.length > 0 ? tabs.join("\n") : "(no tabs open)";
3054
+ }
3055
+ async closeTab(index) {
3056
+ const pages = await this.browser.getPages();
3057
+ if (index < 0 || index >= pages.length) {
3058
+ return `Error: invalid tab index ${index}. Have ${pages.length} tabs.`;
3059
+ }
3060
+ const title = await pages[index].title();
3061
+ await pages[index].close();
3062
+ // Active page likely switched; regardless, current refs are no longer trustworthy.
3063
+ resetRefs();
3064
+ this.logger?.log("close_tab", { index, title });
3065
+ return `Closed tab [${index}]: ${title}`;
3066
+ }
3067
+ async focusTab(index) {
3068
+ const pages = await this.browser.getPages();
3069
+ if (index < 0 || index >= pages.length) {
3070
+ return `Error: invalid tab index ${index}. Have ${pages.length} tabs.`;
3071
+ }
3072
+ await pages[index].bringToFront();
3073
+ // Different tab → different DOM; existing refs belong to the previous tab.
3074
+ resetRefs();
3075
+ const title = await pages[index].title();
3076
+ this.logger?.log("focus_tab", { index, title });
3077
+ return `Focused tab [${index}]: ${title}`;
3078
+ }
3079
+ async closeActivePage() {
3080
+ const page = await this.browser.getActivePage();
3081
+ const title = await page.title();
3082
+ await page.close();
3083
+ resetRefs();
3084
+ this.logger?.log("close_page", { title });
3085
+ return `Closed active page: ${title}`;
3086
+ }
3087
+ // Keep sleep for backward compat (script-runner)
3088
+ async sleep(ms) {
3089
+ const MAX_SLEEP_MS = 30_000;
3090
+ const clamped = Math.min(Math.max(Math.round(ms || 0), 0), MAX_SLEEP_MS);
3091
+ const page = await this.browser.getActivePage();
3092
+ await page.waitForTimeout(clamped);
3093
+ this.logger?.log("sleep", { ms: clamped });
3094
+ return `Waited ${clamped}ms`;
3095
+ }
3096
+ }
3097
+ //# sourceMappingURL=actions.js.map