agent-device 0.21.37 → 0.21.38

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 (485) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.37.apk → agent-device-android-ime-helper-0.21.38.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.38.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.37.manifest.json → agent-device-android-ime-helper-0.21.38.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.37.apk → agent-device-android-snapshot-helper-0.21.38.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.38.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.37.manifest.json → agent-device-android-snapshot-helper-0.21.38.manifest.json} +7 -7
  7. package/apple/fold-helper/Fold.m +8 -4
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerKeyboardReturnKey.swift +53 -0
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +42 -4
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +26 -18
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +42 -11
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +123 -22
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +7 -0
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +570 -53
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +41 -0
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.h +7 -0
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.m +17 -1
  18. package/dist/src/THIRD_PARTY_NOTICES.txt +2 -2
  19. package/dist/src/absence-observation-errors.js +1 -1
  20. package/dist/src/absence-observation.js +1 -1
  21. package/dist/src/adapter.js +1 -1
  22. package/dist/src/adb-executor.js +1 -1
  23. package/dist/src/adb-failure.js +2 -2
  24. package/dist/src/adb-transport.js +1 -1
  25. package/dist/src/agent-browser-lifecycle.js +1 -1
  26. package/dist/src/agent-browser-process-record.js +1 -1
  27. package/dist/src/agent-browser-provider.js +1 -1
  28. package/dist/src/agent-browser-tool.js +1 -1
  29. package/dist/src/ai-sdk.d.ts +1 -1
  30. package/dist/src/ai-sdk.js +1 -1
  31. package/dist/src/alert-contract.js +1 -1
  32. package/dist/src/alert-tree-driver.js +1 -1
  33. package/dist/src/alert.js +1 -1
  34. package/dist/src/android-adb.d.ts +1 -1
  35. package/dist/src/android.js +1 -1
  36. package/dist/src/android2.js +1 -1
  37. package/dist/src/app-backend.js +1 -1
  38. package/dist/src/app-catalog.js +1 -1
  39. package/dist/src/app-deployment-resolution.js +1 -1
  40. package/dist/src/app-inventory.js +1 -1
  41. package/dist/src/app-launch.js +1 -1
  42. package/dist/src/app-lifecycle.js +4 -4
  43. package/dist/src/app-lifecycle2.js +2 -2
  44. package/dist/src/app-log-files.js +1 -1
  45. package/dist/src/app-log-runtime2.js +2 -2
  46. package/dist/src/app-log-session-resource.js +1 -1
  47. package/dist/src/app-resolution.js +1 -1
  48. package/dist/src/app-state-read.js +1 -1
  49. package/dist/src/app-state-runtime.d.ts +1 -1
  50. package/dist/src/application-lifecycle-interaction.js +1 -1
  51. package/dist/src/archive.js +1 -1
  52. package/dist/src/args.js +1 -1
  53. package/dist/src/artifact-download.js +1 -1
  54. package/dist/src/artifact-tracking.js +1 -1
  55. package/dist/src/auth-session.js +1 -1
  56. package/dist/src/auth.js +1 -1
  57. package/dist/src/automation-helper-artifact.js +1 -1
  58. package/dist/src/automation-helper.js +1 -1
  59. package/dist/src/await-with-signal.js +1 -1
  60. package/dist/src/backend-snapshot-options.js +1 -1
  61. package/dist/src/boot-diagnostics.js +1 -1
  62. package/dist/src/bridge-source.js +1 -1
  63. package/dist/src/browser-launch.js +1 -1
  64. package/dist/src/browserstack-device-features.js +1 -1
  65. package/dist/src/browserstack.js +1 -1
  66. package/dist/src/cache.js +1 -1
  67. package/dist/src/capture-disclosure.js +1 -1
  68. package/dist/src/capture-lifecycle.js +1 -1
  69. package/dist/src/cli-config.js +1 -1
  70. package/dist/src/cli-help.js +19 -16
  71. package/dist/src/cli-output.js +11 -11
  72. package/dist/src/cli-runner.js +1 -1
  73. package/dist/src/cli.js +2 -2
  74. package/dist/src/click-button.js +1 -1
  75. package/dist/src/client-metro-companion.js +1 -1
  76. package/dist/src/client-metro.js +1 -1
  77. package/dist/src/client-options.js +1 -1
  78. package/dist/src/client-port.d.ts +246 -208
  79. package/dist/src/clipboard-shell-response.js +1 -1
  80. package/dist/src/cloud-artifacts.d.ts +7 -2
  81. package/dist/src/code-signature-cache.js +1 -1
  82. package/dist/src/command-schema.js +6 -4
  83. package/dist/src/command-tools.js +3 -3
  84. package/dist/src/command.js +1 -1
  85. package/dist/src/composed-inventory-gateways.js +1 -1
  86. package/dist/src/composite-resource-admission.js +1 -1
  87. package/dist/src/config.js +1 -1
  88. package/dist/src/connection-lease-transaction.js +1 -1
  89. package/dist/src/connection-metro-runtime.js +1 -1
  90. package/dist/src/connection-runtime.js +1 -1
  91. package/dist/src/connection-verification.js +1 -1
  92. package/dist/src/connection.js +3 -3
  93. package/dist/src/context.js +1 -1
  94. package/dist/src/contract.d.ts +2 -1
  95. package/dist/src/contracts.d.ts +1 -1
  96. package/dist/src/contracts.js +1 -1
  97. package/dist/src/daemon-client-attach.js +1 -1
  98. package/dist/src/daemon-client-dispatch-disclosure.js +1 -1
  99. package/dist/src/daemon-client-ensure.js +1 -1
  100. package/dist/src/daemon-client-ensuring.js +1 -1
  101. package/dist/src/daemon-client-lease-beat.js +1 -1
  102. package/dist/src/daemon-client-lifecycle.js +1 -1
  103. package/dist/src/daemon-client-liveness-probe.js +1 -1
  104. package/dist/src/daemon-client-remote-health-cache.js +1 -0
  105. package/dist/src/daemon-client-remote-health-recovery.js +1 -0
  106. package/dist/src/daemon-client-transport.js +1 -1
  107. package/dist/src/daemon-command-registry.js +1 -1
  108. package/dist/src/daemon-composition.js +1 -1
  109. package/dist/src/daemon-diagnostics-scope.js +1 -1
  110. package/dist/src/daemon-http.js +1 -1
  111. package/dist/src/daemon-launch-spec.js +1 -1
  112. package/dist/src/daemon-lifecycle-errors.js +1 -1
  113. package/dist/src/daemon-policy-file.js +1 -1
  114. package/dist/src/daemon-registration-owner.js +3 -3
  115. package/dist/src/daemon-registration.js +1 -1
  116. package/dist/src/daemon-resolution.js +1 -1
  117. package/dist/src/daemon-startup-diagnostics.js +1 -1
  118. package/dist/src/daemon-stop.js +1 -1
  119. package/dist/src/daemon.js +1 -1
  120. package/dist/src/debug-symbols-facade.js +3 -3
  121. package/dist/src/device-claim-admission.js +1 -0
  122. package/dist/src/device-claim-reconciliation.js +1 -0
  123. package/dist/src/device-claim-recovery.js +1 -1
  124. package/dist/src/device-claim-rule.js +1 -1
  125. package/dist/src/device-claims.js +1 -1
  126. package/dist/src/device-input-state.d.ts +1 -1
  127. package/dist/src/device-inventory-context.js +1 -1
  128. package/dist/src/device-selection-resolver.js +1 -1
  129. package/dist/src/device-session.js +1 -1
  130. package/dist/src/device-shell.js +1 -1
  131. package/dist/src/device.js +1 -1
  132. package/dist/src/device3.js +3 -3
  133. package/dist/src/devicectl.js +1 -1
  134. package/dist/src/diagnostics.js +1 -1
  135. package/dist/src/discovery.js +1 -1
  136. package/dist/src/dispatch-resolve.js +1 -1
  137. package/dist/src/display-inventory.js +1 -1
  138. package/dist/src/doctor-facade.js +1 -1
  139. package/dist/src/doctor2.js +1 -1
  140. package/dist/src/durable-capture-resource.js +1 -1
  141. package/dist/src/durable-capture.js +1 -1
  142. package/dist/src/durable-resource.js +1 -1
  143. package/dist/src/ended-lease.js +1 -1
  144. package/dist/src/engine-eval-script.js +1 -1
  145. package/dist/src/error.js +2 -2
  146. package/dist/src/errors.js +1 -1
  147. package/dist/src/explicit-session-resolution.js +1 -1
  148. package/dist/src/expo-dev-client-launch.js +1 -1
  149. package/dist/src/failure-output.js +1 -1
  150. package/dist/src/file.js +1 -1
  151. package/dist/src/find.js +1 -1
  152. package/dist/src/finders.js +1 -1
  153. package/dist/src/flag-registry.js +1 -1
  154. package/dist/src/focus-runtime.js +1 -1
  155. package/dist/src/fold-helper.js +1 -1
  156. package/dist/src/generic-settle.js +1 -1
  157. package/dist/src/generic.js +1 -1
  158. package/dist/src/gesture-admission.js +1 -1
  159. package/dist/src/gesture-plan-types.d.ts +1 -1
  160. package/dist/src/gesture-plan.js +1 -1
  161. package/dist/src/gesture-runtime.js +1 -1
  162. package/dist/src/hdc.js +1 -1
  163. package/dist/src/helper-artifacts.js +1 -1
  164. package/dist/src/helper.js +2 -2
  165. package/dist/src/host-file.js +1 -1
  166. package/dist/src/host.js +1 -1
  167. package/dist/src/host2.js +1 -1
  168. package/dist/src/host3.js +1 -1
  169. package/dist/src/host4.js +1 -1
  170. package/dist/src/host5.js +1 -1
  171. package/dist/src/host6.js +1 -1
  172. package/dist/src/human-control-contract.js +1 -1
  173. package/dist/src/human-control.js +1 -1
  174. package/dist/src/ime-rebind.js +1 -1
  175. package/dist/src/ime-settings-record.js +1 -1
  176. package/dist/src/ime-state.js +1 -1
  177. package/dist/src/index.d.ts +3 -3
  178. package/dist/src/index.js +1 -1
  179. package/dist/src/input-actions.js +1 -1
  180. package/dist/src/input-actions2.js +1 -1
  181. package/dist/src/install-artifact-facade.js +1 -1
  182. package/dist/src/install-source-network-transport.js +1 -1
  183. package/dist/src/install-source2.js +1 -1
  184. package/dist/src/interaction-error.js +1 -1
  185. package/dist/src/interaction-positionals.js +1 -1
  186. package/dist/src/interaction-ref-policy.js +1 -1
  187. package/dist/src/interaction2.js +1 -1
  188. package/dist/src/interactor-operation-binding.js +1 -1
  189. package/dist/src/interactor.js +5 -5
  190. package/dist/src/interactor2.js +1 -1
  191. package/dist/src/interactor3.js +1 -1
  192. package/dist/src/interactor4.js +1 -1
  193. package/dist/src/interactor5.js +1 -1
  194. package/dist/src/interactors.js +1 -1
  195. package/dist/src/internal/bin.js +1 -1
  196. package/dist/src/internal/companion-tunnel.js +1 -1
  197. package/dist/src/internal/daemon.js +1 -1
  198. package/dist/src/internal/png-worker.js +1 -1
  199. package/dist/src/internal/run-script-child.js +1 -1
  200. package/dist/src/inventory.js +1 -1
  201. package/dist/src/inventory2.js +1 -1
  202. package/dist/src/inventory3.js +1 -1
  203. package/dist/src/inventory5.js +1 -1
  204. package/dist/src/ios-node-interpretation.js +1 -1
  205. package/dist/src/ios-simulator-accessibility.js +1 -1
  206. package/dist/src/ios-snapshot-acquisition.js +1 -1
  207. package/dist/src/ios-snapshot-engine.js +1 -1
  208. package/dist/src/ios-snapshot-runtime.js +1 -1
  209. package/dist/src/launch-confirmation.js +1 -1
  210. package/dist/src/launch-services-registration.js +1 -1
  211. package/dist/src/lease-context.js +1 -1
  212. package/dist/src/lease-registry-scope.js +1 -1
  213. package/dist/src/lease-release2.js +1 -1
  214. package/dist/src/lease-scope.js +1 -1
  215. package/dist/src/lease.js +1 -1
  216. package/dist/src/leased-recording-retention.js +1 -1
  217. package/dist/src/legacy.js +1 -1
  218. package/dist/src/limrun-download-file.js +1 -1
  219. package/dist/src/limrun-ios-files.js +1 -1
  220. package/dist/src/limrun-ios-runner.js +2 -2
  221. package/dist/src/limrun-runtime-dependencies.js +1 -1
  222. package/dist/src/limrun.d.ts +1 -1
  223. package/dist/src/local-interactor-operation-set.js +1 -1
  224. package/dist/src/local-simulator-apps.js +1 -1
  225. package/dist/src/local-simulator-files.js +1 -1
  226. package/dist/src/location-coordinates.js +1 -1
  227. package/dist/src/manifest.js +1 -1
  228. package/dist/src/mechanics.js +12 -12
  229. package/dist/src/merge-flags.js +1 -1
  230. package/dist/src/metro-reload-endpoints.js +1 -1
  231. package/dist/src/metro-session-hints.js +1 -1
  232. package/dist/src/metro.d.ts +1 -1
  233. package/dist/src/mobile-snapshot-semantics.js +1 -1
  234. package/dist/src/network-traffic.js +1 -1
  235. package/dist/src/node-http.js +1 -1
  236. package/dist/src/node-touch-point.js +1 -1
  237. package/dist/src/observation.js +1 -1
  238. package/dist/src/open-script.js +1 -1
  239. package/dist/src/open-target-device-resolution.js +1 -1
  240. package/dist/src/orientation.js +1 -1
  241. package/dist/src/parameterized-recorded-fill.js +1 -1
  242. package/dist/src/perf-facade.js +1 -1
  243. package/dist/src/perf-runtime-operation-builder.js +1 -1
  244. package/dist/src/perf-runtime-plan.js +1 -1
  245. package/dist/src/perf-target.js +2 -2
  246. package/dist/src/perf.js +1 -1
  247. package/dist/src/physical-device-control.js +1 -1
  248. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  249. package/dist/src/platform-runtime-app-log-process.js +1 -1
  250. package/dist/src/platform-runtime-apple-application-tools.js +1 -1
  251. package/dist/src/platform-runtime-claim-recovery.js +1 -1
  252. package/dist/src/platform-runtime-host.js +1 -1
  253. package/dist/src/platform-runtime-open-target.js +1 -1
  254. package/dist/src/platform-runtime-operation-host.js +3 -3
  255. package/dist/src/platform-runtime-runtime-hints.js +1 -1
  256. package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
  257. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  258. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  259. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  260. package/dist/src/platform-runtime-shutdown-error.js +1 -1
  261. package/dist/src/platform-runtime-unavailable.js +1 -1
  262. package/dist/src/platform-runtime.js +1 -1
  263. package/dist/src/platform-runtime2.js +1 -1
  264. package/dist/src/plist.js +1 -1
  265. package/dist/src/plugins2.js +1 -1
  266. package/dist/src/png-crop-bytes.js +1 -1
  267. package/dist/src/png-resize.js +1 -1
  268. package/dist/src/png-size.js +1 -1
  269. package/dist/src/png-worker-client.js +1 -1
  270. package/dist/src/png.js +1 -1
  271. package/dist/src/post-gesture-stability.js +1 -1
  272. package/dist/src/process-executable-path.js +1 -0
  273. package/dist/src/process-exit.js +1 -1
  274. package/dist/src/provider-device-runtime.d.ts +2 -2
  275. package/dist/src/provider-limrun-credentials.js +1 -1
  276. package/dist/src/provider-plugin.d.ts +1 -1
  277. package/dist/src/provider-profile-fields.js +1 -1
  278. package/dist/src/provider-webdriver.js +1 -1
  279. package/dist/src/provider.js +1 -1
  280. package/dist/src/proxy.js +2 -2
  281. package/dist/src/react-devtools-connection.js +1 -1
  282. package/dist/src/react-devtools-inspect-command.js +1 -1
  283. package/dist/src/react-native-overlay2.js +2 -2
  284. package/dist/src/react-native.js +1 -1
  285. package/dist/src/react-profile-command.js +1 -1
  286. package/dist/src/record-runtime.js +1 -1
  287. package/dist/src/record-trace.js +1 -1
  288. package/dist/src/recording-gestures.js +1 -1
  289. package/dist/src/recording.js +1 -1
  290. package/dist/src/rect-center.js +1 -1
  291. package/dist/src/register-builtins.js +1 -1
  292. package/dist/src/registry.js +1 -1
  293. package/dist/src/remote-config-core.js +1 -1
  294. package/dist/src/remote-config-flags.js +1 -1
  295. package/dist/src/remote-connection-state.js +1 -1
  296. package/dist/src/replay-backend-host.js +1 -1
  297. package/dist/src/replay-divergence.js +1 -1
  298. package/dist/src/replay-maestro-backend.js +2 -2
  299. package/dist/src/replay.d.ts +1 -1
  300. package/dist/src/replay2.js +1 -1
  301. package/dist/src/reporting.js +1 -1
  302. package/dist/src/request-dispatch-disclosure.js +1 -1
  303. package/dist/src/request-ended-leases.js +1 -1
  304. package/dist/src/request-providers.js +1 -1
  305. package/dist/src/request-runtime-binding.js +1 -1
  306. package/dist/src/request.js +1 -1
  307. package/dist/src/result-serialization.js +2 -2
  308. package/dist/src/retry.js +1 -1
  309. package/dist/src/run-script-execution.js +6 -8
  310. package/dist/src/run-script-http.js +1 -1
  311. package/dist/src/runner-cache-metadata.js +1 -1
  312. package/dist/src/runner-cache-retention.js +1 -1
  313. package/dist/src/runner-client.js +1 -1
  314. package/dist/src/runner-contract.js +1 -1
  315. package/dist/src/runner-dev-tools-security.js +1 -1
  316. package/dist/src/runner-device-readiness.js +1 -1
  317. package/dist/src/runner-device-set.js +1 -1
  318. package/dist/src/runner-disposal.js +1 -1
  319. package/dist/src/runner-error-classification.js +2 -2
  320. package/dist/src/runner-exchange.js +1 -1
  321. package/dist/src/runner-io.js +1 -1
  322. package/dist/src/runner-launched-session.js +1 -1
  323. package/dist/src/runner-lease.js +1 -1
  324. package/dist/src/runner-lifecycle.js +1 -1
  325. package/dist/src/runner-operations-facade.js +1 -1
  326. package/dist/src/runner-panel.js +1 -1
  327. package/dist/src/runner-retention.js +1 -1
  328. package/dist/src/runner-runtime.js +1 -1
  329. package/dist/src/runner-selector-query.js +1 -1
  330. package/dist/src/runner-sequence.js +1 -1
  331. package/dist/src/runner-start-budget.js +1 -1
  332. package/dist/src/runner-startup-transport.js +1 -1
  333. package/dist/src/runner-toolchain-identity.js +1 -1
  334. package/dist/src/runtime-admission.js +1 -1
  335. package/dist/src/runtime-deployment.js +1 -1
  336. package/dist/src/runtime-factory.js +1 -1
  337. package/dist/src/runtime-session.js +1 -1
  338. package/dist/src/runtime-transport-hints.js +1 -1
  339. package/dist/src/runtime.js +2 -2
  340. package/dist/src/runtime10.js +1 -1
  341. package/dist/src/runtime11.js +1 -1
  342. package/dist/src/runtime12.js +1 -1
  343. package/dist/src/runtime13.js +2 -2
  344. package/dist/src/runtime2.js +2 -2
  345. package/dist/src/runtime4.js +3 -3
  346. package/dist/src/runtime5.js +1 -1
  347. package/dist/src/runtime6.js +1 -1
  348. package/dist/src/runtime7.js +2 -2
  349. package/dist/src/runtime8.js +1 -1
  350. package/dist/src/runtime9.js +1 -1
  351. package/dist/src/screen-recording-admission-ledger.js +1 -0
  352. package/dist/src/screen-recording-completion.js +1 -1
  353. package/dist/src/screen-recording-options.js +1 -1
  354. package/dist/src/screen-recording-resource-recovery.js +1 -1
  355. package/dist/src/screen-recording-stop-recovery.js +1 -1
  356. package/dist/src/screen-recording-transport.js +1 -1
  357. package/dist/src/screenshot-density.js +1 -1
  358. package/dist/src/screenshot-image-size.js +1 -1
  359. package/dist/src/screenshot-image.js +1 -1
  360. package/dist/src/screenshot-runtime.js +1 -1
  361. package/dist/src/screenshot-runtime2.js +1 -1
  362. package/dist/src/screenshot.js +1 -1
  363. package/dist/src/screenshot2.js +1 -1
  364. package/dist/src/screenshot4.js +1 -1
  365. package/dist/src/script-source.js +1 -1
  366. package/dist/src/script.js +1 -1
  367. package/dist/src/scroll-command.js +1 -1
  368. package/dist/src/scroll-gesture.js +1 -1
  369. package/dist/src/sdk-batch-runner.d.ts +1 -1
  370. package/dist/src/sdk-batch-runner.js +2 -2
  371. package/dist/src/sdk-batch.js +2 -2
  372. package/dist/src/sdk-contracts.d.ts +26 -2
  373. package/dist/src/sdk-contracts.js +2 -2
  374. package/dist/src/sdk-device.js +1 -1
  375. package/dist/src/sdk-finders.d.ts +1 -1
  376. package/dist/src/sdk-finders.js +1 -1
  377. package/dist/src/sdk-io.js +5 -5
  378. package/dist/src/sdk-remote-config.d.ts +1 -1
  379. package/dist/src/sdk-remote-config.js +1 -1
  380. package/dist/src/sdk-selectors.d.ts +9 -6
  381. package/dist/src/sdk-selectors.js +1 -1
  382. package/dist/src/selection.js +0 -0
  383. package/dist/src/selector-pipeline-policy.js +1 -1
  384. package/dist/src/selector-runtime.js +1 -1
  385. package/dist/src/selectors.js +1 -1
  386. package/dist/src/server-shutdown.js +1 -1
  387. package/dist/src/server-startup.js +2 -2
  388. package/dist/src/server.js +4 -4
  389. package/dist/src/session-allocation.js +1 -1
  390. package/dist/src/session-artifact-paths.js +1 -1
  391. package/dist/src/session-capture-binding.js +1 -1
  392. package/dist/src/session-device-resolution.js +1 -1
  393. package/dist/src/session-event-action.js +1 -1
  394. package/dist/src/session-open.js +1 -1
  395. package/dist/src/session-repair-tombstone.js +1 -1
  396. package/dist/src/session-replay-vars.js +1 -1
  397. package/dist/src/session-routing.js +1 -1
  398. package/dist/src/session-runtime-admission.js +1 -1
  399. package/dist/src/session-runtime.js +1 -1
  400. package/dist/src/session-script-destination.js +1 -0
  401. package/dist/src/session-selector.js +1 -1
  402. package/dist/src/session-store.js +3 -3
  403. package/dist/src/session-teardown.js +1 -1
  404. package/dist/src/session-tenant-scope.js +1 -1
  405. package/dist/src/session2.js +5 -5
  406. package/dist/src/settings-bluetooth.js +1 -1
  407. package/dist/src/settings-global-toggle.js +1 -1
  408. package/dist/src/settings.js +1 -1
  409. package/dist/src/settings2.js +1 -1
  410. package/dist/src/settle-observation-capture.js +1 -1
  411. package/dist/src/simctl-execution.js +1 -1
  412. package/dist/src/simctl-facade.js +1 -1
  413. package/dist/src/simctl.js +1 -1
  414. package/dist/src/simulator-app-budget.js +1 -1
  415. package/dist/src/simulator-boot.js +1 -1
  416. package/dist/src/simulator-facade.js +1 -1
  417. package/dist/src/simulator-state.js +1 -1
  418. package/dist/src/simulator.js +1 -1
  419. package/dist/src/snapshot-baseline.js +1 -1
  420. package/dist/src/snapshot-chrome.js +1 -1
  421. package/dist/src/snapshot-desktop-projection.js +1 -1
  422. package/dist/src/snapshot-diagnostics.js +1 -1
  423. package/dist/src/snapshot-helper-install.js +3 -3
  424. package/dist/src/snapshot-helper-session.js +1 -1
  425. package/dist/src/snapshot-lines.js +1 -1
  426. package/dist/src/snapshot-node-lookup.js +1 -1
  427. package/dist/src/snapshot-occlusion.js +1 -1
  428. package/dist/src/snapshot-private-evidence.js +1 -1
  429. package/dist/src/snapshot-runtime-binding.js +1 -1
  430. package/dist/src/snapshot-runtime-capture-input.js +1 -1
  431. package/dist/src/snapshot-runtime.js +1 -1
  432. package/dist/src/snapshot-state.js +1 -1
  433. package/dist/src/snapshot.js +1 -1
  434. package/dist/src/snapshot2.js +1 -1
  435. package/dist/src/snapshot3.js +2 -2
  436. package/dist/src/snapshot4.js +1 -1
  437. package/dist/src/source-channel.js +1 -1
  438. package/dist/src/src.js +1 -1
  439. package/dist/src/src10.js +1 -1
  440. package/dist/src/src11.js +1 -1
  441. package/dist/src/src2.js +1 -1
  442. package/dist/src/src3.js +5 -5
  443. package/dist/src/src4.js +2 -2
  444. package/dist/src/src5.js +1 -1
  445. package/dist/src/src6.js +1 -1
  446. package/dist/src/src8.js +1 -1
  447. package/dist/src/store-legacy.js +1 -1
  448. package/dist/src/store.js +1 -1
  449. package/dist/src/string-enum.js +1 -1
  450. package/dist/src/surface-snapshot.js +1 -1
  451. package/dist/src/surface-snapshot2.js +1 -1
  452. package/dist/src/sync-cache.js +1 -1
  453. package/dist/src/system-surface-foreground.js +2 -2
  454. package/dist/src/takeover.js +1 -1
  455. package/dist/src/tap-keyboard-occlusion.js +1 -1
  456. package/dist/src/target-evidence-tree.js +1 -1
  457. package/dist/src/target-evidence.js +1 -1
  458. package/dist/src/telephony-runtime.js +1 -1
  459. package/dist/src/tool-provider-facade.js +1 -1
  460. package/dist/src/tool-provider.js +3 -3
  461. package/dist/src/tool-provider2.js +1 -1
  462. package/dist/src/tool-provider3.js +1 -1
  463. package/dist/src/toolchain-probe.js +1 -1
  464. package/dist/src/touch-runtime.js +1 -1
  465. package/dist/src/touch-runtime2.js +1 -1
  466. package/dist/src/transport.js +2 -2
  467. package/dist/src/tree.js +1 -1
  468. package/dist/src/tv-remote-runtime.js +1 -1
  469. package/dist/src/tv-remote.js +1 -1
  470. package/dist/src/type-text-runtime.js +1 -1
  471. package/dist/src/unsupported-interactor.js +1 -1
  472. package/dist/src/update-check.js +1 -1
  473. package/dist/src/validation.js +1 -1
  474. package/dist/src/vars.js +1 -1
  475. package/dist/src/vega-executable.js +1 -1
  476. package/dist/src/verified-file.js +1 -1
  477. package/dist/src/video.js +2 -2
  478. package/dist/src/viewport.js +1 -1
  479. package/dist/src/web.js +1 -1
  480. package/dist/src/webdriver-source.js +1 -1
  481. package/package.json +2 -2
  482. package/server.json +2 -2
  483. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.37.apk.sha256 +0 -1
  484. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.37.apk.sha256 +0 -1
  485. package/dist/src/capture-output-ownership.js +0 -1
@@ -1 +1 @@
1
- import{T as e,pt as t}from"./sdk-contracts.js";import"./sdk-batch-runner.js";import{W as n,yt as r}from"./sdk-io.js";import"./diagnostics.js";import{Ar as i,Ln as a,Vn as o,pr as s,zn as c}from"./sdk-batch.js";import{m as l,u}from"./open-script.js";import{i as d}from"./target-evidence.js";import{n as f,t as p}from"./target-evidence-tree.js";import{t as m}from"./android-snapshot-quality.js";import"./retry.js";import{a as h,n as ee,t as g}from"./replay-divergence.js";import{r as _}from"./session-event-action.js";import{n as v}from"./snapshot-chrome.js";import{n as y}from"./snapshot-lines.js";import{t as b}from"./snapshot-quality-verdict.js";import x from"node:fs";import S from"node:path";function C(e){if(e.length===0)return{selectorExpression:null,selectorTimeout:null};let t=e.at(-1),n=t!==void 0&&/^\d+$/.test(t)?t:null,r=n===null?e.slice():e.slice(0,-1),i=c(`positional`,r);return i.kind!==`expression`||i.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:i.expression,selectorTimeout:n}}function te(e){let t=[],n=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];if(t.push(...n),l(e.command)){let n=w(e),r=n[0]??``;r&&!r.startsWith(`@`)&&t.push(n.join(` `))}if(e.command===`fill`){let n=e.positionals?.[0]??``;n&&!n.startsWith(`@`)&&Number.isNaN(Number(n))&&t.push(n)}if(e.command===`get`){let n=e.positionals?.[1]??``;n&&!n.startsWith(`@`)&&t.push(e.positionals.slice(1).join(` `))}if(e.command===`is`){let n=c(`is`,[...e.positionals]);n.kind===`expression`&&t.push(n.expression)}if(e.command===`wait`){let{selectorExpression:n}=C([...e.positionals]);n&&t.push(n)}return i(t).filter(e=>e.trim().length>0)}function w(e){let t=e.positionals;if(e.command!==`longpress`)return t;let n=t.at(-1);return t.length>1&&ne(n)?t.slice(0,-1):t}function ne(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}function T(e){let t=S.dirname(e),n=S.basename(e,S.extname(e));return S.join(t,`${n}.healed.ad`)}function E(e){let t=D({failedIndex:e.failedIndex,actions:e.actions,planDigest:e.planDigest,repairHint:e.repairHint,sessionExists:e.resumeStamper.sessionExists()});return e.resumeStamper.stampCorrectiveWatermark({resume:t,repairHint:e.repairHint,failedIndex:e.failedIndex,actions:e.actions}),t}function D(e){let{failedIndex:t,actions:n,planDigest:r,repairHint:i,sessionExists:a}=e,o=i===`record-and-heal`?t+1:t,s=O({failedIndex:t,actions:n,repairHint:i,sessionExists:a});return{allowed:!0,from:o,planDigest:r,...s===void 0?{}:{alternateFrom:s}}}function O(e){let{failedIndex:t,actions:n,repairHint:r,sessionExists:i}=e;if(r!==`caution`&&r!==`manual`)return;let a=t+1;if(!(a>n.length&&!i))return a}function k(e){let{kind:t,targetEvidence:n,capture:r}=e;if(t===`identity-mismatch`)return`caution`;if(t===`identity-unverifiable`||!n||r.state!==`available`||!re(n))return`manual`;let i=ie(n,r.nodes);return t===`selector-miss`?i?`record-and-heal`:`state-repair`:i?`record-and-heal`:`manual`}function re(e){return e.ancestry.length>0||e.scrollRegion!==void 0&&A(e.scrollRegion)}function ie(e,t){let n=f(t),r=oe(e.ancestry,n,t),i=e.scrollRegion;return i&&A(i)?r&&ae(i,n,t):r}function A(e){return e.id!==void 0||e.label!==void 0}function ae(e,t,n){return n.some(n=>d(n,t,e))}function oe(e,t,n){return e.length===0?n.length>0:n.some(n=>{let r=p(n,t,e.length);return!r.broken&&s(r.chain,e)})}function j(e){let{sessionStore:n,observationStore:r,divergence:i,responseLevel:a}=e,o,s,c=g({divergence:i,level:a,writeOverflowArtifact:e=>{let r=P(t(e),N(e.screen)),i=se(n,r);return`artifactPath`in i&&(o=r,s=i.artifactPath),i}}),l=(o??c).screen;if(l.state!==`available`||l.refs.length===0)return e.evidence&&r.bindAuthority(e.signal).finalize(e.evidence,{refsGeneration:l.state===`available`?l.refsGeneration:void 0,refs:[]}),P(c,new Set);if(!e.evidence)return I(s),M(c,`missing-evidence`);let u=r.bindAuthority(e.signal),d=N(l),f=u.finalize(e.evidence,{refsGeneration:l.refsGeneration,refs:[...d]});return f.published===!0?P(c,d):(I(s),M(c,f.reason))}function M(e,t){let{overflow:n,...r}=P(e,new Set);return{...r,screen:{state:`unavailable`,reason:`ref-publication-${t}`,hint:`The replay observation changed before its refs could be published. Take a new snapshot before targeting an element.`}}}function N(e){return new Set(e.state===`available`?e.refs.map(e=>e.ref):[])}function P(e,t){return{...e,suggestions:e.suggestions.map(e=>F(e,t)),...e.targetBinding?{targetBinding:{...e.targetBinding,candidates:e.targetBinding.candidates.map(e=>F(e,t))}}:{}}}function F(e,t){if(e.ref===void 0||t.has(e.ref))return e;let{ref:n,...r}=e;return r}function I(e){if(e)try{x.unlinkSync(e)}catch{}}function se(e,t){try{let n=S.join(e.ensureSessionDir(),`replay-divergence`);x.mkdirSync(n,{recursive:!0});let r=`${Date.now()}-step${t.step.index}.json`,i=S.join(n,r);return x.writeFileSync(i,`${JSON.stringify(t,null,2)}\n`),{artifactPath:i}}catch{return{artifactUnavailable:!0}}}const ce={id:0,"role-label":1,label:2,other:3};function L(e,t=new Set){let n=new Map;for(let t of e){let e=n.get(t.nodeIndex);(!e||R(t.basis)<R(e.basis))&&n.set(t.nodeIndex,t)}return[...n.values()].sort((e,n)=>R(e.basis)-R(n.basis)||Number(t.has(n.nodeIndex))-Number(t.has(e.nodeIndex))||e.nodeIndex-n.nodeIndex)}function R(e){return ce[e]}async function le(e){let{error:t,action:n,index:r,sourcePath:i,sourceLine:a,session:o,sessionStore:s,observationStore:c,resumeStamper:l,logPath:d,responseLevel:f,scrubVars:p=[],planActions:m,planDigest:h,signal:g}=e,_=ee(p),v={code:t.code,message:_(t.message),...t.hint?{hint:_(t.hint)}:{}},y=t.details?.reason===`bounded_composite_resource_unsupported`&&t.details.dispatched===`no`?{state:`unavailable`,reason:`bounded-composite-resource-unsupported`,hint:`The operation was refused before dispatch. Use its original input in the same session.`}:o?await V({session:o,observationStore:c,logPath:d,action:n,signal:g}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`},b=W(y,_),x=y.state===`available`&&o?he({action:n,session:o,nodes:y.nodes,sanitize:_}):[],S=k({kind:`action-failure`,targetEvidence:n.targetEvidence,capture:z(y)}),C=E({failedIndex:r+1,actions:m,planDigest:h,repairHint:S,resumeStamper:l});return j({sessionStore:s,observationStore:c,divergence:{version:1,kind:`action-failure`,step:{index:r+1,source:{path:_(i),line:a}},action:_(u(n)),cause:v,screen:b,suggestions:x.slice(0,5),suggestionCount:x.length,resume:C,repairHint:S},responseLevel:f,evidence:y.state===`available`?y.evidence:void 0,...g?{signal:g}:{}})}function z(e){return e.state===`available`?{state:`available`,nodes:e.nodes}:{state:`unavailable`}}const B=[300,500,800,1200,2e3,3e3,4e3];async function V(e){let{session:t,observationStore:r,logPath:i,action:a,retryLaunchRace:o=!1,signal:s}=e;if(s?.aborted)return H();let c=ue(a),l=Date.now()+12e3,u=r.bindAuthority(s),d=await U({session:t,observation:u,logPath:i,flags:c});if(!o)return d.observation;for(let e of B){if(d.observation.state===`available`||!d.retryable)break;let r=l-Date.now();if(r<=0)break;if(await n(Math.min(e,r)),s?.aborted)return H();d=await U({session:t,observation:u,logPath:i,flags:c})}return d.observation}function H(){return{state:`unavailable`,reason:`request-canceled`,hint:`Post-failure snapshot skipped after request cancellation; the original replay failure is unaffected.`}}async function U(e){let{session:t,observation:n,logPath:r,flags:i}=e;try{let e=(await n.capture({flags:i,logPath:r})).snapshot;if(b(e.snapshotQuality))return{observation:{state:`unavailable`,reason:`sparse-snapshot`,hint:`The post-failure snapshot was sparse or unavailable; run snapshot -i to observe the current screen.`},retryable:!0};let a=n.store(e);return{observation:{state:`available`,nodes:e.nodes,refsGeneration:a.refsGeneration,evidence:a.evidence,appBundleId:t.appBundleId},retryable:!1}}catch(e){return{observation:{state:`unavailable`,reason:`capture-failed`,hint:`Post-failure snapshot capture failed (${e instanceof Error?e.message:String(e)}); the original replay failure is unaffected.`},retryable:m(e)}}}function ue(e){return{snapshotInteractiveOnly:de(e)}}function de(e){return!K(e.command)||q(e).requiresRect}function W(e,t){if(e.state===`unavailable`)return{state:`unavailable`,reason:t(e.reason),hint:t(e.hint)};let{refs:n,truncated:r}=me(e.nodes,t,e.appBundleId);return{state:`available`,refsGeneration:e.refsGeneration,refs:n,...r?{truncated:!0}:{}}}function fe(t){return!!y(t,e(t.type??`Element`))||t.hittable===!0}function G(e,t){return t!==void 0&&e.bundleId!==void 0&&e.bundleId!==t&&e.hittable===!0}function pe(e,t){let n=v(e,t),r=e.filter(e=>e.ref&&!n.has(e.ref)&&fe(e)),i=r.length>0?r:e.filter(e=>e.ref&&e.hittable===!0),a=i.filter(e=>e.interactionBlocked!==`covered`),o=a.length>0?a:i,s=[...o.filter(e=>G(e,t)),...o.filter(e=>!G(e,t))],c=s.slice(0,20);return{nodes:c,truncated:s.length>c.length}}function me(t,n,r){let{nodes:i,truncated:a}=pe(t,r);return{refs:i.map(t=>{let r=e(t.type??`Element`),i=y(t,r);return{ref:t.ref,role:n(r),...i?{label:n(i)}:{}}}),truncated:a}}function he(e){let{action:t,session:n,nodes:r,sanitize:i}=e;if(!K(t.command))return[];let a=te(t);return a.length===0?[]:ge({candidates:a,nodes:r,session:n,action:t,matching:q(t),sanitize:i})}function K(e){return l(e)||[`fill`,`get`,`is`,`wait`].includes(e)}function q(e){let t=l(e.command);return{requiresRect:t||e.command===`fill`,allowDisambiguation:t||e.command===`fill`||e.command===`get`&&e.positionals?.[0]===`text`}}function ge(e){let{candidates:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,s=[];for(let e of t){let t=_e({candidate:e,nodes:n,session:r,action:i,matching:a,sanitize:o});t&&s.push(t)}let c,l=i.targetEvidence;if(l?.verification===`verified`){let e=f(n);c=new Set;for(let{nodeIndex:t}of s){let n=e.get(t);n&&d(n,e,l.scrollRegion)&&c.add(t)}}return L(s,c).map(e=>e.suggestion)}function _e(e){let{candidate:t,nodes:n,session:r,action:i,matching:a,sanitize:s}=e,c=o(t,n,{platform:r.device.platform,requireRect:a.requiresRect,allowDisambiguation:a.allowDisambiguation});if(c)return{suggestion:J({node:c.node,nodes:n,session:r,action:i,basis:c.basis,sanitize:s}),basis:c.basis,nodeIndex:c.node.index}}function J(t){let{node:n,nodes:r,session:i,action:o,basis:s,sanitize:c}=t,u=a(n,i.device.platform,{action:o.command===`fill`?`fill`:l(o.command)?`click`:`get`,nodes:r}),d=e(n.type??`Element`),f=y(n,d);return{selector:c(u.join(` || `)),basis:s,...n.ref?{ref:n.ref}:{},role:c(d),...f?{label:c(f)}:{}}}function Y(e){return ve({...e,hint:e.hint??Z(e.details,`hint`),diagnosticId:e.diagnosticId??Z(e.details,`diagnosticId`),logPath:e.logPath??Z(e.details,`logPath`)})}function ve(e){return e.details?.reason===`android_shell_text_unsupported`?{...e,hint:"On emulators the test IME activates automatically; on real devices pass `--test-ime` to this test/replay run to enable it for the sessions the flow opens (see `agent-device doctor` for the current IME state)."}:e}function ye(e){let{error:t,action:n,step:r,replayPath:i,artifactPaths:a,snapshotDiagnostics:o,divergence:s,scrubVars:c}=e;return X({error:t,actionLabel:u(n),action:n.command,positionals:_(n)??[],step:r,replayPath:i,artifactPaths:a,snapshotDiagnostics:o,divergence:s,scrubVars:c})}function X(e){let{error:t,actionLabel:n,action:r,positionals:i,step:a,replayPath:o,artifactPaths:s,snapshotDiagnostics:c,divergence:l,scrubVars:u,warnings:d}=e;return{ok:!1,error:{code:`REPLAY_DIVERGENCE`,message:h(`Replay failed at step ${a} (${n}): ${t.message}`,u),hint:t.hint===void 0?void 0:h(t.hint,u),diagnosticId:t.diagnosticId,logPath:t.logPath,...t.retriable===void 0?{}:{retriable:t.retriable},...t.supportedOn===void 0?{}:{supportedOn:t.supportedOn},details:{...xe(t.details,u),replayPath:o,step:a,action:r,positionals:i,artifactPaths:s,...c?{snapshotDiagnostics:c}:{},...d&&d.length>0?{warnings:d.map(e=>h(e,u))}:{},divergence:l}}}}function Z(e,t){let n=e?.[t];return typeof n==`string`&&n.length>0?n:void 0}const be=[`adbFailure`,`reason`,`recovery`,`retriable`,`runnerConnectFailureReason`,`snapshotQuality`,`supportedOn`,`systemSurface`];function xe(e,t){if(!e)return{};let n={};for(let t of be)e[t]!==void 0&&(n[t]=e[t]);if(e.reason===`session_cleanup_incomplete`&&Array.isArray(e.failedSteps)&&e.failedSteps.every(e=>typeof e==`string`)&&(n.failedSteps=e.failedSteps.map(e=>h(e,t))),e.reason===`bounded_composite_resource_unsupported`){e.dispatched===`no`&&(n.dispatched=`no`);let t=Z(e,`shape`);t!==void 0&&(n.shape=t);let r=Z(e,`standaloneCommandName`);r!==void 0&&(n.standaloneCommandName=r)}return n}function Se(e,n){if(e)try{x.appendFileSync(e,`${JSON.stringify(t(n))}\n`)}catch(t){r({level:`warn`,phase:`replay_trace_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}}function Ce(e){let{req:t,sessionName:n,metadata:r,resolvedPath:i,hostCwd:a}=e,o=t.flags??{},s={AD_SESSION:n,AD_FILENAME:we(t,i,a)};return Q(s,`AD_PLATFORM`,o.platform??r.platform),Q(s,`AD_TARGET`,o.target??r.target),Q(s,`AD_DEVICE`,o.device),Q(s,`AD_DEVICE_ID`,Te(o)),$(s,`AD_SHARD_INDEX`,o.shardIndex),$(s,`AD_SHARD_COUNT`,o.shardCount),Q(s,`AD_ARTIFACTS`,o.artifactsDir),s}function we(e,t,n){let r=e.meta?.cwd??n;return S.relative(r,t)||t}function Te(e){return typeof e.serial==`string`?e.serial:e.udid}function Q(e,t,n){typeof n==`string`&&n.length>0&&(e[t]=n)}function $(e,t,n){typeof n==`number`&&(e[t]=String(n))}export{Y as a,le as c,z as d,L as f,T as g,E as h,X as i,V as l,k as m,Se as n,W as o,j as p,ye as r,J as s,Ce as t,q as u};
1
+ import{Bn as e,Hn as t,Nr as n,Wn as r,gr as i}from"./sdk-batch.js";import{X as a,st as o}from"./sdk-contracts.js";import"./sdk-batch-runner.js";import{St as s,q as c}from"./sdk-io.js";import"./diagnostics.js";import{m as l,u}from"./open-script.js";import{i as d}from"./target-evidence.js";import{n as f,t as p}from"./target-evidence-tree.js";import{t as m}from"./android-snapshot-quality.js";import"./retry.js";import{a as h,n as ee,t as g}from"./replay-divergence.js";import{r as _}from"./session-event-action.js";import{n as v}from"./snapshot-chrome.js";import{n as y}from"./snapshot-lines.js";import{t as b}from"./snapshot-quality-verdict.js";import x from"node:fs";import S from"node:path";function C(e){if(e.length===0)return{selectorExpression:null,selectorTimeout:null};let n=e.at(-1),r=n!==void 0&&/^\d+$/.test(n)?n:null,i=r===null?e.slice():e.slice(0,-1),a=t(`positional`,i);return a.kind!==`expression`||a.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:a.expression,selectorTimeout:r}}function te(e){let r=[],i=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];if(r.push(...i),l(e.command)){let t=w(e),n=t[0]??``;n&&!n.startsWith(`@`)&&r.push(t.join(` `))}if(e.command===`fill`){let t=e.positionals?.[0]??``;t&&!t.startsWith(`@`)&&Number.isNaN(Number(t))&&r.push(t)}if(e.command===`get`){let t=e.positionals?.[1]??``;t&&!t.startsWith(`@`)&&r.push(e.positionals.slice(1).join(` `))}if(e.command===`is`){let n=t(`is`,[...e.positionals]);n.kind===`expression`&&r.push(n.expression)}if(e.command===`wait`){let{selectorExpression:t}=C([...e.positionals]);t&&r.push(t)}return n(r).filter(e=>e.trim().length>0)}function w(e){let t=e.positionals;if(e.command!==`longpress`)return t;let n=t.at(-1);return t.length>1&&ne(n)?t.slice(0,-1):t}function ne(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}function T(e){let t=S.dirname(e),n=S.basename(e,S.extname(e));return S.join(t,`${n}.healed.ad`)}function E(e){let t=D({failedIndex:e.failedIndex,actions:e.actions,planDigest:e.planDigest,repairHint:e.repairHint,sessionExists:e.resumeStamper.sessionExists()});return e.resumeStamper.stampCorrectiveWatermark({resume:t,repairHint:e.repairHint,failedIndex:e.failedIndex,actions:e.actions}),t}function D(e){let{failedIndex:t,actions:n,planDigest:r,repairHint:i,sessionExists:a}=e,o=i===`record-and-heal`?t+1:t,s=O({failedIndex:t,actions:n,repairHint:i,sessionExists:a});return{allowed:!0,from:o,planDigest:r,...s===void 0?{}:{alternateFrom:s}}}function O(e){let{failedIndex:t,actions:n,repairHint:r,sessionExists:i}=e;if(r!==`caution`&&r!==`manual`)return;let a=t+1;if(!(a>n.length&&!i))return a}function k(e){let{kind:t,targetEvidence:n,capture:r}=e;if(t===`identity-mismatch`)return`caution`;if(t===`identity-unverifiable`||!n||r.state!==`available`||!re(n))return`manual`;let i=ie(n,r.nodes);return t===`selector-miss`?i?`record-and-heal`:`state-repair`:i?`record-and-heal`:`manual`}function re(e){return e.ancestry.length>0||e.scrollRegion!==void 0&&A(e.scrollRegion)}function ie(e,t){let n=f(t),r=oe(e.ancestry,n,t),i=e.scrollRegion;return i&&A(i)?r&&ae(i,n,t):r}function A(e){return e.id!==void 0||e.label!==void 0}function ae(e,t,n){return n.some(n=>d(n,t,e))}function oe(e,t,n){return e.length===0?n.length>0:n.some(n=>{let r=p(n,t,e.length);return!r.broken&&i(r.chain,e)})}function j(e){let{sessionStore:t,observationStore:n,divergence:r,responseLevel:i}=e,o,s,c=g({divergence:r,level:i,writeOverflowArtifact:e=>{let n=P(a(e),N(e.screen)),r=se(t,n);return`artifactPath`in r&&(o=n,s=r.artifactPath),r}}),l=(o??c).screen;if(l.state!==`available`||l.refs.length===0)return e.evidence&&n.bindAuthority(e.signal).finalize(e.evidence,{refsGeneration:l.state===`available`?l.refsGeneration:void 0,refs:[]}),P(c,new Set);if(!e.evidence)return I(s),M(c,`missing-evidence`);let u=n.bindAuthority(e.signal),d=N(l),f=u.finalize(e.evidence,{refsGeneration:l.refsGeneration,refs:[...d]});return f.published===!0?P(c,d):(I(s),M(c,f.reason))}function M(e,t){let{overflow:n,...r}=P(e,new Set);return{...r,screen:{state:`unavailable`,reason:`ref-publication-${t}`,hint:`The replay observation changed before its refs could be published. Take a new snapshot before targeting an element.`}}}function N(e){return new Set(e.state===`available`?e.refs.map(e=>e.ref):[])}function P(e,t){return{...e,suggestions:e.suggestions.map(e=>F(e,t)),...e.targetBinding?{targetBinding:{...e.targetBinding,candidates:e.targetBinding.candidates.map(e=>F(e,t))}}:{}}}function F(e,t){if(e.ref===void 0||t.has(e.ref))return e;let{ref:n,...r}=e;return r}function I(e){if(e)try{x.unlinkSync(e)}catch{}}function se(e,t){try{let n=S.join(e.ensureSessionDir(),`replay-divergence`);x.mkdirSync(n,{recursive:!0});let r=`${Date.now()}-step${t.step.index}.json`,i=S.join(n,r);return x.writeFileSync(i,`${JSON.stringify(t,null,2)}\n`),{artifactPath:i}}catch{return{artifactUnavailable:!0}}}const ce={id:0,"role-label":1,label:2,other:3};function L(e,t=new Set){let n=new Map;for(let t of e){let e=n.get(t.nodeIndex);(!e||R(t.basis)<R(e.basis))&&n.set(t.nodeIndex,t)}return[...n.values()].sort((e,n)=>R(e.basis)-R(n.basis)||Number(t.has(n.nodeIndex))-Number(t.has(e.nodeIndex))||e.nodeIndex-n.nodeIndex)}function R(e){return ce[e]}async function le(e){let{error:t,action:n,index:r,sourcePath:i,sourceLine:a,session:o,sessionStore:s,observationStore:c,resumeStamper:l,logPath:d,responseLevel:f,scrubVars:p=[],planActions:m,planDigest:h,signal:g}=e,_=ee(p),v={code:t.code,message:_(t.message),...t.hint?{hint:_(t.hint)}:{}},y=t.details?.reason===`bounded_composite_resource_unsupported`&&t.details.dispatched===`no`?{state:`unavailable`,reason:`bounded-composite-resource-unsupported`,hint:`The operation was refused before dispatch. Use its original input in the same session.`}:o?await V({session:o,observationStore:c,logPath:d,action:n,signal:g}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`},b=W(y,_),x=y.state===`available`&&o?he({action:n,session:o,nodes:y.nodes,sanitize:_}):[],S=k({kind:`action-failure`,targetEvidence:n.targetEvidence,capture:z(y)}),C=E({failedIndex:r+1,actions:m,planDigest:h,repairHint:S,resumeStamper:l});return j({sessionStore:s,observationStore:c,divergence:{version:1,kind:`action-failure`,step:{index:r+1,source:{path:_(i),line:a}},action:_(u(n)),cause:v,screen:b,suggestions:x.slice(0,5),suggestionCount:x.length,resume:C,repairHint:S},responseLevel:f,evidence:y.state===`available`?y.evidence:void 0,...g?{signal:g}:{}})}function z(e){return e.state===`available`?{state:`available`,nodes:e.nodes}:{state:`unavailable`}}const B=[300,500,800,1200,2e3,3e3,4e3];async function V(e){let{session:t,observationStore:n,logPath:r,action:i,retryLaunchRace:a=!1,signal:o}=e;if(o?.aborted)return H();let s=ue(i),l=Date.now()+12e3,u=n.bindAuthority(o),d=await U({session:t,observation:u,logPath:r,flags:s});if(!a)return d.observation;for(let e of B){if(d.observation.state===`available`||!d.retryable)break;let n=l-Date.now();if(n<=0)break;if(await c(Math.min(e,n)),o?.aborted)return H();d=await U({session:t,observation:u,logPath:r,flags:s})}return d.observation}function H(){return{state:`unavailable`,reason:`request-canceled`,hint:`Post-failure snapshot skipped after request cancellation; the original replay failure is unaffected.`}}async function U(e){let{session:t,observation:n,logPath:r,flags:i}=e;try{let e=(await n.capture({flags:i,logPath:r})).snapshot;if(b(e.snapshotQuality))return{observation:{state:`unavailable`,reason:`sparse-snapshot`,hint:`The post-failure snapshot was sparse or unavailable; run snapshot -i to observe the current screen.`},retryable:!0};let a=n.store(e);return{observation:{state:`available`,nodes:e.nodes,refsGeneration:a.refsGeneration,evidence:a.evidence,appBundleId:t.appBundleId},retryable:!1}}catch(e){return{observation:{state:`unavailable`,reason:`capture-failed`,hint:`Post-failure snapshot capture failed (${e instanceof Error?e.message:String(e)}); the original replay failure is unaffected.`},retryable:m(e)}}}function ue(e){return{snapshotInteractiveOnly:de(e)}}function de(e){return!K(e.command)||q(e).requiresRect}function W(e,t){if(e.state===`unavailable`)return{state:`unavailable`,reason:t(e.reason),hint:t(e.hint)};let{refs:n,truncated:r}=me(e.nodes,t,e.appBundleId);return{state:`available`,refsGeneration:e.refsGeneration,refs:n,...r?{truncated:!0}:{}}}function fe(e){return!!y(e,o(e.type??`Element`))||e.hittable===!0}function G(e,t){return t!==void 0&&e.bundleId!==void 0&&e.bundleId!==t&&e.hittable===!0}function pe(e,t){let n=v(e,t),r=e.filter(e=>e.ref&&!n.has(e.ref)&&fe(e)),i=r.length>0?r:e.filter(e=>e.ref&&e.hittable===!0),a=i.filter(e=>e.interactionBlocked!==`covered`),o=a.length>0?a:i,s=[...o.filter(e=>G(e,t)),...o.filter(e=>!G(e,t))],c=s.slice(0,20);return{nodes:c,truncated:s.length>c.length}}function me(e,t,n){let{nodes:r,truncated:i}=pe(e,n);return{refs:r.map(e=>{let n=o(e.type??`Element`),r=y(e,n);return{ref:e.ref,role:t(n),...r?{label:t(r)}:{}}}),truncated:i}}function he(e){let{action:t,session:n,nodes:r,sanitize:i}=e;if(!K(t.command))return[];let a=te(t);return a.length===0?[]:ge({candidates:a,nodes:r,session:n,action:t,matching:q(t),sanitize:i})}function K(e){return l(e)||[`fill`,`get`,`is`,`wait`].includes(e)}function q(e){let t=l(e.command);return{requiresRect:t||e.command===`fill`,allowDisambiguation:t||e.command===`fill`||e.command===`get`&&e.positionals?.[0]===`text`}}function ge(e){let{candidates:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,s=[];for(let e of t){let t=_e({candidate:e,nodes:n,session:r,action:i,matching:a,sanitize:o});t&&s.push(t)}let c,l=i.targetEvidence;if(l?.verification===`verified`){let e=f(n);c=new Set;for(let{nodeIndex:t}of s){let n=e.get(t);n&&d(n,e,l.scrollRegion)&&c.add(t)}}return L(s,c).map(e=>e.suggestion)}function _e(e){let{candidate:t,nodes:n,session:i,action:a,matching:o,sanitize:s}=e,c=r(t,n,{platform:i.device.platform,requireRect:o.requiresRect,allowDisambiguation:o.allowDisambiguation});if(c)return{suggestion:J({node:c.node,nodes:n,session:i,action:a,basis:c.basis,sanitize:s}),basis:c.basis,nodeIndex:c.node.index}}function J(t){let{node:n,nodes:r,session:i,action:a,basis:s,sanitize:c}=t,u=e(n,i.device.platform,{action:a.command===`fill`?`fill`:l(a.command)?`click`:`get`,nodes:r}),d=o(n.type??`Element`),f=y(n,d);return{selector:c(u.join(` || `)),basis:s,...n.ref?{ref:n.ref}:{},role:c(d),...f?{label:c(f)}:{}}}function Y(e){return ve({...e,hint:e.hint??Z(e.details,`hint`),diagnosticId:e.diagnosticId??Z(e.details,`diagnosticId`),logPath:e.logPath??Z(e.details,`logPath`)})}function ve(e){return e.details?.reason===`android_shell_text_unsupported`?{...e,hint:"On emulators the test IME activates automatically; on real devices pass `--test-ime` to this test/replay run to enable it for the sessions the flow opens (see `agent-device doctor` for the current IME state)."}:e}function ye(e){let{error:t,action:n,step:r,replayPath:i,artifactPaths:a,snapshotDiagnostics:o,divergence:s,scrubVars:c}=e;return X({error:t,actionLabel:u(n),action:n.command,positionals:_(n)??[],step:r,replayPath:i,artifactPaths:a,snapshotDiagnostics:o,divergence:s,scrubVars:c})}function X(e){let{error:t,actionLabel:n,action:r,positionals:i,step:a,replayPath:o,artifactPaths:s,snapshotDiagnostics:c,divergence:l,scrubVars:u,warnings:d}=e;return{ok:!1,error:{code:`REPLAY_DIVERGENCE`,message:h(`Replay failed at step ${a} (${n}): ${t.message}`,u),hint:t.hint===void 0?void 0:h(t.hint,u),diagnosticId:t.diagnosticId,logPath:t.logPath,...t.retriable===void 0?{}:{retriable:t.retriable},...t.supportedOn===void 0?{}:{supportedOn:t.supportedOn},details:{...xe(t.details,u),replayPath:o,step:a,action:r,positionals:i,artifactPaths:s,...c?{snapshotDiagnostics:c}:{},...d&&d.length>0?{warnings:d.map(e=>h(e,u))}:{},divergence:l}}}}function Z(e,t){let n=e?.[t];return typeof n==`string`&&n.length>0?n:void 0}const be=[`adbFailure`,`reason`,`recovery`,`retriable`,`runnerConnectFailureReason`,`snapshotQuality`,`supportedOn`,`systemSurface`];function xe(e,t){if(!e)return{};let n={};for(let t of be)e[t]!==void 0&&(n[t]=e[t]);if(e.reason===`session_cleanup_incomplete`&&Array.isArray(e.failedSteps)&&e.failedSteps.every(e=>typeof e==`string`)&&(n.failedSteps=e.failedSteps.map(e=>h(e,t))),e.reason===`bounded_composite_resource_unsupported`){e.dispatched===`no`&&(n.dispatched=`no`);let t=Z(e,`shape`);t!==void 0&&(n.shape=t);let r=Z(e,`standaloneCommandName`);r!==void 0&&(n.standaloneCommandName=r)}return n}function Se(e,t){if(e)try{x.appendFileSync(e,`${JSON.stringify(a(t))}\n`)}catch(t){s({level:`warn`,phase:`replay_trace_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}}function Ce(e){let{req:t,sessionName:n,metadata:r,resolvedPath:i,hostCwd:a}=e,o=t.flags??{},s={AD_SESSION:n,AD_FILENAME:we(t,i,a)};return Q(s,`AD_PLATFORM`,o.platform??r.platform),Q(s,`AD_TARGET`,o.target??r.target),Q(s,`AD_DEVICE`,o.device),Q(s,`AD_DEVICE_ID`,Te(o)),$(s,`AD_SHARD_INDEX`,o.shardIndex),$(s,`AD_SHARD_COUNT`,o.shardCount),Q(s,`AD_ARTIFACTS`,o.artifactsDir),s}function we(e,t,n){let r=e.meta?.cwd??n;return S.relative(r,t)||t}function Te(e){return typeof e.serial==`string`?e.serial:e.udid}function Q(e,t,n){typeof n==`string`&&n.length>0&&(e[t]=n)}function $(e,t,n){typeof n==`number`&&(e[t]=String(n))}export{Y as a,le as c,z as d,L as f,T as g,E as h,X as i,V as l,k as m,Se as n,W as o,j as p,ye as r,J as s,Ce as t,q as u};
@@ -1 +1 @@
1
- import{P as e,f as t}from"./sdk-contracts.js";import{L as n,a as r}from"./sdk-device.js";import"./session-store.js";import{i}from"./session-selector.js";import a from"node:crypto";import o from"node:fs";import s from"node:path";const c=`default`,l=new Set(r);function u(e,n,r={}){let i=e.session||c;if(t(e))return i;let a=p(e);return a.kind===`cwd`?_(e,n,a.id,r):i}function d(e){return e.session||c}function f(e){let t=p(e);return t.kind===`cwd`?t:void 0}function p(n){if(n.meta?.sessionIsolation===`tenant`||n.flags?.sessionIsolation===`tenant`){let t=n.meta?.tenantId;if(!t)throw new e(`INTERNAL_ERROR`,`Tenant-scoped request reached session routing without an admitted tenant id`);return{kind:`tenant`,id:t}}if(t(n)||(n.session||c)!==c)return{kind:`named-local`};let r=k(n.meta?.cwd);return r?{kind:`cwd`,id:O(r)}:{kind:`global-default`}}function m(e,t){let n=e.sessionScope;return n?t.kind===`tenant`?n.kind===`tenant`&&n.id===t.id:n.kind===`tenant`?!1:t.kind!==`cwd`||n.kind===`named-local`||n.kind===`cwd`&&n.id===t.id:!1}function h(e,t){let n=f(e);return!n||t.sessionScope?.kind!==`cwd`?!1:t.sessionScope.id!==n.id}function g(e,t){return`cwd:${e}:${t}`}function _(e,t,n,r){let i=C(t,n),a=w(e);return a?v(e,t,n,a,i,r):S(n,i,r)}function v(e,t,n,r,a,o){let s=g(n,r);if(t.get(s))return s;let c=x(e.flags,r),l=a.map(e=>({ref:e,conflicts:i(e.session,c)})),u=l.filter(e=>e.conflicts.length===0),[d]=u;return d&&u.length===1?d.ref.address:u.length>1?(E(o,u.map(e=>e.ref)),s):y(l)?.address??s}function y(e){return e.find(e=>!b(e.conflicts))?.ref}function b(e){return e.some(e=>e.key===`platform`)}function x(e,t){return{...e,platform:t}}function S(e,t,n){let[r]=t;return r&&t.length===1?r.address:(E(n,t),g(e,c))}function C(e,t){let n=new Set,r=[];for(let i of e.listRefs()){let e=i.session.sessionScope;e?.kind===`cwd`&&e.id===t&&(n.has(i.session)||(n.add(i.session),r.push(i)))}return r}function w(e){return T(e.flags?.platform)??T(e.meta?.lockPlatform)}function T(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase();return l.has(t)?t:void 0}function E(e,t){if(t.length>1&&e.attachesToSession===!0)throw D(t)}function D(t){let r=t.map(e=>e.address),i=t.map(e=>n(e.session.device)),a=i.map(e=>`--platform ${e}`).join(` or `);return new e(`AMBIGUOUS_MATCH`,`This workspace has ${t.length} implicit sessions (${r.join(`, `)}); select one explicitly.`,{sessions:r,platforms:i,hint:`Run agent-device session list to inspect them. Add ${a} to run in that platform's session, or pass --session <address> copied from that list.`})}function O(e){return a.createHash(`sha256`).update(e).digest(`hex`).slice(0,16)}function k(e){if(!e||e.trim().length===0)return;let t=A(e);return j(t)??t}function A(e){let t=s.resolve(e);try{return o.realpathSync.native(t)}catch{return t}}function j(e){let t=e;for(;;){if(o.existsSync(s.join(t,`.git`)))return t;let e=s.dirname(t);if(e===t)return;t=e}}export{p as a,d as i,k as n,m as o,u as r,h as t};
1
+ import{_ as e,f as t}from"./sdk-contracts.js";import{R as n,a as r}from"./sdk-device.js";import"./session-store.js";import{i}from"./session-selector.js";import a from"node:crypto";import o from"node:fs";import s from"node:path";const c=`default`,l=new Set(r);function u(e,n,r={}){let i=e.session||c;if(t(e))return i;let a=p(e);return a.kind===`cwd`?_(e,n,a.id,r):i}function d(e){return e.session||c}function f(e){let t=p(e);return t.kind===`cwd`?t:void 0}function p(n){if(n.meta?.sessionIsolation===`tenant`||n.flags?.sessionIsolation===`tenant`){let t=n.meta?.tenantId;if(!t)throw new e(`INTERNAL_ERROR`,`Tenant-scoped request reached session routing without an admitted tenant id`);return{kind:`tenant`,id:t}}if(t(n)||(n.session||c)!==c)return{kind:`named-local`};let r=k(n.meta?.cwd);return r?{kind:`cwd`,id:O(r)}:{kind:`global-default`}}function m(e,t){let n=e.sessionScope;return n?t.kind===`tenant`?n.kind===`tenant`&&n.id===t.id:n.kind===`tenant`?!1:t.kind!==`cwd`||n.kind===`named-local`||n.kind===`cwd`&&n.id===t.id:!1}function h(e,t){let n=f(e);return!n||t.sessionScope?.kind!==`cwd`?!1:t.sessionScope.id!==n.id}function g(e,t){return`cwd:${e}:${t}`}function _(e,t,n,r){let i=C(t,n),a=w(e);return a?v(e,t,n,a,i,r):S(n,i,r)}function v(e,t,n,r,a,o){let s=g(n,r);if(t.get(s))return s;let c=x(e.flags,r),l=a.map(e=>({ref:e,conflicts:i(e.session,c)})),u=l.filter(e=>e.conflicts.length===0),[d]=u;return d&&u.length===1?d.ref.address:u.length>1?(E(o,u.map(e=>e.ref)),s):y(l)?.address??s}function y(e){return e.find(e=>!b(e.conflicts))?.ref}function b(e){return e.some(e=>e.key===`platform`)}function x(e,t){return{...e,platform:t}}function S(e,t,n){let[r]=t;return r&&t.length===1?r.address:(E(n,t),g(e,c))}function C(e,t){let n=new Set,r=[];for(let i of e.listRefs()){let e=i.session.sessionScope;e?.kind===`cwd`&&e.id===t&&(n.has(i.session)||(n.add(i.session),r.push(i)))}return r}function w(e){return T(e.flags?.platform)??T(e.meta?.lockPlatform)}function T(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase();return l.has(t)?t:void 0}function E(e,t){if(t.length>1&&e.attachesToSession===!0)throw D(t)}function D(t){let r=t.map(e=>e.address),i=t.map(e=>n(e.session.device)),a=i.map(e=>`--platform ${e}`).join(` or `);return new e(`AMBIGUOUS_MATCH`,`This workspace has ${t.length} implicit sessions (${r.join(`, `)}); select one explicitly.`,{sessions:r,platforms:i,hint:`Run agent-device session list to inspect them. Add ${a} to run in that platform's session, or pass --session <address> copied from that list.`})}function O(e){return a.createHash(`sha256`).update(e).digest(`hex`).slice(0,16)}function k(e){if(!e||e.trim().length===0)return;let t=A(e);return j(t)??t}function A(e){let t=s.resolve(e);try{return o.realpathSync.native(t)}catch{return t}}function j(e){let t=e;for(;;){if(o.existsSync(s.join(t,`.git`)))return t;let e=s.dirname(t);if(e===t)return;t=e}}export{p as a,d as i,k as n,m as o,u as r,h as t};
@@ -1 +1 @@
1
- import{P as e}from"./sdk-contracts.js";import{a as t}from"./runtime-admission.js";function n(e,n){return n.available?void 0:t(e,n)}function r(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Device runtime facts inspection is unavailable.`,{reason:`runtime-gateway-missing`})}const i=new WeakMap;let a;(class e{static{a=(t,n)=>{let r=new e;return i.set(r,{device:Object.freeze({...t}),plan:n}),Object.freeze(r),r}}#e;constructor(){this.#e=void 0}get admitted(){return this.#e,!0}});function o(t){let n=i.get(t);if(n===void 0)throw new e(`COMMAND_FAILED`,`Runtime plan admission is not one minted by admitRuntimePlan; refusing to bind.`);return n}async function s(e){let t=await r(e.inspectFacts)(e.device);for(let n of e.plan.use.required){let e=t.operations[n];if(!e.available)return{admitted:!1,operation:n,fact:e}}return a(e.device,e.plan)}function c(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Device runtime binding is unavailable.`,{reason:`runtime-gateway-missing`})}export{o as a,n as i,c as n,r,s as t};
1
+ import{_ as e}from"./sdk-contracts.js";import{a as t}from"./runtime-admission.js";function n(e,n){return n.available?void 0:t(e,n)}function r(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Device runtime facts inspection is unavailable.`,{reason:`runtime-gateway-missing`})}const i=new WeakMap;let a;(class e{static{a=(t,n)=>{let r=new e;return i.set(r,{device:Object.freeze({...t}),plan:n}),Object.freeze(r),r}}#e;constructor(){this.#e=void 0}get admitted(){return this.#e,!0}});function o(t){let n=i.get(t);if(n===void 0)throw new e(`COMMAND_FAILED`,`Runtime plan admission is not one minted by admitRuntimePlan; refusing to bind.`);return n}async function s(e){let t=await r(e.inspectFacts)(e.device);for(let n of e.plan.use.required){let e=t.operations[n];if(!e.available)return{admitted:!1,operation:n,fact:e}}return a(e.device,e.plan)}function c(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Device runtime binding is unavailable.`,{reason:`runtime-gateway-missing`})}export{o as a,n as i,c as n,r,s as t};
@@ -1 +1 @@
1
- import{P as e,R as t,l as n,s as r}from"./sdk-contracts.js";import{S as i,et as a}from"./sdk-io.js";import{E as o,L as s,T as c,W as l,w as u}from"./sdk-device.js";import{o as ee}from"./sdk-batch.js";import"./session-store.js";import{o as d}from"./session.js";import{v as f}from"./daemon-http.js";import"./command.js";import{r as p}from"./runtime-transport-hints.js";import{a as m}from"./daemon-command-registry.js";import{r as h}from"./application-lifecycle-runtime.js";import g from"node:os";const te=/^[1-9][0-9]{0,9}$/;function _(t){let n=t?.trim()??``,r=n.lastIndexOf(`@`),i=r<0?n:n.slice(0,r),a=r<0?void 0:n.slice(r+1);if(!o(i)||a!==void 0&&!te.test(a))throw new e(`INVALID_ARGS`,`A macos-app lease device key must be <bundleId> or <bundleId>@<pid>.`,{deviceKey:n});return a===void 0?{bundleId:i}:{bundleId:i,pid:Number(a)}}const v=new Set([`open`,`batch`]),y=[`out`,`saveScript`,`sessionSaveScript`,`baseline`,`launchConsole`,`launchArgs`,`launchUrl`,`bundleUrl`,`artifactsDir`,`stepsFile`,`searchPath`,`retainPaths`,`installSource`,`metroProjectRoot`,`metroRuntimeFile`,`iosXctestrunFile`,`iosXctestDerivedDataPath`,`iosXctestEnvDir`],b=[`device`,`udid`,`serial`,`target`,`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function x(t,n,r={}){return new e(`UNAUTHORIZED`,n,{...r,reason:`MACOS_APP_LEASE_DENIED`,rule:t,retriable:!1,hint:`This lease is limited to one macOS app; retrying will not help. Use an allowed command on the leased app.`})}function ne(e,t,n,r){if(e.backend!==`macos-app`)return;let i=_(e.deviceKey);if(C(r,i,t.command,t.positionals??[],S(t.runtime,{...t.input,...t.flags})),(t.command===`open`||t.command===`batch`)&&t.flags?.platform!==`macos`)throw x(`device`,`A macos-app lease needs platform macos on ${t.command}.`);if(t.command===`batch`)for(let e of t.flags?.batchSteps??[]){let t=Array.isArray(e.positionals)?e.positionals.map(String):[];C(r,i,ee(e.command),t,S(e.runtime,{...e.input,...e.flags}))}if(n)E(i,n);else if(!v.has(t.command))throw x(`session`,`A macos-app lease runs ${t.command} only in a session of ${i.bundleId}; open it first.`,{command:t.command,bundleId:i.bundleId})}function S(e,t){return{...t,...e?.launchUrl?{launchUrl:e.launchUrl}:{},...e?.bundleUrl?{bundleUrl:e.bundleUrl}:{}}}function C(e,t,n,r,i){if(!m(n))throw x(`command`,`A macos-app lease does not allow ${n}.`,{command:n});if(ae(i),ie(i),n===`screenshot`?re(r,i):w(i),n===`open`&&oe(e,t,r),n===`close`&&r.length>0&&r[0]!==t.bundleId)throw x(`app`,`A macos-app lease only closes ${t.bundleId}.`,{bundleId:t.bundleId})}function re(e,t){if(t.screenshotFullscreen===!0)throw x(`capture`,`A macos-app lease captures only the app window.`);let{out:n,...r}=t;w(r);for(let t of[e[0],n])if(!(t===void 0||typeof t==`string`&&f(t,`screenshot`,`.png`)))throw x(`host-path`,`A macos-app lease does not write files on the host.`)}function w(e){let t=y.find(t=>e[t]!==void 0&&e[t]!==!1);if(t)throw x(`host-path`,`A macos-app lease does not accept ${t}, which names a host path or launch.`,{field:t})}function ie(e){let t=b.find(t=>e[t]!==void 0&&e[t]!==``);if(t)throw x(`device`,`A macos-app lease does not accept the ${t} device selector.`,{field:t})}function ae(e){if(e.surface!==void 0&&e.surface!==`app`)throw x(`surface`,`A macos-app lease is limited to the app surface, not ${String(e.surface)}.`,{surface:e.surface});if(e.platform!==void 0&&e.platform!==`macos`)throw x(`app`,`A macos-app lease only drives a macOS app.`,{platform:e.platform})}function oe(e,t,n){if(n.length!==1||n[0]!==t.bundleId)throw x(`app`,`A macos-app lease only opens ${t.bundleId}.`,{bundleId:t.bundleId});T(e)}function T(e){if(d(t=>e[t])!==`native`)throw x(`backend`,`A macos-app lease needs the native macOS app backend (AGENT_DEVICE_MACOS_APP_BACKEND=native).`)}function E(e,t){if(!c(t.device)||(t.surface??`app`)!==`app`||t.appBundleId!==e.bundleId)throw x(`app`,`This session is not the leased app ${e.bundleId}.`,{bundleId:e.bundleId})}const D=/bundleID="([^"]+)"/,O=async e=>{if(!i(e))return;let t=await a(`/usr/bin/lsappinfo`,[`info`,`-only`,`bundleid`,String(e)],{allowFailure:!0,timeoutMs:5e3});return D.exec(t.stdout)?.[1]};async function k(e,t=O){if(e.backend!==`macos-app`)return;let n=_(e.deviceKey);if(n.pid!==void 0&&await t(n.pid)!==n.bundleId)throw x(`process`,`The leased app process ${n.bundleId}@${n.pid} is no longer running.`,{bundleId:n.bundleId,pid:n.pid})}const A=[`sessionStateDir`,`runnerLogPath`,`requestLogPath`,`eventLogPath`,`device`,`id`,`kind`,`serial`,`device_udid`,`ios_simulator_device_set`],j=/(?<![\p{L}\p{N}_./])\/(?:Users|home|private|var|tmp|Volumes|Library|Applications|opt|System|usr|etc|Network|cores)(?:\/[\p{L}\p{N}_.@%+~-]+)*\/?/gu;function M(){return{hostName:g.hostname(),homeDirectory:g.homedir()}}function N(e,t,n=M()){return t.ok?{ok:!0,data:P(e,t.data,n)}:{ok:!1,error:F(t.error,n)}}function P(e,t,n){if(!t)return t;let{fallbackScreenshotPath:r,...i}=t;if(e!==`open`)return i;for(let e of A)delete i[e];let{snapshot:a,initialSnapshotError:o,warnings:s,...c}=i;return{...c,...a===void 0?{}:{snapshot:P(`snapshot`,a,n)},...o===void 0?{}:{initialSnapshotError:F(o,n)},...s===void 0?{}:{warnings:L(s,n)}}}function F(e,t){if(e.code===`DEVICE_IN_USE`)return I(e);let{logPath:n,diagnosticsRecord:r,...i}=e;return L(i,t)}function I(e){let t=e.details?.reason;return{code:`DEVICE_IN_USE`,message:`The leased app is in use by another session.`,hint:`Retry once the other session ends.`,...typeof t==`string`?{details:{reason:t}}:{},...e.retriable===void 0?{}:{retriable:e.retriable}}}function L(e,t){return typeof e==`string`?R(e,t):Array.isArray(e)?e.map(e=>L(e,t)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,L(n,t)]))}function R(e,t){let n=e;if(t.homeDirectory.length>1){let e=t.homeDirectory.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);n=n.replaceAll(RegExp(`${e}[\\w.@%+~/-]*`,`g`),`<host-path>`)}for(let e of new Set([t.hostName,t.hostName.split(`.`)[0]]))e.length>=4&&(n=n.replaceAll(e,`<host>`));return n.replace(j,`<host-path>`)}function z(e,t){if(!(t===void 0||!e.hasHeldMacOsAppLease(t)))throw x(`diagnostics`,`A macos-app lease does not serve request diagnostics.`)}function B(e){return e.device.platform===`web`}function V(e){return e.toArray().flatMap(e=>l(e.device.id)??[])}function H(e){return u(e)&&e.kind===`simulator`}function U(e){return e.platform===`android`&&e.kind===`emulator`}const W=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function G(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function K(e){if(!e)return{};let t={};return e.metroHost!==void 0&&(t.metroHost=e.metroHost),e.metroPort!==void 0&&(t.metroPort=String(e.metroPort)),e.bundleUrl!==void 0&&(t.bundleUrl=e.bundleUrl),e.launchUrl!==void 0&&(t.launchUrl=e.launchUrl),t}function q(e){return h(K(e))}function J(t,n){if(t!==void 0){if(typeof t!=`string`)throw new e(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return p(t)}}function Y(t){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(t)}. Use an integer between 1 and 65535.`);return t}}function se(t){if(t!==void 0){if(typeof t!=`number`)throw new e(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Y(t)}}function ce(t,r,i){if(t===void 0)return i;if(!n(t))throw new e(`INVALID_ARGS`,`Invalid open runtime platform: ${String(t)}. Use "ios", "android", or "harmonyos".`);if(i&&t!==i)throw new e(`INVALID_ARGS`,`open runtime targets ${t}, but session "${r}" is bound to ${i}.`);return t}function X(e){if(n(e))return e}function le(e,t){return{platform:t,metroHost:p(e?.metroHost),metroPort:Y(e?.metroPort),bundleUrl:p(e?.bundleUrl),launchUrl:p(e?.launchUrl)}}function ue(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function de(e){if(U(e))return`10.0.2.2`;if(H(e))return`127.0.0.1`}function Z(e,t){if(!e||p(e.metroHost)||p(e.bundleUrl)||e.metroPort===void 0)return e;let n=de(t);return n?{...e,metroHost:n}:e}function fe(t){let{runtime:n,sessionName:r,platform:i}=t;if(n===void 0)return;if(!n||typeof n!=`object`||Array.isArray(n))throw new e(`INVALID_ARGS`,`open runtime must be an object.`);let a=n,o=Object.keys(a).find(e=>!W.includes(e));if(o)throw new e(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${W.join(`, `)}.`);return{platform:ce(a.platform,r,i),metroHost:J(a.metroHost,`metroHost`),metroPort:se(a.metroPort),bundleUrl:J(a.bundleUrl,`bundleUrl`),launchUrl:J(a.launchUrl,`launchUrl`)}}function pe(e,t,n){if(n){if(G(n)===0){e.setRuntimeHints(t,void 0);return}return e.setRuntimeHints(t,n),n}}function me(t,n,r,i){let a=t.getRuntimeHints(n);if(!a)return;let o=r?s(r):void 0,c=X(o)??i;if(a.platform&&r&&!c)throw new e(`INVALID_ARGS`,`Session runtime hints are only supported on iOS, Android, and HarmonyOS sessions, but session "${n}" is bound to ${o}.`);if(a.platform&&c&&a.platform!==c)throw new e(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${n}" is bound to ${o}. Clear the runtime hints or use a different session.`);return c&&a.platform!==c?{...a,platform:c}:a}function Q(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?X(s(i)):e.platform,o=n.getRuntimeHints(r),c=fe({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=me(n,r,i,a);return{runtime:i?Z(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let l=c&&G(c)>0?c:void 0;return{runtime:i?Z(l,i):l,previousRuntime:o,replacedStoredRuntime:!0}}function he(e){return Q(e).runtime}function ge(e){try{return{ok:!0,data:Q(e)}}catch(e){let n=t(e);return r(n.code,n.message,n.details)}}async function _e(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!$(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:K(t)})}function $(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&q(e.previousRuntime)&&!q(e.runtime)}export{_,ue as a,pe as c,ge as d,B as f,z as g,k as h,_e as i,$ as l,ne as m,G as n,he as o,V as p,q as r,K as s,le as t,X as u,N as v};
1
+ import{o as e}from"./sdk-batch.js";import{_ as t,l as n,s as r,x as i}from"./sdk-contracts.js";import{C as a,rt as o}from"./sdk-io.js";import{E as s,G as c,R as l,T as u,w as ee}from"./sdk-device.js";import"./session-store.js";import{o as d}from"./session.js";import{v as f}from"./daemon-http.js";import"./command.js";import{r as p}from"./runtime-transport-hints.js";import{a as m}from"./daemon-command-registry.js";import{r as te}from"./application-lifecycle-runtime.js";import h from"node:os";const ne=/^[1-9][0-9]{0,9}$/;function g(e){let n=e?.trim()??``,r=n.lastIndexOf(`@`),i=r<0?n:n.slice(0,r),a=r<0?void 0:n.slice(r+1);if(!s(i)||a!==void 0&&!ne.test(a))throw new t(`INVALID_ARGS`,`A macos-app lease device key must be <bundleId> or <bundleId>@<pid>.`,{deviceKey:n});return a===void 0?{bundleId:i}:{bundleId:i,pid:Number(a)}}const _=new Set([`open`,`batch`]),v=[`out`,`saveScript`,`sessionSaveScript`,`baseline`,`launchConsole`,`launchArgs`,`launchUrl`,`bundleUrl`,`artifactsDir`,`stepsFile`,`searchPath`,`retainPaths`,`installSource`,`metroProjectRoot`,`metroRuntimeFile`,`iosXctestrunFile`,`iosXctestDerivedDataPath`,`iosXctestEnvDir`],re=[`device`,`udid`,`serial`,`target`,`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function y(e,n,r={}){return new t(`UNAUTHORIZED`,n,{...r,reason:`MACOS_APP_LEASE_DENIED`,rule:e,retriable:!1,hint:`This lease is limited to one macOS app; retrying will not help. Use an allowed command on the leased app.`})}function b(t,n,r,i){if(t.backend!==`macos-app`)return;let a=g(t.deviceKey);if(S(i,a,n.command,n.positionals??[],x(n.runtime,{...n.input,...n.flags})),(n.command===`open`||n.command===`batch`)&&n.flags?.platform!==`macos`)throw y(`device`,`A macos-app lease needs platform macos on ${n.command}.`);if(n.command===`batch`)for(let t of n.flags?.batchSteps??[]){let n=Array.isArray(t.positionals)?t.positionals.map(String):[];S(i,a,e(t.command),n,x(t.runtime,{...t.input,...t.flags}))}if(r)E(a,r);else if(!_.has(n.command))throw y(`session`,`A macos-app lease runs ${n.command} only in a session of ${a.bundleId}; open it first.`,{command:n.command,bundleId:a.bundleId})}function x(e,t){return{...t,...e?.launchUrl?{launchUrl:e.launchUrl}:{},...e?.bundleUrl?{bundleUrl:e.bundleUrl}:{}}}function S(e,t,n,r,i){if(!m(n))throw y(`command`,`A macos-app lease does not allow ${n}.`,{command:n});if(ae(i),ie(i),n===`screenshot`?C(r,i):w(i),n===`open`&&oe(e,t,r),n===`close`&&r.length>0&&r[0]!==t.bundleId)throw y(`app`,`A macos-app lease only closes ${t.bundleId}.`,{bundleId:t.bundleId})}function C(e,t){if(t.screenshotFullscreen===!0)throw y(`capture`,`A macos-app lease captures only the app window.`);let{out:n,...r}=t;w(r);for(let t of[e[0],n])if(!(t===void 0||typeof t==`string`&&f(t,`screenshot`,`.png`)))throw y(`host-path`,`A macos-app lease does not write files on the host.`)}function w(e){let t=v.find(t=>e[t]!==void 0&&e[t]!==!1);if(t)throw y(`host-path`,`A macos-app lease does not accept ${t}, which names a host path or launch.`,{field:t})}function ie(e){let t=re.find(t=>e[t]!==void 0&&e[t]!==``);if(t)throw y(`device`,`A macos-app lease does not accept the ${t} device selector.`,{field:t})}function ae(e){if(e.surface!==void 0&&e.surface!==`app`)throw y(`surface`,`A macos-app lease is limited to the app surface, not ${String(e.surface)}.`,{surface:e.surface});if(e.platform!==void 0&&e.platform!==`macos`)throw y(`app`,`A macos-app lease only drives a macOS app.`,{platform:e.platform})}function oe(e,t,n){if(n.length!==1||n[0]!==t.bundleId)throw y(`app`,`A macos-app lease only opens ${t.bundleId}.`,{bundleId:t.bundleId});T(e)}function T(e){if(d(t=>e[t])!==`native`)throw y(`backend`,`A macos-app lease needs the native macOS app backend (AGENT_DEVICE_MACOS_APP_BACKEND=native).`)}function E(e,t){if(!u(t.device)||(t.surface??`app`)!==`app`||t.appBundleId!==e.bundleId)throw y(`app`,`This session is not the leased app ${e.bundleId}.`,{bundleId:e.bundleId})}const D=/bundleID="([^"]+)"/,O=async e=>{if(!a(e))return;let t=await o(`/usr/bin/lsappinfo`,[`info`,`-only`,`bundleid`,String(e)],{allowFailure:!0,timeoutMs:5e3});return D.exec(t.stdout)?.[1]};async function k(e,t=O){if(e.backend!==`macos-app`)return;let n=g(e.deviceKey);if(n.pid!==void 0&&await t(n.pid)!==n.bundleId)throw y(`process`,`The leased app process ${n.bundleId}@${n.pid} is no longer running.`,{bundleId:n.bundleId,pid:n.pid})}const A=[`sessionStateDir`,`runnerLogPath`,`requestLogPath`,`eventLogPath`,`device`,`id`,`kind`,`model`,`osVersion`,`serial`,`device_udid`,`ios_simulator_device_set`],j=/(?<![\p{L}\p{N}_./])\/(?:Users|home|private|var|tmp|Volumes|Library|Applications|opt|System|usr|etc|Network|cores)(?:\/[\p{L}\p{N}_.@%+~-]+)*\/?/gu;function M(){return{hostName:h.hostname(),homeDirectory:h.homedir()}}function N(e,t,n=M()){return t.ok?{ok:!0,data:P(e,t.data,n)}:{ok:!1,error:F(t.error,n)}}function P(e,t,n){if(!t)return t;let{fallbackScreenshotPath:r,...i}=t;if(e!==`open`)return i;for(let e of A)delete i[e];let{snapshot:a,initialSnapshotError:o,warnings:s,...c}=i;return{...c,...a===void 0?{}:{snapshot:P(`snapshot`,a,n)},...o===void 0?{}:{initialSnapshotError:F(o,n)},...s===void 0?{}:{warnings:L(s,n)}}}function F(e,t){if(e.code===`DEVICE_IN_USE`)return I(e);let{logPath:n,diagnosticsRecord:r,...i}=e;return L(i,t)}function I(e){let t=e.details?.reason;return{code:`DEVICE_IN_USE`,message:`The leased app is in use by another session.`,hint:`Retry once the other session ends.`,...typeof t==`string`?{details:{reason:t}}:{},...e.retriable===void 0?{}:{retriable:e.retriable}}}function L(e,t){return typeof e==`string`?R(e,t):Array.isArray(e)?e.map(e=>L(e,t)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,L(n,t)]))}function R(e,t){let n=e;if(t.homeDirectory.length>1){let e=t.homeDirectory.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);n=n.replaceAll(RegExp(`${e}[\\w.@%+~/-]*`,`g`),`<host-path>`)}for(let e of new Set([t.hostName,t.hostName.split(`.`)[0]]))e.length>=4&&(n=n.replaceAll(e,`<host>`));return n.replace(j,`<host-path>`)}function z(e,t){if(!(t===void 0||!e.hasHeldMacOsAppLease(t)))throw y(`diagnostics`,`A macos-app lease does not serve request diagnostics.`)}function B(e){return e.device.platform===`web`}function V(e){return e.toArray().flatMap(e=>c(e.device.id)??[])}function H(e){return ee(e)&&e.kind===`simulator`}function U(e){return e.platform===`android`&&e.kind===`emulator`}const W=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function G(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function K(e){if(!e)return{};let t={};return e.metroHost!==void 0&&(t.metroHost=e.metroHost),e.metroPort!==void 0&&(t.metroPort=String(e.metroPort)),e.bundleUrl!==void 0&&(t.bundleUrl=e.bundleUrl),e.launchUrl!==void 0&&(t.launchUrl=e.launchUrl),t}function q(e){return te(K(e))}function J(e,n){if(e!==void 0){if(typeof e!=`string`)throw new t(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return p(e)}}function Y(e){if(e!==void 0){if(!Number.isInteger(e)||e<1||e>65535)throw new t(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function se(e){if(e!==void 0){if(typeof e!=`number`)throw new t(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Y(e)}}function ce(e,r,i){if(e===void 0)return i;if(!n(e))throw new t(`INVALID_ARGS`,`Invalid open runtime platform: ${String(e)}. Use "ios", "android", or "harmonyos".`);if(i&&e!==i)throw new t(`INVALID_ARGS`,`open runtime targets ${e}, but session "${r}" is bound to ${i}.`);return e}function X(e){if(n(e))return e}function le(e,t){return{platform:t,metroHost:p(e?.metroHost),metroPort:Y(e?.metroPort),bundleUrl:p(e?.bundleUrl),launchUrl:p(e?.launchUrl)}}function ue(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function de(e){if(U(e))return`10.0.2.2`;if(H(e))return`127.0.0.1`}function Z(e,t){if(!e||p(e.metroHost)||p(e.bundleUrl)||e.metroPort===void 0)return e;let n=de(t);return n?{...e,metroHost:n}:e}function fe(e){let{runtime:n,sessionName:r,platform:i}=e;if(n===void 0)return;if(!n||typeof n!=`object`||Array.isArray(n))throw new t(`INVALID_ARGS`,`open runtime must be an object.`);let a=n,o=Object.keys(a).find(e=>!W.includes(e));if(o)throw new t(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${W.join(`, `)}.`);return{platform:ce(a.platform,r,i),metroHost:J(a.metroHost,`metroHost`),metroPort:se(a.metroPort),bundleUrl:J(a.bundleUrl,`bundleUrl`),launchUrl:J(a.launchUrl,`launchUrl`)}}function pe(e,t,n){if(n){if(G(n)===0){e.setRuntimeHints(t,void 0);return}return e.setRuntimeHints(t,n),n}}function me(e,n,r,i){let a=e.getRuntimeHints(n);if(!a)return;let o=r?l(r):void 0,s=X(o)??i;if(a.platform&&r&&!s)throw new t(`INVALID_ARGS`,`Session runtime hints are only supported on iOS, Android, and HarmonyOS sessions, but session "${n}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new t(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${n}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function Q(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?X(l(i)):e.platform,o=n.getRuntimeHints(r),s=fe({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=me(n,r,i,a);return{runtime:i?Z(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&G(s)>0?s:void 0;return{runtime:i?Z(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function he(e){return Q(e).runtime}function ge(e){try{return{ok:!0,data:Q(e)}}catch(e){let t=i(e);return r(t.code,t.message,t.details)}}async function _e(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!$(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:K(t)})}function $(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&q(e.previousRuntime)&&!q(e.runtime)}export{g as _,ue as a,pe as c,ge as d,B as f,z as g,k as h,_e as i,$ as l,b as m,G as n,he as o,V as p,q as r,K as s,le as t,X as u,N as v};
@@ -0,0 +1 @@
1
+ import{St as e,gt as t,p as n}from"./sdk-io.js";import"./diagnostics.js";import{n as r}from"./success-text.js";import{n as i,o as a}from"./file.js";import{o}from"./daemon-resolution.js";import s from"node:crypto";import c from"node:fs";import l from"node:path";async function u(e,t,n,r){o(e.capabilities);let{savedScript:i,...a}=t.meta?.clientArtifactPaths??{};if(!e.baseUrl||!i)throw Error(`A remote script open needs a destination.`);let l=s.randomUUID(),u=C(n,e.baseUrl,t,l);await T(u,{destination:i,force:t.flags?.force===!0,revision:0});let d={...t.meta,clientArtifactPaths:a,scriptPublicationId:l},f=await r({...t,meta:d});return(!f.ok||f.data?.scriptPublicationId!==l)&&await k(u,async()=>c.rmSync(u,{force:!0})).catch(()=>{}),f}function d(t,n,i,a,o){let s=i.data?.scriptPublicationId,c=n.command===`close`&&typeof s==`string`?s:void 0,l=async()=>{if(c===void 0)return;let e=C(a,t.baseUrl,n,c);await k(e,async()=>g(e))},u={publish:async(i,s,c)=>{delete s[i.field];let l=await f({endpoint:t,req:n,stateDir:a,download:o},i);if(`failure`in l){let{failure:t,error:i}=l;s.scriptDeliveryFailure=t,s.warnings=[...r(s),`${t.message} ${t.hint}`],e({level:`warn`,phase:`session_script_delivery_failed`,data:{session:n.session,error:String(i)}});return}let{published:u}=l;u!==void 0&&(s.savedScript=u,c.push({...i,localPath:u}))},settleAfter:async t=>{let r=()=>l().catch(t=>e({level:`warn`,phase:`session_script_retire_failed`,data:{session:n.session,error:String(t)}}));try{return await t(u)}finally{await r()}}};return u}async function f(t,n){let{endpoint:r,req:i,stateDir:a}=t,{scriptPublicationId:o,scriptRevision:s,artifactId:u}=n,d=n.field===`savedScript`&&n.artifactType===`session-script`&&typeof o==`string`&&typeof u==`string`&&Number.isSafeInteger(s)&&s>0?C(a,r.baseUrl,i,o):void 0,f=d?E(d):void 0;if(!d||!f)return e({level:`warn`,phase:`session_script_artifact_dropped`,data:{session:i.session,artifactId:u}}),{published:void 0};if(s<=f.revision)return{published:f.destination};let h=l.dirname(f.destination),g={named:!1},_;try{if(await c.promises.mkdir(h,{recursive:!0}),_=await k(d,async()=>p(d,h)),!_)return{published:void 0};let e=l.join(_,`script.ad`);await t.download({...r,artifactId:u,destinationPath:e,requestScope:i.meta,privateFile:{maxBytes:8388608}});let n={revision:s,staging:_,staged:e,pending:g};return{published:await k(d,async()=>y(d,n))}}catch(e){let t=i.command===`close`;return{failure:S(f.destination,o,e,t),error:e}}finally{let e=_;e&&!g.named&&await k(d,async()=>m(d,e)).catch(()=>void 0)}}function p(e,t){let n=E(e);if(!n)return;let r=c.mkdtempSync(l.join(t,`.agent-device-script-`));try{O(e,{...n,staging:[...n.staging??[],r]})}catch(e){throw c.rmSync(r,{recursive:!0,force:!0}),e}return r}function m(e,t){c.rmSync(t,{recursive:!0,force:!0});let n=E(e);n&&O(e,h(n,t))}function h(e,t){return{...e,staging:(e.staging??[]).filter(e=>e!==t)}}function g(e){let t=D(e);if(t&&!t.retired)try{O(e,{...b(t),retired:!0})}catch(n){throw _(e,t),n}for(let e of t?.staging??[])c.rmSync(e,{recursive:!0,force:!0});c.rmSync(e,{force:!0})}function _(e,t){let n=v(e)?void 0:t.publishing?.staging;for(let e of t.staging??[])e!==n&&v(e)}function v(t){try{return c.rmSync(t,{recursive:!0,force:!0}),!0}catch(n){return e({level:`warn`,phase:`session_script_record_cleanup_failed`,data:{target:t,error:String(n)}}),!1}}function y(e,t){let{revision:n,staging:r,staged:i,pending:a}=t,o=E(e);if(!o)return;let s=b(o);if(o.publishing&&(O(e,s),m(e,o.publishing.staging),s=h(s,o.publishing.staging)),n<=s.revision)return s.destination;let l={revision:n,file:x(i)??`missing`,staging:r};c.linkSync(i,`${i}.anchor`),O(e,{...s,publishing:l}),a.named=!0;let u=s.revision===0&&!s.force;try{u?c.linkSync(i,s.destination):c.renameSync(i,s.destination)}catch(t){throw O(e,b({...s,publishing:l})),a.named=!1,t}return O(e,{...s,revision:n}),a.named=!1,s.destination}function b(e){let{publishing:t,...n}=e;return t?x(e.destination)===t.file?{...n,revision:Math.max(n.revision,t.revision)}:n:e}function x(e){let t=c.lstatSync(e,{bigint:!0,throwIfNoEntry:!1});return t?`${t.dev}:${t.ino}`:void 0}function S(e,t,n,r){let i=n?.code===`EEXIST`,a=r?`The session is closed, so no later version follows.`:`The next recorded action or close delivers the full recording again.`;return i?{reason:`script_delivery_failed`,cause:`script_target_exists`,publicationId:t,message:`A file already exists at ${e}.`,hint:`Remove the existing file, or start a new recording with open --save-script --force.`}:{reason:`script_delivery_failed`,cause:`script_download_failed`,publicationId:t,message:`The remote script could not be saved to ${e}.`,hint:`The file may still hold the previous version. ${a}`}}function C(e,t,n,r){let i=s.createHash(`sha256`).update(JSON.stringify([w(t),n.meta?.tenantId??``,n.session??``,r])).digest(`hex`);return l.join(e,`remote-connections`,`session-scripts`,`${i}.json`)}function w(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}async function T(t,n){let r=l.dirname(t);c.mkdirSync(r,{recursive:!0,mode:448});let i=e=>(c.lstatSync(e,{throwIfNoEntry:!1})?.mtimeMs??1/0)<Date.now()-6048e5,a=e=>i(e)||D(e)?.retired===!0;for(let t of c.readdirSync(r)){let n=l.join(r,t);!t.endsWith(`.json`)||!a(n)||await k(n,async()=>{a(n)&&g(n)}).catch(n=>e({level:`warn`,phase:`session_script_sweep_failed`,data:{record:t,error:String(n)}}))}O(t,n)}function E(e){let t=D(e);return t?.retired?void 0:t}function D(e){let t=null;try{t=JSON.parse(c.readFileSync(e,`utf8`))}catch{return}let n=t?.publishing;return typeof t?.destination==`string`&&typeof t.force==`boolean`&&Number.isSafeInteger(t.revision)&&(n===void 0||Number.isSafeInteger(n?.revision)&&typeof n?.file==`string`&&typeof n?.staging==`string`)&&(t.retired===void 0||t.retired===!0)&&(t.staging===void 0||Array.isArray(t.staging)&&t.staging.every(e=>typeof e==`string`))?t:void 0}function O(e,n){t({destination:e,contents:`${JSON.stringify(n)}\n`,mode:384})}async function k(e,t){let{pid:r,startTime:o}=n();return await a({acquire:()=>i({lockDirPath:`${e}.lock`,owner:{pid:r,startTime:o,acquiredAtMs:Date.now()},timeoutMs:3e4,description:`remote session script record`}),task:t})}export{u as sendRemoteScriptOpen,d as sessionScriptDelivery};
@@ -1 +1 @@
1
- import{P as e,s as t}from"./sdk-contracts.js";import{A as n,M as r,P as i,w as a}from"./sdk-device.js";import{c as o}from"./device-shell.js";import{t as s}from"./device-isolation.js";function c(e){return`${e.device.platform} device "${e.device.name.trim()}" (${e.device.id})`}function l(e,t,n={}){return e.session.screenRecording?f(e.address,t):m(e,t,n)}function u(e,n,r={}){return t(`DEVICE_IN_USE`,`Device is already in use by session "${e.address}".`,{session:e.address,deviceId:n.id,deviceName:n.name,...r.waitedMs===void 0?{}:{waitedMs:r.waitedMs},hint:l(e,`device-in-use`,r),dispatched:`no`})}function d(e,n,r={}){return t(`DEVICE_IN_USE`,`Device is already in use by workspace session "${e.address}".`,{reason:`WORKSPACE_SESSION_SCOPE_CONFLICT`,session:e.address,deviceId:n.id,deviceName:n.name,...r.waitedMs===void 0?{}:{waitedMs:r.waitedMs},hint:p(e.address,r),dispatched:`no`})}function f(e,t){let n=o(e),r=`agent-device close --session ${n}`,i=`agent-device record stop --session ${n}`,a=t===`selector-conflict`?`use --session ${n} without device selectors`:`reuse --session ${n}`;return`A recording session, maybe another agent's or user's, holds this device. ${g}Only if it is yours: run ${i}, then ${r} if still open; or ${a}.`}function p(e,t){let n=o(e);return`${_(t)}The holding session belongs to another workspace, possibly another agent's or user's. ${g}${v(t)}Run agent-device close --session ${n} only if that workspace is yours.`}function m(e,t,n){let r=e.address,i=o(r),a=`agent-device close --session ${i}`;return t===`selector-conflict`?`To use the selected device, open it with a different --session name.`+y(e,n)+` Only if session "${r}" is yours: rerun with --session ${i} without device selectors, or run ${a}.`:`${_(n)}${h}${g}${v(n)}Only if that session is yours: reuse --session ${i}, or run ${a} first.`}const h=`The holding session may belong to another agent or user. `,g=`Run agent-device devices and open another device with a device selector. `;function _(e){return e.waitedMs===void 0?``:`Waited ${Math.round(e.waitedMs)}ms for this device and it stayed busy. `}function v(e){return e.offersDeviceWait&&e.waitedMs===void 0?`To wait for the device to free up, run the same open with --wait <ms>. `:``}function y(e,t){return t.offersPlatformSession===!0&&e.session.sessionScope?.kind===`cwd`?` Or name the other platform with --platform to open its own session for this workspace.`:``}function b(t,n){let{address:r,session:i}=t,a=x(i,n);if(a.length===0)return;let o=S(i,a);throw new e(`INVALID_ARGS`,`Session "${r}" is already bound to ${c(i)}, but this request selected ${a.map(C).join(`, `)}.`+(o?` ${o}`:``),{session:r,conflicts:a.map(C),hint:l(t,`selector-conflict`,{offersPlatformSession:a.some(e=>e.key===`platform`)})})}function x(e,t){if(!t)return[];let o=[],c=e.device,l=t.platform;if(l&&!i(c,l)&&o.push({key:`platform`,value:t.platform}),t.target&&t.target!==(c.target??`mobile`)&&o.push({key:`target`,value:t.target}),t.udid&&(!a(c)||t.udid!==c.id)&&o.push({key:`udid`,value:t.udid}),t.serial&&(!n(c.platform)||t.serial!==c.id)&&o.push({key:`serial`,value:t.serial}),t.device&&!r(c,t.device)&&o.push({key:`device`,value:t.device}),t.iosSimulatorDeviceSet){let e=t.iosSimulatorDeviceSet.trim(),n=c.simulatorSetPath?.trim();(!a(c)||c.kind!==`simulator`||e!==n)&&o.push({key:`iosSimulatorDeviceSet`,value:t.iosSimulatorDeviceSet})}if(t.androidDeviceAllowlist){let e=s(t.androidDeviceAllowlist);(c.platform!==`android`||!e.has(c.id))&&o.push({key:`androidDeviceAllowlist`,value:t.androidDeviceAllowlist})}return o}function S(e,t){let n=e.device;if(a(n)&&t.some(e=>e.key===`device`&&e.value===n.id))return`--device selects a device by name; select this device by UDID with --udid ${n.id}.`}function C(e){return`${w(e.key)}=${e.value}`}function w(e){switch(e){case`iosSimulatorDeviceSet`:return`--ios-simulator-device-set`;case`androidDeviceAllowlist`:return`--android-device-allowlist`;default:return`--${e}`}}export{u as a,c,x as i,S as n,d as o,C as r,l as s,b as t};
1
+ import{_ as e,s as t}from"./sdk-contracts.js";import{A as n,M as r,P as i,w as a}from"./sdk-device.js";import{c as o}from"./device-shell.js";import{t as s}from"./device-isolation.js";function c(e){return`${e.device.platform} device "${e.device.name.trim()}" (${e.device.id})`}function l(e,t,n={}){return e.session.screenRecording?f(e.address,t):m(e,t,n)}function u(e,n,r={}){return t(`DEVICE_IN_USE`,`Device is already in use by session "${e.address}".`,{session:e.address,deviceId:n.id,deviceName:n.name,...r.waitedMs===void 0?{}:{waitedMs:r.waitedMs},hint:l(e,`device-in-use`,r),dispatched:`no`})}function d(e,n,r={}){return t(`DEVICE_IN_USE`,`Device is already in use by workspace session "${e.address}".`,{reason:`WORKSPACE_SESSION_SCOPE_CONFLICT`,session:e.address,deviceId:n.id,deviceName:n.name,...r.waitedMs===void 0?{}:{waitedMs:r.waitedMs},hint:p(e.address,r),dispatched:`no`})}function f(e,t){let n=o(e),r=`agent-device close --session ${n}`,i=`agent-device record stop --session ${n}`,a=t===`selector-conflict`?`use --session ${n} without device selectors`:`reuse --session ${n}`;return`A recording session, maybe another agent's or user's, holds this device. ${g}Only if it is yours: run ${i}, then ${r} if still open; or ${a}.`}function p(e,t){let n=o(e);return`${_(t)}The holding session belongs to another workspace, possibly another agent's or user's. ${g}${v(t)}Run agent-device close --session ${n} only if that workspace is yours.`}function m(e,t,n){let r=e.address,i=o(r),a=`agent-device close --session ${i}`;return t===`selector-conflict`?`To use the selected device, open it with a different --session name.`+y(e,n)+` Only if session "${r}" is yours: rerun with --session ${i} without device selectors, or run ${a}.`:`${_(n)}${h}${g}${v(n)}Only if that session is yours: reuse --session ${i}, or run ${a} first.`}const h=`The holding session may belong to another agent or user. `,g=`Run agent-device devices and open another device with a device selector. `;function _(e){return e.waitedMs===void 0?``:`Waited ${Math.round(e.waitedMs)}ms for this device and it stayed busy. `}function v(e){return e.offersDeviceWait&&e.waitedMs===void 0?`To wait for the device to free up, run the same open with --wait <ms>. `:``}function y(e,t){return t.offersPlatformSession===!0&&e.session.sessionScope?.kind===`cwd`?` Or name the other platform with --platform to open its own session for this workspace.`:``}function b(t,n){let{address:r,session:i}=t,a=x(i,n);if(a.length===0)return;let o=S(i,a);throw new e(`INVALID_ARGS`,`Session "${r}" is already bound to ${c(i)}, but this request selected ${a.map(C).join(`, `)}.`+(o?` ${o}`:``),{session:r,conflicts:a.map(C),hint:l(t,`selector-conflict`,{offersPlatformSession:a.some(e=>e.key===`platform`)})})}function x(e,t){if(!t)return[];let o=[],c=e.device,l=t.platform;if(l&&!i(c,l)&&o.push({key:`platform`,value:t.platform}),t.target&&t.target!==(c.target??`mobile`)&&o.push({key:`target`,value:t.target}),t.udid&&(!a(c)||t.udid!==c.id)&&o.push({key:`udid`,value:t.udid}),t.serial&&(!n(c.platform)||t.serial!==c.id)&&o.push({key:`serial`,value:t.serial}),t.device&&!r(c,t.device)&&o.push({key:`device`,value:t.device}),t.iosSimulatorDeviceSet){let e=t.iosSimulatorDeviceSet.trim(),n=c.simulatorSetPath?.trim();(!a(c)||c.kind!==`simulator`||e!==n)&&o.push({key:`iosSimulatorDeviceSet`,value:t.iosSimulatorDeviceSet})}if(t.androidDeviceAllowlist){let e=s(t.androidDeviceAllowlist);(c.platform!==`android`||!e.has(c.id))&&o.push({key:`androidDeviceAllowlist`,value:t.androidDeviceAllowlist})}return o}function S(e,t){let n=e.device;if(a(n)&&t.some(e=>e.key===`device`&&e.value===n.id))return`--device selects a device by name; select this device by UDID with --udid ${n.id}.`}function C(e){return`${w(e.key)}=${e.value}`}function w(e){switch(e){case`iosSimulatorDeviceSet`:return`--ios-simulator-device-set`;case`androidDeviceAllowlist`:return`--android-device-allowlist`;default:return`--${e}`}}export{u as a,c,x as i,S as n,d as o,C as r,l as s,b as t};
@@ -1,4 +1,4 @@
1
- import{P as e,nt as t,pt as n}from"./sdk-contracts.js";import{y as r}from"./sdk-batch-runner.js";import{pt as i,xt as a,yt as o}from"./sdk-io.js";import"./diagnostics.js";import{L as s,p as c}from"./sdk-device.js";import{An as l,P as ee,Sr as te,w as ne,xr as re}from"./sdk-batch.js";import{s as u}from"./script.js";import{a as ie,c as d,d as f,f as ae,i as oe,l as se,m as p,o as ce,p as m,s as le,t as ue,v as h}from"./open-script.js";import{i as de}from"./vars.js";import{A as fe,C as pe,D as me,E as he,F as ge,I as _e,M as ve,N as g,O as ye,P as be,R as xe,S as Se,T as Ce,a as we,b as Te,c as Ee,f as De,k as Oe,n as ke,r as Ae,t as je,u as Me,w as Ne,x as Pe,y as _}from"./parameterized-recorded-fill.js";import{n as Fe}from"./catalog.js";import{a as Ie}from"./flag-registry.js";import"./file.js";import{n as Le,r as Re,t as v}from"./session-paths.js";import{a as ze,i as Be,r as Ve}from"./session-artifact-paths.js";import{a as He}from"./daemon-resolution.js";import{r as Ue}from"./success-text.js";import{i as We,r as Ge,t as Ke}from"./session-repair-tombstone.js";import{a as qe,n as Je,t as Ye}from"./session-event-action.js";import{createHash as Xe,randomUUID as Ze}from"node:crypto";import y from"node:fs";import b from"node:path";import{StringDecoder as Qe}from"node:string_decoder";function $e(e,t={}){let n=[e.command];return e.command===`snapshot`?se(n,e):e.command===`open`?ue(n,e):e.command===`runtime`?ce(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?ie(n,e):e.command===`screenshot`?le(n,e):oe(n,e),n.join(` `)}function et(e){return e.targetEvidences?[re(e.targetEvidences)]:e.targetEvidence?[te(e.targetEvidence)]:[]}function x(e){return e?.scriptPublication??_}function tt(e,t,n){let r=x(e),i=typeof t.saveScript==`string`?v(t.saveScript,n):r.kind===`repair`?void 0:t.healedSiblingPath;e.scriptPublication=Pe(r,{requested:{path:i,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function nt(e){e.scriptPublication=pe(x(e))}function rt(e){e.scriptPublication=me(x(e))}function it(e,t){e.scriptPublication=ye(x(e),t)}function at(e){e.scriptPublication=Te(x(e))}function ot(e,t){let n=x(e);return n.kind===`repair`&&n.closeReceipt===t}function S(e){return x(e).kind===`repair`}function C(e){return he(x(e))}function w(e){return Oe(x(e))}function T(e){return fe(x(e))}function st(e,t,n){if(t.flags?.noRecord||be(t.flags)&&t.flags.recordAs===void 0||vt(e,t))return;t.flags&&Me(e,t.flags,n);let r=dt(t),{entry:i,echoedNames:a}=mt(e,ft(t,r)),s=[...new Set([...r?[r.variableName]:[],...a])];r&&pt(e,r);let c=ct(i,s);return e.actions.push(c),o({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),c}function ct(e,t){let n=lt(e);return{ts:Date.now(),command:e.command,positionals:e.positionals,runtime:e.runtime,flags:bt(e.flags),result:e.result,...n?{publicationIntent:n}:{},...e.targetEvidence?{targetEvidence:e.targetEvidence}:{},...e.targetEvidences?{targetEvidences:e.targetEvidences}:{},...t.length>0?{livePlaceholders:t}:{}}}function lt(e){if(D.has(e.command))return e.interactiveObservation===!1?`authored`:e.flags.record===!0?`explicit-record`:void 0}function ut(e,t,n,r,i,a){!t||!e.resolveCurrent(t)||e.recordAction(t,{command:r,positionals:a?.positionals??n.positionals??[],flags:a?.flags??n.flags??{},result:i??{}})}function dt(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return;let t=xe(e.flags.recordAs),n=_e(t);return{literal:g({ts:0,command:e.command,positionals:e.positionals,flags:e.flags}),placeholder:n,variableName:t}}function ft(e,t){if(!t)return e;let{literal:n,placeholder:r}=t;return{...e,positionals:gt(e.positionals,r),result:je(e.result,n,r),targetEvidence:ke(e.targetEvidence,n,r)}}function pt(e,t){t.literal.trim()&&(e.recordedFillLiterals??=new Map,!e.recordedFillLiterals.has(t.literal)&&e.recordedFillLiterals.set(t.literal,t.placeholder))}function mt(e,t){let n=e.recordedFillLiterals;if(!n||n.size===0)return{entry:t,echoedNames:[]};let{payload:r,insertedPlaceholders:i}=Ae(t.result,n),a=(t.targetEvidenceMode??`action`)===`landmark`?ht(t.targetEvidence,n):E(t.targetEvidence,n),o=t.targetEvidences?{source:E(t.targetEvidences.source,n),destination:E(t.targetEvidences.destination,n)}:t.targetEvidences;return{entry:{...t,result:r,targetEvidence:a,targetEvidences:o},echoedNames:[...i].flatMap(e=>ge(e)??[])}}function ht(e,t){return e&&(Ee(e,t)?void 0:e)}function E(e,t){return!e||!Ee(e,t)?e:{...we(e,t),verification:`unverifiable`}}function gt(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const D=new Set([`snapshot`,`get`,`is`,`find`]);function _t(e){return e.internal?.replayPlanStep!==!0&&D.has(e.command)}function vt(e,t){return!t.interactiveObservation||w(e)===void 0?!1:t.flags.record!==!0}const yt=Ie();function bt(e){if(!e)return{};let t={};for(let n of yt){let r=e[n];r!==void 0&&(t[n]=r)}return t}function O(e){return b.join(e,`idle-expiry.json`)}function xt(e){let t;try{t=y.readFileSync(e,`utf8`)}catch{return}let n;try{n=JSON.parse(t)}catch{return}if(!(typeof n?.expiresAt!=`number`||!Number.isFinite(n.expiresAt))&&!(n.expiresAt<=Date.now())&&typeof n.owner==`string`&&!(!k(n.expiredAtMs)||!k(n.idleExpiryMs))&&(n.deviceKey===void 0||typeof n.deviceKey==`string`))return n}function k(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0}function St(t){let n=t.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new e(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(t.some(e=>e.command===`close`))throw new e(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[e,n]of t.entries())ne({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=e);if(!t.slice(r+1).some(Dt))throw new e(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function Ct(t){for(let n of t){if(wt(n)){Tt(n);continue}let t=Ot(n),r=t??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&ne(n)===`mutates-app`)throw new e(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=t;if(!(!i||!l(i)||n.targetEvidence))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function wt(e){return A(e)!==void 0}function Tt(t){let n=A(t);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!l(n))&&!t.targetEvidences)throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function A(e){return e.command===`gesture`?u(e.positionals):void 0}function Et(t,n){if(t instanceof e){if(t.details?.reason===`script_target_exists`)return new e(t.code,`A file already exists at ${String(t.details.path)}.`,{...t.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=t.details?.retriable===!0;return new e(t.code,t.message,{...t.details,retriable:n,hint:t.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Dt(e){if(e.command!==`wait`)return!1;let t=ee(e.positionals);return t?.kind!==`selector`||!l(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function Ot(e){if(e.command===`get`)return e.positionals[1];if(p(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&j(t)&&j(n)?void 0:t}}function j(e){return e.trim().length>0&&Number.isFinite(Number(e))}function kt(e){let t=e.scriptPublication??_;return t.kind===`repair`?t.status===`committed`||!Ce(t):!1}function At(e){return!Ne(e.scriptPublication??_)||kt(e)}var jt=class{sessionsDir;hostCwd;constructor(e,t){this.sessionsDir=e,this.hostCwd=t}write(e,t){let n=S(e),r=t?.publication===`active`,i;try{if(At(e))return{written:!1};let a=Mt(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=b.dirname(i);return y.existsSync(o)||y.mkdirSync(o,{recursive:!0}),It({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=Se(e.scriptPublication??_)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return Nt({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=ve(e.scriptPublication??_);if(t)return v(t,this.hostCwd);let n=Re(e.name),r=new Date(e.createdAt).toISOString().replaceAll(/[:.]/g,`-`);return b.join(this.sessionsDir,`${n}-${r}.ad`)}};function Mt(e,t){let n=Lt(e,{strictPortableRefs:t.activePublication});return t.activePublication&&St(n),{script:qt(e,n,t.appendCompleteSentinel),actionCount:n.length}}function Nt(e){let{session:t,error:n,scriptPath:r,repairArmed:i,activePublication:a}=e;return o({level:`warn`,phase:`session_script_write_failed`,data:{session:t.name,path:r,error:n instanceof Error?n.message:String(n)}}),i?{written:!1,error:Ft(n,r)}:a?{written:!1,error:Et(n,r)}:{written:!1,error:Pt(n,r)}}function Pt(t,n){if(t instanceof e)return t;let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to write the session script${n?` to ${n}`:``}: ${r}`,{reason:`script_write_failed`,...n?{path:n}:{},hint:`Check the target path and its permissions, then re-record with open --save-script.`},t)}function Ft(t,n){if(t instanceof e)return t;let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to write the healed script${n?` to ${n}`:``}: ${r}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function It(t){let{scriptPath:n,script:r,force:a}=t;try{i({destination:n,contents:r,publish:a?`replace`:`link-exclusive`})}catch(t){throw t.code===`EEXIST`?new e(`COMMAND_FAILED`,`A file already exists at ${n}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:n}):t}}function Lt(e,t={}){let n=w(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`&&n.publicationIntent!==`authored`&&!(r&&n.publicationIntent===`explicit-record`))continue;let i=Bt(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&Rt(n);let o=Kt(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&Ct(a),a}function Rt(t){let n=t.command===`gesture`?u(t.positionals??[]):void 0;if(n){zt(n);return}if(!M(t.command))return;let r=t.command===`get`?t.positionals?.[1]:t.positionals?.[0];if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot write recorded step "${t.command} ${r}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function zt(t){let n=[t.source,t.destination].find(e=>e.startsWith(`@`));if(n)throw new e(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function Bt(e){let t=Vt(e);if(!(!t||!M(e.command)))return m(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?Ut(e,t):e.command===`fill`?Ht(e,t):Wt(e,t)}function Vt(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function M(e){return p(e)||e===`fill`||e===`get`}function Ht(e,t){return typeof e.result?.text==`string`||(e.positionals?.length??0)>1?{...e,positionals:[t,g(e)]}:void 0}function Ut(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):Gt(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Wt(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function Gt(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function Kt(e,t){if(!M(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r},...t.livePlaceholders?{livePlaceholders:t.livePlaceholders}:{}}}function qt(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${s(e.device)} device=${ae(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...et(e)),r.push(Jt(de(e,new Set(e.livePlaceholders)))));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
2
- `)}\n`}function Jt(e){return Yt([e.command],e)||$e(e)}function Yt(e,t){if(m(t.command))return Xt(e,t);if(t.command===`fill`)return Zt(e,t);if(t.command===`get`)return Qt(e,t)}function Xt(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(f(h(n))),N(e,t),d(e,t),e.join(` `);if(t.positionals.length===1)return e.push(f(n)),d(e,t),e.join(` `)}}function Zt(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(f(h(n))),N(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(f(r)),d(e,t),e.join(` `)}function Qt(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(f(n)),e.push(f(h(r))),r.startsWith(`@`)&&N(e,t),e.join(` `)}function N(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(f(n))}const P=65536;function F(e){return Xe(`sha256`).update(e,`utf8`).digest(`hex`).slice(0,32)}function I(e,t){let n=en(e);if(n===void 0)return!1;try{let e=R(t),r=Buffer.allocUnsafe(P),i=0;do if(i=y.readSync(n,r,0,r.length,null),!e.push(r.subarray(0,i)))return!0;while(i>0);return e.end(),!0}finally{y.closeSync(n)}}async function $t(e){let t=await tn(e);if(t===void 0)return{lineCount:0,firstLineDigest:void 0};let n={lineCount:0,firstLineDigest:void 0};try{let e=R(e=>{n.lineCount===0&&(n.firstLineDigest=F(e)),n.lineCount+=1}),r=Buffer.allocUnsafe(P);for(;;){let{bytesRead:n}=await t.read(r,0,r.length,null);if(e.push(r.subarray(0,n)),n===0)break}return e.end(),n}finally{await t.close()}}function L(e){let t;return I(e,e=>(t=F(e),!1)),t}function R(e){let t=new Qe(`utf8`),n=``,r=!1;return{push(i){if(r)return!1;let a=`${n}${t.write(i)}`,o=0;for(let t=a.indexOf(`
1
+ import{Nn as e,P as t,Tr as n,w as r,wr as i}from"./sdk-batch.js";import{X as a,_ as o,z as s}from"./sdk-contracts.js";import{y as c}from"./sdk-batch-runner.js";import{St as l,gt as ee,wt as u}from"./sdk-io.js";import"./diagnostics.js";import{R as te,p as d}from"./sdk-device.js";import{r as ne}from"./success-text.js";import{s as f}from"./script.js";import{a as re,c as p,d as m,f as ie,i as ae,l as oe,m as h,o as se,p as g,s as ce,t as le,v as _}from"./open-script.js";import{i as ue}from"./vars.js";import{A as de,D as fe,E as pe,F as me,G as he,I as ge,J as _e,K as ve,M as ye,N as be,O as xe,P as Se,R as Ce,T as v,U as y,W as we,a as Te,c as b,f as Ee,j as De,k as Oe,n as ke,r as Ae,t as je,u as Me,x as Ne}from"./parameterized-recorded-fill.js";import{n as Pe}from"./catalog.js";import{a as Fe}from"./flag-registry.js";import"./file.js";import{a as Ie}from"./daemon-resolution.js";import{n as Le,r as Re,t as ze}from"./session-paths.js";import{a as Be,i as Ve,r as He}from"./session-artifact-paths.js";import{i as Ue,r as We,t as Ge}from"./session-repair-tombstone.js";import{a as Ke,n as qe,t as Je}from"./session-event-action.js";import Ye,{createHash as Xe,randomUUID as Ze}from"node:crypto";import x from"node:fs";import S from"node:path";import{StringDecoder as Qe}from"node:string_decoder";function $e(e,t={}){let n=[e.command];return e.command===`snapshot`?oe(n,e):e.command===`open`?le(n,e):e.command===`runtime`?se(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?re(n,e):e.command===`screenshot`?ce(n,e):ae(n,e),n.join(` `)}function et(e){return e.targetEvidences?[i(e.targetEvidences)]:e.targetEvidence?[n(e.targetEvidence)]:[]}function C(e){return e?.scriptPublication??v}function tt(e,t,n){let r=C(e),i=typeof t.saveScript==`string`?ze(t.saveScript,n):r.kind===`repair`?void 0:t.healedSiblingPath;e.scriptPublication=fe(r,{requested:{path:i,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function nt(e){e.scriptPublication=Oe(C(e))}function rt(e){e.scriptPublication=be(C(e))}function it(e,t){e.scriptPublication=Se(C(e),t)}function at(e){e.scriptPublication=pe(C(e))}function ot(e,t){let n=C(e);return n.kind===`repair`&&n.closeReceipt===t}function w(e){return C(e).kind===`repair`}function T(e){return ye(C(e))}function E(e){return me(C(e))}function D(e){return ge(C(e))}function st(e,t,n){if(t.flags?.noRecord||we(t.flags)&&t.flags.recordAs===void 0||vt(e,t))return;t.flags&&Me(e,t.flags,n);let r=dt(t),{entry:i,echoedNames:a}=mt(e,ft(t,r)),o=[...new Set([...r?[r.variableName]:[],...a])];r&&pt(e,r);let s=ct(i,o);return e.actions.push(s),l({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),s}function ct(e,t){let n=lt(e);return{ts:Date.now(),command:e.command,positionals:e.positionals,runtime:e.runtime,flags:bt(e.flags),result:e.result,...n?{publicationIntent:n}:{},...e.targetEvidence?{targetEvidence:e.targetEvidence}:{},...e.targetEvidences?{targetEvidences:e.targetEvidences}:{},...t.length>0?{livePlaceholders:t}:{}}}function lt(e){if(k.has(e.command))return e.interactiveObservation===!1?`authored`:e.flags.record===!0?`explicit-record`:void 0}function ut(e,t,n,r,i,a){!t||!e.resolveCurrent(t)||e.recordAction(t,{command:r,positionals:a?.positionals??n.positionals??[],flags:a?.flags??n.flags??{},result:i??{}})}function dt(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return;let t=_e(e.flags.recordAs),n=ve(t);return{literal:y({ts:0,command:e.command,positionals:e.positionals,flags:e.flags}),placeholder:n,variableName:t}}function ft(e,t){if(!t)return e;let{literal:n,placeholder:r}=t;return{...e,positionals:gt(e.positionals,r),result:je(e.result,n,r),targetEvidence:ke(e.targetEvidence,n,r)}}function pt(e,t){t.literal.trim()&&(e.recordedFillLiterals??=new Map,!e.recordedFillLiterals.has(t.literal)&&e.recordedFillLiterals.set(t.literal,t.placeholder))}function mt(e,t){let n=e.recordedFillLiterals;if(!n||n.size===0)return{entry:t,echoedNames:[]};let{payload:r,insertedPlaceholders:i}=Ae(t.result,n),a=(t.targetEvidenceMode??`action`)===`landmark`?ht(t.targetEvidence,n):O(t.targetEvidence,n),o=t.targetEvidences?{source:O(t.targetEvidences.source,n),destination:O(t.targetEvidences.destination,n)}:t.targetEvidences;return{entry:{...t,result:r,targetEvidence:a,targetEvidences:o},echoedNames:[...i].flatMap(e=>he(e)??[])}}function ht(e,t){return e&&(b(e,t)?void 0:e)}function O(e,t){return!e||!b(e,t)?e:{...Te(e,t),verification:`unverifiable`}}function gt(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const k=new Set([`snapshot`,`get`,`is`,`find`]);function _t(e){return e.internal?.replayPlanStep!==!0&&k.has(e.command)}function vt(e,t){return!t.interactiveObservation||E(e)===void 0?!1:t.flags.record!==!0}const yt=Fe();function bt(e){if(!e)return{};let t={};for(let n of yt){let r=e[n];r!==void 0&&(t[n]=r)}return t}function A(e){return S.join(e,`idle-expiry.json`)}function xt(e){let t;try{t=x.readFileSync(e,`utf8`)}catch{return}let n;try{n=JSON.parse(t)}catch{return}if(!(typeof n?.expiresAt!=`number`||!Number.isFinite(n.expiresAt))&&!(n.expiresAt<=Date.now())&&typeof n.owner==`string`&&!(!j(n.expiredAtMs)||!j(n.idleExpiryMs))&&(n.deviceKey===void 0||typeof n.deviceKey==`string`))return n}function j(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0}function St(e){let t=e.flatMap((e,t)=>e.command===`open`?[t]:[]);if(t.length!==1||t[0]!==0)throw new o(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(e.some(e=>e.command===`close`))throw new o(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let n=-1;for(let[t,i]of e.entries())r({command:i.command,positionals:i.positionals,flags:i.flags})===`mutates-app`&&(n=t);if(!e.slice(n+1).some(Dt))throw new o(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function Ct(t){for(let n of t){if(wt(n)){Tt(n);continue}let t=Ot(n),i=t??(n.command===`wait`?n.positionals[0]:void 0);if(i?.startsWith(`@`))throw new o(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&r(n)===`mutates-app`)throw new o(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let a=t;if(!(!a||!e(a)||n.targetEvidence))throw new o(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${a}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function wt(e){return M(e)!==void 0}function Tt(t){let n=M(t);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new o(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!e(n))&&!t.targetEvidences)throw new o(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function M(e){return e.command===`gesture`?f(e.positionals):void 0}function Et(e,t){if(e instanceof o){if(e.details?.reason===`script_target_exists`)return new o(e.code,`A file already exists at ${String(e.details.path)}.`,{...e.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let t=e.details?.retriable===!0;return new o(e.code,e.message,{...e.details,retriable:t,hint:e.details?.hint??(t?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let n=e instanceof Error?e.message:String(e);return new o(`COMMAND_FAILED`,`Failed to publish the active session script${t?` to ${t}`:``}: ${n}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Dt(n){if(n.command!==`wait`)return!1;let r=t(n.positionals);return r?.kind!==`selector`||!e(r.selectorExpression)?!1:n.targetEvidence?.verification===`verified`}function Ot(e){if(e.command===`get`)return e.positionals[1];if(h(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&N(t)&&N(n)?void 0:t}}function N(e){return e.trim().length>0&&Number.isFinite(Number(e))}function kt(e){let t=e.scriptPublication??v;return t.kind===`repair`?t.status===`committed`||!De(t):!1}function At(e){return!de(e.scriptPublication??v)||kt(e)}var jt=class{sessionsDir;hostCwd;constructor(e,t){this.sessionsDir=e,this.hostCwd=t}write(e,t){let n=w(e),r=t?.publication===`active`,i;try{if(At(e))return{written:!1};let a=Mt(e,{appendCompleteSentinel:n,activePublication:r}),o=e.scriptPublication?.kind===`authoring`&&e.scriptPublication.remoteDelivery;i=o?this.remoteScriptPath():this.resolveScriptPath(e);let s=S.dirname(i);return x.existsSync(s)||x.mkdirSync(s,{recursive:!0}),It({scriptPath:i,script:a.script,force:t?.force,...o?{mode:384}:{}}),n&&(e.scriptPublication=xe(e.scriptPublication??v)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return Nt({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}remoteScriptPath(){let e=S.join(this.sessionsDir,`remote-scripts`);return x.mkdirSync(e,{recursive:!0,mode:448}),x.chmodSync(e,448),S.join(e,`${Ye.randomUUID()}.ad`)}resolveScriptPath(e){let t=Ce(e.scriptPublication??v);if(t)return ze(t,this.hostCwd);let n=Re(e.name),r=new Date(e.createdAt).toISOString().replaceAll(/[:.]/g,`-`);return S.join(this.sessionsDir,`${n}-${r}.ad`)}};function Mt(e,t){let n=Lt(e,{strictPortableRefs:t.activePublication});return t.activePublication&&St(n),{script:qt(e,n,t.appendCompleteSentinel),actionCount:n.length}}function Nt(e){let{session:t,error:n,scriptPath:r,repairArmed:i,activePublication:a}=e;return l({level:`warn`,phase:`session_script_write_failed`,data:{session:t.name,path:r,error:n instanceof Error?n.message:String(n)}}),i?{written:!1,error:Ft(n,r)}:a?{written:!1,error:Et(n,r)}:{written:!1,error:Pt(n,r)}}function Pt(e,t){if(e instanceof o)return e;let n=e instanceof Error?e.message:String(e);return new o(`COMMAND_FAILED`,`Failed to write the session script${t?` to ${t}`:``}: ${n}`,{reason:`script_write_failed`,...t?{path:t}:{},hint:`Check the target path and its permissions, then re-record with open --save-script.`},e)}function Ft(e,t){if(e instanceof o)return e;let n=e instanceof Error?e.message:String(e);return new o(`COMMAND_FAILED`,`Failed to write the healed script${t?` to ${t}`:``}: ${n}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function It(e){let{scriptPath:t,script:n,force:r,mode:i}=e;try{ee({destination:t,contents:n,publish:r?`replace`:`link-exclusive`,...i===void 0?{}:{mode:i}})}catch(e){throw e.code===`EEXIST`?new o(`COMMAND_FAILED`,`A file already exists at ${t}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:t}):e}}function Lt(e,t={}){let n=E(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`&&n.publicationIntent!==`authored`&&!(r&&n.publicationIntent===`explicit-record`))continue;let i=Bt(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&Rt(n);let o=Kt(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&Ct(a),a}function Rt(e){let t=e.command===`gesture`?f(e.positionals??[]):void 0;if(t){zt(t);return}if(!P(e.command))return;let n=e.command===`get`?e.positionals?.[1]:e.positionals?.[0];if(n?.startsWith(`@`))throw new o(`COMMAND_FAILED`,`Cannot write recorded step "${e.command} ${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function zt(e){let t=[e.source,e.destination].find(e=>e.startsWith(`@`));if(t)throw new o(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${t}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function Bt(e){let t=Vt(e);if(!(!t||!P(e.command)))return g(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?Ut(e,t):e.command===`fill`?Ht(e,t):Wt(e,t)}function Vt(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function P(e){return h(e)||e===`fill`||e===`get`}function Ht(e,t){return typeof e.result?.text==`string`||(e.positionals?.length??0)>1?{...e,positionals:[t,y(e)]}:void 0}function Ut(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):Gt(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Wt(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function Gt(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function Kt(e,t){if(!P(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r},...t.livePlaceholders?{livePlaceholders:t.livePlaceholders}:{}}}function qt(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${te(e.device)} device=${ie(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...et(e)),r.push(Jt(ue(e,new Set(e.livePlaceholders)))));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
2
+ `)}\n`}function Jt(e){return Yt([e.command],e)||$e(e)}function Yt(e,t){if(g(t.command))return Xt(e,t);if(t.command===`fill`)return Zt(e,t);if(t.command===`get`)return Qt(e,t)}function Xt(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(m(_(n))),F(e,t),p(e,t),e.join(` `);if(t.positionals.length===1)return e.push(m(n)),p(e,t),e.join(` `)}}function Zt(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(m(_(n))),F(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(m(r)),p(e,t),e.join(` `)}function Qt(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(m(n)),e.push(m(_(r))),r.startsWith(`@`)&&F(e,t),e.join(` `)}function F(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(m(n))}const I=65536;function L(e){return Xe(`sha256`).update(e,`utf8`).digest(`hex`).slice(0,32)}function R(e,t){let n=en(e);if(n===void 0)return!1;try{let e=B(t),r=Buffer.allocUnsafe(I),i=0;do if(i=x.readSync(n,r,0,r.length,null),!e.push(r.subarray(0,i)))return!0;while(i>0);return e.end(),!0}finally{x.closeSync(n)}}async function $t(e){let t=await tn(e);if(t===void 0)return{lineCount:0,firstLineDigest:void 0};let n={lineCount:0,firstLineDigest:void 0};try{let e=B(e=>{n.lineCount===0&&(n.firstLineDigest=L(e)),n.lineCount+=1}),r=Buffer.allocUnsafe(I);for(;;){let{bytesRead:n}=await t.read(r,0,r.length,null);if(e.push(r.subarray(0,n)),n===0)break}return e.end(),n}finally{await t.close()}}function z(e){let t;return R(e,e=>(t=L(e),!1)),t}function B(e){let t=new Qe(`utf8`),n=``,r=!1;return{push(i){if(r)return!1;let a=`${n}${t.write(i)}`,o=0;for(let t=a.indexOf(`
3
3
  `);t!==-1;t=a.indexOf(`
4
- `,o)){if(z(a.slice(o,t),e)===!1)return r=!0,!1;o=t+1}return n=a.slice(o),!0},end(){r||z(`${n}${t.end()}`,e)}}}function z(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0)return t(n)}function en(e){try{return y.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function tn(e){try{return await y.promises.open(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}const B=5242880,nn=Ze();function rn(e){let t=e.AGENT_DEVICE_EVENT_LOG_MAX_BYTES?.trim();if(t===void 0||!/^\d+$/.test(t))return B;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:B}function V(e){return`${e}.1`}function H(e){return`${e}.window.json`}function U(e){let t;for(let n=0;n<3;n+=1){let n=K(e);try{let t=an(e);for(let n of t.files)Y(e,n.path);if(K(e)===n)return t}catch(r){if(t=r,K(e)===n)throw r}}throw t??G(e,`the window did not settle while reading`)}function an(e){let t=V(e),n=J(e);if(n===`unverifiable`)throw G(e,`window file is invalid`);if(n===void 0)return on(e,t);let r=n.at(-1);if(!r)throw G(e,`window file records no generation`);let i=X(e),a=W(L(e),r),o=[],s=sn({eventLogPath:e,rotatedPath:t,sidecar:n,activeStart:a,activeExists:i});return s!==void 0&&o.push({path:t,firstLineIndex:s}),i&&o.push({path:e,firstLineIndex:a}),{files:o,earliestCursor:o[0]?.firstLineIndex??a}}function on(e,t){if(L(t)!==void 0)throw G(e,`a rotated event log exists with no window record`);return{files:X(e)?[{path:e,firstLineIndex:0}]:[],earliestCursor:0}}function W(e,t){return e!==void 0&&e===t.firstLineDigest?t.firstLineIndex:t.firstLineIndex+t.lineCount}function sn(e){let{eventLogPath:t,rotatedPath:n,sidecar:r,activeStart:i,activeExists:a}=e,o=L(n);if(o===void 0)return;let s=r.find(e=>e.firstLineDigest===o);if(!s)throw G(t,`the rotated event log matches no window record`);let c=un(n);if(c!==s.lineCount)throw G(t,`the rotated event log holds ${c} lines, the window recorded ${s.lineCount}`);if(a&&s.firstLineIndex+s.lineCount!==i)throw G(t,`retained event log generations are not contiguous`);return s.firstLineIndex}async function cn(e,t,n){let r=pn(e);if(r&&Y(e,e),!r||r.size+n<=t)return!1;U(e);let i=J(e);if(i===`unverifiable`)throw G(e,`window file is invalid`);let a=await $t(e);if(a.firstLineDigest!==void 0){let t=i??[],n=t.at(-1),r=n?.firstLineDigest===a.firstLineDigest;if(r&&n.lineCount>a.lineCount)throw G(e,`active generation differs from its window record`);let o={firstLineIndex:n?W(a.firstLineDigest,n):0,lineCount:a.lineCount,firstLineDigest:a.firstLineDigest};await fn(e,[...r?t.slice(0,-1):t,o].slice(-2))}return await y.promises.rename(e,V(e)),!0}function ln(t,n){if(!(t>=n))throw new e(`COMMAND_FAILED`,`events cursor ${t} precedes the retained event log window; events before cursor ${n} were rotated out.`,{reason:`EVENT_LOG_CURSOR_EXPIRED`,cursor:t,earliestCursor:n,hint:`Resume with cursor ${n}, the oldest retained event; earlier events are no longer available.`})}function G(t,n){return new e(`COMMAND_FAILED`,`Session event log window cannot be verified: ${n}.`,{reason:`EVENT_LOG_WINDOW_UNVERIFIED`,path:t,hint:`Cursor positions for this session cannot be resolved. Delete ${t}, ${V(t)}, and ${H(t)} to restart the timeline, or read the files directly.`})}function un(e){let t=0;return I(e,()=>{t+=1}),t}function K(e){return[q(H(e)),q(e),q(V(e))].join(`|`)}function q(e){try{let t=y.lstatSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return`absent`}}function J(e){let t;try{t=y.readFileSync(H(e),`utf8`)}catch(e){return e.code===`ENOENT`?void 0:`unverifiable`}try{let e=JSON.parse(t);if(!r(e)||e.version!==2)return`unverifiable`;let{generations:n}=e;if(!Array.isArray(n)||n.length===0)return`unverifiable`;let i=n.map(dn);return i.every(e=>e!==void 0)?i:`unverifiable`}catch{return`unverifiable`}}function dn(e){if(!r(e))return;let{firstLineIndex:t,lineCount:n,firstLineDigest:i}=e;if(!(!Number.isSafeInteger(t)||t<0)&&!(!Number.isSafeInteger(n)||n<0)&&typeof i==`string`&&i.length!==0)return{firstLineIndex:t,lineCount:n,firstLineDigest:i}}async function fn(e,t){let n=H(e),r=`${n}.${process.pid}.${nn}.tmp`,i=await y.promises.open(r,`wx`);try{try{await i.writeFile(JSON.stringify({version:2,generations:t}),`utf8`)}finally{await i.close()}await y.promises.rename(r,n)}catch(e){throw await y.promises.unlink(r).catch(()=>void 0),e}}function Y(t,n){try{let e=y.openSync(n,`r`);try{let{size:n}=y.fstatSync(e);if(n===0)return;let r=Buffer.alloc(1);if(y.readSync(e,r,0,1,n-1)!==1||r[0]!==10)throw G(t,`retained event log has an incomplete line`)}finally{y.closeSync(e)}}catch(n){throw n instanceof e?n:G(t,`retained event log completeness cannot be verified`)}}function X(e){return pn(e)!==void 0}function pn(t){try{let n=y.lstatSync(t);if(n.isSymbolicLink())throw new e(`COMMAND_FAILED`,`Session event log must not be a symbolic link: ${t}`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}const Z=16777216,Q=new Map,mn=new Set;function hn(e){return b.join(e,`events.ndjson`)}function gn(e){return e.command!==Fe.events}function _n(e,t,r,i){let a=n({version:1,ts:r.ts??new Date().toISOString(),session:t,...r});yn(e,`${JSON.stringify(a)}\n`,i)}async function vn(e){await(e?Q.get(e)?.pending:Promise.all([...Q.values()].map(e=>e.pending)))}function $(n,r,i,a){o({level:`warn`,phase:`session_event_log_write_failed`,data:{path:n,reason:r,operation:i,errno:a instanceof e?void 0:a?.code,error:a===void 0?void 0:t(a)}})}function yn(e,t,n){let r=rn(n),i=Buffer.byteLength(t,`utf8`);if(i>Math.min(r,Z)){$(e,`entry-too-large`,`admission`);return}let a=Q.get(e);if(a&&(a.entries>=128||a.bytes+i>Z)){$(e,`queue-full`,`admission`);return}a||(a={pending:Promise.resolve(),entries:0,bytes:0},Q.set(e,a));let o=a;o.entries+=1,o.bytes+=i,o.pending=o.pending.then(async()=>{try{await bn(e)}catch(t){$(e,`maintenance-failed`,`mkdir`,t);return}try{await cn(e,r,i)}catch(t){$(e,`maintenance-failed`,`rotation`,t);return}try{await y.promises.appendFile(e,t,`utf8`)}catch(t){$(e,`append-failed`,`append`,t)}}).finally(()=>{--o.entries,o.bytes-=i,o.entries===0&&Q.delete(e)})}async function bn(e){let t=b.dirname(e);mn.has(t)||(await y.promises.mkdir(t,{recursive:!0}),mn.add(t))}function xn(e,t,n,r){_n(e,t,{kind:`action.recorded`,requestId:a().requestId,command:n.command,summary:Je(n),details:Ye(n)},r)}function Sn(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??a().requestId,command:t.command,summary:`Started ${t.command}`}}function Cn(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=qe(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??a().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??a().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function wn(e,t={}){let n=En(t.cursor),r=Dn(t.limit),i=U(e);ln(n,i.earliestCursor);let a=Tn(i.files,n,r),o=a.lines.flatMap(e=>{let t=On(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:o,...a.nextCursor===void 0?{}:{nextCursor:String(a.nextCursor)},endCursor:String(a.endCursor)}}function Tn(e,t,n){let r=[],i,a=0;for(let o of e){let e=o.firstLineIndex;if(I(o.path,a=>{if(e>=t+n)return i=t+n,!1;e>=t&&r.push(a),e+=1}),a=e,i!==void 0)break}let o=Math.max(t,Math.min(t+n,a));return{lines:r,...i===void 0?{}:{nextCursor:i},endCursor:o}}function En(t){if(t===void 0||t.trim()===``)return 0;let n=Number(t);if(Number.isInteger(n)&&n>=0)return n;throw new e(`INVALID_ARGS`,`events cursor must be a non-negative integer string.`)}function Dn(t){if(t===void 0||typeof t==`string`&&t.trim()===``)return 100;let n=typeof t==`string`?Number(t):t;if(Number.isInteger(n)&&n>=1&&n<=500)return n;throw new e(`INVALID_ARGS`,`events limit must be between 1 and 500.`)}function On(e){try{let t=kn(JSON.parse(e));return t?An(t):void 0}catch{return}}function kn(e){if(r(e)&&e.version===1&&typeof e.ts==`string`&&typeof e.session==`string`&&jn(e.kind))return e}function An(e){let t=r(e.details)?e.details:void 0;return{version:1,ts:e.ts,session:e.session,kind:e.kind,...typeof e.requestId==`string`?{requestId:e.requestId}:{},...typeof e.command==`string`?{command:e.command}:{},...Mn(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function jn(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function Mn(e){return e===`ok`||e===`error`}const Nn=36e5;var Pn=class{sessions=new Map;retainedExecutionHosts=new Map;acceptingSessions=!0;runtimeHints=new Map;sessionsDir;scriptWriter;host;constructor(e,t){this.sessionsDir=e,this.host=t,this.scriptWriter=new jt(e,t.cwd)}get(e){return this.sessions.get(e)?.current}closeAdmission(){this.acceptingSessions=!1}assertAdmissionOpen(t){if(!this.acceptingSessions)throw new e(`COMMAND_FAILED`,`Daemon is shutting down`,{reason:He,session:t})}assertPublishable(t){if(this.assertAdmissionOpen(t),this.sessions.has(t))throw new e(`COMMAND_FAILED`,`Session address is already occupied`,{reason:`session_address_occupied`,session:t})}publish(e,t){this.assertPublishable(e);let n={current:t};this.sessions.set(e,n);for(let e of this.retainedExecutionHosts.values())c(e.device.id,t.device.id)&&this.releaseRetainedExecutionHost(e);return this.clearIdleExpiryTombstone(e),this.captureRef(e,n)}resolveCurrent(e){let t=this.sessions.get(e.address);return t===e.lifetime?t.current:void 0}refresh(e){let t=this.sessions.get(e.address);return t===e.lifetime?this.captureRef(e.address,t):e}requireCurrent(t){let n=this.resolveCurrent(t);if(!n)throw new e(`COMMAND_FAILED`,`Session lifetime has ended`,{reason:`session_lifetime_ended`,session:t.address,hint:`Open a new session before retrying the command.`});return n}update(e,t){let n=this.requireCurrent(e),r=this.sessions.get(e.address),i=typeof t==`function`?t(n):t,a={...n,...i};return r.current=a,a}retire(e,t={}){let n=this.resolveCurrent(e);return n?(t.retainExecutionHost&&n.lease&&this.retainedExecutionHosts.set(n.device.id,{address:e.address,device:n.device,lease:{...n.lease}}),this.runtimeHints.delete(e.address),this.sessions.delete(e.address)):!1}listRetainedExecutionHosts(e){return Array.from(this.retainedExecutionHosts.values()).filter(t=>t.lease.leaseId===e)}ownsRetainedExecutionHost(e){return this.retainedExecutionHosts.get(e.device.id)===e}releaseRetainedExecutionHost(e){return this.ownsRetainedExecutionHost(e)?this.retainedExecutionHosts.delete(e.device.id):!1}captureRef(e,t){return Object.freeze({address:e,session:t.current,lifetime:t})}*values(){for(let e of this.sessions.values())yield e.current}toArray(){return Array.from(this.values())}lookup(e){let t=this.sessions.get(e);return t?this.captureRef(e,t):void 0}findByDevice(e){for(let[t,n]of this.sessions)if(c(n.current.device.id,e))return this.captureRef(t,n)}listRefs(){return Array.from(this.sessions,([e,t])=>this.captureRef(e,t))}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){t?this.runtimeHints.set(e,t):this.runtimeHints.delete(e)}clearRuntimeHints(e){return this.requireCurrent(e),this.runtimeHints.delete(e.address)}recordAction(e,t){let n=st(this.requireCurrent(e),t,this.host.cwd);n&&xn(this.resolveEventLogPath(e.address),e.address,n,this.host.env)}recordEvent(e,t){_n(this.resolveEventLogPath(e),e,t,this.host.env)}readEvents(e,t={}){return wn(this.resolveEventLogPath(e),t)}async flushEvents(e){await vn(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.requireCurrent(e),r=this.scriptWriter.write(n,t);return r.written&&o({level:`info`,phase:`session_script_written`,data:{session:n.name,path:r.path}}),r}finalizeRepairTeardown(e){let t=this.resolveCurrent(e);if(!t)return;this.recordRepairFinalizeCloseIfCommitting(e);let n=this.writeSessionLog(e,{force:De(t,void 0)});C(t)&&(!n.written&&n.error?this.writeRepairTombstone(e,Nn,{code:String(n.error.code),message:n.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){let t=this.requireCurrent(e),n=t.scriptPublication??_;Ce(n)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:t.name,...Ue(`Closed: ${t.name}`)}})}writeRepairTombstone(e,t=Nn,n){let r=this.resolveCurrent(e);if(r)try{let i=this.resolveSessionDir(e.address);y.mkdirSync(i,{recursive:!0});let a={owner:e.address,reapedAt:Date.now(),expiresAt:Date.now()+t,...T(r)?{sourcePath:T(r)}:{},...n?{commitFailure:n}:{}};y.writeFileSync(this.repairTombstonePath(e.address),`${JSON.stringify(a)}\n`)}catch(t){o({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.address,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return Ge(this.repairTombstonePath(e),e)}clearRepairTombstone(e){Ke(this.repairTombstonePath(e),e)}noteSessionActivity(e,t=Date.now()){let n=this.get(e);n&&(n.lastActivityAtMs=t)}markCloseEffectsUnconfirmed(e){this.update(e,{closeEffectsUnconfirmed:!0})}clearCloseEffectsUnconfirmed(e){delete this.requireCurrent(e).closeEffectsUnconfirmed}writeIdleExpiryTombstone(e,t){try{y.mkdirSync(this.resolveSessionDir(e),{recursive:!0}),y.writeFileSync(O(this.resolveSessionDir(e)),`${JSON.stringify(t)}\n`)}catch(t){o({level:`warn`,phase:`idle_expiry_tombstone_write_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}readIdleExpiryTombstone(e){if(!Le(e))return;let t=xt(O(this.resolveSessionDir(e)));return t?.owner===e?t:void 0}clearIdleExpiryTombstone(e){try{y.rmSync(O(this.resolveSessionDir(e)),{force:!0})}catch(t){o({level:`warn`,phase:`idle_expiry_tombstone_clear_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}repairTombstonePath(e){return We(this.resolveSessionDir(e))}defaultTracePath(e){let t=Re(e.name),n=new Date().toISOString().replaceAll(/[:.]/g,`-`);return b.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(e){return ze(this.sessionsDir,e)}resolveDaemonStateDir(){return b.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return y.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return Ve(this.sessionsDir,e)}resolveAppLogPidPath(e){return Be(this.sessionsDir,e)}resolveEventLogPath(e){return hn(this.resolveSessionDir(e))}};export{_t as a,tt as c,C as d,rt as f,nt as h,gn as i,ot as l,w as m,Cn as n,ut as o,it as p,Sn as r,at as s,Pn as t,S as u};
4
+ `,o)){if(V(a.slice(o,t),e)===!1)return r=!0,!1;o=t+1}return n=a.slice(o),!0},end(){r||V(`${n}${t.end()}`,e)}}}function V(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0)return t(n)}function en(e){try{return x.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function tn(e){try{return await x.promises.open(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}const H=5242880,nn=Ze();function rn(e){let t=e.AGENT_DEVICE_EVENT_LOG_MAX_BYTES?.trim();if(t===void 0||!/^\d+$/.test(t))return H;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:H}function U(e){return`${e}.1`}function W(e){return`${e}.window.json`}function G(e){let t;for(let n=0;n<3;n+=1){let n=J(e);try{let t=an(e);for(let n of t.files)pn(e,n.path);if(J(e)===n)return t}catch(r){if(t=r,J(e)===n)throw r}}throw t??q(e,`the window did not settle while reading`)}function an(e){let t=U(e),n=X(e);if(n===`unverifiable`)throw q(e,`window file is invalid`);if(n===void 0)return on(e,t);let r=n.at(-1);if(!r)throw q(e,`window file records no generation`);let i=mn(e),a=K(z(e),r),o=[],s=sn({eventLogPath:e,rotatedPath:t,sidecar:n,activeStart:a,activeExists:i});return s!==void 0&&o.push({path:t,firstLineIndex:s}),i&&o.push({path:e,firstLineIndex:a}),{files:o,earliestCursor:o[0]?.firstLineIndex??a}}function on(e,t){if(z(t)!==void 0)throw q(e,`a rotated event log exists with no window record`);return{files:mn(e)?[{path:e,firstLineIndex:0}]:[],earliestCursor:0}}function K(e,t){return e!==void 0&&e===t.firstLineDigest?t.firstLineIndex:t.firstLineIndex+t.lineCount}function sn(e){let{eventLogPath:t,rotatedPath:n,sidecar:r,activeStart:i,activeExists:a}=e,o=z(n);if(o===void 0)return;let s=r.find(e=>e.firstLineDigest===o);if(!s)throw q(t,`the rotated event log matches no window record`);let c=un(n);if(c!==s.lineCount)throw q(t,`the rotated event log holds ${c} lines, the window recorded ${s.lineCount}`);if(a&&s.firstLineIndex+s.lineCount!==i)throw q(t,`retained event log generations are not contiguous`);return s.firstLineIndex}async function cn(e,t,n){let r=hn(e);if(r&&pn(e,e),!r||r.size+n<=t)return!1;G(e);let i=X(e);if(i===`unverifiable`)throw q(e,`window file is invalid`);let a=await $t(e);if(a.firstLineDigest!==void 0){let t=i??[],n=t.at(-1),r=n?.firstLineDigest===a.firstLineDigest;if(r&&n.lineCount>a.lineCount)throw q(e,`active generation differs from its window record`);let o={firstLineIndex:n?K(a.firstLineDigest,n):0,lineCount:a.lineCount,firstLineDigest:a.firstLineDigest};await fn(e,[...r?t.slice(0,-1):t,o].slice(-2))}return await x.promises.rename(e,U(e)),!0}function ln(e,t){if(!(e>=t))throw new o(`COMMAND_FAILED`,`events cursor ${e} precedes the retained event log window; events before cursor ${t} were rotated out.`,{reason:`EVENT_LOG_CURSOR_EXPIRED`,cursor:e,earliestCursor:t,hint:`Resume with cursor ${t}, the oldest retained event; earlier events are no longer available.`})}function q(e,t){return new o(`COMMAND_FAILED`,`Session event log window cannot be verified: ${t}.`,{reason:`EVENT_LOG_WINDOW_UNVERIFIED`,path:e,hint:`Cursor positions for this session cannot be resolved. Delete ${e}, ${U(e)}, and ${W(e)} to restart the timeline, or read the files directly.`})}function un(e){let t=0;return R(e,()=>{t+=1}),t}function J(e){return[Y(W(e)),Y(e),Y(U(e))].join(`|`)}function Y(e){try{let t=x.lstatSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return`absent`}}function X(e){let t;try{t=x.readFileSync(W(e),`utf8`)}catch(e){return e.code===`ENOENT`?void 0:`unverifiable`}try{let e=JSON.parse(t);if(!c(e)||e.version!==2)return`unverifiable`;let{generations:n}=e;if(!Array.isArray(n)||n.length===0)return`unverifiable`;let r=n.map(dn);return r.every(e=>e!==void 0)?r:`unverifiable`}catch{return`unverifiable`}}function dn(e){if(!c(e))return;let{firstLineIndex:t,lineCount:n,firstLineDigest:r}=e;if(!(!Number.isSafeInteger(t)||t<0)&&!(!Number.isSafeInteger(n)||n<0)&&typeof r==`string`&&r.length!==0)return{firstLineIndex:t,lineCount:n,firstLineDigest:r}}async function fn(e,t){let n=W(e),r=`${n}.${process.pid}.${nn}.tmp`,i=await x.promises.open(r,`wx`);try{try{await i.writeFile(JSON.stringify({version:2,generations:t}),`utf8`)}finally{await i.close()}await x.promises.rename(r,n)}catch(e){throw await x.promises.unlink(r).catch(()=>void 0),e}}function pn(e,t){try{let n=x.openSync(t,`r`);try{let{size:t}=x.fstatSync(n);if(t===0)return;let r=Buffer.alloc(1);if(x.readSync(n,r,0,1,t-1)!==1||r[0]!==10)throw q(e,`retained event log has an incomplete line`)}finally{x.closeSync(n)}}catch(t){throw t instanceof o?t:q(e,`retained event log completeness cannot be verified`)}}function mn(e){return hn(e)!==void 0}function hn(e){try{let t=x.lstatSync(e);if(t.isSymbolicLink())throw new o(`COMMAND_FAILED`,`Session event log must not be a symbolic link: ${e}`);return t}catch(e){if(e.code===`ENOENT`)return;throw e}}const Z=16777216,Q=new Map,gn=new Set;function _n(e){return S.join(e,`events.ndjson`)}function vn(e){return e.command!==Pe.events}function yn(e,t,n,r){let i=a({version:1,ts:n.ts??new Date().toISOString(),session:t,...n});xn(e,`${JSON.stringify(i)}\n`,r)}async function bn(e){await(e?Q.get(e)?.pending:Promise.all([...Q.values()].map(e=>e.pending)))}function $(e,t,n,r){l({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,reason:t,operation:n,errno:r instanceof o?void 0:r?.code,error:r===void 0?void 0:s(r)}})}function xn(e,t,n){let r=rn(n),i=Buffer.byteLength(t,`utf8`);if(i>Math.min(r,Z)){$(e,`entry-too-large`,`admission`);return}let a=Q.get(e);if(a&&(a.entries>=128||a.bytes+i>Z)){$(e,`queue-full`,`admission`);return}a||(a={pending:Promise.resolve(),entries:0,bytes:0},Q.set(e,a));let o=a;o.entries+=1,o.bytes+=i,o.pending=o.pending.then(async()=>{try{await Sn(e)}catch(t){$(e,`maintenance-failed`,`mkdir`,t);return}try{await cn(e,r,i)}catch(t){$(e,`maintenance-failed`,`rotation`,t);return}try{await x.promises.appendFile(e,t,`utf8`)}catch(t){$(e,`append-failed`,`append`,t)}}).finally(()=>{--o.entries,o.bytes-=i,o.entries===0&&Q.delete(e)})}async function Sn(e){let t=S.dirname(e);gn.has(t)||(await x.promises.mkdir(t,{recursive:!0}),gn.add(t))}function Cn(e,t,n,r){yn(e,t,{kind:`action.recorded`,requestId:u().requestId,command:n.command,summary:qe(n),details:Je(n)},r)}function wn(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??u().requestId,command:t.command,summary:`Started ${t.command}`}}function Tn(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=Ke(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??u().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??u().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function En(e,t={}){let n=On(t.cursor),r=kn(t.limit),i=G(e);ln(n,i.earliestCursor);let a=Dn(i.files,n,r),o=a.lines.flatMap(e=>{let t=An(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:o,...a.nextCursor===void 0?{}:{nextCursor:String(a.nextCursor)},endCursor:String(a.endCursor)}}function Dn(e,t,n){let r=[],i,a=0;for(let o of e){let e=o.firstLineIndex;if(R(o.path,a=>{if(e>=t+n)return i=t+n,!1;e>=t&&r.push(a),e+=1}),a=e,i!==void 0)break}let o=Math.max(t,Math.min(t+n,a));return{lines:r,...i===void 0?{}:{nextCursor:i},endCursor:o}}function On(e){if(e===void 0||e.trim()===``)return 0;let t=Number(e);if(Number.isInteger(t)&&t>=0)return t;throw new o(`INVALID_ARGS`,`events cursor must be a non-negative integer string.`)}function kn(e){if(e===void 0||typeof e==`string`&&e.trim()===``)return 100;let t=typeof e==`string`?Number(e):e;if(Number.isInteger(t)&&t>=1&&t<=500)return t;throw new o(`INVALID_ARGS`,`events limit must be between 1 and 500.`)}function An(e){try{let t=jn(JSON.parse(e));return t?Mn(t):void 0}catch{return}}function jn(e){if(c(e)&&e.version===1&&typeof e.ts==`string`&&typeof e.session==`string`&&Nn(e.kind))return e}function Mn(e){let t=c(e.details)?e.details:void 0;return{version:1,ts:e.ts,session:e.session,kind:e.kind,...typeof e.requestId==`string`?{requestId:e.requestId}:{},...typeof e.command==`string`?{command:e.command}:{},...Pn(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function Nn(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function Pn(e){return e===`ok`||e===`error`}const Fn=36e5;var In=class{sessions=new Map;retainedExecutionHosts=new Map;acceptingSessions=!0;runtimeHints=new Map;sessionsDir;scriptWriter;host;constructor(e,t){this.sessionsDir=e,this.host=t,this.scriptWriter=new jt(e,t.cwd)}get(e){return this.sessions.get(e)?.current}closeAdmission(){this.acceptingSessions=!1}assertAdmissionOpen(e){if(!this.acceptingSessions)throw new o(`COMMAND_FAILED`,`Daemon is shutting down`,{reason:Ie,session:e})}assertPublishable(e){if(this.assertAdmissionOpen(e),this.sessions.has(e))throw new o(`COMMAND_FAILED`,`Session address is already occupied`,{reason:`session_address_occupied`,session:e})}publish(e,t){this.assertPublishable(e);let n={current:t};this.sessions.set(e,n);for(let e of this.retainedExecutionHosts.values())d(e.device.id,t.device.id)&&this.releaseRetainedExecutionHost(e);return this.clearIdleExpiryTombstone(e),this.captureRef(e,n)}resolveCurrent(e){let t=this.sessions.get(e.address);return t===e.lifetime?t.current:void 0}refresh(e){let t=this.sessions.get(e.address);return t===e.lifetime?this.captureRef(e.address,t):e}requireCurrent(e){let t=this.resolveCurrent(e);if(!t)throw new o(`COMMAND_FAILED`,`Session lifetime has ended`,{reason:`session_lifetime_ended`,session:e.address,hint:`Open a new session before retrying the command.`});return t}update(e,t){let n=this.requireCurrent(e),r=this.sessions.get(e.address),i=typeof t==`function`?t(n):t,a={...n,...i};return r.current=a,a}retire(e,t={}){let n=this.resolveCurrent(e);return n?(t.retainExecutionHost&&n.lease&&this.retainedExecutionHosts.set(n.device.id,{address:e.address,device:n.device,lease:{...n.lease}}),this.runtimeHints.delete(e.address),this.sessions.delete(e.address)):!1}listRetainedExecutionHosts(e){return Array.from(this.retainedExecutionHosts.values()).filter(t=>t.lease.leaseId===e)}ownsRetainedExecutionHost(e){return this.retainedExecutionHosts.get(e.device.id)===e}releaseRetainedExecutionHost(e){return this.ownsRetainedExecutionHost(e)?this.retainedExecutionHosts.delete(e.device.id):!1}captureRef(e,t){return Object.freeze({address:e,session:t.current,lifetime:t})}*values(){for(let e of this.sessions.values())yield e.current}toArray(){return Array.from(this.values())}lookup(e){let t=this.sessions.get(e);return t?this.captureRef(e,t):void 0}findByDevice(e){for(let[t,n]of this.sessions)if(d(n.current.device.id,e))return this.captureRef(t,n)}listRefs(){return Array.from(this.sessions,([e,t])=>this.captureRef(e,t))}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){t?this.runtimeHints.set(e,t):this.runtimeHints.delete(e)}clearRuntimeHints(e){return this.requireCurrent(e),this.runtimeHints.delete(e.address)}recordAction(e,t){let n=st(this.requireCurrent(e),t,this.host.cwd);n&&Cn(this.resolveEventLogPath(e.address),e.address,n,this.host.env)}recordEvent(e,t){yn(this.resolveEventLogPath(e),e,t,this.host.env)}readEvents(e,t={}){return En(this.resolveEventLogPath(e),t)}async flushEvents(e){await bn(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.requireCurrent(e),r=this.scriptWriter.write(n,t);return r.written&&l({level:`info`,phase:`session_script_written`,data:{session:n.name,path:r.path}}),r}writeRemoteScriptVersion(e){return this.scriptWriter.write(this.requireCurrent(e))}finalizeRepairTeardown(e){let t=this.resolveCurrent(e);if(!t||Ne(t))return;this.recordRepairFinalizeCloseIfCommitting(e);let n=this.writeSessionLog(e,{force:Ee(t,void 0)});T(t)&&(!n.written&&n.error?this.writeRepairTombstone(e,Fn,{code:String(n.error.code),message:n.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){let t=this.requireCurrent(e),n=t.scriptPublication??v;De(n)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:t.name,...ne(`Closed: ${t.name}`)}})}writeRepairTombstone(e,t=Fn,n){let r=this.resolveCurrent(e);if(r)try{let i=this.resolveSessionDir(e.address);x.mkdirSync(i,{recursive:!0});let a={owner:e.address,reapedAt:Date.now(),expiresAt:Date.now()+t,...D(r)?{sourcePath:D(r)}:{},...n?{commitFailure:n}:{}};x.writeFileSync(this.repairTombstonePath(e.address),`${JSON.stringify(a)}\n`)}catch(t){l({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.address,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return We(this.repairTombstonePath(e),e)}clearRepairTombstone(e){Ge(this.repairTombstonePath(e),e)}noteSessionActivity(e,t=Date.now()){let n=this.get(e);n&&(n.lastActivityAtMs=t)}markCloseEffectsUnconfirmed(e){this.update(e,{closeEffectsUnconfirmed:!0})}clearCloseEffectsUnconfirmed(e){delete this.requireCurrent(e).closeEffectsUnconfirmed}writeIdleExpiryTombstone(e,t){try{x.mkdirSync(this.resolveSessionDir(e),{recursive:!0}),x.writeFileSync(A(this.resolveSessionDir(e)),`${JSON.stringify(t)}\n`)}catch(t){l({level:`warn`,phase:`idle_expiry_tombstone_write_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}readIdleExpiryTombstone(e){if(!Le(e))return;let t=xt(A(this.resolveSessionDir(e)));return t?.owner===e?t:void 0}clearIdleExpiryTombstone(e){try{x.rmSync(A(this.resolveSessionDir(e)),{force:!0})}catch(t){l({level:`warn`,phase:`idle_expiry_tombstone_clear_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}repairTombstonePath(e){return Ue(this.resolveSessionDir(e))}defaultTracePath(e){let t=Re(e.name),n=new Date().toISOString().replaceAll(/[:.]/g,`-`);return S.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(e){return Be(this.sessionsDir,e)}resolveDaemonStateDir(){return S.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return x.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return He(this.sessionsDir,e)}resolveAppLogPidPath(e){return Ve(this.sessionsDir,e)}resolveEventLogPath(e){return _n(this.resolveSessionDir(e))}};export{_t as a,tt as c,T as d,rt as f,nt as h,vn as i,ot as l,E as m,Tn as n,ut as o,it as p,wn as r,at as s,In as t,w as u};
@@ -1 +1 @@
1
- import{P as e}from"./sdk-contracts.js";import{yt as t}from"./sdk-io.js";import"./diagnostics.js";import{n}from"./runtime-slots.js";import{s as r}from"./durable-capture.js";import{n as i,o as a}from"./perf-capture-session-resource.js";import{n as o}from"./screen-recording-session-resource.js";import{c as s}from"./artifact-tracking.js";import{p as c}from"./session-runtime.js";import{a as l,i as u,n as d}from"./session-capture-binding.js";import f from"node:crypto";import{rmSync as p}from"node:fs";import m from"node:os";import h from"node:path";import g from"node:fs/promises";const _=2147483647,v={label:`Materialized paths`,plural:!0,expiredHint:`Materialized paths are released automatically when their TTL expires; re-run the command that materialized them if the paths are still needed.`},y=Symbol(`materializedPaths`),b=()=>n(y,()=>new Map,e=>{for(let t of e.values()){clearTimeout(t.timer);try{p(t.rootPath,{recursive:!0,force:!0})}catch{}}});async function x(e){let t=S(e.ttlMs),n=await g.mkdtemp(h.join(m.tmpdir(),`agent-device-materialized-`));try{let r=await D(e.installablePath,h.join(n,`installable`)),i=e.archivePath?await D(e.archivePath,h.join(n,`archive`)):void 0,a=f.randomUUID(),o=Date.now()+t,s=setTimeout(()=>{T(a)},t);return b().set(a,{rootPath:n,installablePath:r,archivePath:i,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:o,timer:s}),{materializationId:a,installablePath:r,...i?{archivePath:i}:{},expiresAt:new Date(o).toISOString()}}catch(e){throw await g.rm(n,{recursive:!0,force:!0}),e}}function S(t=9e5){if(typeof t!=`number`||!Number.isInteger(t)||t<=0||t>_)throw new e(`INVALID_ARGS`,`retentionMs must be an integer from 1 to ${_}`);return t}async function C(e,t){await E(e,s(b(),e,t,v))}async function w(e){let t=Array.from(b().entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await E(e,t)}))}async function T(e){let t=b().get(e);if(t)try{await E(e,t)}catch{}}async function E(e,t){clearTimeout(t.timer),b().delete(e),await g.rm(t.rootPath,{recursive:!0,force:!0})}async function D(e,t){let n=await g.stat(e);await g.mkdir(t,{recursive:!0});let r=h.join(t,h.basename(e));return n.isDirectory()?(await g.cp(e,r,{recursive:!0}),r):(await g.copyFile(e,r),r)}async function O(e){let t=e.sessionStore.refresh(e.ref);if(!t.session.appLog)return;let{forceCleanupSessionAppLog:n}=await import(`./app-log-session-resource.js`).then(e=>e.n);await n({...e,ref:t})}async function k(e){let t=u(e.sessionStore,e.ref);t.read()&&await i({binding:t,intent:`disposal`})}async function A(e,t){await t.stopSnapshotHelper(e.device)}async function j(e){let{ref:t,sessionStore:n,platformCleanup:r}=e,i=n.resolveCurrent(t)??t.session;await r.closeManagedBrowser({device:i.device,stateDir:n.resolveDaemonStateDir(),openSessionNames:()=>c(n)})}async function M(e){let t=[];for(let{step:n,run:r}of e)try{await r()}catch(e){t.push({step:n,error:e})}return t}function N(n){if(n.failures.length===0)return;let r=n.failures.map(({step:e})=>e),i=n.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return t({level:`error`,phase:n.phase,data:{session:n.sessionName,failedSteps:r,errors:i}}),new e(`COMMAND_FAILED`,`Session cleanup left ${n.failures.length} resource(s) unreleased: ${i.join(`; `)}`,{reason:`session_cleanup_incomplete`,session:n.sessionName,failedSteps:r,hint:n.hint??`Some session resources failed to release. The session was retired; inspect the session log, device state, and retained claims before recovery. Do not retry close on the retired session.`})}function P(e){let{ref:t,sessionStore:n,platformCleanup:r}=e,i=n.resolveCurrent(t)??t.session;return[...[{step:`recording`,run:()=>L({ref:t,sessionStore:n})},...e.appLog===`run`?[{step:`app_log`,run:()=>O({ref:t,sessionStore:n})}]:[],{step:`audio_probe`,run:()=>R({ref:t,sessionStore:n})},{step:`perf_capture`,run:()=>k({ref:t,sessionStore:n})}].map(F),{step:`platform_snapshot_helper`,run:()=>A(i,r)}]}function F(e){return{...e,run:async()=>{try{await e.run()}catch(e){if(!r(e))throw e}}}}async function I(t){let{ref:n,sessionStore:r}=t,i=n.address;if(!t.platformCleanup)throw new e(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let a=t.platformCleanup,o=[...P({...t,platformCleanup:a}),{step:`web_browser`,run:()=>j({ref:n,sessionStore:r,platformCleanup:a})}];o.push({step:`materialized_paths`,run:()=>w(i)});let s=N({sessionName:i,phase:`session_teardown_cleanup_failed`,failures:await M(o)});if(s)throw s}async function L(e){let t=l(e.sessionStore,e.ref),n=t.read();if(!n)return;let r=n.envelope.metadata?.remoteCaptureOutput===!0,i=await o({binding:t,intent:`disposal`});if(!e.ref.session.lease)return;let{retainLeasedSessionRecording:a}=await import(`./leased-recording-retention.js`);a(e.ref,i,r)}async function R(e){let t=d(e.sessionStore,e.ref);t.read()&&await a({binding:t,intent:`disposal`})}export{C as a,x as c,I as i,P as n,w as o,O as r,S as s,N as t};
1
+ import{_ as e}from"./sdk-contracts.js";import{St as t}from"./sdk-io.js";import"./diagnostics.js";import{n}from"./runtime-slots.js";import{s as r}from"./durable-capture.js";import{n as i,o as a}from"./perf-capture-session-resource.js";import{n as o}from"./screen-recording-session-resource.js";import{c as s}from"./artifact-tracking.js";import{p as c}from"./session-runtime.js";import{a as l,i as u,n as d}from"./session-capture-binding.js";import f from"node:crypto";import{rmSync as p}from"node:fs";import m from"node:os";import h from"node:path";import g from"node:fs/promises";const _=2147483647,v={label:`Materialized paths`,plural:!0,expiredHint:`Materialized paths are released automatically when their TTL expires; re-run the command that materialized them if the paths are still needed.`},y=Symbol(`materializedPaths`),b=()=>n(y,()=>new Map,e=>{for(let t of e.values()){clearTimeout(t.timer);try{p(t.rootPath,{recursive:!0,force:!0})}catch{}}});async function x(e){let t=S(e.ttlMs),n=await g.mkdtemp(h.join(m.tmpdir(),`agent-device-materialized-`));try{let r=await D(e.installablePath,h.join(n,`installable`)),i=e.archivePath?await D(e.archivePath,h.join(n,`archive`)):void 0,a=f.randomUUID(),o=Date.now()+t,s=setTimeout(()=>{T(a)},t);return b().set(a,{rootPath:n,installablePath:r,archivePath:i,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:o,timer:s}),{materializationId:a,installablePath:r,...i?{archivePath:i}:{},expiresAt:new Date(o).toISOString()}}catch(e){throw await g.rm(n,{recursive:!0,force:!0}),e}}function S(t=9e5){if(typeof t!=`number`||!Number.isInteger(t)||t<=0||t>_)throw new e(`INVALID_ARGS`,`retentionMs must be an integer from 1 to ${_}`);return t}async function C(e,t){await E(e,s(b(),e,t,v))}async function w(e){let t=Array.from(b().entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await E(e,t)}))}async function T(e){let t=b().get(e);if(t)try{await E(e,t)}catch{}}async function E(e,t){clearTimeout(t.timer),b().delete(e),await g.rm(t.rootPath,{recursive:!0,force:!0})}async function D(e,t){let n=await g.stat(e);await g.mkdir(t,{recursive:!0});let r=h.join(t,h.basename(e));return n.isDirectory()?(await g.cp(e,r,{recursive:!0}),r):(await g.copyFile(e,r),r)}async function O(e){let t=e.sessionStore.refresh(e.ref);if(!t.session.appLog)return;let{forceCleanupSessionAppLog:n}=await import(`./app-log-session-resource.js`).then(e=>e.n);await n({...e,ref:t})}async function k(e){let t=u(e.sessionStore,e.ref);t.read()&&await i({binding:t,intent:`disposal`})}async function A(e,t){await t.stopSnapshotHelper(e.device)}async function j(e){let{ref:t,sessionStore:n,platformCleanup:r}=e,i=n.resolveCurrent(t)??t.session;await r.closeManagedBrowser({device:i.device,stateDir:n.resolveDaemonStateDir(),openSessionNames:()=>c(n)})}async function M(e){let t=[];for(let{step:n,run:r}of e)try{await r()}catch(e){t.push({step:n,error:e})}return t}function N(n){if(n.failures.length===0)return;let r=n.failures.map(({step:e})=>e),i=n.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return t({level:`error`,phase:n.phase,data:{session:n.sessionName,failedSteps:r,errors:i}}),new e(`COMMAND_FAILED`,`Session cleanup left ${n.failures.length} resource(s) unreleased: ${i.join(`; `)}`,{reason:`session_cleanup_incomplete`,session:n.sessionName,failedSteps:r,hint:n.hint??`Some session resources failed to release. The session was retired; inspect the session log, device state, and retained claims before recovery. Do not retry close on the retired session.`})}function P(e){let{ref:t,sessionStore:n,platformCleanup:r}=e,i=n.resolveCurrent(t)??t.session;return[...[{step:`recording`,run:()=>L({ref:t,sessionStore:n})},...e.appLog===`run`?[{step:`app_log`,run:()=>O({ref:t,sessionStore:n})}]:[],{step:`audio_probe`,run:()=>R({ref:t,sessionStore:n})},{step:`perf_capture`,run:()=>k({ref:t,sessionStore:n})}].map(F),{step:`platform_snapshot_helper`,run:()=>A(i,r)}]}function F(e){return{...e,run:async()=>{try{await e.run()}catch(e){if(!r(e))throw e}}}}async function I(t){let{ref:n,sessionStore:r}=t,i=n.address;if(!t.platformCleanup)throw new e(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let a=t.platformCleanup,o=[...P({...t,platformCleanup:a}),{step:`web_browser`,run:()=>j({ref:n,sessionStore:r,platformCleanup:a})}];o.push({step:`materialized_paths`,run:()=>w(i)});let s=N({sessionName:i,phase:`session_teardown_cleanup_failed`,failures:await M(o)});if(s)throw s}async function L(e){let t=l(e.sessionStore,e.ref),n=t.read();if(!n)return;let r=n.envelope.metadata?.remoteCaptureOutput===!0,i=await o({binding:t,intent:`disposal`});if(!e.ref.session.lease)return;let{retainLeasedSessionRecording:a}=await import(`./leased-recording-retention.js`);a(e.ref,i,r)}async function R(e){let t=d(e.sessionStore,e.ref);t.read()&&await a({binding:t,intent:`disposal`})}export{C as a,x as c,I as i,P as n,w as o,O as r,S as s,N as t};
@@ -1 +1 @@
1
- import{P as e}from"./sdk-contracts.js";import{y as t}from"./daemon-http.js";function n(e,n){return t(e,n)?n:`${e}:${n}`}function r(e,n){return t(e,n)?n.slice(e.length+1):n}function i(e,t,n){let i=t.meta?.sessionIsolation===`tenant`?t.meta.tenantId:void 0;return n.kind===`cwd`&&e!==``?{kind:`workspace`,id:n.id}:i===void 0?{name:e}:{name:r(i,e),namespace:{kind:`tenant`,id:i}}}function a(t){let n=t.internal?.webSession;if(n===void 0)throw new e(`UNKNOWN`,`A request reached device resolution outside a request scope.`,{reason:`request_web_session_missing`});return n}function o(e,n){return!e.partitioned||t(e.tenant,n)}export{n as a,r as i,o as n,a as r,i as t};
1
+ import{_ as e}from"./sdk-contracts.js";import{y as t}from"./daemon-http.js";function n(e,n){return t(e,n)?n:`${e}:${n}`}function r(e,n){return t(e,n)?n.slice(e.length+1):n}function i(e,t,n){let i=t.meta?.sessionIsolation===`tenant`?t.meta.tenantId:void 0;return n.kind===`cwd`&&e!==``?{kind:`workspace`,id:n.id}:i===void 0?{name:e}:{name:r(i,e),namespace:{kind:`tenant`,id:i}}}function a(t){let n=t.internal?.webSession;if(n===void 0)throw new e(`UNKNOWN`,`A request reached device resolution outside a request scope.`,{reason:`request_web_session_missing`});return n}function o(e,n){return!e.partitioned||t(e.tenant,n)}export{n as a,r as i,o as n,a as r,i as t};