agent-device 0.21.20 → 0.21.22

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 (357) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.20.apk → agent-device-android-ime-helper-0.21.22.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.22.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.20.manifest.json → agent-device-android-ime-helper-0.21.22.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.22.apk +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.22.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.20.manifest.json → agent-device-android-snapshot-helper-0.21.22.manifest.json} +6 -6
  7. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/AppWindowScreenshot.swift +73 -0
  8. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/BackgroundInteraction.swift +557 -0
  9. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/GhostCursor.swift +141 -0
  10. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift +107 -3
  11. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift +136 -22
  12. package/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/BackgroundInteractionTests.swift +88 -0
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +121 -4
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +10 -2
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +36 -9
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +28 -0
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +27 -0
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedCommitDeadline.swift +6 -1
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +7 -2
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +21 -7
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +121 -17
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +179 -6
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryConfirmation.swift +119 -0
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +8 -1
  25. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryReadiness.swift +23 -11
  26. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +59 -6
  27. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +112 -23
  28. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TypeExecution.swift +25 -12
  29. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/RecordingExportSupport.swift +6 -1
  30. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +43 -13
  31. package/dist/src/adapter.js +1 -1
  32. package/dist/src/adb-executor.js +2 -2
  33. package/dist/src/adb-failure.js +1 -1
  34. package/dist/src/adb-transport.js +1 -1
  35. package/dist/src/agent-browser-lifecycle.js +1 -1
  36. package/dist/src/agent-browser-process-record.js +1 -1
  37. package/dist/src/agent-browser-provider.js +1 -1
  38. package/dist/src/agent-browser-tool.js +1 -1
  39. package/dist/src/agent-device-client.js +2 -2
  40. package/dist/src/ai-sdk.js +1 -1
  41. package/dist/src/alert-runtime.js +1 -1
  42. package/dist/src/alert.js +1 -1
  43. package/dist/src/android-adb.d.ts +12 -0
  44. package/dist/src/android-input-ownership.js +1 -1
  45. package/dist/src/app-backend.js +1 -0
  46. package/dist/src/app-catalog.js +1 -1
  47. package/dist/src/app-deployment-resolution.js +1 -1
  48. package/dist/src/app-inventory.js +1 -1
  49. package/dist/src/app-launch.js +1 -1
  50. package/dist/src/app-lifecycle.js +2 -2
  51. package/dist/src/app-lifecycle2.js +1 -1
  52. package/dist/src/app-log-files.js +1 -1
  53. package/dist/src/app-log-reconnect.js +1 -1
  54. package/dist/src/app-log-runtime2.js +3 -3
  55. package/dist/src/app-log-session-resource.js +1 -0
  56. package/dist/src/app-resolution.js +2 -2
  57. package/dist/src/apple-runner-platform.js +1 -1
  58. package/dist/src/application-lifecycle-interaction.js +1 -1
  59. package/dist/src/archive.js +2 -2
  60. package/dist/src/artifact-download.js +1 -1
  61. package/dist/src/auth-session.js +1 -1
  62. package/dist/src/auth.js +1 -1
  63. package/dist/src/back-mode.js +1 -1
  64. package/dist/src/backend-snapshot-options.js +1 -1
  65. package/dist/src/boot-diagnostics.js +1 -1
  66. package/dist/src/cache.js +1 -1
  67. package/dist/src/capabilities.js +1 -1
  68. package/dist/src/capture.js +1 -1
  69. package/dist/src/cli-config.js +1 -1
  70. package/dist/src/cli-help.js +13 -5
  71. package/dist/src/cli.js +4 -4
  72. package/dist/src/click-button.js +1 -1
  73. package/dist/src/client-metro-companion.js +1 -1
  74. package/dist/src/client-metro.js +1 -1
  75. package/dist/src/client-options.js +3 -0
  76. package/dist/src/client-types.d.ts +88 -5
  77. package/dist/src/clipboard-shell-response.js +1 -1
  78. package/dist/src/cloud-artifacts.d.ts +7 -2
  79. package/dist/src/code-signature-cache.js +1 -1
  80. package/dist/src/code-signature.js +1 -1
  81. package/dist/src/command-schema.js +1 -1
  82. package/dist/src/command-tools.js +2 -2
  83. package/dist/src/connection-runtime.js +1 -1
  84. package/dist/src/connection.js +5 -5
  85. package/dist/src/contracts.d.ts +1 -1
  86. package/dist/src/contracts.js +1 -1
  87. package/dist/src/daemon-artifacts.js +1 -0
  88. package/dist/src/daemon-client-lease-beat.js +1 -1
  89. package/dist/src/daemon-client-lifecycle.js +1 -1
  90. package/dist/src/daemon-client-liveness-probe.js +1 -0
  91. package/dist/src/daemon-client-transport.js +1 -1
  92. package/dist/src/daemon-http.js +1 -0
  93. package/dist/src/daemon-policy-file.js +1 -1
  94. package/dist/src/daemon-registration-owner.js +1 -0
  95. package/dist/src/daemon-registration.js +1 -1
  96. package/dist/src/daemon-resolution.js +1 -1
  97. package/dist/src/daemon-shutdown-report.js +1 -1
  98. package/dist/src/daemon.js +2 -2
  99. package/dist/src/debug-symbols-facade.js +1 -1
  100. package/dist/src/device-claim-inspection.js +1 -1
  101. package/dist/src/device-claim-rule.js +1 -1
  102. package/dist/src/device-inventory-context.js +1 -1
  103. package/dist/src/device-readiness-runtime.js +1 -1
  104. package/dist/src/device-release.js +1 -1
  105. package/dist/src/device-rotation.js +1 -1
  106. package/dist/src/device-selection-resolver.js +1 -1
  107. package/dist/src/device-session.js +1 -1
  108. package/dist/src/device-shell.js +1 -1
  109. package/dist/src/device.js +1 -1
  110. package/dist/src/device2.js +1 -3
  111. package/dist/src/device3.js +3 -0
  112. package/dist/src/devicectl.js +1 -1
  113. package/dist/src/diagnostics.js +3 -3
  114. package/dist/src/dispatch-resolve.js +4 -1
  115. package/dist/src/display-inventory.js +1 -1
  116. package/dist/src/doctor-facade.js +1 -1
  117. package/dist/src/doctor2.js +1 -1
  118. package/dist/src/durable-capture-resource.js +1 -0
  119. package/dist/src/engine-eval-script.js +1 -1
  120. package/dist/src/error.js +1 -1
  121. package/dist/src/exec.js +1 -1
  122. package/dist/src/file.js +1 -1
  123. package/dist/src/find.js +1 -1
  124. package/dist/src/generic-settle.js +1 -1
  125. package/dist/src/generic.js +1 -1
  126. package/dist/src/gesture-admission.js +1 -1
  127. package/dist/src/gesture-plan.js +1 -1
  128. package/dist/src/gesture-runtime.js +1 -1
  129. package/dist/src/harmonyos.js +1 -1
  130. package/dist/src/hdc.js +1 -1
  131. package/dist/src/helper.js +2 -2
  132. package/dist/src/host-file.js +1 -1
  133. package/dist/src/host.js +1 -1
  134. package/dist/src/human-control-contract.js +1 -1
  135. package/dist/src/human-control.js +1 -1
  136. package/dist/src/index.d.ts +1 -1
  137. package/dist/src/index.js +1 -1
  138. package/dist/src/input-actions.js +1 -1
  139. package/dist/src/input-actions2.js +2 -2
  140. package/dist/src/install-artifact-facade.js +1 -1
  141. package/dist/src/install-source-network-transport.js +1 -1
  142. package/dist/src/install-source.d.ts +5 -0
  143. package/dist/src/install-source2.js +1 -1
  144. package/dist/src/instance-client.js +1 -0
  145. package/dist/src/interaction-positionals.js +1 -1
  146. package/dist/src/interaction-ref-policy.js +1 -1
  147. package/dist/src/interaction.js +1 -1
  148. package/dist/src/interaction2.js +1 -1
  149. package/dist/src/interactor-operation-binding.js +1 -1
  150. package/dist/src/interactor.js +5 -5
  151. package/dist/src/interactor2.js +1 -1
  152. package/dist/src/interactors.js +1 -1
  153. package/dist/src/internal/bin.js +1 -1
  154. package/dist/src/internal/daemon.js +1 -2
  155. package/dist/src/internal/png-worker.js +1 -1
  156. package/dist/src/internal/run-script-http-child.js +1 -1
  157. package/dist/src/inventory.js +4 -4
  158. package/dist/src/inventory2.js +1 -1
  159. package/dist/src/inventory3.js +1 -1
  160. package/dist/src/inventory5.js +1 -1
  161. package/dist/src/ios-client.js +4 -30
  162. package/dist/src/ios-settings.js +1 -0
  163. package/dist/src/ios-snapshot-engine.js +1 -1
  164. package/dist/src/ios-snapshot-runtime.js +1 -1
  165. package/dist/src/launch-confirmation.js +1 -1
  166. package/dist/src/lease-context.js +1 -1
  167. package/dist/src/lease-registry-scope.js +1 -0
  168. package/dist/src/lease-scope.js +1 -1
  169. package/dist/src/lease.js +1 -1
  170. package/dist/src/legacy-xctest-device-set.js +1 -1
  171. package/dist/src/limrun-download-file.js +1 -1
  172. package/dist/src/limrun-runtime-dependencies.js +1 -1
  173. package/dist/src/limrun.d.ts +28 -2
  174. package/dist/src/limrun.js +1 -1
  175. package/dist/src/linux.js +1 -1
  176. package/dist/src/load.js +1 -0
  177. package/dist/src/location-coordinates.js +1 -1
  178. package/dist/src/macos-facade.js +1 -1
  179. package/dist/src/managed-device-scope.js +1 -1
  180. package/dist/src/mechanics.js +16 -16
  181. package/dist/src/observation.js +1 -1
  182. package/dist/src/observe-until.js +1 -1
  183. package/dist/src/overlay.js +2 -2
  184. package/dist/src/owner-identity.js +3 -3
  185. package/dist/src/path-resolution.js +1 -1
  186. package/dist/src/perf-facade.js +1 -1
  187. package/dist/src/perf-runtime-operation-builder.js +1 -1
  188. package/dist/src/perf-runtime-plan.js +1 -1
  189. package/dist/src/perf-target.js +1 -1
  190. package/dist/src/perf.js +1 -1
  191. package/dist/src/physical-device-control.js +1 -1
  192. package/dist/src/platform-request-scope.js +1 -1
  193. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  194. package/dist/src/platform-runtime-app-log-process.js +1 -1
  195. package/dist/src/platform-runtime-host.js +1 -1
  196. package/dist/src/platform-runtime-managed-owner.js +1 -1
  197. package/dist/src/platform-runtime-open-target.js +1 -1
  198. package/dist/src/platform-runtime-operation-host.js +2 -2
  199. package/dist/src/platform-runtime-runtime-hints.js +2 -2
  200. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  201. package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
  202. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  203. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  204. package/dist/src/platform-runtime-screen-recording-output-host.js +1 -1
  205. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  206. package/dist/src/platform-runtime-unavailable.js +1 -1
  207. package/dist/src/platform-runtime.js +1 -1
  208. package/dist/src/platform-runtime2.js +1 -1
  209. package/dist/src/plugins.d.ts +9 -0
  210. package/dist/src/plugins.js +1 -0
  211. package/dist/src/plugins2.js +2 -0
  212. package/dist/src/png-crop-bytes.js +1 -1
  213. package/dist/src/png-size.js +1 -1
  214. package/dist/src/png-worker-client.js +1 -1
  215. package/dist/src/png.js +1 -1
  216. package/dist/src/prepare-kind.js +1 -1
  217. package/dist/src/process.js +1 -1
  218. package/dist/src/project-runtime.js +1 -1
  219. package/dist/src/provider-credential-fingerprint.js +1 -0
  220. package/dist/src/provider-device-admission.js +1 -1
  221. package/dist/src/provider-device-runtimes.js +1 -0
  222. package/dist/src/provider-limrun-credentials.js +1 -0
  223. package/dist/src/provider-profile-fields.js +1 -0
  224. package/dist/src/provider-session-ownership.js +2 -2
  225. package/dist/src/provider-webdriver.js +2 -1
  226. package/dist/src/providers.js +1 -1
  227. package/dist/src/proxy.js +1 -1
  228. package/dist/src/quality-warnings.js +1 -1
  229. package/dist/src/react-native.js +1 -1
  230. package/dist/src/record-runtime.js +1 -1
  231. package/dist/src/record-trace.js +1 -1
  232. package/dist/src/recording.js +1 -1
  233. package/dist/src/rect-center.js +1 -1
  234. package/dist/src/register-builtins.js +1 -1
  235. package/dist/src/registry.js +39 -39
  236. package/dist/src/remote-config2.js +1 -1
  237. package/dist/src/replay-divergence.js +1 -1
  238. package/dist/src/replay.js +2 -2
  239. package/dist/src/reporting.js +5 -5
  240. package/dist/src/request-admission.js +1 -1
  241. package/dist/src/request-cancel.js +1 -1
  242. package/dist/src/request-cancellation.js +1 -1
  243. package/dist/src/request-runtime-binding.js +1 -1
  244. package/dist/src/result-serialization.js +1 -1
  245. package/dist/src/retry.js +1 -1
  246. package/dist/src/runner-artifact-manifest.js +1 -1
  247. package/dist/src/runner-cache-metadata.js +3 -3
  248. package/dist/src/runner-client.js +1 -1
  249. package/dist/src/runner-dev-tools-security.js +1 -1
  250. package/dist/src/runner-device-readiness.js +1 -1
  251. package/dist/src/runner-disposal.js +1 -1
  252. package/dist/src/runner-error-classification.js +2 -2
  253. package/dist/src/runner-exchange.js +1 -1
  254. package/dist/src/runner-operations-facade.js +1 -1
  255. package/dist/src/runner-session-types.js +1 -1
  256. package/dist/src/runner-start-budget.js +1 -1
  257. package/dist/src/runner.js +1 -1
  258. package/dist/src/runtime-admission.js +1 -1
  259. package/dist/src/runtime-transport-hints.js +1 -1
  260. package/dist/src/runtime.js +1 -1
  261. package/dist/src/runtime10.js +2 -2
  262. package/dist/src/runtime2.js +3 -3
  263. package/dist/src/runtime3.js +1 -1
  264. package/dist/src/runtime4.js +5 -5
  265. package/dist/src/runtime5.js +1 -1
  266. package/dist/src/runtime6.js +1 -1
  267. package/dist/src/runtime7.js +1 -1
  268. package/dist/src/runtime8.js +1 -1
  269. package/dist/src/runtime9.js +1 -1
  270. package/dist/src/screen-recording-admission-ledger.js +1 -1
  271. package/dist/src/screen-recording-completion.js +1 -1
  272. package/dist/src/screen-recording-options.js +1 -1
  273. package/dist/src/screen-recording-resource-recovery.js +1 -1
  274. package/dist/src/screen-recording-transport.js +1 -1
  275. package/dist/src/screenshot-density.js +1 -1
  276. package/dist/src/screenshot-image.js +1 -1
  277. package/dist/src/screenshot-result.js +1 -1
  278. package/dist/src/screenshot-runtime.js +1 -1
  279. package/dist/src/screenshot.js +1 -1
  280. package/dist/src/screenshot3.js +1 -1
  281. package/dist/src/script.js +1 -1
  282. package/dist/src/scroll-command.js +1 -1
  283. package/dist/src/scroll-gesture.js +1 -1
  284. package/dist/src/sdk-batch-runner.js +2 -2
  285. package/dist/src/sdk-batch.js +2 -2
  286. package/dist/src/sdk-contracts.d.ts +45 -2
  287. package/dist/src/sdk-contracts.js +2 -2
  288. package/dist/src/sdk-device.js +1 -1
  289. package/dist/src/sdk-io.js +1 -1
  290. package/dist/src/sdk-remote-config.js +1 -1
  291. package/dist/src/sdk-selectors.d.ts +33 -4
  292. package/dist/src/selection.js +0 -0
  293. package/dist/src/selector-runtime.js +1 -1
  294. package/dist/src/selectors.d.ts +2 -2
  295. package/dist/src/selectors.js +1 -1
  296. package/dist/src/server.js +1 -1
  297. package/dist/src/session-allocation.js +1 -1
  298. package/dist/src/session-artifact-paths.js +1 -1
  299. package/dist/src/session-repair-tombstone.js +1 -1
  300. package/dist/src/session-routing.js +1 -1
  301. package/dist/src/session-runtime-admission.js +1 -1
  302. package/dist/src/session-snapshot.js +1 -1
  303. package/dist/src/session-stream.js +27 -0
  304. package/dist/src/session.js +1 -1
  305. package/dist/src/session2.js +5 -5
  306. package/dist/src/settings.js +1 -1
  307. package/dist/src/settings2.js +1 -1
  308. package/dist/src/simctl-settings-facade.js +1 -0
  309. package/dist/src/simctl-settings.js +1 -0
  310. package/dist/src/simctl.js +1 -1
  311. package/dist/src/simulator.js +1 -1
  312. package/dist/src/snapshot-diagnostics.js +1 -1
  313. package/dist/src/snapshot-runtime-binding.js +1 -1
  314. package/dist/src/snapshot-runtime.js +1 -1
  315. package/dist/src/snapshot-state.js +1 -1
  316. package/dist/src/snapshot2.js +1 -1
  317. package/dist/src/snapshot3.js +1 -1
  318. package/dist/src/snapshot4.js +1 -1
  319. package/dist/src/src.js +1 -1
  320. package/dist/src/src7.js +1 -1
  321. package/dist/src/src8.js +2 -2
  322. package/dist/src/store.js +1 -0
  323. package/dist/src/string-enum.js +1 -1
  324. package/dist/src/surface-snapshot.js +1 -1
  325. package/dist/src/takeover.js +1 -1
  326. package/dist/src/target-evidence.js +1 -1
  327. package/dist/src/telemetry.js +1 -1
  328. package/dist/src/text-entry-focus.js +1 -1
  329. package/dist/src/tool-provider.js +1 -1
  330. package/dist/src/tool-provider2.js +1 -1
  331. package/dist/src/toolchain-probe.js +2 -2
  332. package/dist/src/touch-runtime.js +1 -1
  333. package/dist/src/touch-runtime2.js +1 -1
  334. package/dist/src/transport.js +2 -2
  335. package/dist/src/tv-remote.js +1 -1
  336. package/dist/src/type-text-runtime.js +1 -1
  337. package/dist/src/update-check.js +1 -1
  338. package/dist/src/vars.js +1 -1
  339. package/dist/src/verified-file.js +1 -1
  340. package/dist/src/version.js +1 -1
  341. package/dist/src/video.js +1 -1
  342. package/dist/src/viewport.js +1 -1
  343. package/dist/src/web.js +1 -1
  344. package/dist/src/web2.js +1 -1
  345. package/dist/src/webdriver-source.js +1 -1
  346. package/package.json +5 -1
  347. package/server.json +2 -2
  348. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.20.apk.sha256 +0 -1
  349. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.20.apk +0 -0
  350. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.20.apk.sha256 +0 -1
  351. package/dist/src/api.js +0 -3
  352. package/dist/src/daemon-process.js +0 -1
  353. package/dist/src/multitouch-support.js +0 -1
  354. package/dist/src/parameterized-recorded-fill.js +0 -1
  355. package/dist/src/runner-startup-transport.js +0 -1
  356. package/dist/src/runner-xctestrun.js +0 -1
  357. package/dist/src/session-store.js +0 -4
@@ -0,0 +1,3 @@
1
+ import{P as e}from"./sdk-contracts.js";import{w as t}from"./sdk-device.js";import{s as n}from"./device-shell.js";import{i as r,n as i,t as a}from"./device-claim-inspection.js";import{t as o}from"./shared.js";const s=async({positionals:t,flags:n})=>{if(t.length!==1||t[0]!==`status`&&t[0]!==`release`)throw new e(`INVALID_ARGS`,`device accepts only: status, release`);if(t[0]===`release`)return await c(n);let s=r({platform:n.platform,device:n.device,udid:n.udid,serial:n.serial}),l=s.filter(e=>i(e.classification)),u=(n.stale?l:s.filter(e=>!i(e.classification))).map(m),d={claims:u,...n.stale?{}:{hiddenStaleClaims:l.length}};return await o(n,d,()=>g(u,{staleOnly:n.stale===!0,hiddenStaleClaims:l.length,staleCommand:x(n,`status`),releasableClaims:l.filter(e=>a(e.classification)).length,releaseCommand:x(n,`release`)})),!0};async function c(t){if(t.stale!==!0)throw new e(`INVALID_ARGS`,`device release only releases provably stale claims; pass --stale to confirm.`,{hint:`A live owner is released by closing its session from its own workspace, or by stopping its daemon: agent-device daemon stop --state-dir <owner state dir>.`});let{runStaleDeviceClaimRelease:n}=await import(`./device-release.js`),r=await n({platform:t.platform,device:t.device,udid:t.udid,serial:t.serial}),i={released:r.filter(e=>e.status===`released`).map(l),retained:r.filter(e=>e.status===`retained`).map(l),refused:r.filter(e=>e.status===`refused`).map(l),changed:r.filter(e=>e.status===`changed`).map(l)};return await o(t,i,()=>u(r)),!0}function l(e){let{device:t,...n}=e;return{...n,...t?{device:h(t)}:{}}}function u(e){return e.length===0?`No local device claims matched.`:e.map(d).join(`
2
+ `)}function d(e){let n=e.device?`${t({platform:e.device.family,appleOs:e.device.appleOs})} ${e.device.name}`:e.deviceKey??e.fileName,r=f(e);switch(e.status){case`released`:return`released ${n}${r}`;case`retained`:return`retained ${n}${r} — resources not settled (${e.reason}); the claim stays until they are.`;case`refused`:return`refused ${n}${r} — ${e.reason} (${e.classification}); ${p(e)}`;case`changed`:return`changed ${n} — the claim changed while releasing; re-run device status.`}}function f(e){return e.allocator?` allocator=${e.allocator.instanceId} incarnation=${e.allocator.identityIncarnationId}`:e.session?` session=${e.session} workspace=${e.workspace}`:``}function p(e){return e.classification===`allocator-held`?`held by its managed-device allocator; it is cleared only after the allocator proves the identity removed.`:e.classification===`live`||e.classification===`owner-state-dir-gone`?e.stateDir?`close the owning session from its workspace, or stop its daemon: agent-device daemon stop --state-dir ${n(e.stateDir)}`:`close the owning session from its workspace first.`:`only provably dead owners are released; nothing was changed.`}function m(e){let t=e.claim??e.allocatorClaim;return{...e.deviceKey?{deviceKey:e.deviceKey}:{},...t?{}:{fileName:e.fileName},classification:e.classification,...t?{device:h(t.device)}:{},...e.claim?{owner:{session:e.claim.session,workspace:e.claim.workspace,stateDir:e.claim.stateDir,pid:e.claim.ownerPid,startTime:e.claim.ownerStartTime}}:{},...e.allocatorClaim?{owner:{kind:`allocator`,stateDir:e.allocatorClaim.stateDir,allocator:e.allocatorClaim.allocator}}:{},...e.error?{error:e.error}:{}}}function h(e){let{family:n,...r}=e;return{...r,platform:t({platform:n,appleOs:e.appleOs})}}function g(e,t){let n=e.map(v);if(n.length===0){if(t.staleOnly)return`No stale local device claims found.`;if(t.hiddenStaleClaims===0)return`No local device claims found.`}return[...n.length===0?[`No live local device claims found.`]:n,..._(t)].join(`
3
+ `)}function _(e){if(e.staleOnly)return e.releasableClaims>0?[`Release provably dead owners with: ${e.releaseCommand}`]:[];if(e.hiddenStaleClaims===0)return[];let t=e.hiddenStaleClaims===1?`claim`:`claims`;return[`${e.hiddenStaleClaims} stale ${t} hidden; inspect with: ${e.staleCommand}`]}function v(e){return`${y(e)}: ${e.classification}${b(e.owner)}`}function y(e){let t=e.device;return t?`${t.platform??`unknown`} ${t.name??t.id??`claim`}`:String(e.deviceKey??e.fileName??`claim`)}function b(e){if(!e||typeof e!=`object`)return``;let t=e;return t.allocator?` allocator=${t.allocator.instanceId} incarnation=${t.allocator.identityIncarnationId} installation=${t.stateDir}`:` session=${t.session} workspace=${t.workspace}`}function x(e,t){let r=[e.platform?`--platform ${n(e.platform)}`:null,e.device?`--device ${n(e.device)}`:null,e.udid?`--udid ${n(e.udid)}`:null,e.serial?`--serial ${n(e.serial)}`:null].filter(e=>!!e);return[`agent-device device ${t}`,...r,`--stale`].join(` `)}export{s as deviceCommand};
@@ -1 +1 @@
1
- import{N as e}from"./sdk-contracts.js";import{f as t}from"./owner-identity.js";import{r as n}from"./exec.js";import"./command.js";import"./process.js";import{T as r,p as i,y as a}from"./host-file.js";import"./config.js";import{l as o,o as s}from"./tool-provider.js";import c from"node:path";async function l(t,r,i={}){let a=[`devicectl`,...t],o=await s(a,{allowFailure:!0,signal:i.signal,timeoutMs:i.timeoutMs??2e4});if(o.exitCode===0)return;let{stdout:c,stderr:l}=o;if(!i.tolerateOutput?.(c,l))throw new e(`COMMAND_FAILED`,`Failed to ${r.action}`,n(o,{cmd:`xcrun`,args:a,stdout:c,stderr:l,deviceId:r.deviceId,hint:O(c,l)??`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`}))}async function u(e,t){return C(x(await g(e,{jsonPrefix:`agent-device-ios-apps`,args:[`devicectl`,`device`,`info`,`apps`,`--device`,e.id,`--include-all-apps`],failureMessage:`Failed to list iOS apps`,parseFailureMessage:`Failed to parse iOS apps list`})),t)}async function d(t){let n=await g(t,{jsonPrefix:`agent-device-ios-processes`,args:[`devicectl`,`device`,`info`,`processes`,`--device`,t.id],failureMessage:`Failed to list iOS processes`,parseFailureMessage:`Failed to parse iOS process list`,fallbackHint:T});if(!y(n))throw new e(`COMMAND_FAILED`,`Unsupported iOS process list response`,{deviceId:t.id,hint:T});return S(n)}async function f(e,t){let{appBundleUrl:n,processes:r}=await p(e,t),i=r.sort((e,t)=>v(e,n)-v(t,n))[0];i&&await g(e,{jsonPrefix:`agent-device-ios-process-terminate`,args:[`devicectl`,`device`,`process`,`terminate`,`--device`,e.id,`--pid`,String(i.pid),`--kill`],failureMessage:`Failed to terminate iOS app`,parseFailureMessage:`Failed to parse iOS process termination response`,tolerateFailurePayload:b})}async function p(t,n){let r=(await u(t,`all`)).find(e=>e.bundleId===n);if(!r)throw new e(`APP_NOT_INSTALLED`,`No iOS device app found for ${n}`,{appBundleId:n,deviceId:t.id});if(!r.url)throw new e(`COMMAND_FAILED`,`Missing app bundle URL for ${n}`,{appBundleId:n,deviceId:t.id,hint:`Installed-app metadata from devicectl did not include the bundle URL required to match running processes. Use an Xcode/CoreDevice toolchain that reports app URLs.`});let i=r.url.replace(/\/+$/,``);return{appBundleUrl:i,processes:(await d(t)).filter(e=>e.executable.startsWith(`${i}/`))}}async function m(e){let n=c.join(i(),`${e.jsonPrefix}-${t()}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),a=[...e.args,`--json-output`,n];try{let t=await s(a,{allowFailure:!0,signal:e.signal,timeoutMs:e.timeoutMs??2e4});if(t.exitCode!==0){let r=await _(n).catch(()=>void 0);return r!==void 0&&e.tolerateFailurePayload?.(r)?{ok:!0,payload:r}:{ok:!1,reason:`command-failed`,args:a,result:t,payload:r}}return await h(n,a,t)}finally{await r(n).catch(()=>{})}}async function h(t,n,r){try{return{ok:!0,payload:await _(t)}}catch(t){if(t instanceof e)throw t;return{ok:!1,reason:`unreadable-json`,args:n,result:r,cause:String(t)}}}async function g(t,r){let i=await m(r);if(i.ok)return i.payload;if(i.reason===`command-failed`){let{stdout:a,stderr:o}=i.result;throw new e(`COMMAND_FAILED`,r.failureMessage,n(i.result,{cmd:`xcrun`,args:i.args,stdout:a,stderr:o,deviceId:t.id,hint:O(a,o)??r.fallbackHint??`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`}))}throw new e(`COMMAND_FAILED`,r.parseFailureMessage,{deviceId:t.id,cause:i.cause})}async function _(e){return JSON.parse(await a(e))}function v(e,t){return e.executable.slice(t.length+1).split(`/`).length}function y(e){return Array.isArray(e?.result?.runningProcesses)}function b(e){let t=e?.error?.userInfo?.NSUnderlyingError?.error;return t?.domain===`NSPOSIXErrorDomain`&&t.code===3}function x(e){let t=e?.result?.apps;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!e||typeof e!=`object`)continue;let t=typeof e.bundleIdentifier==`string`?e.bundleIdentifier.trim():``;if(!t)continue;let r=typeof e.name==`string`&&e.name.trim().length>0?e.name.trim():t,i=typeof e.url==`string`&&e.url.trim().length>0?e.url.trim():void 0;n.push({bundleId:t,name:r,url:i})}return n}function S(e){let t=e?.result?.runningProcesses;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!e||typeof e!=`object`)continue;let t=typeof e.executable==`string`?e.executable.trim():``,r=typeof e.processIdentifier==`number`&&Number.isFinite(e.processIdentifier)?e.processIdentifier:NaN;!t||!Number.isFinite(r)||n.push({executable:t,pid:r})}return n}function C(e,t){return o(e,t)}const w=`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`,T=`This Xcode/CoreDevice toolchain must support 'devicectl device info processes' with JSON runningProcesses so agent-device can resolve app process IDs. Inspect diagnostics for the exact devicectl API failure.`,E=`Enable Developer Mode on the iOS device (Settings > Privacy & Security > Developer Mode), restart it when prompted, unlock it, then retry.`,D=`Let Xcode finish preparing this device: keep it unlocked and connected by cable, open Xcode > Settings > Platforms (or Window > Devices and Simulators), wait for device support to install, then retry.`;function O(e,t){let n=`${e}\n${t}`.toLowerCase();return n.includes(`device is busy`)&&n.includes(`connecting`)?`iOS device is still connecting. Keep it unlocked and connected by cable until it is fully available in Xcode Devices, then retry.`:n.includes(`coredeviceservice`)&&n.includes(`timed out`)?`CoreDevice service timed out. Reconnect the device and retry; if it persists restart Xcode and the iOS device.`:n.includes(`developer mode is disabled`)?E:n.includes(`developer disk image`)?D:n.includes(`must be paired`)?`Pair the iOS device with this Mac: connect it by cable, unlock it, accept the Trust prompt, and enter the device passcode, then retry.`:null}export{p as a,m as c,u as i,f as l,D as n,O as o,E as r,l as s,w as t};
1
+ import{P as e}from"./sdk-contracts.js";import{p as t}from"./owner-identity.js";import{r as n}from"./exec.js";import"./command.js";import"./process.js";import{T as r,p as i,y as a}from"./host-file.js";import"./config.js";import{l as o,o as s}from"./tool-provider.js";import c from"node:path";async function l(t,r,i={}){let a=[`devicectl`,...t],o=await s(a,{allowFailure:!0,signal:i.signal,timeoutMs:i.timeoutMs??2e4});if(o.exitCode===0)return;let{stdout:c,stderr:l}=o;if(!i.tolerateOutput?.(c,l))throw new e(`COMMAND_FAILED`,`Failed to ${r.action}`,n(o,{cmd:`xcrun`,args:a,stdout:c,stderr:l,deviceId:r.deviceId,hint:O(c,l)??`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`}))}async function u(e,t){return C(x(await g(e,{jsonPrefix:`agent-device-ios-apps`,args:[`devicectl`,`device`,`info`,`apps`,`--device`,e.id,`--include-all-apps`],failureMessage:`Failed to list iOS apps`,parseFailureMessage:`Failed to parse iOS apps list`})),t)}async function d(t){let n=await g(t,{jsonPrefix:`agent-device-ios-processes`,args:[`devicectl`,`device`,`info`,`processes`,`--device`,t.id],failureMessage:`Failed to list iOS processes`,parseFailureMessage:`Failed to parse iOS process list`,fallbackHint:T});if(!y(n))throw new e(`COMMAND_FAILED`,`Unsupported iOS process list response`,{deviceId:t.id,hint:T});return S(n)}async function f(e,t){let{appBundleUrl:n,processes:r}=await p(e,t),i=r.sort((e,t)=>v(e,n)-v(t,n))[0];i&&await g(e,{jsonPrefix:`agent-device-ios-process-terminate`,args:[`devicectl`,`device`,`process`,`terminate`,`--device`,e.id,`--pid`,String(i.pid),`--kill`],failureMessage:`Failed to terminate iOS app`,parseFailureMessage:`Failed to parse iOS process termination response`,tolerateFailurePayload:b})}async function p(t,n){let r=(await u(t,`all`)).find(e=>e.bundleId===n);if(!r)throw new e(`APP_NOT_INSTALLED`,`No iOS device app found for ${n}`,{appBundleId:n,deviceId:t.id});if(!r.url)throw new e(`COMMAND_FAILED`,`Missing app bundle URL for ${n}`,{appBundleId:n,deviceId:t.id,hint:`Installed-app metadata from devicectl did not include the bundle URL required to match running processes. Use an Xcode/CoreDevice toolchain that reports app URLs.`});let i=r.url.replace(/\/+$/,``);return{appBundleUrl:i,processes:(await d(t)).filter(e=>e.executable.startsWith(`${i}/`))}}async function m(e){let n=c.join(i(),`${e.jsonPrefix}-${t()}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),a=[...e.args,`--json-output`,n];try{let t=await s(a,{allowFailure:!0,signal:e.signal,timeoutMs:e.timeoutMs??2e4});if(t.exitCode!==0){let r=await _(n).catch(()=>void 0);return r!==void 0&&e.tolerateFailurePayload?.(r)?{ok:!0,payload:r}:{ok:!1,reason:`command-failed`,args:a,result:t,payload:r}}return await h(n,a,t)}finally{await r(n).catch(()=>{})}}async function h(t,n,r){try{return{ok:!0,payload:await _(t)}}catch(t){if(t instanceof e)throw t;return{ok:!1,reason:`unreadable-json`,args:n,result:r,cause:String(t)}}}async function g(t,r){let i=await m(r);if(i.ok)return i.payload;if(i.reason===`command-failed`){let{stdout:a,stderr:o}=i.result;throw new e(`COMMAND_FAILED`,r.failureMessage,n(i.result,{cmd:`xcrun`,args:i.args,stdout:a,stderr:o,deviceId:t.id,hint:O(a,o)??r.fallbackHint??`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`}))}throw new e(`COMMAND_FAILED`,r.parseFailureMessage,{deviceId:t.id,cause:i.cause})}async function _(e){return JSON.parse(await a(e))}function v(e,t){return e.executable.slice(t.length+1).split(`/`).length}function y(e){return Array.isArray(e?.result?.runningProcesses)}function b(e){let t=e?.error?.userInfo?.NSUnderlyingError?.error;return t?.domain===`NSPOSIXErrorDomain`&&t.code===3}function x(e){let t=e?.result?.apps;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!e||typeof e!=`object`)continue;let t=typeof e.bundleIdentifier==`string`?e.bundleIdentifier.trim():``;if(!t)continue;let r=typeof e.name==`string`&&e.name.trim().length>0?e.name.trim():t,i=typeof e.url==`string`&&e.url.trim().length>0?e.url.trim():void 0;n.push({bundleId:t,name:r,url:i})}return n}function S(e){let t=e?.result?.runningProcesses;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!e||typeof e!=`object`)continue;let t=typeof e.executable==`string`?e.executable.trim():``,r=typeof e.processIdentifier==`number`&&Number.isFinite(e.processIdentifier)?e.processIdentifier:NaN;!t||!Number.isFinite(r)||n.push({executable:t,pid:r})}return n}function C(e,t){return o(e,t)}const w=`Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.`,T=`This Xcode/CoreDevice toolchain must support 'devicectl device info processes' with JSON runningProcesses so agent-device can resolve app process IDs. Inspect diagnostics for the exact devicectl API failure.`,E=`Enable Developer Mode on the iOS device (Settings > Privacy & Security > Developer Mode), restart it when prompted, unlock it, then retry.`,D=`Let Xcode finish preparing this device: keep it unlocked and connected by cable, open Xcode > Settings > Platforms (or Window > Devices and Simulators), wait for device support to install, then retry.`;function O(e,t){let n=`${e}\n${t}`.toLowerCase();return n.includes(`device is busy`)&&n.includes(`connecting`)?`iOS device is still connecting. Keep it unlocked and connected by cable until it is fully available in Xcode Devices, then retry.`:n.includes(`coredeviceservice`)&&n.includes(`timed out`)?`CoreDevice service timed out. Reconnect the device and retry; if it persists restart Xcode and the iOS device.`:n.includes(`developer mode is disabled`)?E:n.includes(`developer disk image`)?D:n.includes(`must be paired`)?`Pair the iOS device with this Mac: connect it by cable, unlock it, accept the Trust prompt, and enter the device passcode, then retry.`:null}export{p as a,m as c,u as i,f as l,D as n,O as o,E as r,l as s,w as t};
@@ -1,3 +1,3 @@
1
- import{tt as e}from"./sdk-contracts.js";import t from"node:path";import n from"node:fs";import r from"node:crypto";import{AsyncLocalStorage as i}from"node:async_hooks";import a from"node:os";const o=new i;function s(){return r.randomBytes(8).toString(`hex`)}function c(){return`${Date.now().toString(36)}-${r.randomBytes(4).toString(`hex`)}`}async function l(e,t){let n={...e,diagnosticId:c(),events:[],liveWrittenEventCount:0,phaseCounts:new Map,sensitiveValues:new Set,ensuredDirectories:new Set};return await o.run(n,t)}function u(e){let t=o.getStore();t&&Object.assign(t,e)}function d(){let e=o.getStore();if(!e)return{};let{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}=e;return{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}}function f(e){if(!e)return;let t=o.getStore();t&&(t.sensitiveValues.add(e),t.sortedSensitiveValues=void 0)}function p(e){let t=o.getStore();if(!t)return 0;let n=0;for(let r of e)n+=t.phaseCounts.get(r)??0;return n}function m(e){let t=o.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??`info`,phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?v(t,e.data):void 0};if(t.events.push(n),t.phaseCounts.set(e.phase,(t.phaseCounts.get(e.phase)??0)+1),!t.debug&&!t.traceLogPath)return;let r=`${JSON.stringify(n)}\n`;try{t.debug&&t.logPath&&(x(t,t.logPath,r),t.liveWrittenEventCount=t.events.length),t.traceLogPath&&x(t,t.traceLogPath,r),t.debug&&!t.logPath&&!t.traceLogPath&&process.stderr.write(`[agent-device][diag] ${r}`)}catch{}}async function h(e,t,n){let r=Date.now();try{let i=await t();return m({level:`info`,phase:e,durationMs:Date.now()-r,data:n}),i}catch(t){throw m({level:`error`,phase:e,durationMs:Date.now()-r,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function g(e={}){let r=o.getStore();if(!r||!e.force&&!r.debug&&!r.flushOnSuccess||r.events.length===0)return null;let i=_(r);try{if(r.logPath){let e=r.events.slice(r.liveWrittenEventCount);if(e.length>0){let t=e.map(e=>JSON.stringify(y(e,i)));x(r,r.logPath,`${t.join(`
2
- `)}\n`)}let t=r.logRecord;return r.events=[],r.liveWrittenEventCount=0,{path:r.logPath,...t?{ref:t}:{}}}let e=b(r.session??`default`),o=new Date().toISOString().slice(0,10),s=t.join(a.homedir(),`.agent-device`,`logs`,e,o);n.mkdirSync(s,{recursive:!0});let c=new Date().toISOString().replaceAll(/[:.]/g,`-`),l=t.join(s,`${c}-${r.diagnosticId}.ndjson`),u=r.events.map(e=>JSON.stringify(y(e,i)));return n.writeFileSync(l,`${u.join(`
3
- `)}\n`),r.events=[],{path:l}}catch{return null}}function _(e){return e.sortedSensitiveValues??=[...e.sensitiveValues].sort((e,t)=>t.length-e.length),e.sortedSensitiveValues}function v(t,n){return y(e(n),_(t))}function y(e,t){return typeof e==`string`?t.reduce((e,t)=>e.replaceAll(t,`[REDACTED]`),e):Array.isArray(e)?e.map(e=>y(e,t)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,y(n,t)]))}function b(e){return e.replaceAll(/[^a-zA-Z0-9._-]/g,`_`)}function x(e,r,i){let a=t.dirname(r);e.ensuredDirectories.has(a)||(n.mkdirSync(a,{recursive:!0}),e.ensuredDirectories.add(a)),n.appendFileSync(r,i,`utf8`)}export{d as a,h as c,g as i,l,s as n,f as o,m as r,u as s,p as t};
1
+ import{it as e}from"./sdk-contracts.js";import{AsyncLocalStorage as t}from"node:async_hooks";import n from"node:crypto";import r from"node:fs";import i from"node:os";import a from"node:path";const o=new t;function s(){return n.randomBytes(8).toString(`hex`)}function c(){return`${Date.now().toString(36)}-${n.randomBytes(4).toString(`hex`)}`}async function l(e,t){let n={...e,diagnosticId:c(),events:[],liveWrittenEventCount:0,phaseCounts:new Map,sensitiveValues:new Set,ensuredDirectories:new Set};return await o.run(n,t)}function u(e){let t=o.getStore();t&&Object.assign(t,e)}function d(){let e=o.getStore();if(!e)return{};let{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}=e;return{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}}function f(e){if(!e)return;let t=o.getStore();t&&(t.sensitiveValues.add(e),t.sortedSensitiveValues=void 0)}function p(e){let t=o.getStore();if(!t)return 0;let n=0;for(let r of e)n+=t.phaseCounts.get(r)??0;return n}function m(e){let t=o.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??`info`,phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?v(t,e.data):void 0};if(t.events.push(n),t.phaseCounts.set(e.phase,(t.phaseCounts.get(e.phase)??0)+1),!t.debug&&!t.traceLogPath)return;let r=`${JSON.stringify(n)}\n`;try{t.debug&&t.logPath&&(x(t,t.logPath,r),t.liveWrittenEventCount=t.events.length),t.traceLogPath&&x(t,t.traceLogPath,r),t.debug&&!t.logPath&&!t.traceLogPath&&process.stderr.write(`[agent-device][diag] ${r}`)}catch{}}async function h(e,t,n){let r=Date.now();try{let i=await t();return m({level:`info`,phase:e,durationMs:Date.now()-r,data:n}),i}catch(t){throw m({level:`error`,phase:e,durationMs:Date.now()-r,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function g(e={}){let t=o.getStore();if(!t||!e.force&&!t.debug&&!t.flushOnSuccess||t.events.length===0)return null;let n=_(t);try{if(t.logPath){let e=t.events.slice(t.liveWrittenEventCount);if(e.length>0){let r=e.map(e=>JSON.stringify(y(e,n)));x(t,t.logPath,`${r.join(`
2
+ `)}\n`)}let r=t.logRecord;return t.events=[],t.liveWrittenEventCount=0,{path:t.logPath,...r?{ref:r}:{}}}let e=b(t.session??`default`),o=new Date().toISOString().slice(0,10),s=a.join(i.homedir(),`.agent-device`,`logs`,e,o);r.mkdirSync(s,{recursive:!0});let c=new Date().toISOString().replaceAll(/[:.]/g,`-`),l=a.join(s,`${c}-${t.diagnosticId}.ndjson`),u=t.events.map(e=>JSON.stringify(y(e,n)));return r.writeFileSync(l,`${u.join(`
3
+ `)}\n`),t.events=[],{path:l}}catch{return null}}function _(e){return e.sortedSensitiveValues??=[...e.sensitiveValues].sort((e,t)=>t.length-e.length),e.sortedSensitiveValues}function v(t,n){return y(e(n),_(t))}function y(e,t){return typeof e==`string`?t.reduce((e,t)=>e.replaceAll(t,`[REDACTED]`),e):Array.isArray(e)?e.map(e=>y(e,t)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,y(n,t)]))}function b(e){return e.replaceAll(/[^a-zA-Z0-9._-]/g,`_`)}function x(e,t,n){let i=a.dirname(t);e.ensuredDirectories.has(i)||(r.mkdirSync(i,{recursive:!0}),e.ensuredDirectories.add(i)),r.appendFileSync(t,n,`utf8`)}export{d as a,h as c,g as i,l,s as n,f as o,m as r,u as s,p as t};
@@ -1 +1,4 @@
1
- import{N as e}from"./sdk-contracts.js";import{T as t,d as n,l as r}from"./sdk-device.js";import{c as i}from"./diagnostics.js";import"./diagnostics2.js";import{n as a,r as o}from"./device-isolation.js";import{a as s,i as c,r as l}from"./device-inventory-context.js";import{AsyncLocalStorage as u}from"node:async_hooks";async function d(e){let{resolveInventoryDeviceSelection:t}=await import(`./device-selection-resolver.js`).then(e=>e.t);return await t(e)}const f=new u;function p(t,n){return!r(n)&&t instanceof e&&t.code===`DEVICE_NOT_FOUND`}function m(e,t){return!r(e)&&(!e.platform||e.platform===`apple`||e.platform===`ios`)&&e.target!==`desktop`&&(!t||t.kind===`device`)}async function h(e,t={}){return(await g(e,t)).device}async function g(e,t={}){let r={...y(e),androidAvdSelection:t.androidAvdSelection??`running-only`},{iosSimulatorSetPath:a,...o}=r,s=C(r,t),l={platform:r.platform,target:e.target,cacheHit:!1};return await i(`resolve_target_device`,async()=>{let e=x(s);if(e)return l.cacheHit=!0,e;let i=await c(r),u=[...i.devices];if(n(o.platform)&&i.source===`local`){let e=await _(u,o,{simulatorSetPath:a,appleSimulatorAppTarget:t.appleSimulatorAppTarget});return S(s,e)}return S(s,await d({devices:u,selector:o,source:i.source}))},l)}async function _(t,n,r){let i;try{i=await d({devices:t,selector:n,source:`local`,appleSimulatorAppTarget:r.appleSimulatorAppTarget})}catch(e){if(!p(e,n))throw e}let a=await v(n,r,i?.device);if(a)return a;if(i)return i;throw new e(`DEVICE_NOT_FOUND`,`No devices found`,{selector:n})}async function v(e,t,n){if(m(e,n))try{return await d({devices:await l({platform:e.platform??`ios`,target:e.target,iosSimulatorSetPath:t.simulatorSetPath,kind:`simulator`}),selector:e,source:`local`})}catch(e){if(s(e))throw e;return}}function y(n){let r=n.platform;if(n.target&&!r)throw new e(`INVALID_ARGS`,`Device target selector requires --platform. Use --platform ios|macos|android|vega|linux|apple with --target mobile|tv|desktop.`);let i=t({simulatorSetPath:o(n.iosSimulatorDeviceSet),platform:r,target:n.target}),s=a(n.androidDeviceAllowlist);return{platform:r,target:n.target,deviceName:n.device,udid:n.udid,serial:n.serial,leaseId:n.leaseId,leaseProvider:n.leaseProvider,deviceKey:n.deviceKey,clientId:n.clientId,iosSimulatorSetPath:i,androidSerialAllowlist:s?Array.from(s).sort():void 0}}async function b(e){return f.getStore()?await e():await f.run(new Map,e)}function x(e){let t=f.getStore()?.get(e);if(t)return{...t,device:{...t.device}}}function S(e,t){return f.getStore()?.set(e,{...t,device:{...t.device}}),t}function C(e,t){let{appleSimulatorAppTarget:n,...r}=t;return JSON.stringify({request:e,options:r})}export{b as i,h as n,g as r,y as t};
1
+ import{P as e,it as t}from"./sdk-contracts.js";import{v as n}from"./sdk-batch-runner.js";import{a as r,c as i,r as a}from"./diagnostics.js";import"./diagnostics2.js";import{E as o,a as s,d as c,i as l,l as ee,n as te,w as ne}from"./sdk-device.js";import{$n as re,S as ie,er as ae,ln as u,m as oe,sn as se}from"./sdk-batch.js";import{t as ce}from"./recording-scope.js";import{a as le}from"./scroll-gesture.js";import{_ as d,c as ue,d as de,g as fe,h as pe,i as me,l as he,m as ge,o as _e,p as f,s as ve,u as p,y as ye}from"./script.js";import{C as be,D as xe,E as Se,F as Ce,M as we,O as Te,P as Ee,S as De,T as Oe,a as ke,b as Ae,d as je,i as Me,j as Ne,k as Pe,l as Fe,o as Ie,r as Le,s as Re,v as m,w as h,x as ze,y as Be}from"./provider-device-admission.js";import{n as g,t as _}from"./catalog.js";import{o as Ve,t as v}from"./back-mode.js";import{t as He}from"./session.js";import{r as Ue}from"./success-text.js";import{t as We}from"./click-button.js";import"./device.js";import{r as Ge,t as Ke}from"./device-rotation.js";import{A as qe}from"./owner-identity.js";import"./file.js";import{t as Je}from"./tv-remote.js";import{n as Ye,r as Xe,t as Ze}from"./session-paths.js";import{i as Qe,n as $e,r as et}from"./session-artifact-paths.js";import{i as tt,r as nt,t as rt}from"./session-repair-tombstone.js";import{t as it}from"./keyboard-actions.js";import{n as at,r as ot}from"./device-isolation.js";import{a as st,i as ct,r as lt}from"./device-inventory-context.js";import{AsyncLocalStorage as ut}from"node:async_hooks";import{createHash as dt}from"node:crypto";import y from"node:fs";import b from"node:path";import{StringDecoder as ft}from"node:string_decoder";function pt(e,t={}){let n=[e.command];return e.command===`snapshot`?de(n,e):e.command===`open`?me(n,e):e.command===`runtime`?ue(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?ve(n,e):e.command===`screenshot`?he(n,e):_e(n,e),n.join(` `)}function mt(e){return e.targetEvidences?[re(e.targetEvidences)]:e.targetEvidence?[ae(e.targetEvidence)]:[]}function x(e){return e?.scriptPublication??m}function ht(e,t){let n=x(e),r=typeof t.saveScript==`string`?Ze(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath;e.scriptPublication=Ae(n,{requested:{path:r,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function gt(e){e.scriptPublication=De(x(e))}function _t(e){e.scriptPublication=Se(x(e))}function vt(e,t){e.scriptPublication=xe(x(e),t)}function yt(e){e.scriptPublication=Be(x(e))}function bt(e,t){let n=x(e);return n.kind===`repair`&&n.closeReceipt===t}function xt(e){return x(e).kind===`repair`}function St(e){return Oe(x(e))}function S(e){return Te(x(e))}function Ct(e){return Pe(x(e))}function wt(e,t){if(t.flags?.noRecord||Pt(e,t))return;t.flags&&Fe(e,t.flags);let n=Et(t),r=kt(e,Dt(t,n));n&&Ot(e,n);let i={ts:Date.now(),command:r.command,positionals:r.positionals,runtime:r.runtime,flags:It(r.flags),result:r.result,...r.targetEvidence?{targetEvidence:r.targetEvidence}:{},...r.targetEvidences?{targetEvidences:r.targetEvidences}:{}};return e.actions.push(i),a({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),i}function Tt(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 Et(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return;let t=Ce(e.flags.recordAs),n=Ee(t);return{literal:we({ts:0,command:e.command,positionals:e.positionals,flags:e.flags}),placeholder:n}}function Dt(e,t){if(!t)return e;let{literal:n,placeholder:r}=t;return{...e,positionals:jt(e.positionals,r),result:Le(e.result,n,r),targetEvidence:Me(e.targetEvidence,n,r)}}function Ot(e,t){t.literal.trim()&&(e.recordedFillLiterals??=new Map,!e.recordedFillLiterals.has(t.literal)&&e.recordedFillLiterals.set(t.literal,t.placeholder))}function kt(e,t){let n=e.recordedFillLiterals;if(!n||n.size===0)return t;let r=ke(t.result,n),i=(t.targetEvidenceMode??`action`)===`landmark`?At(t.targetEvidence,n):C(t.targetEvidence,n),a=t.targetEvidences?{source:C(t.targetEvidences.source,n),destination:C(t.targetEvidences.destination,n)}:t.targetEvidences;return{...t,result:r,targetEvidence:i,targetEvidences:a}}function At(e,t){return e&&(Re(e,t)?void 0:e)}function C(e,t){return!e||!Re(e,t)?e:{...Ie(e,t),verification:`unverifiable`}}function jt(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 Mt=new Set([`snapshot`,`get`,`is`,`find`]);function Nt(e){return e.internal?.replayPlanStep!==!0&&Mt.has(e.command)}function Pt(e,t){return!t.interactiveObservation||S(e)===void 0?!1:t.flags?.record!==!0}const Ft=Ve();function It(e){if(!e)return{};let t={};for(let n of Ft){let r=e[n];r!==void 0&&(t[n]=r)}return t}function w(e){return b.join(e,`idle-expiry.json`)}function Lt(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`&&!(!Rt(n.expiredAtMs)||!Rt(n.idleExpiryMs))&&(n.deviceKey===void 0||typeof n.deviceKey==`string`))return n}function Rt(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0}function zt(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())ie({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=e);if(!t.slice(r+1).some(Gt))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 Bt(t){for(let n of t){if(Vt(n)){Ht(n);continue}let t=Kt(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`&&ie(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||!u(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 Vt(e){return Ut(e)!==void 0}function Ht(t){let n=Ut(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||!u(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 Ut(e){return e.command===`gesture`?ye(e.positionals):void 0}function Wt(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 Gt(e){if(e.command!==`wait`)return!1;let t=se(e.positionals);return t?.kind!==`selector`||!u(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function Kt(e){if(e.command===`get`)return e.positionals[1];if(fe(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&qt(t)&&qt(n)?void 0:t}}function qt(e){return e.trim().length>0&&Number.isFinite(Number(e))}function Jt(e){let t=e.scriptPublication??m;return t.kind===`repair`?t.status===`committed`||!h(t):!1}function Yt(e){return!be(e.scriptPublication??m)||Jt(e)}var Xt=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=xt(e),r=t?.publication===`active`,i;try{if(Yt(e))return{written:!1};let a=Zt(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=b.dirname(i);return y.existsSync(o)||y.mkdirSync(o,{recursive:!0}),en({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=ze(e.scriptPublication??m)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return Qt({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=Ne(e.scriptPublication??m);if(t)return Ze(t);let n=Xe(e.name),r=new Date(e.createdAt).toISOString().replaceAll(/[:.]/g,`-`);return b.join(this.sessionsDir,`${n}-${r}.ad`)}};function Zt(e,t){let n=tn(e,{strictPortableRefs:t.activePublication});return t.activePublication&&zt(n),{script:fn(e,n,t.appendCompleteSentinel),actionCount:n.length}}function Qt(t){let{session:n,error:r,scriptPath:i,repairArmed:o,activePublication:s}=t;if(a({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),o)return{written:!1,error:$t(r,i)};if(s)return{written:!1,error:Wt(r,i)};if(r instanceof e)throw r;return{written:!1}}function $t(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 en(t){let{scriptPath:n,script:r,force:i}=t;try{qe({destination:n,contents:r,publish:i?`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 tn(e,t={}){let n=S(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=an(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&nn(n);let o=dn(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&Bt(a),a}function nn(t){let n=t.command===`gesture`?ye(t.positionals??[]):void 0;if(n){rn(n);return}if(!T(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 rn(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 an(e){let t=on(e);if(!(!t||!T(e.command)))return pe(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?cn(e,t):e.command===`fill`?sn(e,t):ln(e,t)}function on(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 T(e){return fe(e)||e===`fill`||e===`get`}function sn(e,t){let n=we(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function cn(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):un(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function ln(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function un(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function dn(e,t){if(!T(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}}}function fn(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${ne(e.device)} device=${ge(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...mt(e)),r.push(pn(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
2
+ `)}\n`}function pn(e){return mn([e.command],e)||pt(e)}function mn(e,t){if(pe(t.command))return hn(e,t);if(t.command===`fill`)return gn(e,t);if(t.command===`get`)return _n(e,t)}function hn(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(f(d(n))),E(e,t),p(e,t),e.join(` `);if(t.positionals.length===1)return e.push(f(n)),p(e,t),e.join(` `)}}function gn(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(f(d(n))),E(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(f(r)),p(e,t),e.join(` `)}function _n(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(f(n)),e.push(f(d(r))),r.startsWith(`@`)&&E(e,t),e.join(` `)}function E(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(f(n))}const vn=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],yn={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function bn(e,t){let n=t??{};switch(e.command){case g.devices:return xn(n.devices);case g.apps:return Sn(n.apps,e.flags?.appsFilter);case g.boot:return Cn(`Booted`,n,!0);case g.shutdown:return Cn(`Shut down`,n,!1);case g.install:return wn(`Installed`,n);case g.reinstall:return wn(`Reinstalled`,n);case g.screenshot:return Tn(e,n);default:return{}}}function xn(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=Dn(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:In(`Found ${t.length} ${Ln(`device`,t.length)}`,i.map(e=>Pn(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function Sn(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=k(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:In(`Found ${n.length} ${Ln(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function Cn(e,t,n){let r=On(t);if(!r)return{};let i={device:r,...Nn(t),booted:n};return{summary:`${e} ${Pn(i,!1)}`,details:i}}function wn(e,t){let n=k(t.appName),r=k(t.bundleId),i=D(t,[`packageName`,`package`]),a=k(t.platform),o=k(t.launchTarget),s=D(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=Fn(n,s);if(!c)return{};let l={};return O(l,`appName`,n),O(l,`bundleId`,r),O(l,`packageName`,i),O(l,`platform`,a),o!==s&&O(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function Tn(e,t){let n=En(e,t);return n?{details:{requestedFileName:n}}:{}}function En(e,t){let n=F(e.meta?.clientArtifactPaths?.path)??F(t.path);if(n)return P(n)}function Dn(e){if(!n(e))return;let t=On(e);if(t)return{name:t,...Nn(e)}}function On(e){let t=D(e,[`name`,`deviceName`,`device`]);return!t||!kn(e,t)?t:jn(e)}function kn(e,t){let n=An(t);return vn.some(t=>{let r=k(e[t]);return r!==void 0&&An(r)===n})}function An(e){return e.toLowerCase()}function jn(e){let t=k(e.appleOs),n=k(e.platform),r=k(e.kind),i=Mn(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function Mn(e,t){let n=e??t;if(!(!n||!Object.hasOwn(yn,n)))return yn[n]}function Nn(e){let t=k(e.platform),n=k(e.appleOs),r=k(e.kind),i=k(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function Pn(e,t){let n=k(e.name)??k(e.device)??`device`,r=k(e.platform),i=k(e.appleOs),a=[r,i===r?void 0:i,k(e.kind),k(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function Fn(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function D(e,t){for(let n of t){let t=k(e[n]);if(t)return t}}function O(e,t,n){n&&(e[t]=n)}function In(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function Ln(e,t){return t===1?e:`${e}s`}function k(e){let t=F(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function A(e){return k(e)}function j(e){return typeof e==`boolean`?e:void 0}function M(e,t){let n=A(e);return n&&t.includes(n)?n:void 0}function N(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function P(e){let t=F(e);return t?k(t.split(/[\\/]/).at(-1)):void 0}function F(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function I(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const Rn=[`up`,`down`,`left`,`right`],zn=[`top`,`bottom`];function Bn(e){return`${e.command===g.reinstall?`Reinstalled`:`Installed`} ${Wn(e.result??{})??`app`}`}function Vn(e){let t=e.result??{};switch(e.command){case g.scroll:return Kn(t);case g.screenshot:return Yn(t);case g.home:return`Went home`;case g.back:return Zn(t);case g.appSwitcher:return`Opened app switcher`;case g.actionButton:return`Pressed Action Button`;case g.orientation:return $n(t);case g.fold:return Qn(t);case g.viewport:return er(t);case g.clipboard:return tr(t);case g.keyboard:return nr(t);case g.tvRemote:return ar(t);case g.gesture:return or(t);case g.swipe:return sr(t);case g.trace:return lr(`trace`,e);case g.record:return lr(`recording`,e);default:return}}function Hn(e){let t=e.result??{};switch(e.command){case g.scroll:return N({direction:M(t.direction,Rn),edge:M(t.edge,zn),passes:I(t.passes),amount:I(t.amount),pixels:I(t.pixels),durationMs:I(t.durationMs),x1:I(t.x1),y1:I(t.y1),x2:I(t.x2),y2:I(t.y2)});case g.screenshot:return N({requestedFileName:Xn(t)});case g.back:return N({mode:M(t.mode,v)});case g.orientation:return N({orientation:M(t.orientation,Ke)});case g.fold:return N({pose:M(t.pose,Ge)});case g.viewport:return N({width:I(t.width),height:I(t.height)});case g.clipboard:return N({action:M(t.action,[`read`,`write`])});case g.keyboard:return ir(t);case g.tvRemote:return N({button:M(t.button,Je),durationMs:I(t.durationMs)});case g.gesture:case g.swipe:return cr(t);case g.trace:case g.record:return N({action:M(t.action,[`start`,`stop`]),fileName:dr(e),showTouches:j(t.showTouches)});default:return{}}}function Un(e,t){if(e.command!==g.screenshot)return t;let n=En(e,t);return n?{...t,requestedFileName:n}:t}function Wn(e){let t=A(e.appName),n=fr(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??Gn(e)}function Gn(e){let t=A(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function Kn(e){let t=M(e.direction,Rn),n=M(e.edge,zn),r=I(e.passes);return n?qn(n,r):t?Jn(t,e):`Scrolled`}function qn(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function Jn(e,t){let n=I(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=I(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function Yn(e){let t=Xn(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function Xn(e){return P(e.requestedFileName)??P(e.path)}function Zn(e){return M(e.mode,v)===`system`?`Went back using system navigation`:`Went back`}function Qn(e){let t=M(e.pose,Ge);return t?`Folded to ${t}`:`Changed fold pose`}function $n(e){let t=M(e.orientation,Ke);return t?j(e.confirmed)===!1?`Requested ${t} (unconfirmed)`:`Rotated to ${t}`:`Changed orientation`}function er(e){let t=I(e.width),n=I(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function tr(e){let t=M(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function nr(e){let t=F(e.action);if(!t||!it(t))return`Used keyboard`;if(t===`dismiss`)return rr(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=j(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function rr(e){return j(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function ir(e){let t=F(e.action);return N({action:t&&it(t)?t:void 0,platform:M(e.platform,[`ios`,`android`]),visible:j(e.visible),wasVisible:j(e.wasVisible),dismissed:j(e.dismissed),attempts:I(e.attempts),mechanism:M(e.mechanism,[`dismissKey`])})}function ar(e){let t=M(e.button,Je);return t?`Pressed TV remote ${t}`:`Used TV remote`}function or(e){let t=M(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function sr(e){let t=I(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function cr(e){return N({kind:M(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:I(e.durationMs),pointerCount:I(e.pointerCount),x1:I(e.x1),y1:I(e.y1),x2:I(e.x2),y2:I(e.y2),count:I(e.count),pauseMs:I(e.pauseMs),pattern:M(e.pattern,[`one-way`,`ping-pong`]),scale:I(e.scale)})}function lr(e,t){let n=ur(e,M(t.result?.action,[`start`,`stop`])),r=dr(t);return r?`${n} ${r}`:n}function ur(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function dr(e){let t=e.result??{};return P(t.requestedFileName)??P(t.outPath)??P(t.path)??P(e.positionals[1])}function fr(e,t){for(let n of t){let t=A(e[n]);if(t)return t}}function pr(e){switch(e.command){case g.open:return`Opened ${L(e)??`session`}`;case g.close:return`Closed ${A(e.result?.session)??`session`}`;case g.click:case g.press:return`Tapped ${L(e)??`target`}`;case g.longPress:return`Long pressed ${L(e)??`target`}`;case g.hover:return`Hovered ${L(e)??`target`}`;case g.fill:return`Filled ${L(e)??`target`}`;case g.type:return`Typed text`;case g.install:case g.reinstall:case _.installSource:return Bn(e);default:return Vn(e)??`Ran ${e.command}`}}function mr(e){return N({command:e.command,positionals:Cr(e),flags:Fr(e),...hr(e),...gr(e),..._r(e),...Hn(e)})}function hr(e){if(!vr(e.command))return{};let t=e.result??{};return N({ref:H(t),targetLabel:L(e),selectorChainLength:jr(t.selectorChain)?.length,x:I(t.x),y:I(t.y),x2:I(t.x2),y2:I(t.y2),durationMs:I(t.durationMs)})}function gr(e){if(!yr(e.command))return{};let t=e.result??{};return N({platform:M(t.platform,s),target:M(t.target,te),appName:A(t.appName),appBundleId:A(t.appBundleId),bundleId:A(t.bundleId),packageName:A(t.packageName),launchTarget:A(t.launchTarget)})}function _r(e){let t=e.result??{};return e.command===g.snapshot?Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}:e.command!==g.wait&&e.command!==g.find&&e.command!==g.get&&e.command!==g.is?{}:N({waitedMs:I(t.waitedMs),found:j(t.found)})}function vr(e){return e===g.click||e===g.press||e===g.longPress||e===g.hover||e===g.focus||e===g.fill}function yr(e){return e===g.open||e===g.install||e===g.reinstall||e===_.installSource}function L(e){let t=e.result??{};return br(t)??xr(t)??Sr(t)??kr(e.positionals[0])}function br(e){let t=H(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function xr(e){let t=I(e.x),n=I(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function Sr(e){return A(e.appName)??A(e.appBundleId)??A(e.bundleId)??A(e.packageName)}function Cr(e){if(e.positionals.length!==0)return e.command===g.type?[z(`text`)]:e.command===g.fill?wr(e):e.command===g.find?Tr(e):e.command===g.clipboard?Er(e):e.command===g.push?Dr(e,`app`,`payload`):e.command===g.triggerAppEvent?Dr(e,`event`,`payload`):e.positionals.map(R)}function wr(e){let t=z(`text`),n=e.result??{},r=H(n);if(r)return[`@${r}`,t];if(A(n.selector))return[z(`target`),t];let i=I(n.x),a=I(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function Tr(e){let t=+!!Ar(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],z(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,z(`text`)]:[...r,...e.positionals.slice(n).map(Or)]:r}function Er(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,z(`text`)]:e.positionals.map(R)}function Dr(e,t,n){let[r,i,...a]=e.positionals;return[...r?[z(t)]:[],...i?[z(n)]:[],...a.map(R)]}function Or(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:R(e)}function R(e){return kr(e)??z(`arg`)}function kr(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function z(e){return`<${e}>`}function Ar(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function jr(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const Mr={enums:[{source:`platform`,values:l},{source:`target`,values:te}]},Nr={booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}]},Pr={[g.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:He}]},[g.click]:B(),[g.press]:B(),[g.longPress]:B(),[g.hover]:B(),[g.fill]:Lr(),[g.type]:Lr(),[g.scroll]:{numbers:[{source:`pixels`},{source:`durationMs`}]},[g.gesture]:Rr(),[g.swipe]:Rr(),[g.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[g.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[g.back]:{enums:[{source:`backMode`,output:`mode`,values:v}]},[g.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:ce}]},[g.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[g.boot]:{booleans:[{source:`headless`}]},[g.close]:{booleans:[{source:`shutdown`}]}};function Fr(e){let t=e.flags??{},n={},r=Object.hasOwn(Pr,e.command)?Pr[e.command]:void 0;return V(n,t,Mr),V(n,t,r),V(n,t,Ir(e.command)),Object.keys(n).length>0?n:void 0}function Ir(e){return oe(e)?Nr:void 0}function B(){return{booleans:[{source:`doubleTap`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`}],enums:[{source:`clickButton`,values:We}]}}function Lr(){return{numbers:[{source:`delayMs`}]}}function Rr(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:le}]}}function V(e,t,n){n&&(zr(e,t,n.booleans??[]),Br(e,t,n.numbers??[]),Vr(e,t,n.enums??[]))}function zr(e,t,n){for(let r of n)Hr(e,r.output??r.source,t[r.source])}function Br(e,t,n){for(let r of n)Ur(e,r.output??r.source,t[r.source])}function Vr(e,t,n){for(let r of n)Wr(e,r.output??r.source,t[r.source],r.values)}function H(e){let t=A(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function Hr(e,t,n){typeof n==`boolean`&&(e[t]=n)}function Ur(e,t,n){let r=I(n);r!==void 0&&(e[t]=r)}function Wr(e,t,n,r){let i=M(n,r);i!==void 0&&(e[t]=i)}const Gr=65536;function Kr(e){return dt(`sha256`).update(e,`utf8`).digest(`hex`).slice(0,32)}function U(e,t){let n=Xr(e);if(n===void 0)return!1;try{let e=Jr(t),r=Buffer.allocUnsafe(Gr),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 qr(e){let t=await Zr(e);if(t===void 0)return{lineCount:0,firstLineDigest:void 0};let n={lineCount:0,firstLineDigest:void 0};try{let e=Jr(e=>{n.lineCount===0&&(n.firstLineDigest=Kr(e)),n.lineCount+=1}),r=Buffer.allocUnsafe(Gr);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 W(e){let t;return U(e,e=>(t=Kr(e),!1)),t}function Jr(e){let t=new ft(`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
+ `);t!==-1;t=a.indexOf(`
4
+ `,o)){if(Yr(a.slice(o,t),e)===!1)return r=!0,!1;o=t+1}return n=a.slice(o),!0},end(){r||Yr(`${n}${t.end()}`,e)}}}function Yr(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0)return t(n)}function Xr(e){try{return y.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Zr(e){try{return await y.promises.open(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}const Qr=5242880;function $r(e=process.env){let t=e.AGENT_DEVICE_EVENT_LOG_MAX_BYTES?.trim();if(t===void 0||!/^\d+$/.test(t))return Qr;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:Qr}function G(e){return`${e}.1`}function K(e){return`${e}.window.json`}function ei(e){let t;for(let n=0;n<3;n+=1){let n=J(e);try{let t=ti(e);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 ti(e){let t=G(e),n=X(e);if(n===`unverifiable`)throw q(e,`window file is invalid`);if(n===void 0)return ni(e,t);let r=n.at(-1);if(!r)throw q(e,`window file records no generation`);let i=ui(e),a=ri(e,r),o=[],s=ii({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 ni(e,t){if(W(t)!==void 0)throw q(e,`a rotated event log exists with no window record`);return{files:ui(e)?[{path:e,firstLineIndex:0}]:[],earliestCursor:0}}function ri(e,t){let n=W(e);return n!==void 0&&n===t.firstLineDigest?t.firstLineIndex:t.firstLineIndex+t.lineCount}function ii(e){let{eventLogPath:t,rotatedPath:n,sidecar:r,activeStart:i,activeExists:a}=e,o=W(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=si(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 ai(e,t){let n=di(e);if(!n||n.size<t)return!1;let r=X(e);if(r===`unverifiable`)return await y.promises.rename(e,G(e)),!0;let i=await qr(e);if(i.firstLineDigest!==void 0){let t=r??[],n=t.at(-1),a=n&&n.firstLineDigest===i.firstLineDigest?n:{firstLineIndex:n?n.firstLineIndex+n.lineCount:0,lineCount:i.lineCount,firstLineDigest:i.firstLineDigest};await li(e,(a===n?t:[...t,a]).slice(-2))}return await y.promises.rename(e,G(e)),!0}function oi(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 q(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}, ${G(t)}, and ${K(t)} to restart the timeline, or read the files directly.`})}function si(e){let t=0;return U(e,()=>{t+=1}),t}function J(e){return[Y(K(e)),Y(e),Y(G(e))].join(`|`)}function Y(e){try{let t=y.lstatSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return`absent`}}function X(e){let t;try{t=y.readFileSync(K(e),`utf8`)}catch(e){return e.code===`ENOENT`?void 0:`unverifiable`}try{let e=JSON.parse(t);if(!n(e)||e.version!==2)return`unverifiable`;let{generations:r}=e;if(!Array.isArray(r)||r.length===0)return`unverifiable`;let i=r.map(ci);return i.every(e=>e!==void 0)?i:`unverifiable`}catch{return`unverifiable`}}function ci(e){if(!n(e))return;let{firstLineIndex:t,lineCount:r,firstLineDigest:i}=e;if(!(!Number.isSafeInteger(t)||t<0)&&!(!Number.isSafeInteger(r)||r<0)&&typeof i==`string`&&i.length!==0)return{firstLineIndex:t,lineCount:r,firstLineDigest:i}}async function li(e,t){let n=K(e),r=`${n}.${process.pid}.tmp`;await y.promises.writeFile(r,JSON.stringify({version:2,generations:t}),`utf8`),await y.promises.rename(r,n)}function ui(e){return di(e)!==void 0}function di(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=new Map,fi=new Set;function pi(e){return b.join(e,`events.ndjson`)}function mi(e){return e.command!==g.events}function hi(e,n,r){let i=t({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});_i(e,`${JSON.stringify(i)}\n`)}async function gi(e){await(e?Z.get(e):Promise.all(Z.values()))}function _i(e,t){let n=(Z.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await vi(e),await ai(e,$r()),await y.promises.appendFile(e,t,`utf8`)}).catch(t=>{a({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{Z.get(e)===n&&Z.delete(e)});Z.set(e,n)}async function vi(e){let t=b.dirname(e);if(!fi.has(t))try{await y.promises.mkdir(t,{recursive:!0}),fi.add(t)}catch(t){throw a({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function yi(e,t,n){hi(e,t,{kind:`action.recorded`,requestId:r().requestId,command:n.command,summary:pr(n),details:mr(n)})}function bi(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??r().requestId,command:t.command,summary:`Started ${t.command}`}}function xi(e){let{req:t,response:n,durationMs:i}=e;if(n.ok){let e=bn(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??r().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:i,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??r().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:i,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function Si(e,t={}){let n=wi(t.cursor),r=Ti(t.limit),i=ei(e);oi(n,i.earliestCursor);let a=Ci(i.files,n,r),o=a.lines.flatMap(e=>{let t=Ei(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:o,...a.nextCursor===void 0?{}:{nextCursor:String(a.nextCursor)}}}function Ci(e,t,n){let r=[],i;for(let a of e){let e=a.firstLineIndex;if(U(a.path,a=>{if(e>=t+n)return i=t+n,!1;e>=t&&r.push(a),e+=1}),i!==void 0)break}return{lines:r,...i===void 0?{}:{nextCursor:i}}}function wi(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 Ti(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 Ei(e){try{let t=Di(JSON.parse(e));return t?Oi(t):void 0}catch{return}}function Di(e){if(n(e)&&e.version===1&&typeof e.ts==`string`&&typeof e.session==`string`&&ki(e.kind))return e}function Oi(e){let t=n(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}:{},...Ai(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function ki(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function Ai(e){return e===`ok`||e===`error`}const ji=36e5;var Mi=class{sessions=new Map;acceptingSessions=!0;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new Xt(e)}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:`daemon_shutting_down`,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};return this.sessions.set(e,n),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){return this.resolveCurrent(e)?(this.runtimeHints.delete(e.address),this.sessions.delete(e.address)):!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(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=wt(this.requireCurrent(e),t);n&&yi(this.resolveEventLogPath(e.address),e.address,n)}recordEvent(e,t){hi(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return Si(this.resolveEventLogPath(e),t)}async flushEvents(e){await gi(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.requireCurrent(e),r=this.scriptWriter.write(n,t);return r.written&&a({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:je(t,void 0)});St(t)&&(!n.written&&n.error?this.writeRepairTombstone(e,ji,{code:String(n.error.code),message:n.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){let t=this.requireCurrent(e),n=t.scriptPublication??m;h(n)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:t.name,...Ue(`Closed: ${t.name}`)}})}writeRepairTombstone(e,t=ji,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,...Ct(r)?{sourcePath:Ct(r)}:{},...n?{commitFailure:n}:{}};y.writeFileSync(this.repairTombstonePath(e.address),`${JSON.stringify(a)}\n`)}catch(t){a({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.address,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return nt(this.repairTombstonePath(e),e)}clearRepairTombstone(e){rt(this.repairTombstonePath(e),e)}noteSessionActivity(e,t=Date.now()){let n=this.get(e);n&&(n.lastActivityAtMs=t)}writeIdleExpiryTombstone(e,t){try{y.mkdirSync(this.resolveSessionDir(e),{recursive:!0}),y.writeFileSync(w(this.resolveSessionDir(e)),`${JSON.stringify(t)}\n`)}catch(t){a({level:`warn`,phase:`idle_expiry_tombstone_write_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}readIdleExpiryTombstone(e){if(!Ye(e))return;let t=Lt(w(this.resolveSessionDir(e)));return t?.owner===e?t:void 0}clearIdleExpiryTombstone(e){try{y.rmSync(w(this.resolveSessionDir(e)),{force:!0})}catch(t){a({level:`warn`,phase:`idle_expiry_tombstone_clear_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}repairTombstonePath(e){return tt(this.resolveSessionDir(e))}defaultTracePath(e){let t=Xe(e.name),n=new Date().toISOString().replaceAll(/[:.]/g,`-`);return b.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(e){return Qe(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 $e(this.sessionsDir,e)}resolveAppLogPidPath(e){return et(this.sessionsDir,e)}resolveEventLogPath(e){return pi(this.resolveSessionDir(e))}};async function Q(e){let{resolveInventoryDeviceSelection:t}=await import(`./device-selection-resolver.js`).then(e=>e.t);return await t(e)}const $=new ut;function Ni(t,n){return!ee(n)&&t instanceof e&&t.code===`DEVICE_NOT_FOUND`}function Pi(e,t){return!ee(e)&&(!e.platform||e.platform===`apple`||e.platform===`ios`)&&e.target!==`desktop`&&(!t||t.kind===`device`)}async function Fi(e,t={}){return(await Ii(e,t)).device}async function Ii(e,t={}){let n={...zi(e),androidAvdSelection:t.androidAvdSelection??`running-only`},{iosSimulatorSetPath:r,...a}=n,o=Ui(n,t),s={platform:n.platform,target:e.target,cacheHit:!1};return await i(`resolve_target_device`,async()=>{let e=Vi(o);if(e)return s.cacheHit=!0,e;let i=await ct(n),l=[...i.devices];if(c(a.platform)&&i.source===`local`){let e=await Li(l,a,{simulatorSetPath:r,appleSimulatorAppTarget:t.appleSimulatorAppTarget});return Hi(o,e)}return Hi(o,await Q({devices:l,selector:a,source:i.source}))},s)}async function Li(t,n,r){let i;try{i=await Q({devices:t,selector:n,source:`local`,appleSimulatorAppTarget:r.appleSimulatorAppTarget})}catch(e){if(!Ni(e,n))throw e}let a=await Ri(n,r,i?.device);if(a)return a;if(i)return i;throw new e(`DEVICE_NOT_FOUND`,`No devices found`,{selector:n})}async function Ri(e,t,n){if(Pi(e,n))try{return await Q({devices:await lt({platform:e.platform??`ios`,target:e.target,iosSimulatorSetPath:t.simulatorSetPath,kind:`simulator`}),selector:e,source:`local`})}catch(e){if(st(e))throw e;return}}function zi(t){let n=t.platform;if(t.target&&!n)throw new e(`INVALID_ARGS`,`Device target selector requires --platform. Use --platform ios|macos|android|vega|linux|apple with --target mobile|tv|desktop.`);let r=o({simulatorSetPath:ot(t.iosSimulatorDeviceSet),platform:n,target:t.target}),i=at(t.androidDeviceAllowlist);return{platform:n,target:t.target,deviceName:t.device,udid:t.udid,serial:t.serial,leaseId:t.leaseId,leaseProvider:t.leaseProvider,deviceKey:t.deviceKey,clientId:t.clientId,iosSimulatorSetPath:r,androidSerialAllowlist:i?Array.from(i).sort():void 0}}async function Bi(e){return $.getStore()?await e():await $.run(new Map,e)}function Vi(e){let t=$.getStore()?.get(e);if(t)return{...t,device:{...t.device}}}function Hi(e,t){return $.getStore()?.set(e,{...t,device:{...t.device}}),t}function Ui(e,t){let{appleSimulatorAppTarget:n,...r}=t;return JSON.stringify({request:e,options:r})}export{St as _,Mi as a,S as b,mi as c,Nt as d,Tt as f,xt as g,bt as h,Bi as i,Cr as l,ht as m,Fi as n,xi as o,yt as p,Ii as r,bi as s,zi as t,Un as u,_t as v,gt as x,vt as y};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{r as t}from"./diagnostics.js";import{i as n}from"./exec.js";import"./diagnostics2.js";import"./command.js";import"./config.js";import{c as r}from"./devicectl.js";var i=e({appleSimulatorDisplayArgvFragment:()=>T,buildInventory:()=>y,parseCoreDeviceDisplays:()=>u,queryAppleDisplayInventory:()=>s,readPanelPower:()=>_,resolveAppleCaptureDisplay:()=>x,resolveAppleCaptureTarget:()=>S});const a=new Set([`activeOn`,`inactiveOn`,`activeDimmed`]),o=new Set([`off`]);async function s(e,t){try{let n=await r({jsonPrefix:`agent-device-apple-displays`,args:[`devicectl`,`device`,`info`,`displays`,`--device`,e.id],timeoutMs:t.timeoutMs??5e3,signal:t.signal});if(!n.ok)return c(e,n.reason,n.result.stderr.trim()),l();let i=u(n.payload);return i.length===0?(c(e,`empty-display-list`,``),l()):y(i)}catch(t){return c(e,n(t)?`probe-timed-out`:`probe-failed`,t instanceof Error?t.message:String(t)),l()}}function c(e,n,r){t({level:`warn`,phase:`apple_display_inventory_unresolved`,data:{platform:e.platform,deviceId:e.id,reason:n,...r?{detail:r}:{},...n===`command-failed`||n===`unreadable-json`?{hint:`This Xcode/CoreDevice toolchain does not report 'devicectl device info displays'. Update Xcode to a version that ships the display-information feature before targeting multi-display Apple devices.`}:{}}})}function l(){return{displays:[],multiScreen:!1,ambiguous:!1,unresolved:!0}}function u(e){let t=e?.result?.displays;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!e||typeof e!=`object`)continue;let t=d(e);t&&n.push(t)}return n}function d(e){let t=f(e);if(t)return{...t,power:_(e.backlightState,e.active),primary:e.primary===!0,currentOrientation:typeof e.currentOrientation==`string`?e.currentOrientation:`unknown`,integrated:v(e.type)}}function f(e){let t=p(e.name),n=h(e.displayId),r=g(e.pointScale),i=m(e.nativeSize);if(!(!t||n===void 0||r===void 0||!i))return{name:t,displayId:n,pointScale:r,widthPx:i.widthPx,heightPx:i.heightPx}}function p(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function m(e){if(!Array.isArray(e))return;let t=g(e[0]),n=g(e[1]);if(t!==void 0&&n!==void 0)return{widthPx:t,heightPx:n}}function h(e){return typeof e==`number`&&Number.isInteger(e)?e:void 0}function g(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function _(e,t){return typeof e==`string`?a.has(e)?`lit`:o.has(e)?`dark`:`unknown`:t===!0?`lit`:t===!1?`dark`:`unknown`}function v(e){return typeof e==`object`&&!!e&&Object.hasOwn(e,`integrated`)}function y(e){let n=e.filter(e=>e.integrated);if(n.length<2)return{displays:e,multiScreen:!1,ambiguous:!1,unresolved:!1};b(n);let r=n.filter(e=>e.power===`lit`),i=n.find(e=>e.primary),a=r.length===1,o=a?r[0]:i??r[0]??n[0],s=!a||i===void 0;return s&&t({level:`warn`,phase:`apple_display_capture_ambiguous`,data:{reason:i===void 0?`no-primary-panel`:`lit-panel-count`,litPanelCount:r.length,capturedDisplay:o.name,hint:`Panel power did not identify exactly one lit panel, so the capture names the primary panel without claiming to know which panel the device is showing. Read the device pose from the app under test with UIHinge.status.`}}),{displays:n,multiScreen:!0,activeDisplay:o,ambiguous:s,unresolved:!1}}function b(e){let n=e.find(e=>e.primary);if(!n)return;let r=e=>e.widthPx*e.heightPx,i=e.filter(e=>e!==n).reduce((e,t)=>r(t)>r(e)?t:e);r(n)<r(i)||t({level:`warn`,phase:`apple_display_primary_geometry_conflict`,data:{primaryDisplay:n.name,largestDisplay:i.name,hint:"CoreDevice reported the primary panel as at least as large as the other panel. CoreDevice `primary` still selects the capture fallback; verify the device type capabilities."}})}async function x(e,t={}){return(await S(e,t)).display}async function S(e,t={}){let n=await s(e,t);if(n.unresolved)return{};if(n.multiScreen)return n.activeDisplay?{display:n.activeDisplay}:{};let r=n.displays.find(e=>e.integrated),i=r?w(r):void 0;return i?{displayRotation:i}:{}}const C=new Map([[`rot0`,`portrait`],[`rot90`,`landscape-right`],[`rot180`,`portrait-upside-down`],[`rot270`,`landscape-left`]]);function w(e){return C.get(e.currentOrientation)}function T(e){return e?[`--display=${e.name}`]:[]}export{S as i,i as n,s as r,T as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{r as t}from"./diagnostics.js";import"./diagnostics2.js";import{i as n}from"./exec.js";import"./command.js";import"./config.js";import{c as r}from"./devicectl.js";var i=e({appleSimulatorDisplayArgvFragment:()=>T,buildInventory:()=>y,parseCoreDeviceDisplays:()=>u,queryAppleDisplayInventory:()=>s,readPanelPower:()=>_,resolveAppleCaptureDisplay:()=>x,resolveAppleCaptureTarget:()=>S});const a=new Set([`activeOn`,`inactiveOn`,`activeDimmed`]),o=new Set([`off`]);async function s(e,t){try{let n=await r({jsonPrefix:`agent-device-apple-displays`,args:[`devicectl`,`device`,`info`,`displays`,`--device`,e.id],timeoutMs:t.timeoutMs??5e3,signal:t.signal});if(!n.ok)return c(e,n.reason,n.result.stderr.trim()),l();let i=u(n.payload);return i.length===0?(c(e,`empty-display-list`,``),l()):y(i)}catch(t){return c(e,n(t)?`probe-timed-out`:`probe-failed`,t instanceof Error?t.message:String(t)),l()}}function c(e,n,r){t({level:`warn`,phase:`apple_display_inventory_unresolved`,data:{platform:e.platform,deviceId:e.id,reason:n,...r?{detail:r}:{},...n===`command-failed`||n===`unreadable-json`?{hint:`This Xcode/CoreDevice toolchain does not report 'devicectl device info displays'. Update Xcode to a version that ships the display-information feature before targeting multi-display Apple devices.`}:{}}})}function l(){return{displays:[],multiScreen:!1,ambiguous:!1,unresolved:!0}}function u(e){let t=e?.result?.displays;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!e||typeof e!=`object`)continue;let t=d(e);t&&n.push(t)}return n}function d(e){let t=f(e);if(t)return{...t,power:_(e.backlightState,e.active),primary:e.primary===!0,currentOrientation:typeof e.currentOrientation==`string`?e.currentOrientation:`unknown`,integrated:v(e.type)}}function f(e){let t=p(e.name),n=h(e.displayId),r=g(e.pointScale),i=m(e.nativeSize);if(!(!t||n===void 0||r===void 0||!i))return{name:t,displayId:n,pointScale:r,widthPx:i.widthPx,heightPx:i.heightPx}}function p(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function m(e){if(!Array.isArray(e))return;let t=g(e[0]),n=g(e[1]);if(t!==void 0&&n!==void 0)return{widthPx:t,heightPx:n}}function h(e){return typeof e==`number`&&Number.isInteger(e)?e:void 0}function g(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function _(e,t){return typeof e==`string`?a.has(e)?`lit`:o.has(e)?`dark`:`unknown`:t===!0?`lit`:t===!1?`dark`:`unknown`}function v(e){return typeof e==`object`&&!!e&&Object.hasOwn(e,`integrated`)}function y(e){let n=e.filter(e=>e.integrated);if(n.length<2)return{displays:e,multiScreen:!1,ambiguous:!1,unresolved:!1};b(n);let r=n.filter(e=>e.power===`lit`),i=n.find(e=>e.primary),a=r.length===1,o=a?r[0]:i??r[0]??n[0],s=!a||i===void 0;return s&&t({level:`warn`,phase:`apple_display_capture_ambiguous`,data:{reason:i===void 0?`no-primary-panel`:`lit-panel-count`,litPanelCount:r.length,capturedDisplay:o.name,hint:`Panel power did not identify exactly one lit panel, so the capture names the primary panel without claiming to know which panel the device is showing. Read the device pose from the app under test with UIHinge.status.`}}),{displays:n,multiScreen:!0,activeDisplay:o,ambiguous:s,unresolved:!1}}function b(e){let n=e.find(e=>e.primary);if(!n)return;let r=e=>e.widthPx*e.heightPx,i=e.filter(e=>e!==n).reduce((e,t)=>r(t)>r(e)?t:e);r(n)<r(i)||t({level:`warn`,phase:`apple_display_primary_geometry_conflict`,data:{primaryDisplay:n.name,largestDisplay:i.name,hint:"CoreDevice reported the primary panel as at least as large as the other panel. CoreDevice `primary` still selects the capture fallback; verify the device type capabilities."}})}async function x(e,t={}){return(await S(e,t)).display}async function S(e,t={}){let n=await s(e,t);if(n.unresolved)return{};if(n.multiScreen)return n.activeDisplay?{display:n.activeDisplay}:{};let r=n.displays.find(e=>e.integrated),i=r?w(r):void 0;return i?{displayRotation:i}:{}}const C=new Map([[`rot0`,`portrait`],[`rot90`,`landscape-right`],[`rot180`,`portrait-upside-down`],[`rot270`,`landscape-left`]]);function w(e){return C.get(e.currentOrientation)}function T(e){return e?[`--display=${e.name}`]:[]}export{S as i,i as n,s as r,T as t};
@@ -1 +1 @@
1
- import{p as e}from"./sdk-device.js";import{d as t}from"./owner-identity.js";import"./process.js";import{n}from"./toolchain-probe.js";import{a as r}from"./runner-client.js";import{r as i}from"./runner-xctestrun.js";async function a(){let e=await n(`xcodebuild`,[`-version`]);return e?s({selectedPath:await n(`xcode-select`,[`-p`]),versionLine:e}):u()}async function o(n,a){if(!(!e(n)||n.kind!==`simulator`)&&!(t()!==`darwin`||a.isProviderDevice(n)))return a.emitProgress(`Checking iOS runner build cache (${n.name})...`),await i(n)?{id:`ios-runner-cache`,status:`pass`,summary:`iOS runner artifact cached; first open skips the runner build`}:(r(n,{}),a.emitProgress(`Warming iOS runner build cache in the background (${n.name})...`),{id:`ios-runner-cache`,status:`pass`,summary:`iOS runner build started in the background; the first open gets faster once it completes`,hint:"Run `agent-device prepare ios-runner` to wait for a fully warmed runner instead."})}function s(e){return{id:`toolchain`,status:c(e),summary:l(e),evidence:{selectedPath:e.selectedPath??null,xcodeVersion:e.versionLine??null}}}function c(e){return e.versionLine?`pass`:`info`}function l(e){return e.versionLine?e.selectedPath?`Apple toolchain: ${e.versionLine}; xcode-select ${e.selectedPath}.`:`Apple toolchain: ${e.versionLine}; xcode-select path unavailable.`:`Apple toolchain: xcodebuild version check failed.`}function u(){return{id:`toolchain`,status:`info`,summary:`Apple toolchain: xcodebuild version check failed.`,hint:`Install/select Xcode and complete first launch/license setup if xcodebuild reports it.`,command:`xcodebuild -version`}}export{o as appleRunnerWarmupCheck,a as appleToolchainCheck};
1
+ import{p as e}from"./sdk-device.js";import{f as t}from"./owner-identity.js";import"./process.js";import{n}from"./toolchain-probe.js";import{a as r}from"./runner-client.js";import{C as i}from"./runner-disposal.js";async function a(){let e=await n(`xcodebuild`,[`-version`]);return e?s({selectedPath:await n(`xcode-select`,[`-p`]),versionLine:e}):u()}async function o(n,a){if(!(!e(n)||n.kind!==`simulator`)&&!(t()!==`darwin`||a.isProviderDevice(n)))return a.emitProgress(`Checking iOS runner build cache (${n.name})...`),await i(n)?{id:`ios-runner-cache`,status:`pass`,summary:`iOS runner artifact cached; first open skips the runner build`}:(r(n,{}),a.emitProgress(`Warming iOS runner build cache in the background (${n.name})...`),{id:`ios-runner-cache`,status:`pass`,summary:`iOS runner build started in the background; the first open gets faster once it completes`,hint:"Run `agent-device prepare ios-runner` to wait for a fully warmed runner instead."})}function s(e){return{id:`toolchain`,status:c(e),summary:l(e),evidence:{selectedPath:e.selectedPath??null,xcodeVersion:e.versionLine??null}}}function c(e){return e.versionLine?`pass`:`info`}function l(e){return e.versionLine?e.selectedPath?`Apple toolchain: ${e.versionLine}; xcode-select ${e.selectedPath}.`:`Apple toolchain: ${e.versionLine}; xcode-select path unavailable.`:`Apple toolchain: xcodebuild version check failed.`}function u(){return{id:`toolchain`,status:`info`,summary:`Apple toolchain: xcodebuild version check failed.`,hint:`Install/select Xcode and complete first launch/license setup if xcodebuild reports it.`,command:`xcodebuild -version`}}export{o as appleRunnerWarmupCheck,a as appleToolchainCheck};
@@ -1 +1 @@
1
- import{N as e}from"./sdk-contracts.js";import{r as t,t as n}from"./toolchain-probe.js";import{t as r}from"./tool-provider3.js";async function i(e){let i=r();if(!await i.isAvailable())return{id:`toolchain`,status:`info`,summary:`Vega toolchain: Vega CLI not found.`,hint:`Install Vega Developer Tools or ensure ~/vega/bin/vega is executable.`,command:`vega --version`};let o=await i.version({allowFailure:!0,timeoutMs:n}),s=await a(e),l=t(o.stdout),u=s.devices.some(e=>e.platform===`vega`&&e.kind===`emulator`&&e.target===`tv`&&e.booted===!0);return{id:`toolchain`,status:o.exitCode===0?`pass`:`info`,summary:l?`Vega toolchain: ${l}; ${u?`VVD running`:`no running VVD`}.`:`Vega toolchain: CLI found but version check failed.`,hint:u?void 0:`Start the Vega Virtual Device and retry doctor.`,evidence:{vegaVersion:l??null,deviceList:c(s)}}}async function a(e){try{return{devices:await e.listLocalDeviceInventory({platform:`vega`,target:`tv`}),listedSerials:[]}}catch(t){if(e.shouldPropagateInventoryProbeError(t))throw t;return{devices:[],listedSerials:o(t)}}}function o(t){if(!(t instanceof e)||t.code!==`DEVICE_NOT_FOUND`)return[];let n=t.details?.listedSerials;return s(n)?n:[]}function s(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function c(e){return(e.devices.length>0?e.devices.map(e=>e.id):e.listedSerials).join(`, `)||null}export{i as vegaToolchainCheck};
1
+ import{P as e}from"./sdk-contracts.js";import{i as t,t as n}from"./toolchain-probe.js";import{t as r}from"./tool-provider3.js";async function i(e){let i=r();if(!await i.isAvailable())return{id:`toolchain`,status:`info`,summary:`Vega toolchain: Vega CLI not found.`,hint:`Install Vega Developer Tools or ensure ~/vega/bin/vega is executable.`,command:`vega --version`};let o=await i.version({allowFailure:!0,timeoutMs:n}),s=await a(e),l=t(o.stdout),u=s.devices.some(e=>e.platform===`vega`&&e.kind===`emulator`&&e.target===`tv`&&e.booted===!0);return{id:`toolchain`,status:o.exitCode===0?`pass`:`info`,summary:l?`Vega toolchain: ${l}; ${u?`VVD running`:`no running VVD`}.`:`Vega toolchain: CLI found but version check failed.`,hint:u?void 0:`Start the Vega Virtual Device and retry doctor.`,evidence:{vegaVersion:l??null,deviceList:c(s)}}}async function a(e){try{return{devices:await e.listLocalDeviceInventory({platform:`vega`,target:`tv`}),listedSerials:[]}}catch(t){if(e.shouldPropagateInventoryProbeError(t))throw t;return{devices:[],listedSerials:o(t)}}}function o(t){if(!(t instanceof e)||t.code!==`DEVICE_NOT_FOUND`)return[];let n=t.details?.listedSerials;return s(n)?n:[]}function s(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function c(e){return(e.devices.length>0?e.devices.map(e=>e.id):e.listedSerials).join(`, `)||null}export{i as vegaToolchainCheck};
@@ -0,0 +1 @@
1
+ import{P as e}from"./sdk-contracts.js";import{r as t}from"./diagnostics.js";import"./diagnostics2.js";import{M as n,P as r,j as i}from"./sdk-device.js";import{en as a}from"./sdk-batch.js";import{k as o}from"./owner-identity.js";import{i as s}from"./verified-file.js";import"./file.js";import{r as c}from"./session-paths.js";import{i as l,n as u,t as d}from"./durable-resource.js";import f from"node:crypto";import p from"node:fs";import m from"node:path";function h(t){let n=t.read(t.resolveCurrent()??t.initialSession),r=()=>{if(t.assertAdmissionOpen(),t.read(t.requireCurrent()))throw new e(`COMMAND_FAILED`,`Session capture resource has changed`,{reason:`session_resource_changed`,session:t.address})};return Object.freeze({address:t.address,sessionDir:t.sessionDir,read:()=>{let e=t.resolveCurrent();return e!==void 0&&(n=t.read(e)),n},assertAdoptable:r,canPersist:()=>{let e=t.resolveCurrent();return e!==void 0&&t.read(e)===void 0},adopt:e=>{r(),t.write(e),n=e},clear:e=>{let r=t.resolveCurrent();if(r===void 0)return`retired`;let i=t.read(r);return n=i,i?.handle!==e.handle||i.envelope.fence.token!==e.envelope.fence.token||i.envelope.fence.generation!==e.envelope.fence.generation?`resource-changed`:(t.write(void 0),n=void 0,`cleared`)}})}function g(e,t,n){return h({address:t.address,sessionDir:e.resolveSessionDir(t.address),initialSession:t.session,resolveCurrent:()=>e.resolveCurrent(t),requireCurrent:()=>e.requireCurrent(t),assertAdmissionOpen:()=>e.assertAdmissionOpen(t.address),...n})}function ee(e,t){return g(e,t,{read:e=>e.audioProbe,write:n=>{e.update(t,{audioProbe:n})}})}function te(e,t){return g(e,t,{read:e=>e.perfCapture,write:n=>{e.update(t,{perfCapture:n})}})}function _(e,t){return g(e,t,{read:e=>e.screenRecording,write:n=>{e.update(t,{screenRecording:n})}})}function v(t,n,r){let i,a=()=>{if(i)throw t.requireCurrent(i.ref),new e(`COMMAND_FAILED`,`Recording draft has already been published`,{reason:`session_resource_changed`,session:n});t.assertPublishable(n)},o=Object.freeze({address:n,sessionDir:t.resolveSessionDir(n),read:()=>i?.binding.read(),assertAdoptable:a,canPersist:()=>!i&&t.lookup(n)===void 0,adopt:o=>{if(a(),r.screenRecording)throw new e(`COMMAND_FAILED`,`Recording draft already owns a resource`,{reason:`session_resource_changed`,session:n});let s=t.publish(n,r),c=_(t,s);c.adopt(o),i=Object.freeze({ref:s,binding:c})},clear:e=>i?.binding.clear(e)??`retired`});return Object.freeze({binding:o,requireRef:()=>{if(!i)throw TypeError(`Screen recording did not publish its session`);return i.ref}})}function y(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function b(e){return e.replaceAll(`-`,`_`)}async function x(e,t,n){let r={kind:`pending`};try{t.binding.assertAdoptable();let i=T(w(e,t),`active`);e.store.write(n,i),r={kind:`persisted`},t.throwIfCanceled();let a=t.pendingHandle.transfer();r={kind:`transferred`,handle:a},t.binding.adopt({handle:a,envelope:i})}catch(i){throw await ne(e,t,n,r,i),i}}async function ne(e,t,n,r,i){let a=t.binding.canPersist(),o=r.kind!==`pending`||a&&ie(e,t,n),s=re(e,t,n,await S(t,r));t.reportUndurableCleanup(t.device,!o&&s.cleanupError===void 0||s.confirmed?{confirmed:!0}:{confirmed:!1,reason:s.cleanupError instanceof Error?s.cleanupError.message:`The durable cleanup transition could not be confirmed`}),s.cleanupError!==void 0&&ce(e,t,i,s.cleanupError)}function re(e,n,r,i){try{return{confirmed:se(e,r,n.fence,i),cleanupError:i}}catch(r){return t({level:`error`,phase:`${b(e.resourceKind)}_pending_adoption_transition_failed`,data:{session:n.binding.address,transitionError:r instanceof Error?r.message:String(r)}}),{confirmed:!1,cleanupError:i??r}}}async function S(e,t){try{t.kind===`transferred`?await t.handle[Symbol.asyncDispose]():await e.pendingHandle[Symbol.asyncDispose]();return}catch(e){return e}}function ie(e,n,r){try{return e.store.write(r,ae(e,n)),!0}catch(i){try{return e.store.write(r,C(e,n,{version:0,body:{reason:`runtime-contract-invalid`}})),!0}catch(r){return t({level:`error`,phase:`${b(e.resourceKind)}_runtime_contract_tombstone_failed`,data:{session:n.binding.address,descriptorError:i instanceof Error?i.message:String(i),persistenceError:r instanceof Error?r.message:String(r)}}),!1}}}function ae(e,t){try{return T(w(e,t),`active`)}catch{return C(e,t,t.envelope.descriptor)}}function C(e,t,n){return u({resourceKind:e.resourceKind,sessionId:t.binding.address,device:i(t.device),owner:t.owner,fence:t.fence,lifecycle:`open`,descriptor:n,metadata:{phase:`runtime-contract-invalid`,runtimeContractInvalid:!0}})}function w(t,n){let r=l(n.envelope);if(r.status===`decoded`&&oe(r.envelope,n,t.resourceKind))return r.envelope;throw new e(`COMMAND_FAILED`,`${y(t.displayName)} runtime returned an incoherent durable envelope`,{reason:`runtime-contract-invalid`,hint:`Retain the runtime diagnostics and report the selected device and owner.`})}function oe(e,t,n){return e.resourceKind===n&&e.sessionId===t.binding.address&&r(e.device,i(t.device))&&a(e.owner)===a(t.owner)&&e.fence.token===t.fence.token&&e.fence.generation===t.fence.generation&&e.lifecycle===`open`}function se(e,t,n,r){let i=e.store.read(t);return i.status!==`decoded`||i.envelope.fence.token!==n.token||i.envelope.fence.generation!==n.generation?!1:(e.store.write(t,{...i.envelope,lifecycle:r===void 0?`completed`:`open`,metadata:{...i.envelope.metadata??{},phase:r===void 0?`completed`:`cleanup-pending`,cleanupStatus:r===void 0?`cleaned`:`cleanup-pending`}}),!0)}function ce(e,n,r,i){t({level:`error`,phase:`${b(e.resourceKind)}_pending_adoption_cleanup_failed`,data:{session:n.binding.address,primaryError:r instanceof Error?r.message:String(r),cleanupError:i instanceof Error?i.message:String(i)}})}function T(e,t){return Object.freeze({...e,lifecycle:`open`,metadata:{...e.metadata??{},phase:t}})}async function E(e){e.scope.signal.throwIfAborted();let t=new AbortController,n={...e.scope,signal:AbortSignal.any([e.scope.signal,t.signal])},r=()=>{},i=new Promise((e,t)=>{r=t}),a=()=>{},o=new Promise((t,n)=>{let r=()=>{try{e.scope.signal.throwIfAborted()}catch(e){n(e)}};if(e.scope.signal.aborted){r();return}e.scope.signal.addEventListener(`abort`,r,{once:!0}),a=()=>e.scope.signal.removeEventListener(`abort`,r)}),s=setTimeout(()=>{let n=new k(e.displayName,e.deadlineMs);t.abort(n),r(n)},e.deadlineMs);s.unref?.();let c=le(e,n),l,u=c.then(e=>(l??={kind:`acquisition`},e),e=>{throw l??={kind:`acquisition-error`},e}),d=i.catch(e=>{throw l??={kind:`deadline`,error:e},e}),f=o.catch(e=>{throw l??={kind:`cancellation`,error:e},e});try{return await Promise.race([u,d,f])}finally{if(clearTimeout(s),a(),l?.kind===`deadline`||l?.kind===`cancellation`){let t=l.error;c.then(n=>D(e,n,t),()=>{}).catch(()=>{})}else c.catch(()=>{})}}async function D(e,t,n){try{t.reattached.status===`active`&&await O(e,t.reattached.handle,`late_handle_cleanup_failed`,n)}finally{await O(e,t.control,`late_control_cleanup_failed`,n)}}async function le(e,t){let n,r;try{return n=await e.acquireControl(e.envelope,t),t.signal.throwIfAborted(),r=await n.reattach(e.envelope),t.signal.throwIfAborted(),{control:n,reattached:r}}catch(t){try{r?.status===`active`&&await O(e,r.handle,`late_handle_cleanup_failed`,t)}finally{n&&await O(e,n,`late_control_cleanup_failed`,t)}throw t}}async function O(e,t,n,r){try{await t[Symbol.asyncDispose]()}catch(t){e.onLateCleanupFailure(n,t,r)}}var k=class extends Error{deadlineMs;constructor(e,t){super(`${y(e)} recovery exceeded its ${t}ms deadline`),this.name=`DurableCaptureRecoveryDeadlineError`,this.deadlineMs=t}};const A=new Map;async function j(e){return await de(e.resourcePath,async()=>{let t=e.store.read(e.resourcePath);if(t.status!==`decoded`)throw M(e.store,t.status===`missing`?`${e.store.displayName} resource record is missing`:`${e.store.displayName} resource record is unreattachable: ${t.message}`);if(!ue(t.envelope.fence,e.expected))throw M(e.store,`${e.store.displayName} resource ownership fence was lost`);let n=t.envelope;return await e.run({get envelope(){return n},transition(t,r={}){return n=Object.freeze({...n,lifecycle:t,...r.descriptor===void 0?{}:{descriptor:r.descriptor},...r.metadata===void 0?{}:{metadata:r.metadata}}),e.store.write(e.resourcePath,n),n}})})}function ue(e,t){return e.token===t.token&&e.generation===t.generation}async function de(e,t){let n=A.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>i);A.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),A.get(e)===a&&A.delete(e)}}function M(t,n){return new e(`COMMAND_FAILED`,n,{reason:`ownership-fence-lost`,retriable:!1,hint:`Use the current ${t.displayName.toLowerCase()} resource owner or retain the recovery record for manual recovery.`})}async function fe(t,n,r){let i=n.binding.read();if(!i)throw new e(`INVALID_ARGS`,t.messages.noActive);try{let e=await N(t,{handle:i.handle,fence:i.envelope.fence,resourcePath:r,intent:n.intent});return n.binding.clear(i),e}catch(e){let a=t.store.read(r);throw a.status===`decoded`&&a.envelope.lifecycle===`completed`&&n.binding.clear(i),e}}async function N(e,t){return await j({store:e.store,resourcePath:t.resourcePath,expected:t.fence,run:async n=>{W(n);let r=pe(n),i;try{i=await t.handle.finish(r)}catch(r){throw await P(e,n,t,r,t.intent),r}if(i.status===`completed`)return U(e,n,i),i.result;U(e,n,i);let a=H(e,i);throw await P(e,n,t,a,t.intent),a}})}async function P(e,t,n,r,i){if(i===`capture`&&e.failedFinishPolicy===`preserve-retry-material`){I(e,n,r);return}let a;try{a=await n.handle.forceCleanup()}catch(i){L(e,n,r,i,F(t,i));return}try{B(t,a)}catch(t){L(e,n,r,a.status===`cleanup-pending`?a.message??a.reason:`cleanup returned ${a.status}`,t);return}d(a)||L(e,n,r,a.message)}function F(e,t){try{B(e,{status:`cleanup-pending`,reason:`cleanup-unconfirmed`,message:R(t)});return}catch(e){return e}}function I(e,n,r){t({level:`error`,phase:`${b(e.resourceKind)}_finish_evidence_preserved`,data:{resourcePath:n.resourcePath,finishError:R(r),failedFinishPolicy:e.failedFinishPolicy}})}function L(e,n,r,i,a){t({level:`error`,phase:`${b(e.resourceKind)}_finish_cleanup_failed`,data:{resourcePath:n.resourcePath,finishError:R(r),cleanupError:i===void 0?`cleanup could not be confirmed`:R(i),...a===void 0?{}:{transitionError:R(a)}}})}function R(e){return e instanceof Error?e.message:String(e)}async function z(e,t){let n=t.binding.read();n&&(V(e,await j({store:e.store,resourcePath:t.resourcePath,expected:n.envelope.fence,run:async e=>{W(e);let t=await n.handle.forceCleanup();return B(e,t),t}})),t.binding.clear(n))}function B(e,t){e.transition(d(t)?`completed`:`open`,{metadata:{...e.envelope.metadata??{},phase:d(t)?`completed`:`cleanup-pending`,cleanupStatus:t.status,...t.status===`cleanup-pending`?{cleanupPendingReason:t.reason,...t.message?{cleanupPendingMessage:t.message}:{}}:{}}})}function V(e,t){if(!d(t))throw H(e,t)}function H(t,n){return new e(`COMMAND_FAILED`,n.message??`${y(t.displayName)} cleanup could not be confirmed`,{reason:n.reason,retriable:n.reason!==`ownership-fence-lost`,hint:t.messages.cleanupPendingHint})}function U(e,t,n){if(n.status===`completed`){t.transition(`completed`,{metadata:{...t.envelope.metadata??{},...e.completionMetadata(n.result),phase:`completed`}});return}B(t,n)}function pe(e){return Object.freeze({learned:e.envelope.metadata,record:t=>{e.transition(`open`,{metadata:{...e.envelope.metadata??{},...t}})}})}function W(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}async function me(e){let t=e.definition.store.list(e.sessionsDir),n=[];for(let r of t)n.push(await G(e,r));return{scanned:t.length,recovered:n.filter(e=>e===`recovered`).length,retained:n.filter(e=>e===`retained`).length}}async function G(e,t){let n=K(e,t);if(n.status!==`recoverable`)return n.status;try{return await he(e,t,n.envelope,e.perRecordDeadlineMs??5e3)?`recovered`:`retained`}catch(n){return Y(e,n instanceof k?`timed_out`:`failed`,t,{error:n instanceof Error?n.message:String(n),...n instanceof k?{deadlineMs:n.deadlineMs}:{}}),`retained`}}function K(e,t){let n=e.definition.store.read(t);if(n.status===`unreattachable`)return Y(e,`record_unreattachable`,t,{reason:n.reason,message:n.message,version:n.version}),{status:`retained`};if(n.status===`missing`||n.envelope.lifecycle===`completed`)return{status:`ignored`};let r=e.definition.store.resolvePath(e.resolveSessionDir(n.envelope.sessionId));return m.resolve(t)===m.resolve(r)?{status:`recoverable`,envelope:n.envelope}:(Y(e,`session_path_mismatch`,t,{envelopeSessionId:n.envelope.sessionId,canonicalPath:r}),{status:`retained`})}async function he(e,t,n,r){return await ge(e,t,n,await E({displayName:e.definition.displayName,envelope:n,scope:e.scope,deadlineMs:r,acquireControl:e.acquireControl,onLateCleanupFailure:(n,r,i)=>Y(e,n,t,{error:r instanceof Error?r.message:String(r),primaryError:i instanceof Error?i.message:String(i)})}))}async function ge(e,t,n,r){try{switch(r.reattached.status){case`active`:{let i=r.reattached.handle,a=await j({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{_e(e);let t=await i.forceCleanup();return B(e,t),t}});return d(a)}case`completed`:return await q(e,t,n,{...e.definition.completionMetadata(r.reattached.result)}),!0;case`missing`:return await q(e,t,n,{recoveryStatus:`already-missing`}),!0;case`unreattachable`:{if(!J(r.reattached.reason))return Y(e,`retained`,t,{reason:r.reattached.reason,message:r.reattached.message}),!1;let i=await r.control.cleanup(n);return await j({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>B(e,i)}),d(i)}}}finally{await r.control[Symbol.asyncDispose]()}}async function q(e,t,n,r){await j({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{e.transition(`completed`,{metadata:{...e.envelope.metadata??{},phase:`completed`,...r}})}})}function _e(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}function J(e){switch(e){case`descriptor-invalid`:case`descriptor-version-unsupported`:case`ownership-fence-lost`:return!1;case`owner-unavailable`:case`transport-not-reattachable`:return!0}}function Y(e,n,r,i){let a={phase:`${b(e.definition.resourceKind)}_recovery_${n}`,resourcePath:r,data:i};e.onDiagnostic?e.onDiagnostic(a):t({level:`warn`,phase:a.phase,data:{resourcePath:r,...i}})}async function ve(t,n){let r=t.store.read(n.resourcePath);if(r.status!==`decoded`||r.envelope.lifecycle!==`open`)throw ye(t,r.status);let i=r.envelope,a=await E({displayName:t.displayName,envelope:i,scope:n.scope,deadlineMs:n.deadlineMs??5e3,acquireControl:n.acquireControl,onLateCleanupFailure:(e,r,i)=>n.scope.diagnostics.emit({level:`error`,phase:`${b(t.resourceKind)}_recovery_${e}`,data:{resourcePath:n.resourcePath,error:X(r),primaryError:X(i)}})});try{switch(a.reattached.status){case`active`:return await N(t,{handle:a.reattached.handle,fence:i.fence,resourcePath:n.resourcePath,intent:`capture`});case`completed`:{let e=a.reattached.result;return await j({store:t.store,resourcePath:n.resourcePath,expected:i.fence,run:async n=>{U(t,n,{status:`completed`,result:e,alreadyCompleted:!0})}}),e}case`missing`:throw new e(`COMMAND_FAILED`,`${y(t.displayName)} is missing`,{reason:`resource-missing`,hint:t.messages.cleanupPendingHint});case`unreattachable`:if(J(a.reattached.reason)){let e=await a.control.cleanup(i);await j({store:t.store,resourcePath:n.resourcePath,expected:i.fence,run:async t=>B(t,e)}),V(t,e)}throw new e(`COMMAND_FAILED`,a.reattached.message??`${y(t.displayName)} cannot be reattached`,{reason:a.reattached.reason,hint:t.messages.cleanupPendingHint})}}finally{await a.control[Symbol.asyncDispose]()}}function ye(t,n){return new e(`INVALID_ARGS`,n===`missing`?t.messages.noActive:`${y(t.displayName)} recovery record is not open`)}function X(e){return e instanceof Error?e.message:String(e)}function be(e){Se(e.fileName);let t=t=>m.join(t,e.fileName);return Object.freeze({resourceKind:e.resourceKind,displayName:e.displayName,resolvePath:t,read(t){let n,r;try{if(n=s(t),n===void 0)return{status:`missing`};r=JSON.parse(p.readFileSync(n,`utf8`))}catch(t){return Q(t)?{status:`missing`}:Z(we(t,e.displayName))}finally{n!==void 0&&p.closeSync(n)}return xe(l(r),e.resourceKind)},write(e,t){let n=m.dirname(e);p.mkdirSync(n,{recursive:!0}),o({destination:e,contents:`${JSON.stringify(t)}\n`})},list(e){let n;try{n=p.readdirSync(e,{withFileTypes:!0})}catch{return[]}return n.filter(e=>e.isDirectory()).map(n=>t(m.join(e,n.name))).filter(Ce).sort()}})}function xe(e,t){return e.status===`decoded`?e.envelope.resourceKind===t?{status:`decoded`,envelope:e.envelope}:Z(`Expected ${t} resource record, received ${e.envelope.resourceKind}`):e}function Se(e){if(e.length===0||m.basename(e)!==e)throw TypeError(`Durable capture resource fileName must be one file name`)}function Ce(e){try{return p.lstatSync(e),!0}catch(e){return!Q(e)}}function Z(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function Q(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function we(e,t){return e instanceof Error?e.message:`${t} resource record is invalid`}function Te(e,t){t.admissionLedger.assertStartAllowed(t.device),Ee(e,t.resourcePath,t.device);let n=e.store.read(t.resourcePath);return Object.freeze({token:f.randomUUID(),generation:n.status===`decoded`?n.envelope.fence.generation+1:1})}function Ee(t,r,a){let o=n(i(a));for(let i of t.store.list(m.dirname(m.dirname(r)))){let a=t.store.read(i);if(a.status===`unreattachable`)throw new e(`COMMAND_FAILED`,`${y($(t.displayName))} ${t.displayName} recovery record is unreattachable: ${a.message}`,{reason:a.reason,retriable:!1,hint:`Retain the corrupt or future-version ${t.displayName} manifest for manual recovery; no replacement capture is safe.`});if(a.status===`decoded`&&a.envelope.lifecycle!==`completed`&&(i===r||n(a.envelope.device)===o))throw new e(`COMMAND_FAILED`,`${y($(t.displayName))} ${t.displayName} resource for this device has not reached a confirmed terminal state`,{reason:`cleanup-unconfirmed`,hint:`Retry exact-owner cleanup using the existing ${t.displayName} manifest before starting a replacement.`})}}function $(e){return/^[aeiou]/i.test(e)?`an`:`a`}function De(e){let t=(t,n)=>e.store.resolvePath(t.resolveSessionDir(n)),n=t=>({definition:e,resolveSessionDir:e=>m.join(t.sessionsDir,c(e)),...t});return Object.freeze({store:e.store,resourcePath:t,createNextFence(t){return Te(e,t)},adoptStarted(t){return x(e,{...t,reportUndurableCleanup:(e,n)=>{n.confirmed?t.admissionLedger.clearUndurableCleanup(e):t.admissionLedger.blockUndurableCleanup(e,n.reason)}},e.store.resolvePath(t.binding.sessionDir))},finishLive(t){return fe(e,t,e.store.resolvePath(t.binding.sessionDir))},finishRecovered(t){return ve(e,t)},forceCleanupLive(t){return z(e,{...t,resourcePath:e.store.resolvePath(t.binding.sessionDir)})},recoverAll(e){return me(n(e))},recoverOne(e,t){return G(n(e),t)}})}export{g as a,ee as i,be as n,te as o,v as r,_ as s,De as t};
@@ -1 +1 @@
1
- import{N as e,V as t}from"./sdk-contracts.js";const n=new Set([`__proto__`,`constructor`,`prototype`]);async function r(n,r){let o=a(r),c=i(n),{default:l}=await import(`node:vm`),u={...r,output:o};try{l.runInNewContext(c,u,{filename:`evalScript`,timeout:1e4})}catch(n){throw new e(`COMMAND_FAILED`,`Maestro evalScript failed: ${t(n)}`,void 0,n instanceof Error?n:void 0)}return s(u.output)}function i(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1):t}function a(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))!n.startsWith(`output.`)||n===`output`||o(t,n.slice(7),r);return t}function o(e,t,n){let r=t.split(`.`).filter(l);if(r.length===0)return;let i=e;for(let e of r.slice(0,-1)){let t=i[e];(typeof t!=`object`||!t)&&(i[e]=Object.create(null)),i=i[e]}i[r.at(-1)]=n}function s(e){let t={};return c(e,[],t,new Set),t}function c(e,t,n,r){if(e!==void 0){if(typeof e!=`object`||!e){n[`output${t.map(e=>`.${e}`).join(``)}`]=u(e);return}if(!r.has(e)){r.add(e);try{let i=Array.isArray(e)?[...e.keys(),`length`]:Object.keys(e).filter(l);for(let a of i){let i=String(a);c(Array.isArray(e)&&i===`length`?e.length:e[i],[...t,i],n,r)}}finally{r.delete(e)}}}}function l(e){return!n.has(e)}function u(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}export{r as evaluateMaestroEvalScript};
1
+ import{H as e,P as t}from"./sdk-contracts.js";const n=new Set([`__proto__`,`constructor`,`prototype`]);async function r(e,t){return(await a(e,t,`evalScript`,{})).outputEnv}async function i(e,t,n,r){return await a(e,t,r,{maestro:{platform:n}})}async function a(n,r,i,a){let c=s(r),u=o(n),{default:d}=await import(`node:vm`),f={...r,...a,output:c},p;try{p=d.runInNewContext(u,f,{filename:i,timeout:1e4})}catch(n){throw new t(`COMMAND_FAILED`,`Maestro ${i} failed: ${e(n)}`,void 0,n instanceof Error?n:void 0)}return{value:p,outputEnv:l(f.output)}}function o(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1):t}function s(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))!n.startsWith(`output.`)||n===`output`||c(t,n.slice(7),r);return t}function c(e,t,n){let r=t.split(`.`).filter(d);if(r.length===0)return;let i=e;for(let e of r.slice(0,-1)){let t=i[e];(typeof t!=`object`||!t)&&(i[e]=Object.create(null)),i=i[e]}i[r.at(-1)]=n}function l(e){let t={};return u(e,[],t,new Set),t}function u(e,t,n,r){if(e!==void 0){if(typeof e!=`object`||!e){n[`output${t.map(e=>`.${e}`).join(``)}`]=f(e);return}if(!r.has(e)){r.add(e);try{let i=Array.isArray(e)?[...e.keys(),`length`]:Object.keys(e).filter(d);for(let a of i){let i=String(a);u(Array.isArray(e)&&i===`length`?e.length:e[i],[...t,i],n,r)}}finally{r.delete(e)}}}}function d(e){return!n.has(e)}function f(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}export{i as evaluateMaestroConditionScript,r as evaluateMaestroEvalScript};
package/dist/src/error.js CHANGED
@@ -1,2 +1,2 @@
1
- import{r as e}from"./rolldown-runtime.js";import{N as t,X as n,q as r}from"./sdk-contracts.js";import{n as i}from"./success-text.js";import{t as a}from"./output-common.js";import{r as o}from"./replay-divergence.js";var s=e({formatErrorCandidateViews:()=>l,printHumanError:()=>c});function c(e,s={}){let c=e instanceof t?r(e):e;if(process.stderr.write(`Error (${c.code}): ${c.message}\n`),c.cause){let e=c.cause.code?`${c.cause.code} `:``;process.stderr.write(`Cause: ${e}${c.cause.message}\n`)}c.hint&&process.stderr.write(`Hint: ${c.hint}\n`);for(let e of i(c.details))process.stderr.write(`Warning: ${a(e)}\n`);let u=l(n(c.details));u.length>0&&process.stderr.write(`${u.join(`
1
+ import{r as e}from"./rolldown-runtime.js";import{J as t,P as n,Z as r}from"./sdk-contracts.js";import{n as i}from"./success-text.js";import{t as a}from"./output-common.js";import{r as o}from"./replay-divergence.js";var s=e({formatErrorCandidateViews:()=>l,printHumanError:()=>c});function c(e,s={}){let c=e instanceof n?t(e):e;if(process.stderr.write(`Error (${c.code}): ${c.message}\n`),c.cause){let e=c.cause.code?`${c.cause.code} `:``;process.stderr.write(`Cause: ${e}${c.cause.message}\n`)}c.hint&&process.stderr.write(`Hint: ${c.hint}\n`);for(let e of i(c.details))process.stderr.write(`Warning: ${a(e)}\n`);let u=l(r(c.details));u.length>0&&process.stderr.write(`${u.join(`
2
2
  `)}\n`),c.diagnosticId&&process.stderr.write(`Diagnostic ID: ${c.diagnosticId}\n`),c.logPath&&process.stderr.write(`Diagnostics Log: ${c.logPath}\n`),c.logPathUnavailable&&process.stderr.write(`Remote Diagnostics: unavailable (${c.logPathUnavailable})\n`);let d=o(c.details);d&&process.stderr.write(`${d}\n`),s.showDetails&&c.details&&process.stderr.write(`${JSON.stringify(c.details,null,2)}\n`)}function l(e){return e.flatMap(e=>{if(e.kind===`element-match`){let t=e.matches-e.candidates.length;return[`Candidates:`,...e.candidates.map(t=>` ${u(t,e.refsGeneration)}`),...t>0?[` +${t} more`]:[]]}return[`Devices:`,...e.devices.map(e=>` ${e.id} ${e.name}`)]})}function u(e,t){return t===void 0?e:e.replace(/^@(e\d+)(?=\s|$)/,`@$1~s${t}`)}export{l as n,s as t};
package/dist/src/exec.js CHANGED
@@ -1 +1 @@
1
- import{F as e,N as t}from"./sdk-contracts.js";import{o as n}from"./sdk-remote-config.js";import{a as r,r as i,s as a}from"./diagnostics.js";import o from"node:path";import{constants as s}from"node:fs";import{AsyncLocalStorage as c}from"node:async_hooks";import{access as l,stat as u}from"node:fs/promises";import{spawn as d,spawnSync as f}from"node:child_process";import{Readable as p}from"node:stream";import{pipeline as m}from"node:stream/promises";const h=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,g=[`.com`,`.exe`,`.bat`,`.cmd`],_=new c;async function v(e,t){return e?await _.run(e,t):await t()}async function y(e){return await _.run(void 0,e)}const b=new c;async function ee(e,t){return e?await b.run(e,t):await t()}function x(){let e=b.getStore();return e&&Object.hasOwn(e,`DEVELOPER_DIR`)?e.DEVELOPER_DIR||void 0:process.env.DEVELOPER_DIR||void 0}function S(e){let t=b.getStore();return t?{...e??process.env,...t}:e}async function te(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?w(await r):await T(e,t,n)}async function C(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?w(await r):await T(e,t,n)}function w(e){let t=typeof e.stdout==`string`?e.stdout:String(e.stdout??``),n=typeof e.stderr==`string`?e.stderr:String(e.stderr??``),r=typeof e.exitCode==`number`?e.exitCode:1;return t===e.stdout&&n===e.stderr&&r===e.exitCode?e:{...e,stdout:t,stderr:n,exitCode:r}}function T(e,t,n={}){let r=M(e),i=k();return new Promise((a,o)=>{let s=d(r,t,{cwd:n.cwd,env:S(n.env),stdio:[`pipe`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});n.onSpawn?.(s);let c=``,l=n.binaryStdout?[]:void 0,u=``,f=!1,p=q(n.timeoutMs),m=null,h=!1;function g(){return!h&&(h=!0,m&&clearTimeout(m),b.dispose(),$(s),i.emitForegroundCompletion(e,t),!0)}function _(e){g()&&o(e)}function v(i){if(!g())return;let s=i??1;if(!b.didAbort&&f&&p){o(se(r,e,t,p,s,c,u));return}let d=H(b,r,e,t,s,n.allowFailure,c,u);if(d){o(d);return}a({stdout:c,stderr:u,exitCode:s,stdoutBuffer:l?Buffer.concat(l):void 0})}let y=J({killProcessTree:()=>Z(s,n),settle:v}),b=Y(n,y.requestKill);m=p?setTimeout(()=>{f=!0,y.requestKill()},p):null,n.binaryStdout||s.stdout.setEncoding(`utf8`),s.stderr.setEncoding(`utf8`),fe(s,n.stdin).catch(i=>{b.didAbort||f||pe(i)||(_(oe(r,e,t,i)),Z(s,n))}),s.stdout.on(`data`,e=>{if(n.binaryStdout){l?.push(Buffer.isBuffer(e)?e:Buffer.from(e));return}let t=String(e);c+=t,n.onStdoutChunk?.(t)}),s.stderr.on(`data`,e=>{let t=String(e);u+=t,n.onStderrChunk?.(t)}),s.on(`error`,n=>{_(V(b,r,e,t,n))}),s.once(`exit`,y.recordExit),s.once(`close`,v)})}async function ne(e){let t=W(e);if(!t)return!1;if(o.isAbsolute(t))return G(t);let n=process.env.PATH;if(!n)return!1;let r=ue();for(let e of n.split(o.delimiter)){let n=e.trim();if(n){for(let e of de(t,r))if(await G(o.join(n,e)))return!0}}return!1}async function re(e,n){let r=U(e,n,`executable`);if(r){if(!await G(r))throw new t(`TOOL_MISSING`,`${n} points to a missing or non-executable file: ${r}`,{envName:n,path:r});return r}}async function ie(e,n){let r=U(e,n,`file`);if(r){if(!await K(r))throw new t(`TOOL_MISSING`,`${n} points to a missing or non-file path: ${r}`,{envName:n,path:r});return r}}function ae(e,n,r={}){let i=M(e),a=f(i,n,{cwd:r.cwd,env:S(r.env),stdio:[`pipe`,`pipe`,`pipe`],encoding:r.binaryStdout?void 0:`utf8`,input:r.stdin,timeout:q(r.timeoutMs),windowsHide:!0,shell:!1,...r.maxBuffer===void 0?{}:{maxBuffer:r.maxBuffer}});if(a.error){let o=a.error.code;throw o===`ETIMEDOUT`?new t(`COMMAND_FAILED`,`${i} timed out after ${q(r.timeoutMs)}ms`,{cmd:e,args:n,timeoutMs:q(r.timeoutMs)},a.error):o===`ENOENT`?P(i,e,a.error):F(i,e,n,a.error)}let o=r.binaryStdout?Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(a.stdout??``):void 0,s=r.binaryStdout?``:typeof a.stdout==`string`?a.stdout:(a.stdout??``).toString(),c=typeof a.stderr==`string`?a.stderr:(a.stderr??``).toString(),l=a.status??1;if(l!==0&&!r.allowFailure)throw L(i,e,n,l,s,c);return{stdout:s,stderr:c,exitCode:l,stdoutBuffer:o}}function E(e,t,n={}){return D(e,t,n).pid}function D(e,t,n={}){let r=M(e),i=d(r,t,{cwd:n.cwd,env:S(n.env),stdio:n.stdio??`ignore`,detached:!0,windowsHide:!0,shell:!1}),a=i.pid??0,o=new Promise(e=>{i.once(`error`,t=>{e({pid:a,error:t.message})}),i.once(`exit`,(t,n)=>{e({pid:a,...typeof t==`number`?{exitCode:t}:{},...n?{signal:n}:{}})})});return i.unref(),{pid:a,exited:o}}function O(e,t,n={}){let r=M(e),i=k(),a=d(r,t,{cwd:n.cwd,env:S(n.env),stdio:n.stdio??[`ignore`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});i.emitBackgroundSpawn(e,t);let o=``,s=``;return(n.captureOutput??!0)&&(a.stdout?.setEncoding(`utf8`),a.stderr?.setEncoding(`utf8`),a.stdout?.on(`data`,e=>{o+=e}),a.stderr?.on(`data`,e=>{s+=e})),{child:a,wait:new Promise((c,l)=>{let u=!1;function d(n){return!u&&(u=!0,m.dispose(),$(a),i.emitBackgroundCompletion(e,t,n),!0)}function f(i){if(!d(`exit`))return;let a=i??1,u=H(m,r,e,t,a,n.allowFailure,o,s);if(u){l(u);return}c({stdout:o,stderr:s,exitCode:a})}let p=J({killProcessTree:()=>Z(a,n),settle:f}),m=Y(n,p.requestKill);a.on(`error`,n=>{d(`error`)&&l(V(m,r,e,t,n))}),a.once(`exit`,p.recordExit),a.once(`close`,f)})}}function k(){let e=r(),t=e.debug===!0,i=n(process.env.AGENT_DEVICE_EXEC_TRACE??``)===!0;if(!t&&!i)return A();i&&e.flushOnSuccess!==!0&&a({flushOnSuccess:!0});let o=Date.now(),s=!1;return{emitForegroundCompletion:(e,t)=>{s||(s=!0,j({cmd:e,args:t,startedAtMs:o}))},emitBackgroundSpawn:(e,t)=>{j({cmd:e,args:t,data:{event:`spawn`}})},emitBackgroundCompletion:(e,t,n)=>{s||(s=!0,j({cmd:e,args:t,startedAtMs:o,data:{event:n}}))}}}function A(){return{emitForegroundCompletion:()=>{},emitBackgroundSpawn:()=>{},emitBackgroundCompletion:()=>{}}}function j(e){let t=e.args.slice(0,6);i({level:`debug`,phase:`exec_command`,durationMs:e.startedAtMs===void 0?void 0:Math.max(0,Date.now()-e.startedAtMs),data:{command:e.cmd,argsPrefix:t,...e.args.length>t.length?{omittedArgCount:e.args.length-t.length}:{},...e.data??{}}})}function M(e){let n=W(e);if(!n)throw new t(`INVALID_ARGS`,`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e,hint:`Use a bare command name from PATH or an absolute executable path.`});return n}function N(e,t,n,r){return r.code===`ENOENT`?P(e,t,r):F(e,t,n,r)}function P(e,n,r){return new t(`TOOL_MISSING`,`${e} not found in PATH`,{cmd:n},r)}function F(e,n,r,i){return new t(`COMMAND_FAILED`,`Failed to run ${e}`,{cmd:n,args:r},i)}function oe(e,n,r,i){return new t(`COMMAND_FAILED`,`Failed to write stdin for ${e}`,{cmd:n,args:r},i instanceof Error?i:void 0)}function I(t,n,r){return e({cmd:n,args:r,executable:t})}function se(e,n,r,i,a,o,s){return new t(`COMMAND_FAILED`,`${e} timed out after ${i}ms`,{cmd:n,args:r,stdout:o,stderr:s,exitCode:a,timeoutMs:i})}function ce(e){return e instanceof t&&e.code===`COMMAND_FAILED`&&typeof e.details?.timeoutMs==`number`}function L(e,n,r,i,a,o){return new t(`COMMAND_FAILED`,`${e} exited with code ${i}`,B({stdout:a,stderr:o,exitCode:i},{cmd:n,args:r}))}const R=/xcrun: error: unable to find utility "([^"]+)"/;function le(e){let t=R.exec(e)?.[1];if(!t)return{};let n=x(),r=n?`DEVELOPER_DIR ${n}`:`the developer dir selected by xcode-select (see xcode-select -p)`;return{reason:`xcrun-tool-not-found`,developerDir:n??null,hint:`xcrun could not find ${t} in ${r}. Export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer (or your Xcode's path) before running agent-device, or run sudo xcode-select -s /Applications/Xcode.app.`}}function z(e,n,r){if(e.exitCode===0)return e;throw new t(`COMMAND_FAILED`,n,B(e,typeof r==`function`?r(e):r))}function B(e,t){return{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,processExitError:!0,...t,...le(e.stderr)}}function V(e,t,n,r,i){return e.didAbort?I(t,n,r):N(t,n,r,i)}function H(e,t,n,r,i,a,o,s){return e.didAbort?I(t,n,r):i!==0&&!a?L(t,n,r,i,o,s):null}function U(e,n,r){let i=e?.trim();if(i){if(!o.isAbsolute(i)||i.includes(`\0`))throw new t(`INVALID_ARGS`,`${n} must be an absolute ${r} path, not ${JSON.stringify(e)}`,{envName:n,path:e});return i}}function W(e){let t=e.trim();return!t||t.includes(`\0`)?null:o.isAbsolute(t)?t:t.includes(`/`)||t.includes(`\\`)?null:h.test(t)?t:null}function ue(){if(process.platform!==`win32`)return[``];let e=process.env.PATHEXT;if(!e)return g;let t=e.split(`;`).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:g}function de(e,t){if(process.platform!==`win32`)return[e];let n=e.toLowerCase();return t.some(e=>n.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}async function G(e){try{return await K(e)?(await l(e,process.platform===`win32`?s.F_OK:s.X_OK),!0):!1}catch{return!1}}async function K(e){try{return(await u(e)).isFile()}catch{return!1}}function q(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function J(e){let t=!1,n=!1,r=null,i=()=>{t&&n&&e.settle(r)};return{requestKill:()=>{t=!0,e.killProcessTree(),i()},recordExit:e=>{n=!0,r=e??1,i()}}}function Y(e,t){let n=!1,r=()=>{n=!0,t()};return e.signal?.aborted?r():e.signal?.addEventListener(`abort`,r,{once:!0}),{get didAbort(){return n},dispose:()=>{e.signal?.removeEventListener(`abort`,r)}}}function X(e,t){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(-e,t),!0}catch{return!1}}function Z(e,t){if(!t.kill){Q(e,t.detached,`SIGKILL`);return}Q(e,t.detached,t.kill.signal);let n=setTimeout(()=>Q(e,t.detached,`SIGKILL`),t.kill.graceMs);n.unref(),e.once(`exit`,()=>clearTimeout(n))}function Q(e,t,n){if(t&&e.pid&&process.platform!==`win32`){X(e.pid,n);return}e.exitCode===null&&e.signalCode===null&&e.kill(n)}function $(e){e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()}async function fe(e,t){if(e.stdin){if(t===void 0){e.stdin?.end();return}await m(p.from([t]),e.stdin)}}function pe(e){return e instanceof Error&&`code`in e&&e.code===`EPIPE`}export{v as _,G as a,ie as c,E as d,D as f,ne as g,X as h,ce as i,te as l,ae as m,x as n,z as o,C as p,B as r,re as s,w as t,O as u,ee as v,y};
1
+ import{I as e,P as t}from"./sdk-contracts.js";import{a as n,r,s as i}from"./diagnostics.js";import{o as a}from"./sdk-remote-config.js";import{AsyncLocalStorage as o}from"node:async_hooks";import{constants as s}from"node:fs";import c from"node:path";import{access as l,stat as u}from"node:fs/promises";import{spawn as d,spawnSync as f}from"node:child_process";import{Readable as p}from"node:stream";import{pipeline as m}from"node:stream/promises";const h=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,g=[`.com`,`.exe`,`.bat`,`.cmd`],_=new o;async function v(e,t){return e?await _.run(e,t):await t()}async function y(e){return await _.run(void 0,e)}const b=new o;async function ee(e,t){return e?await b.run(e,t):await t()}function x(){let e=b.getStore();return e&&Object.hasOwn(e,`DEVELOPER_DIR`)?e.DEVELOPER_DIR||void 0:process.env.DEVELOPER_DIR||void 0}function S(e){let t=b.getStore();return t?{...e??process.env,...t}:e}async function te(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?w(await r):await T(e,t,n)}async function C(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?w(await r):await T(e,t,n)}function w(e){let t=typeof e.stdout==`string`?e.stdout:String(e.stdout??``),n=typeof e.stderr==`string`?e.stderr:String(e.stderr??``),r=typeof e.exitCode==`number`?e.exitCode:1;return t===e.stdout&&n===e.stderr&&r===e.exitCode?e:{...e,stdout:t,stderr:n,exitCode:r}}function T(e,t,n={}){let r=M(e),i=k();return new Promise((a,o)=>{let s=d(r,t,{cwd:n.cwd,env:S(n.env),stdio:[`pipe`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});n.onSpawn?.(s);let c=``,l=n.binaryStdout?[]:void 0,u=``,f=!1,p=q(n.timeoutMs),m=null,h=!1;function g(){return!h&&(h=!0,m&&clearTimeout(m),b.dispose(),$(s),i.emitForegroundCompletion(e,t),!0)}function _(e){g()&&o(e)}function v(i){if(!g())return;let s=i??1;if(!b.didAbort&&f&&p){o(se(r,e,t,p,s,c,u));return}let d=H(b,r,e,t,s,n.allowFailure,c,u);if(d){o(d);return}a({stdout:c,stderr:u,exitCode:s,stdoutBuffer:l?Buffer.concat(l):void 0})}let y=J({killProcessTree:()=>Z(s,n),settle:v}),b=Y(n,y.requestKill);m=p?setTimeout(()=>{f=!0,y.requestKill()},p):null,n.binaryStdout||s.stdout.setEncoding(`utf8`),s.stderr.setEncoding(`utf8`),fe(s,n.stdin).catch(i=>{b.didAbort||f||pe(i)||(_(oe(r,e,t,i)),Z(s,n))}),s.stdout.on(`data`,e=>{if(n.binaryStdout){l?.push(Buffer.isBuffer(e)?e:Buffer.from(e));return}let t=String(e);c+=t,n.onStdoutChunk?.(t)}),s.stderr.on(`data`,e=>{let t=String(e);u+=t,n.onStderrChunk?.(t)}),s.on(`error`,n=>{_(V(b,r,e,t,n))}),s.once(`exit`,y.recordExit),s.once(`close`,v)})}async function ne(e){let t=W(e);if(!t)return!1;if(c.isAbsolute(t))return G(t);let n=process.env.PATH;if(!n)return!1;let r=ue();for(let e of n.split(c.delimiter)){let n=e.trim();if(n){for(let e of de(t,r))if(await G(c.join(n,e)))return!0}}return!1}async function re(e,n){let r=U(e,n,`executable`);if(r){if(!await G(r))throw new t(`TOOL_MISSING`,`${n} points to a missing or non-executable file: ${r}`,{envName:n,path:r});return r}}async function ie(e,n){let r=U(e,n,`file`);if(r){if(!await K(r))throw new t(`TOOL_MISSING`,`${n} points to a missing or non-file path: ${r}`,{envName:n,path:r});return r}}function ae(e,n,r={}){let i=M(e),a=f(i,n,{cwd:r.cwd,env:S(r.env),stdio:[`pipe`,`pipe`,`pipe`],encoding:r.binaryStdout?void 0:`utf8`,input:r.stdin,timeout:q(r.timeoutMs),windowsHide:!0,shell:!1,...r.maxBuffer===void 0?{}:{maxBuffer:r.maxBuffer}});if(a.error){let o=a.error.code;throw o===`ETIMEDOUT`?new t(`COMMAND_FAILED`,`${i} timed out after ${q(r.timeoutMs)}ms`,{cmd:e,args:n,timeoutMs:q(r.timeoutMs)},a.error):o===`ENOENT`?P(i,e,a.error):F(i,e,n,a.error)}let o=r.binaryStdout?Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(a.stdout??``):void 0,s=r.binaryStdout?``:typeof a.stdout==`string`?a.stdout:(a.stdout??``).toString(),c=typeof a.stderr==`string`?a.stderr:(a.stderr??``).toString(),l=a.status??1;if(l!==0&&!r.allowFailure)throw L(i,e,n,l,s,c);return{stdout:s,stderr:c,exitCode:l,stdoutBuffer:o}}function E(e,t,n={}){return D(e,t,n).pid}function D(e,t,n={}){let r=M(e),i=d(r,t,{cwd:n.cwd,env:S(n.env),stdio:n.stdio??`ignore`,detached:!0,windowsHide:!0,shell:!1}),a=i.pid??0,o=new Promise(e=>{i.once(`error`,t=>{e({pid:a,error:t.message})}),i.once(`exit`,(t,n)=>{e({pid:a,...typeof t==`number`?{exitCode:t}:{},...n?{signal:n}:{}})})});return i.unref(),{pid:a,exited:o}}function O(e,t,n={}){let r=M(e),i=k(),a=d(r,t,{cwd:n.cwd,env:S(n.env),stdio:n.stdio??[`ignore`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});i.emitBackgroundSpawn(e,t);let o=``,s=``;return(n.captureOutput??!0)&&(a.stdout?.setEncoding(`utf8`),a.stderr?.setEncoding(`utf8`),a.stdout?.on(`data`,e=>{o+=e}),a.stderr?.on(`data`,e=>{s+=e})),{child:a,wait:new Promise((c,l)=>{let u=!1;function d(n){return!u&&(u=!0,m.dispose(),$(a),i.emitBackgroundCompletion(e,t,n),!0)}function f(i){if(!d(`exit`))return;let a=i??1,u=H(m,r,e,t,a,n.allowFailure,o,s);if(u){l(u);return}c({stdout:o,stderr:s,exitCode:a})}let p=J({killProcessTree:()=>Z(a,n),settle:f}),m=Y(n,p.requestKill);a.on(`error`,n=>{d(`error`)&&l(V(m,r,e,t,n))}),a.once(`exit`,p.recordExit),a.once(`close`,f)})}}function k(){let e=n(),t=e.debug===!0,r=a(process.env.AGENT_DEVICE_EXEC_TRACE??``)===!0;if(!t&&!r)return A();r&&e.flushOnSuccess!==!0&&i({flushOnSuccess:!0});let o=Date.now(),s=!1;return{emitForegroundCompletion:(e,t)=>{s||(s=!0,j({cmd:e,args:t,startedAtMs:o}))},emitBackgroundSpawn:(e,t)=>{j({cmd:e,args:t,data:{event:`spawn`}})},emitBackgroundCompletion:(e,t,n)=>{s||(s=!0,j({cmd:e,args:t,startedAtMs:o,data:{event:n}}))}}}function A(){return{emitForegroundCompletion:()=>{},emitBackgroundSpawn:()=>{},emitBackgroundCompletion:()=>{}}}function j(e){let t=e.args.slice(0,6);r({level:`debug`,phase:`exec_command`,durationMs:e.startedAtMs===void 0?void 0:Math.max(0,Date.now()-e.startedAtMs),data:{command:e.cmd,argsPrefix:t,...e.args.length>t.length?{omittedArgCount:e.args.length-t.length}:{},...e.data??{}}})}function M(e){let n=W(e);if(!n)throw new t(`INVALID_ARGS`,`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e,hint:`Use a bare command name from PATH or an absolute executable path.`});return n}function N(e,t,n,r){return r.code===`ENOENT`?P(e,t,r):F(e,t,n,r)}function P(e,n,r){return new t(`TOOL_MISSING`,`${e} not found in PATH`,{cmd:n},r)}function F(e,n,r,i){return new t(`COMMAND_FAILED`,`Failed to run ${e}`,{cmd:n,args:r},i)}function oe(e,n,r,i){return new t(`COMMAND_FAILED`,`Failed to write stdin for ${e}`,{cmd:n,args:r},i instanceof Error?i:void 0)}function I(t,n,r){return e({cmd:n,args:r,executable:t})}function se(e,n,r,i,a,o,s){return new t(`COMMAND_FAILED`,`${e} timed out after ${i}ms`,{cmd:n,args:r,stdout:o,stderr:s,exitCode:a,timeoutMs:i})}function ce(e){return e instanceof t&&e.code===`COMMAND_FAILED`&&typeof e.details?.timeoutMs==`number`}function L(e,n,r,i,a,o){return new t(`COMMAND_FAILED`,`${e} exited with code ${i}`,B({stdout:a,stderr:o,exitCode:i},{cmd:n,args:r}))}const R=/xcrun: error: unable to find utility "([^"]+)"/;function le(e){let t=R.exec(e)?.[1];if(!t)return{};let n=x(),r=n?`DEVELOPER_DIR ${n}`:`the developer dir selected by xcode-select (see xcode-select -p)`;return{reason:`xcrun-tool-not-found`,developerDir:n??null,hint:`xcrun could not find ${t} in ${r}. Export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer (or your Xcode's path) before running agent-device, or run sudo xcode-select -s /Applications/Xcode.app.`}}function z(e,n,r){if(e.exitCode===0)return e;throw new t(`COMMAND_FAILED`,n,B(e,typeof r==`function`?r(e):r))}function B(e,t){return{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,processExitError:!0,...t,...le(e.stderr)}}function V(e,t,n,r,i){return e.didAbort?I(t,n,r):N(t,n,r,i)}function H(e,t,n,r,i,a,o,s){return e.didAbort?I(t,n,r):i!==0&&!a?L(t,n,r,i,o,s):null}function U(e,n,r){let i=e?.trim();if(i){if(!c.isAbsolute(i)||i.includes(`\0`))throw new t(`INVALID_ARGS`,`${n} must be an absolute ${r} path, not ${JSON.stringify(e)}`,{envName:n,path:e});return i}}function W(e){let t=e.trim();return!t||t.includes(`\0`)?null:c.isAbsolute(t)?t:t.includes(`/`)||t.includes(`\\`)?null:h.test(t)?t:null}function ue(){if(process.platform!==`win32`)return[``];let e=process.env.PATHEXT;if(!e)return g;let t=e.split(`;`).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:g}function de(e,t){if(process.platform!==`win32`)return[e];let n=e.toLowerCase();return t.some(e=>n.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}async function G(e){try{return await K(e)?(await l(e,process.platform===`win32`?s.F_OK:s.X_OK),!0):!1}catch{return!1}}async function K(e){try{return(await u(e)).isFile()}catch{return!1}}function q(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function J(e){let t=!1,n=!1,r=null,i=()=>{t&&n&&e.settle(r)};return{requestKill:()=>{t=!0,e.killProcessTree(),i()},recordExit:e=>{n=!0,r=e??1,i()}}}function Y(e,t){let n=!1,r=()=>{n=!0,t()};return e.signal?.aborted?r():e.signal?.addEventListener(`abort`,r,{once:!0}),{get didAbort(){return n},dispose:()=>{e.signal?.removeEventListener(`abort`,r)}}}function X(e,t){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(-e,t),!0}catch{return!1}}function Z(e,t){if(!t.kill){Q(e,t.detached,`SIGKILL`);return}Q(e,t.detached,t.kill.signal);let n=setTimeout(()=>Q(e,t.detached,`SIGKILL`),t.kill.graceMs);n.unref(),e.once(`exit`,()=>clearTimeout(n))}function Q(e,t,n){if(t&&e.pid&&process.platform!==`win32`){X(e.pid,n);return}e.exitCode===null&&e.signalCode===null&&e.kill(n)}function $(e){e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()}async function fe(e,t){if(e.stdin){if(t===void 0){e.stdin?.end();return}await m(p.from([t]),e.stdin)}}function pe(e){return e instanceof Error&&`code`in e&&e.code===`EPIPE`}export{v as _,G as a,ie as c,E as d,D as f,ne as g,X as h,ce as i,te as l,ae as m,x as n,z as o,C as p,B as r,re as s,w as t,O as u,ee as v,y};
package/dist/src/file.js CHANGED
@@ -1 +1 @@
1
- import{N as e}from"./sdk-contracts.js";import{r as t}from"./diagnostics.js";import{i as n,k as r,t as i}from"./owner-identity.js";import{t as a}from"./timeouts.js";import o from"node:path";import s from"node:fs";import c from"node:crypto";const l=`.lock`;async function u(e){let t=await e.acquire();try{let n=await e.task();return await t(),n}catch(e){throw await t().catch(()=>void 0),e}}const d=new Set,f=c.randomUUID();async function p(n){let{lockDirPath:r,owner:i}=n,l=o.join(r,`owner.json`),u=Date.now()+(n.timeoutMs??3e4),p=n.pollMs??100,_=n.ownerGraceMs??5e3,y=n.description??`process lock`;s.mkdirSync(o.dirname(r),{recursive:!0});let b=c.randomUUID(),x={...i,claimToken:b,claimIssuerId:f};for(;Date.now()<u;)try{s.mkdirSync(r),h(l,x),d.add(b);let n=!1;return async()=>{if(!n){if(d.delete(b),g(r,l,x)!==`unverified`){n=!0;return}throw t({level:`warn`,phase:`process_lock_release_unverified`,data:{lockDirPath:r,description:y,ownerReleaseUnverified:!0}}),new e(`COMMAND_FAILED`,`Cannot verify ownership of ${y}`,{lockDirPath:r,ownerReleaseUnverified:!0,hint:m(r)})}}}catch(e){let t=e;if(t.code!==`EEXIST`)throw t;if(v(r,l,_))continue;await a(p)}let S=k(l);throw new e(`COMMAND_FAILED`,`Timed out waiting for ${y}`,{lockDirPath:r,...M(r,S),...S.kind===`unreadable`?{hint:m(r)}:{}})}function m(e){return`Remove ${e} once you have confirmed no live process holds it, then retry.`}function h(e,t){r({destination:e,contents:JSON.stringify(t)})}function g(e,t,r){let i=k(t);return i.kind===`unreadable`?`unverified`:i.kind===`unwritten`||!n(i.owner,r)||i.owner.claimToken!==r.claimToken?`not-owner`:_(e,t)}function _(e,t){try{s.unlinkSync(t)}catch(e){if(O(e)!==`ENOENT`)return`unverified`}try{return s.rmdirSync(e),`removed`}catch(e){return O(e)===`ENOENT`?`removed`:`unverified`}}function v(e,t,n){let r;try{r=s.statSync(e)}catch{return!0}if(!r.isDirectory())return y(r,n)&&b(e,t,n,{kind:`stray`});let i=k(t);return i.kind===`owner`?(!N(i.owner)||P(i.owner))&&b(e,t,n,{kind:`dead-claim`,claimToken:i.owner.claimToken}):i.kind!==`unreadable`&&y(r,n)&&b(e,t,n,{kind:`empty`})}function y(e,t){return Date.now()-e.mtimeMs>=t}function b(e,t,n,r){if(!T(e,n))return!1;try{switch(r.kind){case`dead-claim`:return x(e,t,r.claimToken);case`empty`:return S(e,n);case`stray`:return C(e)}}finally{D(e)}}function x(e,t,n){let r=k(t);if(r.kind!==`owner`||r.owner.claimToken!==n)return!1;try{return s.rmSync(e,{recursive:!0,force:!0}),!0}catch{return!1}}function S(e,t){let n;try{n=s.statSync(e)}catch{return!1}if(!n.isDirectory()||!y(n,t))return!1;try{return s.rmdirSync(e),!0}catch{return!1}}function C(e){try{return s.unlinkSync(e),!0}catch{return!1}}function w(e){return`${e.endsWith(l)?e.slice(0,-5):e}.reclaim${l}`}function T(e,t){let n=w(e);for(let e=0;e<2;e+=1)try{return s.mkdirSync(n),!0}catch(e){if(O(e)!==`EEXIST`)throw e;if(!E(n,t))return!1}return!1}function E(e,t){let n;try{n=s.statSync(e)}catch{return!0}if(Date.now()-n.mtimeMs<t)return!1;try{s.rmdirSync(e)}catch{}return!0}function D(e){try{s.rmdirSync(w(e))}catch{}}function O(e){return e?.code}function k(e){let t;try{t=s.readFileSync(e,`utf8`)}catch(e){return e?.code===`ENOENT`?{kind:`unwritten`}:{kind:`unreadable`}}let n=A(t);return n?{kind:`owner`,owner:n}:{kind:`unreadable`}}function A(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let n=t;for(let[e,t]of Object.entries(j))if(!t(n[e]))return null;return{pid:n.pid,startTime:typeof n.startTime==`string`?n.startTime:null,acquiredAtMs:n.acquiredAtMs,claimToken:typeof n.claimToken==`string`?n.claimToken:null,claimIssuerId:typeof n.claimIssuerId==`string`?n.claimIssuerId:void 0}}const j={pid:e=>typeof e==`number`&&Number.isInteger(e)&&e>0,acquiredAtMs:e=>typeof e==`number`&&Number.isFinite(e),startTime:e=>e==null||typeof e==`string`};function M(e,t){let n=Date.now(),r;try{r=Math.max(0,Math.round(n-s.statSync(e).mtimeMs))}catch{}return{...r===void 0?{}:{lockAgeMs:r},...t.kind===`owner`?{ownerPid:t.owner.pid,ownerStartTime:t.owner.startTime,ownerAgeMs:Math.max(0,Math.round(n-t.owner.acquiredAtMs)),ownerLiveness:i({owner:t.owner})}:t.kind===`unreadable`?{ownerRecordUnreadable:!0}:{}}}function N(e){let t=i({owner:e});return t!==`owner-process-dead`&&t!==`owner-process-reused`}function P(e){return e.pid!==process.pid||e.claimToken===null||e.claimIssuerId!==f?!1:!d.has(e.claimToken)}export{u as n,p as t};
1
+ import{J as e,P as t}from"./sdk-contracts.js";import{r as n}from"./diagnostics.js";import{A as r,a as i,r as a,t as o}from"./owner-identity.js";import{t as s}from"./timeouts.js";import c from"node:crypto";import l from"node:fs";import u from"node:path";const d=`owner.json`,f=`.lock`;async function p(e){let t=await e.acquire();try{let n=await e.task();return await t(),n}catch(e){throw await t().catch(()=>void 0),e}}const m=new Set,h=c.randomUUID();function g(e){let t;try{t=l.lstatSync(e)}catch(t){return I(t)===`ENOENT`?{state:l.existsSync(M(e))?`publishing`:`absent`}:{state:`unproven`,reason:`owner-unreadable`}}if(!t.isDirectory())return{state:`unproven`,reason:`non-directory`};let n=L(u.join(e,d));if(n.kind===`unreadable`)return{state:`unproven`,reason:`owner-unreadable`};if(n.kind===`unwritten`)return l.existsSync(M(e))?{state:`publishing`}:{state:`unproven`,reason:`owner-unwritten`};let{pid:r,startTime:i,acquiredAtMs:a}=n.owner;return{state:`held`,owner:{pid:r,startTime:i,acquiredAtMs:a},liveness:o({owner:n.owner})}}function _(e){let{lockDirPath:t}=e;l.mkdirSync(u.dirname(t),{recursive:!0});let n=x(u.join(t,d));if(n.kind===`live`)return{status:`busy`,inspection:n.inspection};if(!N(t))return{status:`busy`,inspection:g(t)};let r=v(t,()=>y(e,n),e=>{e.status===`acquired`&&m.delete(e.claimToken)});return r.status===`acquired`?{status:`acquired`,acquisition:r.acquisition}:{status:r.status,inspection:r.inspection??g(t)}}function v(t,r,i){let a;try{a=r()}catch(r){try{F(t)}catch(r){n({level:`warn`,phase:`process_lock_guard_release_failed`,data:{lockDirPath:t,error:e(r)}})}throw r}try{F(t)}catch(e){throw i(a),e}return a}function y(e,t){let{lockDirPath:n}=e,r=u.join(n,d),i=S(n,r);if(i.kind===`unproven`)return{status:`unproven`,inspection:i.inspection};if(i.kind===`owner`){if(t.kind!==`reclaimable`||!C(i.owner,t.owner))return{status:`busy`};if(k(n,r,i.owner)!==`removed`)return{status:`unproven`}}return b(e,r)}function b(e,t){let{lockDirPath:n,owner:r}=e;try{l.mkdirSync(n)}catch(e){if(I(e)!==`EEXIST`)throw e;return{status:`unproven`}}let i=c.randomUUID(),a={...r,claimToken:i,claimIssuerId:h};try{O(t,a)}catch(e){try{l.rmdirSync(n)}catch{}throw e}return m.add(i),{status:`acquired`,claimToken:i,acquisition:E(e,a)}}function x(e){let t=L(e);if(t.kind!==`owner`)return{kind:`none`};let n=o({owner:t.owner});if(V(n)&&!H(t.owner)){let{pid:e,startTime:r,acquiredAtMs:i}=t.owner;return{kind:`live`,inspection:{state:`held`,owner:{pid:e,startTime:r,acquiredAtMs:i},liveness:n}}}return{kind:`reclaimable`,owner:t.owner}}function S(e,t){let n;try{n=l.lstatSync(e)}catch(e){return I(e)===`ENOENT`?{kind:`absent`}:{kind:`unproven`,inspection:{state:`unproven`,reason:`owner-unreadable`}}}if(!n.isDirectory())return{kind:`unproven`,inspection:{state:`unproven`,reason:`non-directory`}};let r=L(t);return r.kind===`owner`?{kind:`owner`,owner:r.owner}:{kind:`unproven`,inspection:{state:`unproven`,reason:r.kind===`unwritten`?`owner-unwritten`:`owner-unreadable`}}}function C(e,t){return e.pid===t.pid&&e.startTime===t.startTime&&e.acquiredAtMs===t.acquiredAtMs&&e.claimToken===t.claimToken&&e.claimIssuerId===t.claimIssuerId}async function w(e){return(await T(e)).release}async function T(e){let n=Date.now()+(e.timeoutMs??3e4),r=e.pollMs??100;do{let t=_(e);if(t.status===`acquired`)return t.acquisition;let i=n-Date.now();if(i<=0)break;await s(Math.min(r,i))}while(Date.now()<n);let i=L(u.join(e.lockDirPath,d));throw new t(`COMMAND_FAILED`,`Timed out waiting for ${e.description??`process lock`}`,{lockDirPath:e.lockDirPath,reason:`process_lock_timeout`,...B(e.lockDirPath,i),inspection:g(e.lockDirPath),hint:D(e.lockDirPath)})}function E(e,r){let{lockDirPath:i}=e,a=u.join(i,d),o=!0,s=!1;return Object.freeze({assertHeld(){if(!o||A(i,r)!==`owned`)throw new t(`COMMAND_FAILED`,`Process lock acquisition is no longer held`,{lockDirPath:i,ownerOwnershipLost:!0})},async release(){if(s)return;o=!1,m.delete(r.claimToken);let c=A(i,r);if(c===`absent`||c===`not-owner`){s=!0;return}let l=`unverified`;if(await P(i))try{l=k(i,a,r)}finally{F(i)}if(l!==`unverified`){s=!0;return}throw n({level:`warn`,phase:`process_lock_release_unverified`,data:{lockDirPath:i,description:e.description,ownerReleaseUnverified:!0}}),new t(`COMMAND_FAILED`,`Cannot verify ownership of ${e.description??`process lock`}`,{lockDirPath:i,ownerReleaseUnverified:!0,hint:D(i)})}})}function D(e){return`Restore process inspection or stop the verified owner, then retry. Remove ${e} and ${M(e)} only after confirming all users of this state directory have stopped.`}function O(e,t){r({destination:e,contents:JSON.stringify(t)})}function k(e,t,n){let r=A(e,n);return r===`owned`?j(e,t,n):r===`absent`?`removed`:r}function A(e,t){let n=L(u.join(e,d));return n.kind===`unreadable`?`unverified`:n.kind===`unwritten`?l.existsSync(e)?`unverified`:`absent`:i(n.owner,t)&&n.owner.claimToken===t.claimToken?`owned`:`not-owner`}function j(e,t,n){try{if(l.readdirSync(e).some(e=>e!==d))return`unverified`}catch(e){return I(e)===`ENOENT`?`removed`:`unverified`}try{l.unlinkSync(t)}catch(e){if(I(e)!==`ENOENT`)return`unverified`}try{return l.rmdirSync(e),`removed`}catch(e){if(I(e)===`ENOENT`)return`removed`;try{r({destination:t,contents:JSON.stringify(n),publish:`link-exclusive`})}catch{}return`unverified`}}function M(e){return`${e.endsWith(f)?e.slice(0,-5):e}.reclaim${f}`}function N(e){let t;try{t=l.openSync(M(e),`wx`,384)}catch(e){if(I(e)!==`EEXIST`)throw e;return!1}return l.closeSync(t),!0}async function P(e){let t=Date.now()+5e3;for(;!N(e);){if(Date.now()>=t)return!1;await s(5)}return!0}function F(e){try{l.unlinkSync(M(e))}catch(n){throw new t(`COMMAND_FAILED`,`Process lock mutation guard release could not be confirmed.`,{reason:`process_lock_guard_release_failed`,lockDirPath:e,hint:D(e)},n)}}function I(e){return e?.code}function L(e){let t;try{t=l.readFileSync(e,`utf8`)}catch(e){return e?.code===`ENOENT`?{kind:`unwritten`}:{kind:`unreadable`}}let n=R(t);return n?{kind:`owner`,owner:n}:{kind:`unreadable`}}function R(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let n=t;for(let[e,t]of Object.entries(z))if(!t(n[e]))return null;return{pid:n.pid,startTime:typeof n.startTime==`string`?n.startTime:null,acquiredAtMs:n.acquiredAtMs,claimToken:typeof n.claimToken==`string`?n.claimToken:null,claimIssuerId:typeof n.claimIssuerId==`string`?n.claimIssuerId:void 0}}const z={pid:a,acquiredAtMs:e=>typeof e==`number`&&Number.isFinite(e),startTime:e=>e==null||typeof e==`string`};function B(e,t){let n=Date.now(),r;try{r=Math.max(0,Math.round(n-l.statSync(e).mtimeMs))}catch{}return{...r===void 0?{}:{lockAgeMs:r},...t.kind===`owner`?{ownerPid:t.owner.pid,ownerStartTime:t.owner.startTime,ownerAgeMs:Math.max(0,Math.round(n-t.owner.acquiredAtMs)),ownerLiveness:o({owner:t.owner})}:t.kind===`unreadable`?{ownerRecordUnreadable:!0}:{}}}function V(e){return e!==`owner-process-dead`&&e!==`owner-process-reused`}function H(e){return e.pid!==process.pid||e.claimToken===null||e.claimIssuerId!==h?!1:!m.has(e.claimToken)}export{p as a,_ as i,T as n,g as r,w as t};
package/dist/src/find.js CHANGED
@@ -1 +1 @@
1
- import{d as e,o as t,y as n}from"./sdk-contracts.js";import{Fn as r,Nn as i,Pn as a,Rn as o,Rt as s,_t as c}from"./sdk-batch.js";import{c as l}from"./session-store.js";import{c as u}from"./target-evidence.js";import{f as d,m as f,p,u as m}from"./runtime.js";import{r as h,t as g}from"./success-text.js";import{m as _}from"./overlay.js";import{O as v,h as y,v as b}from"./session-snapshot.js";import{t as x}from"./selector-pipeline-policy.js";import{s as S}from"./quality-warnings.js";import{r as C}from"./internal/daemon.js";import{t as w}from"./snapshot-runtime-binding.js";import{l as T,n as E}from"./selector-runtime.js";import{t as D}from"./type-text-runtime.js";function O(e,t){let r=t[0]?.rect;if(!r)return e;let i=e.filter(e=>{if(!e.rect)return!1;let t=n(e.rect);return t.x>=r.x&&t.x<=r.x+r.width&&t.y>=r.y&&t.y<=r.y+r.height}),a=i.length>0?i:e;return a.length<2?a:k(a,t,p(t))}function k(e,t,n){return e.map((e,r)=>({node:e,index:r,score:A(e,t,n)})).sort((e,t)=>t.score===e.score?M(e.node)-M(t.node)||e.index-t.index:t.score-e.score).map(e=>e.node)}function A(e,t,n){let r=n(e);if(r.reason===`covered`)return 0;let i=j(r,t[0]);return i>0?i:e.hittable&&e.rect&&!f(e,t[0])?3:+!!e.rect}function j(e,t){return e.node.rect?e.reason===`semantic-target`||e.reason===`same-rect-descendant`?4:e.reason===`hittable-ancestor`&&!f(e.node,t)?2:0:0}function M(e){return e.rect?e.rect.width*e.rect.height:1/0}function N(e,n,r){let i={matches:e.length,candidates:e.slice(0,5).map(e=>_(e,0,!1))};return t(`AMBIGUOUS_MATCH`,`find matched ${e.length} elements for ${n} "${r}". Use a more specific locator or selector.`,{locator:n,query:r,...i})}function P(e){if(e.ambiguity!==`reject-candidates`)throw Error(`find's resolution policy must reject candidates, got "${e.ambiguity}"`)}function F(e){let{nodes:n,locator:r,query:i,selectorExpression:o,flags:s,platform:c}=e,l=x.findAct,u=n.filter(e=>!f(e,n[0])),d=l.resolution,p;if(p=o?m(l,u,o,{platform:c}).list?.matchedNodes??[]:a(u,r,i,{requireRect:d.requireRect}).matches,p=O(p,n),p.length>1){P(d);let e=I(p,s);if(!e)return{ok:!1,response:N(p,r,i)};p=e}let h=p[0]??null;return h?{ok:!0,node:h}:{ok:!1,response:t(`COMMAND_FAILED`,`find did not match any element`)}}function I(e,t){return t?.findFirst?[e[0]]:t?.findLast?[e.at(-1)]:null}function L(e){let{device:t,session:n,req:r,logPath:i,locator:a,query:o,sessionStore:s,sessionName:c}=e,l=T({device:t,session:n,sessionStore:s,sessionName:c,req:r,logPath:i,capture:e.capture,captureProof:e.captureProof});return async()=>{let{snapshot:e}=await l.capture({flags:{...r.flags,snapshotInteractiveOnly:!0},recovery:{legacyIosSparse:{query:o,shouldScope:z(a)},sparseVerdictQueryScope:{query:o,shouldScope:z(a)}}});return e}}function R(e){return t(`COMMAND_FAILED`,`find could not read the current accessibility tree`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen.`})}function z(e){return e!==`role`}async function B(n){let{req:a,sessionName:l,logPath:f,sessionStore:p,invoke:m}=n,h=a.command;if(h!==`find`)return null;let g=a.positionals??[],_=i(g,a.flags);if(!_.ok)return t(_.code,_.message);let{locator:v,query:y,action:b,value:C}=_.parsed;if(a.flags?.record&&!r(b))return t(`INVALID_ARGS`,`find ${b} is a mutating action and is always recorded; --record only applies to a read-only find (exists, wait, list, get text, get attrs).`);let T=await E({req:a,sessionName:l,logPath:f,sessionStore:p,inspectFacts:n.inspectFacts,bindDevice:n.bindDevice});if(T)return T;let D=p.get(l);if(!D)return e();let O=D.device,k=await w({command:`find`,device:O,session:D,plan:s({hasActiveApp:D.appBundleId!==void 0,intent:c(b)}),inspectFacts:n.inspectFacts,bindDevice:n.bindDevice});if(!k.ok)return k.response;let A=o(v,y),j={},M=L({device:O,session:D,req:a,logPath:f,locator:v,query:y,sessionStore:p,sessionName:l,capture:k.capture,captureProof:j}),N={req:a,sessionName:l,logPath:f,sessionStore:p,invoke:m,session:D,device:O,command:h,locator:v,query:y,publicFlags:X(a.flags),boundFocusPoint:k.focusPoint,boundTypeText:k.typeText},P=await M();if(S(P.snapshotQuality))return u({response:R(P.snapshotQuality),consumedTree:P,captureProof:j});let{nodes:I}=P,z=F({nodes:I,locator:v,query:y,selectorExpression:A,flags:a.flags,platform:O.platform});if(!z.ok)return u({response:z.response,consumedTree:P,captureProof:j});let B=z.node,H=await d(x.findAct,I,B),U=H.node,W=`@${U.ref}`,G={...a.flags??{},noRecord:!0},K=await V(N,{node:B,resolvedNode:U,ref:W,nodes:I,...P.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:P.iosSystemSurfaceBundleId}:{},...P.keyboard?{keyboard:P.keyboard}:{},actionFlags:G,...H.kind===`occluded`?{occludedNode:H.node}:{}},b,C);return K&&u({response:K,consumedTree:P,captureProof:j})}async function V(e,t,n,r){let i={click:()=>U(e,t),fill:()=>W(e,t,r),focus:()=>G(e,t),type:()=>K(e,t,r)}[n];return i?await i():null}function H(e){return{ref:e.ref,node:e.resolvedNode,nodes:e.nodes,...e.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:e.iosSystemSurfaceBundleId}:{},...e.keyboard?{keyboard:e.keyboard}:{}}}async function U(e,t){let{req:r,sessionName:i,sessionStore:a,session:o,invoke:s,command:c,locator:u,query:d,publicFlags:f}=e,p=await s({token:r.token,session:i,command:`click`,positionals:[t.ref],flags:t.actionFlags,internal:{findResolvedTarget:H(t)}});if(!p.ok)return p;let m=t.resolvedNode.rect?n(t.resolvedNode.rect):t.node.rect?n(t.node.rect):null,_={ref:t.ref,locator:u,query:d};m&&(_.x=m.x,_.y=m.y);let v=g(p.data)??`Tapped ${t.ref}${m?` (${m.x}, ${m.y})`:``}`;return Object.assign(_,h(v)),l(a,o,r,c,{ref:t.ref,action:`click`,locator:u,query:d},{flags:f}),{ok:!0,data:_}}async function W(e,n,r){let{req:i,sessionName:a,sessionStore:o,session:s,invoke:c,command:u,publicFlags:d}=e;if(r===void 0)return t(`INVALID_ARGS`,`find fill requires text (use "" to clear the field)`);let f=await c({token:i.token,session:a,command:`fill`,positionals:[n.ref,r],flags:n.actionFlags,internal:{findResolvedTarget:H(n)}});return f.ok&&l(o,s,i,u,{ref:n.ref,action:`fill`},{flags:d}),f}async function G(e,t){let n=await q(e,t);return n.ok&&Y(e,t,`focus`),n}async function K(e,n,r){let{req:i,logPath:a,session:o}=e;if(!r)return t(`INVALID_ARGS`,`find type requires text`);let s=await q(e,n);if(!s.ok)return s;v(o);let c=e.boundTypeText;if(!c)return t(`COMMAND_FAILED`,`find type was admitted without a text-entry operation`);let l=await D({operations:{typeText:c}},[r],y(a,i.flags,o.appBundleId,o.trace?.outPath));return Y(e,n,`type`),{ok:!0,data:l??{ref:n.ref}}}async function q(e,r){let{req:i,logPath:a,session:o}=e,s=J(r,`be focused`);if(s)return s;let c=r.resolvedNode.rect?n(r.resolvedNode.rect):null;if(!c)return t(`COMMAND_FAILED`,`matched element has no bounds`);v(o);let l=e.boundFocusPoint;return l?{ok:!0,data:await C({operations:{focusPoint:l}},c,y(a,i.flags,o.appBundleId,o.trace?.outPath))??{ref:r.ref}}:t(`COMMAND_FAILED`,`find focus was admitted without a focus operation`)}function J(e,n){let r=e.occludedNode;return r?t(`COMMAND_FAILED`,`Matched element ${e.ref} is covered by another visible element and cannot ${n} safely`,{ref:`@${r.ref}`,interactionBlocked:r.interactionBlocked,hint:`Use a different visible target, scroll it clear of the overlay, or inspect with snapshot/screenshot before retrying.`}):null}function Y(e,t,n){let{req:r,sessionStore:i,session:a,command:o,publicFlags:s}=e;l(i,a,r,o,{ref:t.ref,action:n},{flags:s})}function X(e){return{...b(e)??{}}}export{B as handleFindCommands};
1
+ import{b as e,f as t,s as n}from"./sdk-contracts.js";import{Fn as r,Nn as i,Pn as a,Rn as o,Rt as s,_t as c}from"./sdk-batch.js";import{f as l}from"./dispatch-resolve.js";import{c as u}from"./target-evidence.js";import{f as d,m as f,p,u as m}from"./runtime.js";import{r as h,t as g}from"./success-text.js";import{m as _}from"./overlay.js";import{A as v,_ as y,b}from"./session-snapshot.js";import{t as x}from"./selector-pipeline-policy.js";import{s as S}from"./quality-warnings.js";import{r as C}from"./internal/daemon.js";import{t as w}from"./snapshot-runtime-binding.js";import{l as T,n as E}from"./selector-runtime.js";import{t as D}from"./type-text-runtime.js";function O(t,n){let r=n[0]?.rect;if(!r)return t;let i=t.filter(t=>{if(!t.rect)return!1;let n=e(t.rect);return n.x>=r.x&&n.x<=r.x+r.width&&n.y>=r.y&&n.y<=r.y+r.height}),a=i.length>0?i:t;return a.length<2?a:k(a,n,p(n))}function k(e,t,n){return e.map((e,r)=>({node:e,index:r,score:A(e,t,n)})).sort((e,t)=>t.score===e.score?M(e.node)-M(t.node)||e.index-t.index:t.score-e.score).map(e=>e.node)}function A(e,t,n){let r=n(e);if(r.reason===`covered`)return 0;let i=j(r,t[0]);return i>0?i:e.hittable&&e.rect&&!f(e,t[0])?3:+!!e.rect}function j(e,t){return e.node.rect?e.reason===`semantic-target`||e.reason===`same-rect-descendant`?4:e.reason===`hittable-ancestor`&&!f(e.node,t)?2:0:0}function M(e){return e.rect?e.rect.width*e.rect.height:1/0}function N(e,t,r){let i={matches:e.length,candidates:e.slice(0,5).map(e=>_(e,0,!1))};return n(`AMBIGUOUS_MATCH`,`find matched ${e.length} elements for ${t} "${r}". Use a more specific locator or selector.`,{locator:t,query:r,...i})}function P(e){if(e.ambiguity!==`reject-candidates`)throw Error(`find's resolution policy must reject candidates, got "${e.ambiguity}"`)}function F(e){let{nodes:t,locator:r,query:i,selectorExpression:o,flags:s,platform:c}=e,l=x.findAct,u=t.filter(e=>!f(e,t[0])),d=l.resolution,p;if(p=o?m(l,u,o,{platform:c}).list?.matchedNodes??[]:a(u,r,i,{requireRect:d.requireRect}).matches,p=O(p,t),p.length>1){P(d);let e=I(p,s);if(!e)return{ok:!1,response:N(p,r,i)};p=e}let h=p[0]??null;return h?{ok:!0,node:h}:{ok:!1,response:n(`COMMAND_FAILED`,`find did not match any element`)}}function I(e,t){return t?.findFirst?[e[0]]:t?.findLast?[e.at(-1)]:null}function L(e){let{device:t,req:n,logPath:r,locator:i,query:a,sessionStore:o,sessionName:s}=e,c=T({ref:e.ref,device:t,sessionStore:o,sessionName:s,req:n,logPath:r,capture:e.capture,captureProof:e.captureProof});return async()=>{let{snapshot:e}=await c.capture({flags:{...n.flags,snapshotInteractiveOnly:!0},recovery:{legacyIosSparse:{query:a,shouldScope:z(i)},sparseVerdictQueryScope:{query:a,shouldScope:z(i)}}});return e}}function R(e){return n(`COMMAND_FAILED`,`find could not read the current accessibility tree`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen.`})}function z(e){return e!==`role`}async function B(e){let{req:a,sessionName:l,logPath:f,sessionStore:p,invoke:m}=e,h=p.lookup(l),g=a.command;if(g!==`find`)return null;let _=a.positionals??[],v=i(_,a.flags);if(!v.ok)return n(v.code,v.message);let{locator:y,query:b,action:C,value:T}=v.parsed;if(a.flags?.record&&!r(C))return n(`INVALID_ARGS`,`find ${C} is a mutating action and is always recorded; --record only applies to a read-only find (exists, wait, list, get text, get attrs).`);let D=await E({req:a,sessionName:l,logPath:f,sessionStore:p,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(D)return D;let O=h?p.requireCurrent(h):void 0;if(!O||!h)return t();let k=O.device,A=await w({command:`find`,device:k,session:O,plan:s({hasActiveApp:O.appBundleId!==void 0,intent:c(C)}),inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(!A.ok)return A.response;let j=o(y,b),M={},N=L({ref:h,device:k,req:a,logPath:f,locator:y,query:b,sessionStore:p,sessionName:l,capture:A.capture,captureProof:M}),P={sessionRef:h,req:a,sessionName:l,logPath:f,sessionStore:p,invoke:m,device:k,command:g,locator:y,query:b,publicFlags:X(a.flags),boundFocusPoint:A.focusPoint,boundTypeText:A.typeText},I=await N();if(S(I.snapshotQuality))return u({response:R(I.snapshotQuality),consumedTree:I,captureProof:M});let{nodes:z}=I,B=F({nodes:z,locator:y,query:b,selectorExpression:j,flags:a.flags,platform:k.platform});if(!B.ok)return u({response:B.response,consumedTree:I,captureProof:M});let H=B.node,U=await d(x.findAct,z,H),W=U.node,G=`@${W.ref}`,K={...a.flags??{},noRecord:!0},q=await V(P,{node:H,resolvedNode:W,ref:G,nodes:z,...I.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:I.iosSystemSurfaceBundleId}:{},...I.keyboard?{keyboard:I.keyboard}:{},actionFlags:K,...U.kind===`occluded`?{occludedNode:U.node}:{}},C,T);return q&&u({response:q,consumedTree:I,captureProof:M})}async function V(e,t,n,r){let i={click:()=>U(e,t),fill:()=>W(e,t,r),focus:()=>G(e,t),type:()=>K(e,t,r)}[n];return i?await i():null}function H(e){return{ref:e.ref,node:e.resolvedNode,nodes:e.nodes,...e.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:e.iosSystemSurfaceBundleId}:{},...e.keyboard?{keyboard:e.keyboard}:{}}}async function U(t,n){let{req:r,sessionName:i,sessionStore:a,sessionRef:o,invoke:s,command:c,locator:u,query:d,publicFlags:f}=t,p=await s({token:r.token,session:i,command:`click`,positionals:[n.ref],flags:n.actionFlags,internal:{findResolvedTarget:H(n)}});if(!p.ok)return p;let m=n.resolvedNode.rect?e(n.resolvedNode.rect):n.node.rect?e(n.node.rect):null,_={ref:n.ref,locator:u,query:d};m&&(_.x=m.x,_.y=m.y);let v=g(p.data)??`Tapped ${n.ref}${m?` (${m.x}, ${m.y})`:``}`;return Object.assign(_,h(v)),l(a,o,r,c,{ref:n.ref,action:`click`,locator:u,query:d},{flags:f}),{ok:!0,data:_}}async function W(e,t,r){let{req:i,sessionName:a,sessionStore:o,sessionRef:s,invoke:c,command:u,publicFlags:d}=e;if(r===void 0)return n(`INVALID_ARGS`,`find fill requires text (use "" to clear the field)`);let f=await c({token:i.token,session:a,command:`fill`,positionals:[t.ref,r],flags:t.actionFlags,internal:{findResolvedTarget:H(t)}});return f.ok&&l(o,s,i,u,{ref:t.ref,action:`fill`},{flags:d}),f}async function G(e,t){let n=await q(e,t);return n.ok&&Y(e,t,`focus`),n}async function K(e,t,r){let{req:i,logPath:a}=e;if(!r)return n(`INVALID_ARGS`,`find type requires text`);let o=await q(e,t);if(!o.ok)return o;let s=e.sessionStore.requireCurrent(e.sessionRef);v(s);let c=e.boundTypeText;if(!c)return n(`COMMAND_FAILED`,`find type was admitted without a text-entry operation`);let l=await D({operations:{typeText:c}},[r],y(a,i.flags,s.appBundleId,s.trace?.outPath));return Y(e,t,`type`),{ok:!0,data:l??{ref:t.ref}}}async function q(t,r){let{req:i,logPath:a}=t,o=J(r,`be focused`);if(o)return o;let s=r.resolvedNode.rect?e(r.resolvedNode.rect):null;if(!s)return n(`COMMAND_FAILED`,`matched element has no bounds`);let c=t.sessionStore.requireCurrent(t.sessionRef);v(c);let l=t.boundFocusPoint;return l?{ok:!0,data:await C({operations:{focusPoint:l}},s,y(a,i.flags,c.appBundleId,c.trace?.outPath))??{ref:r.ref}}:n(`COMMAND_FAILED`,`find focus was admitted without a focus operation`)}function J(e,t){let r=e.occludedNode;return r?n(`COMMAND_FAILED`,`Matched element ${e.ref} is covered by another visible element and cannot ${t} safely`,{ref:`@${r.ref}`,interactionBlocked:r.interactionBlocked,hint:`Use a different visible target, scroll it clear of the overlay, or inspect with snapshot/screenshot before retrying.`}):null}function Y(e,t,n){let{req:r,sessionStore:i,sessionRef:a,command:o,publicFlags:s}=e;l(i,a,r,o,{ref:t.ref,action:n},{flags:s})}function X(e){return{...b(e)??{}}}export{B as handleFindCommands};
@@ -1 +1 @@
1
- import{m as e}from"./sdk-batch.js";import{t}from"./session-snapshot.js";import{i as n,r}from"./interaction-ref-policy.js";import{captureSnapshotForSession as i,createInteractionRuntime as a}from"./interaction.js";function o(t){if(!e(t.command))return{};let i=n(t.command,t.flags);if(i)return{response:i};let a=r(t.flags);if(!a)return{};let o=t.session.snapshot,c={nodes:o?.nodes??[],...o?.iosSystemSurfaceBundleId?{surfaceBundleId:o.iosSystemSurfaceBundleId}:{}};return{observe:async()=>await s(t,a,c)}}async function s(e,n,r){let i=c(e);if(!i)return;let a=await i.interactions.settleObservation({...n,baseline:r,session:e.sessionName,requestId:e.req.meta?.requestId}),o=t(e.session,a);return o===void 0?a:{...a,refsGeneration:o}}function c(e){try{return a({req:e.req,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,contextFromFlags:e.contextFromFlags,captureSnapshotForSession:i})}catch{return}}export{o as planGenericSettleObservation};
1
+ import{m as e}from"./sdk-batch.js";import{n as t}from"./session-snapshot.js";import{i as n,r}from"./interaction-ref-policy.js";import{captureSnapshotForSession as i,createInteractionRuntime as a}from"./interaction.js";function o(t){if(!e(t.command))return{};let i=n(t.command,t.flags);if(i)return{response:i};let a=r(t.flags);if(!a)return{};let o=t.session.snapshot,c={nodes:o?.nodes??[],...o?.iosSystemSurfaceBundleId?{surfaceBundleId:o.iosSystemSurfaceBundleId}:{}};return{observe:async()=>await s(t,a,c)}}async function s(e,n,r){let i=c(e);if(!i)return;let a=await i.interactions.settleObservation({...n,baseline:r,session:e.sessionName,requestId:e.req.meta?.requestId});if(e.sessionRef&&!e.sessionStore.resolveCurrent(e.sessionRef))return;let o=t(e.sessionRef,e.sessionStore,a);return o===void 0?a:{...a,refsGeneration:o}}function c(e){try{return a({req:e.req,sessionName:e.sessionName,sessionRef:e.sessionRef,logPath:e.logPath,sessionStore:e.sessionStore,contextFromFlags:e.contextFromFlags,captureSnapshotForSession:i})}catch{return}}export{o as planGenericSettleObservation};
@@ -1 +1 @@
1
- import{s as e}from"./sdk-contracts.js";import{t}from"./success-text.js";import{o as n}from"./output-common.js";import{n as r}from"./cli-output.js";import{t as i}from"./shared.js";import{n as a}from"./cli-runner.js";async function o({command:t,positionals:n,flags:r,client:o,debug:l,replayTestReporterRuntime:u,commandProgress:d}){let{result:f,cliOutput:p}=await a({client:o,command:t,positionals:n,flags:r,commandProgress:d});if(e(r.responseLevel))return await i(r,f,()=>JSON.stringify(f,null,2)),!0;if(p)await c(r,p);else{let e=await s(t,r,f,{debug:l,replayTestReporterRuntime:u});e!==0&&process.exit(e)}return!0}async function s(e,i,a,o={}){return e===`test`?import(`./reporting.js`).then(({renderReplayTestResponse:e})=>e({suite:a,debug:o.debug,verbose:i.verbose,json:i.json,reporter:i.reporter,reportJunit:i.reportJunit,reporterRuntime:o.replayTestReporterRuntime})):(await c(i,n({data:a,text:t(a)},a,r(e)?`stderr`:`text`)),0)}async function c(e,t){!e.json&&t.stderr&&process.stderr.write(t.stderr),await i(e,e.json?t.jsonData??t.data:t.data,()=>t.text)}export{o as runGenericClientBackedCommand};
1
+ import{c as e}from"./sdk-contracts.js";import{t}from"./success-text.js";import{o as n}from"./output-common.js";import{n as r}from"./cli-output.js";import{t as i}from"./shared.js";import{n as a}from"./cli-runner.js";async function o({command:t,positionals:n,flags:r,client:o,debug:l,replayTestReporterRuntime:u,commandProgress:d}){let{result:f,cliOutput:p}=await a({client:o,command:t,positionals:n,flags:r,commandProgress:d});if(e(r.responseLevel))return await i(r,f,()=>JSON.stringify(f,null,2)),!0;if(p)await c(r,p);else{let e=await s(t,r,f,{debug:l,replayTestReporterRuntime:u});e!==0&&process.exit(e)}return!0}async function s(e,i,a,o={}){return e===`test`?import(`./reporting.js`).then(({renderReplayTestResponse:e})=>e({suite:a,debug:o.debug,verbose:i.verbose,json:i.json,reporter:i.reporter,reportJunit:i.reportJunit,reporterRuntime:o.replayTestReporterRuntime})):(await c(i,n({data:a,text:t(a)},a,r(e)?`stderr`:`text`)),0)}async function c(e,t){!e.json&&t.stderr&&process.stderr.write(t.stderr),await i(e,e.json?t.jsonData??t.data:t.data,()=>t.text)}export{o as runGenericClientBackedCommand};
@@ -1 +1 @@
1
- import{D as e,d as t}from"./sdk-device.js";const n={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`},r=`Target-authored drag requires an adapter that preserves source hold, timed movement, and destination hold; it is supported on Android touch devices and iOS/iPadOS.`,i=`Android TV has no touch input — this gesture is supported on Android phones, tablets, and the iOS simulator only.`,a=`Two-finger gesture synthesis is iOS-simulator only — not available on physical iOS devices.`;function o(e,t){return(t===`multi-touch`?s(e):t===`directional-fling`&&e.platform===`linux`?`Linux`:void 0)??e.appleOs??e.platform}function s(r){if(r.platform===`android`)return r.target===`tv`?`Android TV`:void 0;if(!t(r.platform))return;let i=e(r);if(i===`ios`||i===`ipados`)return`physical iOS devices`;if(i===`macos`||i===`tvos`||i===`visionos`)return n[i]}function c(e,t,n){return`gesture ${n} is not supported on ${o(e,t)}`}export{c as a,r as i,n,a as r,i as t};
1
+ import{O as e,d as t}from"./sdk-device.js";const n={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`},r=`Target-authored drag requires an adapter that preserves source hold, timed movement, and destination hold; it is supported on Android touch devices and iOS/iPadOS.`,i=`Android TV has no touch input — this gesture is supported on Android phones, tablets, and the iOS simulator only.`,a=`Two-finger gesture synthesis is iOS-simulator only — not available on physical iOS devices.`;function o(e,t){return(t===`multi-touch`?s(e):t===`directional-fling`&&e.platform===`linux`?`Linux`:void 0)??e.appleOs??e.platform}function s(r){if(r.platform===`android`)return r.target===`tv`?`Android TV`:void 0;if(!t(r.platform))return;let i=e(r);if(i===`ios`||i===`ipados`)return`physical iOS devices`;if(i===`macos`||i===`tvos`||i===`visionos`)return n[i]}function c(e,t,n){return`gesture ${n} is not supported on ${o(e,t)}`}export{c as a,r as i,n,a as r,i as t};
@@ -1 +1 @@
1
- import{N as e}from"./sdk-contracts.js";import{f as t,m as n}from"./scroll-gesture.js";import{t as r}from"./gesture-plan-types.js";const i={pinchAxisDegrees:-90,samplingProfile:`default`},a={ios:i,macos:i,android:{pinchAxisDegrees:0,samplingProfile:`android`},harmonyos:i,vega:i,linux:i,web:i};function o(e,t,n){let r=b(t),i=N(n);switch(e.intent){case`fling`:return u(e,r);case`pan`:return d(e,r,i);case`pinch`:return p({intent:`pinch`,origin:e.origin??k(r),delta:{x:0,y:0},scale:D(e.scale,`gesture pinch scale`),rotationDegrees:0,durationMs:300},r,i);case`rotate`:{let t=E(e.degrees,`gesture rotate degrees`);return p({intent:`rotate`,origin:e.origin??k(r),delta:{x:0,y:0},scale:1,rotationDegrees:t,durationMs:w(t)},r,i)}case`transform`:{let t=E(e.degrees,`gesture transform degrees`);return p({intent:`transform`,origin:e.origin,delta:e.delta,scale:D(e.scale,`gesture transform scale`),rotationDegrees:t,durationMs:x(e.durationMs,w(t),`gesture transform durationMs`)},r,i)}}}function s(e){let[{samples:t}]=e.pointers,n=t[0],r=t.at(-1);return{start:n.point,end:r.point}}function c(t,n){let i=b(n),a=S(t.sourceHoldMs,800,`gesture drag sourceHoldMs`),o=x(t.moveMs,500,`gesture drag moveMs`),s=C(t.destinationHoldMs,0,`gesture drag destinationHoldMs`);if(a+o+s>1e4)throw new e(`INVALID_ARGS`,`gesture drag total duration must be at most ${r}`);return l(f(`pan`,t.from,t.to,o,i,`timed-pan`),a,s)}function l(e,t,n){let r=e.pointers[0],[i,a]=r.samples,o=t+e.durationMs+n,s=[{offsetMs:0,point:i.point},{...i,offsetMs:i.offsetMs+t},{...a,offsetMs:a.offsetMs+t},...n>0?[{offsetMs:o,point:a.point}]:[]];return{...e,durationMs:o,pointers:[{...r,samples:s}]}}function u(e,t){if(`preset`in e){let{from:n,to:r}=M(e.preset,t);return f(`fling`,n,r,100,t,`endpoint-hold`)}if(`from`in e)return f(`fling`,e.from,e.to,100,t,`endpoint-hold`);let r=T(e.origin,`gesture fling origin`),i=O(e.distance??180,`gesture fling distance`);return f(`fling`,r,A(r,n(e.direction,i)),100,t,`endpoint-hold`)}function d(t,n,r){let i=x(t.durationMs,500,`gesture pan durationMs`);if((t.pointerCount??1)===1){let e=T(t.origin,`gesture pan origin`);return f(`pan`,e,A(e,T(t.delta,`gesture pan delta`)),i,n,t.executionProfile??`timed-pan`)}if(t.pointerCount!==2)throw new e(`INVALID_ARGS`,`gesture pan pointerCount must be 1 or 2`);return p({intent:`pan`,origin:t.origin,delta:t.delta,scale:1,rotationDegrees:0,durationMs:i},n,r)}function f(e,t,n,r,i,a){let o=T(t,`gesture ${e} start`),s=T(n,`gesture ${e} end`),c=[{offsetMs:0,point:o},{offsetMs:r,point:s}];return v(c,i,{intent:e,pointerId:0}),{topology:`single`,intent:e,executionProfile:a,durationMs:r,viewport:i,pointers:[{pointerId:0,samples:c}]}}function p(e,t,n){let r=T(e.origin,`gesture ${e.intent} origin`),i=A(r,T(e.delta,`gesture ${e.intent} delta`)),a=Math.min(t.width,t.height)*g(e.intent),o=e.scale>1?a/e.scale:a,s=o*e.scale;if(Math.min(o,s)<48)throw y({intent:e.intent,viewport:t,initialSpan:o,finalSpan:s,minimumReliableSpan:48});let c=o/2,l=_(e.durationMs,n.samplingProfile),u=(a,o)=>{let s=l.map(t=>({offsetMs:t,point:m({...e,start:r,end:i,initialRadius:c,offsetMs:t,side:o,profile:n})}));return v(s,t,{intent:e.intent,pointerId:a}),{pointerId:a,samples:s}};return{topology:`two`,intent:e.intent,durationMs:e.durationMs,viewport:t,pointers:[u(0,1),u(1,-1)]}}function m(e){let t=e.offsetMs/e.durationMs,n=j(e.start,e.end,t),r=e.initialRadius*(1+(e.scale-1)*t),i=P(h(e.intent,e.profile)+e.rotationDegrees*t);return{x:n.x+Math.cos(i)*r*e.side,y:n.y+Math.sin(i)*r*e.side}}function h(e,t){return e===`pinch`?t.pinchAxisDegrees:-90}function g(e){return e===`pinch`?.4:.25}function _(t,n){if(!Number.isFinite(t)||t<=0)throw new e(`INVALID_ARGS`,`gesture sample duration must be a positive finite number`);let r=t/16,i=Math.max(3,n===`android`?Math.round(r):Math.floor(r));return Array.from({length:i+1},(e,n)=>Math.round(t*n/i))}function v(t,n,r){let i=n.x+n.width-1,a=n.y+n.height-1;for(let o of t){let{x:t,y:s}=o.point;if(!Number.isFinite(t)||!Number.isFinite(s))throw new e(`INVALID_ARGS`,`Gesture motion produces non-finite pointer coordinates`,{...r,reason:`GESTURE_TRAJECTORY_NON_FINITE`,hint:`Reduce the requested rotation, translation, or scale.`});if(t<n.x+1||t>i||s<n.y+1||s>a)throw y({...r,viewport:n,sample:o})}}function y(t){return new e(`INVALID_ARGS`,`Gesture trajectory does not fit inside the viewport`,{...t,reason:`GESTURE_TRAJECTORY_OUT_OF_BOUNDS`,hint:`Move the gesture away from the edge or reduce its translation, scale, or rotation.`})}function b(t){let n={x:E(t.x,`gesture viewport x`),y:E(t.y,`gesture viewport y`),width:E(t.width,`gesture viewport width`),height:E(t.height,`gesture viewport height`)};if(n.width<=0||n.height<=0)throw new e(`INVALID_ARGS`,`gesture viewport width and height must be positive`);return n}function x(t,n,i){let a=t??n;if(!Number.isInteger(a)||a<16||a>1e4)throw new e(`INVALID_ARGS`,`${i} must be an integer between 16 and ${r}`);return a}function S(t,n,i){let a=t??n;if(!Number.isInteger(a)||a<1||a>1e4)throw new e(`INVALID_ARGS`,`${i} must be an integer between 1 and ${r}`);return a}function C(t,n,i){let a=t??n;if(!Number.isInteger(a)||a<0||a>1e4)throw new e(`INVALID_ARGS`,`${i} must be an integer between 0 and ${r}`);return a}function w(e){let t=Math.ceil(Math.abs(e)/3)*16;return Math.min(Math.max(300,t),2400)}function T(e,t){return{x:E(e.x,`${t} x`),y:E(e.y,`${t} y`)}}function E(t,n){if(!Number.isFinite(t))throw new e(`INVALID_ARGS`,`${n} must be a finite number`);return t}function D(t,n){let r=E(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be greater than 0`);return r}function O(t,n){let r=E(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be a positive number`);return r}function k(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function A(e,t){return{x:e.x+t.x,y:e.y+t.y}}function j(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function M(e,n){let r=t(e,{referenceWidth:n.width,referenceHeight:n.height});return{from:{x:n.x+r.x1,y:n.y+r.y1},to:{x:n.x+r.x2,y:n.y+r.y2}}}function N(e){return e===void 0?i:a[e]}function P(e){return e*Math.PI/180}export{s as a,_ as i,o as n,j as r,c as t};
1
+ import{P as e}from"./sdk-contracts.js";import{f as t,m as n}from"./scroll-gesture.js";import{t as r}from"./gesture-plan-types.js";const i={pinchAxisDegrees:-90,samplingProfile:`default`},a={ios:i,macos:i,android:{pinchAxisDegrees:0,samplingProfile:`android`},harmonyos:i,vega:i,linux:i,web:i};function o(e,t,n){let r=b(t),i=N(n);switch(e.intent){case`fling`:return u(e,r);case`pan`:return d(e,r,i);case`pinch`:return p({intent:`pinch`,origin:e.origin??k(r),delta:{x:0,y:0},scale:D(e.scale,`gesture pinch scale`),rotationDegrees:0,durationMs:300},r,i);case`rotate`:{let t=E(e.degrees,`gesture rotate degrees`);return p({intent:`rotate`,origin:e.origin??k(r),delta:{x:0,y:0},scale:1,rotationDegrees:t,durationMs:w(t)},r,i)}case`transform`:{let t=E(e.degrees,`gesture transform degrees`);return p({intent:`transform`,origin:e.origin,delta:e.delta,scale:D(e.scale,`gesture transform scale`),rotationDegrees:t,durationMs:x(e.durationMs,w(t),`gesture transform durationMs`)},r,i)}}}function s(e){let[{samples:t}]=e.pointers,n=t[0],r=t.at(-1);return{start:n.point,end:r.point}}function c(t,n){let i=b(n),a=S(t.sourceHoldMs,800,`gesture drag sourceHoldMs`),o=x(t.moveMs,500,`gesture drag moveMs`),s=C(t.destinationHoldMs,0,`gesture drag destinationHoldMs`);if(a+o+s>1e4)throw new e(`INVALID_ARGS`,`gesture drag total duration must be at most ${r}`);return l(f(`pan`,t.from,t.to,o,i,`timed-pan`),a,s)}function l(e,t,n){let r=e.pointers[0],[i,a]=r.samples,o=t+e.durationMs+n,s=[{offsetMs:0,point:i.point},{...i,offsetMs:i.offsetMs+t},{...a,offsetMs:a.offsetMs+t},...n>0?[{offsetMs:o,point:a.point}]:[]];return{...e,durationMs:o,pointers:[{...r,samples:s}]}}function u(e,t){if(`preset`in e){let{from:n,to:r}=M(e.preset,t);return f(`fling`,n,r,100,t,`endpoint-hold`)}if(`from`in e)return f(`fling`,e.from,e.to,100,t,`endpoint-hold`);let r=T(e.origin,`gesture fling origin`),i=O(e.distance??180,`gesture fling distance`);return f(`fling`,r,A(r,n(e.direction,i)),100,t,`endpoint-hold`)}function d(t,n,r){let i=x(t.durationMs,500,`gesture pan durationMs`);if((t.pointerCount??1)===1){let e=T(t.origin,`gesture pan origin`);return f(`pan`,e,A(e,T(t.delta,`gesture pan delta`)),i,n,t.executionProfile??`timed-pan`)}if(t.pointerCount!==2)throw new e(`INVALID_ARGS`,`gesture pan pointerCount must be 1 or 2`);return p({intent:`pan`,origin:t.origin,delta:t.delta,scale:1,rotationDegrees:0,durationMs:i},n,r)}function f(e,t,n,r,i,a){let o=T(t,`gesture ${e} start`),s=T(n,`gesture ${e} end`),c=[{offsetMs:0,point:o},{offsetMs:r,point:s}];return v(c,i,{intent:e,pointerId:0}),{topology:`single`,intent:e,executionProfile:a,durationMs:r,viewport:i,pointers:[{pointerId:0,samples:c}]}}function p(e,t,n){let r=T(e.origin,`gesture ${e.intent} origin`),i=A(r,T(e.delta,`gesture ${e.intent} delta`)),a=Math.min(t.width,t.height)*g(e.intent),o=e.scale>1?a/e.scale:a,s=o*e.scale;if(Math.min(o,s)<48)throw y({intent:e.intent,viewport:t,initialSpan:o,finalSpan:s,minimumReliableSpan:48});let c=o/2,l=_(e.durationMs,n.samplingProfile),u=(a,o)=>{let s=l.map(t=>({offsetMs:t,point:m({...e,start:r,end:i,initialRadius:c,offsetMs:t,side:o,profile:n})}));return v(s,t,{intent:e.intent,pointerId:a}),{pointerId:a,samples:s}};return{topology:`two`,intent:e.intent,durationMs:e.durationMs,viewport:t,pointers:[u(0,1),u(1,-1)]}}function m(e){let t=e.offsetMs/e.durationMs,n=j(e.start,e.end,t),r=e.initialRadius*(1+(e.scale-1)*t),i=P(h(e.intent,e.profile)+e.rotationDegrees*t);return{x:n.x+Math.cos(i)*r*e.side,y:n.y+Math.sin(i)*r*e.side}}function h(e,t){return e===`pinch`?t.pinchAxisDegrees:-90}function g(e){return e===`pinch`?.4:.25}function _(t,n){if(!Number.isFinite(t)||t<=0)throw new e(`INVALID_ARGS`,`gesture sample duration must be a positive finite number`);let r=t/16,i=Math.max(3,n===`android`?Math.round(r):Math.floor(r));return Array.from({length:i+1},(e,n)=>Math.round(t*n/i))}function v(t,n,r){let i=n.x+n.width-1,a=n.y+n.height-1;for(let o of t){let{x:t,y:s}=o.point;if(!Number.isFinite(t)||!Number.isFinite(s))throw new e(`INVALID_ARGS`,`Gesture motion produces non-finite pointer coordinates`,{...r,reason:`GESTURE_TRAJECTORY_NON_FINITE`,hint:`Reduce the requested rotation, translation, or scale.`});if(t<n.x+1||t>i||s<n.y+1||s>a)throw y({...r,viewport:n,sample:o})}}function y(t){return new e(`INVALID_ARGS`,`Gesture trajectory does not fit inside the viewport`,{...t,reason:`GESTURE_TRAJECTORY_OUT_OF_BOUNDS`,hint:`Move the gesture away from the edge or reduce its translation, scale, or rotation.`})}function b(t){let n={x:E(t.x,`gesture viewport x`),y:E(t.y,`gesture viewport y`),width:E(t.width,`gesture viewport width`),height:E(t.height,`gesture viewport height`)};if(n.width<=0||n.height<=0)throw new e(`INVALID_ARGS`,`gesture viewport width and height must be positive`);return n}function x(t,n,i){let a=t??n;if(!Number.isInteger(a)||a<16||a>1e4)throw new e(`INVALID_ARGS`,`${i} must be an integer between 16 and ${r}`);return a}function S(t,n,i){let a=t??n;if(!Number.isInteger(a)||a<1||a>1e4)throw new e(`INVALID_ARGS`,`${i} must be an integer between 1 and ${r}`);return a}function C(t,n,i){let a=t??n;if(!Number.isInteger(a)||a<0||a>1e4)throw new e(`INVALID_ARGS`,`${i} must be an integer between 0 and ${r}`);return a}function w(e){let t=Math.ceil(Math.abs(e)/3)*16;return Math.min(Math.max(300,t),2400)}function T(e,t){return{x:E(e.x,`${t} x`),y:E(e.y,`${t} y`)}}function E(t,n){if(!Number.isFinite(t))throw new e(`INVALID_ARGS`,`${n} must be a finite number`);return t}function D(t,n){let r=E(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be greater than 0`);return r}function O(t,n){let r=E(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be a positive number`);return r}function k(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function A(e,t){return{x:e.x+t.x,y:e.y+t.y}}function j(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function M(e,n){let r=t(e,{referenceWidth:n.width,referenceHeight:n.height});return{from:{x:n.x+r.x1,y:n.y+r.y1},to:{x:n.x+r.x2,y:n.y+r.y2}}}function N(e){return e===void 0?i:a[e]}function P(e){return e*Math.PI/180}export{s as a,_ as i,o as n,j as r,c as t};
@@ -1 +1 @@
1
- import{N as e,q as t}from"./sdk-contracts.js";import{Ft as n,bt as r}from"./sdk-batch.js";import{f as i}from"./session-snapshot.js";import{n as a,t as o}from"./runtime-admission.js";import{a as s}from"./gesture-admission.js";async function c(e){let t=await a({command:`runtime gesture-viewport`,device:e.device,use:r,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});return t.type===`response`?{ok:!1,response:t.response}:{ok:!0,read:d(t.runtime).gestureViewport}}async function l(r){let i=n(r.input),a=await o({command:`gesture`,device:r.device,required:i.use.required,inspectFacts:r.inspectFacts,bindDevice:r.bindDevice,unavailableResponse:n=>({ok:!1,error:t(new e(`UNSUPPORTED_OPERATION`,s(r.device,i.tier,r.input.intent),{gesture:r.input.intent,...n.hint===void 0?{}:{hint:n.hint}}))})});return a.type===`response`?{ok:!1,response:a.response}:{ok:!0,gestures:await u(a.bind,r.device,i)}}async function u(e,t,n){switch(n.tier){case`plan`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performGesturePlan(f(e,t)),...d(r)}}case`directional-fling`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performDirectionalFlingPlan(f(e,t)),...d(r)}}case`multi-touch`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performMultiTouchGesturePlan(f(e,t)),...d(r)}}case`target-authored-drag`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performTargetAuthoredDrag(f(e,t)),...d(r)}}}}function d(e){let{gestureViewport:t}=e.operations,n=e.operations.captureSnapshot?{operations:{captureSnapshot:e.operations.captureSnapshot}}:void 0,r=t?{operations:{gestureViewport:t}}:void 0;return Object.freeze({...n?{captureSnapshot:async e=>await n.operations.captureSnapshot(e)}:{},...r?{gestureViewport:async e=>await r.operations.gestureViewport(p(e))}:{}})}function f(e,t){return{plan:e,...t.appBundleId===void 0?{}:{options:{appBundleId:t.appBundleId}},execution:i(t)}}function p(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:i(e)}}export{c as n,l as t};
1
+ import{J as e,P as t}from"./sdk-contracts.js";import{Ft as n,bt as r}from"./sdk-batch.js";import{m as i}from"./session-snapshot.js";import{n as a,t as o}from"./runtime-admission.js";import{a as s}from"./gesture-admission.js";async function c(e){let t=await a({command:`runtime gesture-viewport`,device:e.device,use:r,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});return t.type===`response`?{ok:!1,response:t.response}:{ok:!0,read:d(t.runtime).gestureViewport}}async function l(r){let i=n(r.input),a=await o({command:`gesture`,device:r.device,required:i.use.required,inspectFacts:r.inspectFacts,bindDevice:r.bindDevice,unavailableResponse:n=>({ok:!1,error:e(new t(`UNSUPPORTED_OPERATION`,s(r.device,i.tier,r.input.intent),{gesture:r.input.intent,...n.hint===void 0?{}:{hint:n.hint}}))})});return a.type===`response`?{ok:!1,response:a.response}:{ok:!0,gestures:await u(a.bind,r.device,i)}}async function u(e,t,n){switch(n.tier){case`plan`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performGesturePlan(f(e,t)),...d(r)}}case`directional-fling`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performDirectionalFlingPlan(f(e,t)),...d(r)}}case`multi-touch`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performMultiTouchGesturePlan(f(e,t)),...d(r)}}case`target-authored-drag`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performTargetAuthoredDrag(f(e,t)),...d(r)}}}}function d(e){let{gestureViewport:t}=e.operations,n=e.operations.captureSnapshot?{operations:{captureSnapshot:e.operations.captureSnapshot}}:void 0,r=t?{operations:{gestureViewport:t}}:void 0;return Object.freeze({...n?{captureSnapshot:async e=>await n.operations.captureSnapshot(e)}:{},...r?{gestureViewport:async e=>await r.operations.gestureViewport(p(e))}:{}})}function f(e,t){return{plan:e,...t.appBundleId===void 0?{}:{options:{appBundleId:t.appBundleId}},execution:i(t)}}function p(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:i(e)}}export{c as n,l as t};
@@ -1 +1 @@
1
- import{N as e}from"./sdk-contracts.js";import{c as t}from"./diagnostics.js";import"./diagnostics2.js";import{_ as n,a as r,c as i,d as a,f as o,g as s,h as c,l,n as u,o as d,p as f,r as p,s as m,t as h,u as g,v as _,x as v,y}from"./src4.js";function b(b,x){let S=t=>async()=>{throw new e(`UNSUPPORTED_OPERATION`,`${t} is not supported on HarmonyOS`)};return{open:(e,t)=>l(b,e,{activity:t?.activity}),openDevice:()=>m(b),close:e=>p(b,e),tap:(e,t)=>a(b,e,t),doubleTap:(e,t)=>r(b,e,t),longPress:(e,t,n)=>i(b,e,t,n),focus:(e,t)=>a(b,e,t),type:(e,t)=>v(b,e,t),fill:(e,t,n,r)=>d(b,e,t,n,r),scroll:(e,t)=>s(b,e,t),performGesture:e=>g(b,e),gestureViewport:()=>f(b),screenshot:e=>c(b,e),snapshot:async e=>({...await t(`snapshot_capture`,async()=>await y(b,e),{backend:`harmonyos-arkui`}),backend:`harmonyos-arkui`,producer:`harmonyos-uitest`}),back:()=>u(b),home:()=>m(b),setOrientation:e=>n(b,e),appSwitcher:()=>h(b),tvRemote:S(`tv-remote`),keyboardDismiss:async()=>(await o(b,`Back`),{kind:`acknowledged`}),keyboardEnter:async()=>(await o(b,`Enter`),{kind:`harmonyos-acknowledged`}),readClipboard:S(`clipboard`),writeClipboard:S(`clipboard`),setSetting:(e,t,n)=>_(b,e,t,n)}}export{b as createHarmonyInteractor};
1
+ import{P as e}from"./sdk-contracts.js";import{c as t}from"./diagnostics.js";import"./diagnostics2.js";import{_ as n,a as r,c as i,d as a,f as o,g as s,h as c,l,n as u,o as d,p as f,r as p,s as m,t as h,u as g,v as _,x as v,y}from"./src4.js";function b(b,x){let S=t=>async()=>{throw new e(`UNSUPPORTED_OPERATION`,`${t} is not supported on HarmonyOS`)};return{open:(e,t)=>l(b,e,{activity:t?.activity}),openDevice:()=>m(b),close:e=>p(b,e),tap:(e,t)=>a(b,e,t),doubleTap:(e,t)=>r(b,e,t),longPress:(e,t,n)=>i(b,e,t,n),focus:(e,t)=>a(b,e,t),type:(e,t)=>v(b,e,t),fill:(e,t,n,r)=>d(b,e,t,n,r),scroll:(e,t)=>s(b,e,t),performGesture:e=>g(b,e),gestureViewport:()=>f(b),screenshot:e=>c(b,e),snapshot:async e=>({...await t(`snapshot_capture`,async()=>await y(b,e),{backend:`harmonyos-arkui`}),backend:`harmonyos-arkui`,producer:`harmonyos-uitest`}),back:()=>u(b),home:()=>m(b),setOrientation:e=>n(b,e),appSwitcher:()=>h(b),tvRemote:S(`tv-remote`),keyboardDismiss:async()=>(await o(b,`Back`),{kind:`acknowledged`}),keyboardEnter:async()=>(await o(b,`Enter`),{kind:`harmonyos-acknowledged`}),readClipboard:S(`clipboard`),writeClipboard:S(`clipboard`),setSetting:(e,t,n)=>_(b,e,t,n)}}export{b as createHarmonyInteractor};
package/dist/src/hdc.js CHANGED
@@ -1 +1 @@
1
- import{c as e}from"./owner-identity.js";import{a as t,l as n}from"./exec.js";import"./command.js";import{n as r,t as i}from"./device-shell.js";import"./process.js";import a from"node:path";async function o(e,t,r){return i(t,`hdc`),await n(`hdc`,[`-t`,e.id,...t],{timeoutMs:15e3,...r})}async function s(e,t,n){return await o(e,r(`hdc`,`shell`,t),n)}async function c(n=e()){let r=[n.HDC_SDK_PATH,n.DEVECO_SDK_HOME?a.join(n.DEVECO_SDK_HOME,`default`,`openharmony`,`toolchains`):void 0,n.HARMONYOS_COMMAND_LINE_TOOLS?a.join(n.HARMONYOS_COMMAND_LINE_TOOLS,`sdk`,`default`,`openharmony`,`toolchains`):void 0].filter(e=>!!e?.trim()),i=[];for(let e of r)await t(a.join(e,`hdc`))&&i.push(e);if(i.length===0)return;let o=(n.PATH??``).split(a.delimiter).filter(Boolean);n.PATH=[...new Set([...i,...o])].join(a.delimiter)}export{c as ensureHarmonyToolchainPathConfigured,o as runHarmonyHdc,s as runHarmonyShell};
1
+ import{l as e}from"./owner-identity.js";import{a as t,l as n}from"./exec.js";import"./command.js";import"./process.js";import{n as r,t as i}from"./device-shell.js";import a from"node:path";async function o(e,t,r){return i(t,`hdc`),await n(`hdc`,[`-t`,e.id,...t],{timeoutMs:15e3,...r})}async function s(e,t,n){return await o(e,r(`hdc`,`shell`,t),n)}async function c(n=e()){let r=[n.HDC_SDK_PATH,n.DEVECO_SDK_HOME?a.join(n.DEVECO_SDK_HOME,`default`,`openharmony`,`toolchains`):void 0,n.HARMONYOS_COMMAND_LINE_TOOLS?a.join(n.HARMONYOS_COMMAND_LINE_TOOLS,`sdk`,`default`,`openharmony`,`toolchains`):void 0].filter(e=>!!e?.trim()),i=[];for(let e of r)await t(a.join(e,`hdc`))&&i.push(e);if(i.length===0)return;let o=(n.PATH??``).split(a.delimiter).filter(Boolean);n.PATH=[...new Set([...i,...o])].join(a.delimiter)}export{c as ensureHarmonyToolchainPathConfigured,o as runHarmonyHdc,s as runHarmonyShell};
@@ -1,2 +1,2 @@
1
- import{r as e}from"./rolldown-runtime.js";import{N as t}from"./sdk-contracts.js";import{D as n,d as r,y as i}from"./owner-identity.js";import{s as a,u as o}from"./exec.js";import"./command.js";import"./process.js";import{D as s,c,f as l,g as u,h as d,n as f,o as p,r as m,t as h,w as g,y as _}from"./host-file.js";import{a as v,i as y,n as b}from"./tool-provider.js";import x from"node:path";import{createHash as S}from"node:crypto";import{fileURLToPath as C}from"node:url";var w=e({macOsClickScheduleMs:()=>X,quitMacOsApp:()=>G,resolveFrontmostMacOsApp:()=>W,resolveMacOsHelperPackageRootFrom:()=>M,runMacOsAlertAction:()=>q,runMacOsPermissionAction:()=>K,runMacOsPressAction:()=>Z,runMacOsReadTextAction:()=>Y,runMacOsScreenshotAction:()=>Q,runMacOsSnapshotAction:()=>J,startMacOsAudioProbeProcess:()=>V});const T=`agent-device-macos-helper`,E=`AGENT_DEVICE_MACOS_HELPER_BIN`,D=x.join(l(),`.agent-device`,`macos-helper`,`current`),O=x.join(D,`manifest.json`),k=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/;function A(e){let n=e.trim();if(!k.test(n))throw new t(`INVALID_ARGS`,`macOS bundle id must use reverse-DNS form like com.example.App`,{bundleId:e});return n}function j(e,t){t.bundleId&&e.push(`--bundle-id`,A(t.bundleId)),t.surface&&e.push(`--surface`,t.surface)}function M(e){let n=x.dirname(e);for(;;){let e=x.join(n,`apple`,`macos-helper`);if(c(x.join(e,`Package.swift`)))return e;let t=x.dirname(n);if(t===n)break;n=t}throw new t(`COMMAND_FAILED`,`Unable to locate macOS helper package root`,{modulePath:e})}function N(){return M(C(import.meta.url))}function P(){return x.join(N(),`.build`,`release`,T)}function F(){return x.join(D,T)}async function I(e){let t=await u(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>{let n=x.join(e,t.name);return t.isDirectory()?t.name===`.build`?[]:await I(n):!t.isFile()||!t.name.endsWith(`.swift`)&&t.name!==`Package.swift`?[]:[n]}))).flat().sort()}async function L(e){let t=await I(e),n=S(`sha256`);for(let r of t)n.update(x.relative(e,r)),n.update(`\0`),n.update(await d(r)),n.update(`\0`);let r=await v(`swift`,[`--version`],{allowFailure:!0,cwd:e,timeoutMs:1e4});return n.update(`swift-version`),n.update(`\0`),n.update(r.stdout||r.stderr||`exit:${r.exitCode}`),n.update(`\0`),n.digest(`hex`)}async function R(){try{let e=JSON.parse(await _(O));return typeof e.fingerprint==`string`?e.fingerprint:null}catch{return null}}async function z(){let e=await a(i(E),E);if(e)return e;let t=N(),r=await L(t),o=F();try{if(await R()===r)return await h(o),o}catch{}let c=P();n(`agent-device: building macOS helper (first run or helper update)
2
- `),await v(`swift`,[`build`,`-c`,`release`,`--package-path`,t],{cwd:t,timeoutMs:12e4}),await p(D);let l=`${o}.tmp`;return await m(c,l),await g(l,o),await f(o,493),await s(O,`${JSON.stringify({fingerprint:r},null,2)}\n`),o}async function B(){let e=i(E)?.trim();if(e){let t=await a(e,E);if(t)return t}if(b())return T;if(r()!==`darwin`)throw new t(`UNSUPPORTED_PLATFORM`,`macOS helper is only available on macOS`);return await z()}async function V(e){let t=await B();return o(t,[`audio-probe`,`--duration-ms`,String(e.durationMs),`--bucket-ms`,String(e.bucketMs),`--out`,e.statusPath],{allowFailure:!0,captureOutput:!0})}const H=3e4;async function U(e,n={}){let r={allowFailure:!0,timeoutMs:n.timeoutMs??H,signal:n.signal,kill:{signal:`SIGTERM`,graceMs:1e3}},i=y().macosHelper,a=i?T:await B(),o=i?await i.run(e,r):await v(a,e,r),s=o.stdout.trim(),c=null;if(s)try{c=JSON.parse(s)}catch{c=null}if(o.exitCode===0&&c?.ok)return c.data;let l=c&&!c.ok?c.error?.message??`macOS helper exited with code ${o.exitCode}`:s||o.stderr.trim()||`macOS helper exited with code ${o.exitCode}`;throw new t(`COMMAND_FAILED`,l,{helperPath:a,args:e,stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode,...c&&!c.ok?c.error?.details:{}})}async function W(){return await U([`app`,`frontmost`])}async function G(e){return await U([`app`,`quit`,`--bundle-id`,A(e)])}async function K(e,t){return await U([`permission`,e,t])}async function q(e,t={}){let n=[`alert`,e];return j(n,t),await U(n)}async function J(e,t={}){let n=[`snapshot`,`--surface`,e];return j(n,t),await U(n,{signal:t.signal})}async function Y(e,t,n){let r=[`read`,`--x`,String(e),`--y`,String(t)];return j(r,n),await U(r)}function X(e){let t=e.holdMs&&e.holdMs>0?Math.max(e.holdMs,40):60,n=Math.max(e.clicks??1,1),r=Math.max(e.intervalMs??120,0);return n*(e.doubleClick?2*t+80:t)+(n-1)*r}async function Z(e,t,n){let r=[`press`,`--x`,String(e),`--y`,String(t)];n.holdMs&&n.holdMs>0&&r.push(`--hold-ms`,String(n.holdMs));let i=n.clicks??1;return i>1&&(r.push(`--clicks`,String(i)),n.intervalMs!==void 0&&r.push(`--interval-ms`,String(Math.max(n.intervalMs,0)))),n.doubleClick&&r.push(`--double-click`),j(r,n),await U(r,{signal:n.signal,timeoutMs:X(n)+H})}async function Q(e,t){let n=[`screenshot`,`--out`,e];return j(n,t),await U(n)}export{K as a,q as i,G as n,Q as o,W as r,V as s,w as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{P as t}from"./sdk-contracts.js";import{O as n,b as r,f as i}from"./owner-identity.js";import{s as a,u as o}from"./exec.js";import"./command.js";import"./process.js";import{D as s,c,f as l,g as u,h as d,n as f,o as ee,r as te,t as p,w as m,y as h}from"./host-file.js";import{a as g,i as _,n as v}from"./tool-provider.js";import{createHash as ne}from"node:crypto";import y from"node:path";import{fileURLToPath as re}from"node:url";var b=e({MACOS_HELPER_REFUSAL_REASONS:()=>A,macOsClickScheduleMs:()=>J,quitMacOsApp:()=>U,resolveFrontmostMacOsApp:()=>H,resolveMacOsHelperPackageRootFrom:()=>j,runMacOsAlertAction:()=>G,runMacOsFillAction:()=>Z,runMacOsPermissionAction:()=>W,runMacOsPressAction:()=>Y,runMacOsReadTextAction:()=>q,runMacOsScreenshotAction:()=>$,runMacOsScrollAction:()=>Q,runMacOsSnapshotAction:()=>K,runMacOsTypeAction:()=>X,startMacOsAudioProbeProcess:()=>z});const x=`agent-device-macos-helper`,S=`AGENT_DEVICE_MACOS_HELPER_BIN`,C=y.join(l(),`.agent-device`,`macos-helper`,`current`),w=y.join(C,`manifest.json`),T=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/;function E(e){let n=e.trim();if(!T.test(n))throw new t(`INVALID_ARGS`,`macOS bundle id must use reverse-DNS form like com.example.App`,{bundleId:e});return n}function D(e,t){t.bundleId&&e.push(`--bundle-id`,E(t.bundleId)),t.surface&&e.push(`--surface`,t.surface)}function O(e,t){t===`app`&&r(`AGENT_DEVICE_MACOS_GHOST_CURSOR`)?.trim()!==`0`&&e.push(`--ghost-cursor`)}function k(e){return e.includes(`--ghost-cursor`)?1e3:0}const A=[`background-pointer-gesture`,`no-accessible-target`,`no-settable-text-input`,`no-scroll-bar`];function j(e){let n=y.dirname(e);for(;;){let e=y.join(n,`apple`,`macos-helper`);if(c(y.join(e,`Package.swift`)))return e;let t=y.dirname(n);if(t===n)break;n=t}throw new t(`COMMAND_FAILED`,`Unable to locate macOS helper package root`,{modulePath:e})}function M(){return j(re(import.meta.url))}function N(){return y.join(M(),`.build`,`release`,x)}function ie(){return y.join(C,x)}async function P(e){let t=await u(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>{let n=y.join(e,t.name);return t.isDirectory()?t.name===`.build`?[]:await P(n):!t.isFile()||!t.name.endsWith(`.swift`)&&t.name!==`Package.swift`?[]:[n]}))).flat().sort()}async function F(e){let t=await P(e),n=ne(`sha256`);for(let r of t)n.update(y.relative(e,r)),n.update(`\0`),n.update(await d(r)),n.update(`\0`);let r=await g(`swift`,[`--version`],{allowFailure:!0,cwd:e,timeoutMs:1e4});return n.update(`swift-version`),n.update(`\0`),n.update(r.stdout||r.stderr||`exit:${r.exitCode}`),n.update(`\0`),n.digest(`hex`)}async function I(){try{let e=JSON.parse(await h(w));return typeof e.fingerprint==`string`?e.fingerprint:null}catch{return null}}async function L(){let e=await a(r(S),S);if(e)return e;let t=M(),i=await F(t),o=ie();try{if(await I()===i)return await p(o),o}catch{}let c=N();n(`agent-device: building macOS helper (first run or helper update)
2
+ `),await g(`swift`,[`build`,`-c`,`release`,`--package-path`,t],{cwd:t,timeoutMs:12e4}),await ee(C);let l=`${o}.tmp`;return await te(c,l),await m(l,o),await f(o,493),await s(w,`${JSON.stringify({fingerprint:i},null,2)}\n`),o}async function R(){let e=r(S)?.trim();if(e){let t=await a(e,S);if(t)return t}if(v())return x;if(i()!==`darwin`)throw new t(`UNSUPPORTED_PLATFORM`,`macOS helper is only available on macOS`);return await L()}async function z(e){let t=await R();return o(t,[`audio-probe`,`--duration-ms`,String(e.durationMs),`--bucket-ms`,String(e.bucketMs),`--out`,e.statusPath],{allowFailure:!0,captureOutput:!0})}const B=3e4;async function V(e,n={}){let r={allowFailure:!0,timeoutMs:n.timeoutMs??B,signal:n.signal,kill:{signal:`SIGTERM`,graceMs:1e3}},i=_().macosHelper,a=i?x:await R(),o=i?await i.run(e,r):await g(a,e,r),s=o.stdout.trim(),c=null;if(s)try{c=JSON.parse(s)}catch{c=null}if(o.exitCode===0&&c?.ok)return c.data;let l=c&&!c.ok?c.error?.message??`macOS helper exited with code ${o.exitCode}`:s||o.stderr.trim()||`macOS helper exited with code ${o.exitCode}`;throw new t(`COMMAND_FAILED`,l,{helperPath:a,args:e,stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode,...c&&!c.ok?c.error?.details:{}})}async function H(){return await V([`app`,`frontmost`])}async function U(e){return await V([`app`,`quit`,`--bundle-id`,E(e)])}async function W(e,t){return await V([`permission`,e,t])}async function G(e,t={}){let n=[`alert`,e];return D(n,t),await V(n)}async function K(e,t={}){let n=[`snapshot`,`--surface`,e];return D(n,t),await V(n,{signal:t.signal})}async function q(e,t,n){let r=[`read`,`--x`,String(e),`--y`,String(t)];return D(r,n),await V(r,{signal:n.signal})}function J(e){let t=e.holdMs&&e.holdMs>0?Math.max(e.holdMs,40):60,n=Math.max(e.clicks??1,1),r=Math.max(e.intervalMs??120,0);return n*(e.doubleClick?2*t+80:t)+(n-1)*r}async function Y(e,t,n){let r=[`press`,`--x`,String(e),`--y`,String(t)];n.holdMs&&n.holdMs>0&&r.push(`--hold-ms`,String(n.holdMs));let i=n.clicks??1;return i>1&&(r.push(`--clicks`,String(i)),n.intervalMs!==void 0&&r.push(`--interval-ms`,String(Math.max(n.intervalMs,0)))),n.doubleClick&&r.push(`--double-click`),D(r,n),O(r,n.surface),await V(r,{signal:n.signal,timeoutMs:J(n)+B+k(r)})}async function X(e,t){let n=[`type`,`--text`,e];return t.delayMs&&t.delayMs>0&&n.push(`--delay-ms`,String(t.delayMs)),D(n,{bundleId:t.bundleId}),O(n,`app`),await V(n,{signal:t.signal,timeoutMs:B+k(n)+e.length*(t.delayMs??0)})}async function Z(e,t,n,r){let i=[`fill`,`--x`,String(e),`--y`,String(t),`--text`,n];return D(i,{bundleId:r.bundleId}),O(i,`app`),await V(i,{signal:r.signal,timeoutMs:B+k(i)})}async function Q(e,t){let n=[`scroll`,`--direction`,e];return t.amount!==void 0&&n.push(`--amount`,String(t.amount)),t.pixels!==void 0&&n.push(`--pixels`,String(t.pixels)),D(n,{bundleId:t.bundleId}),O(n,`app`),await V(n,{signal:t.signal,timeoutMs:B+k(n)})}async function $(e,t){let n=[`screenshot`,`--out`,e];return D(n,t),await V(n,{signal:t.signal})}export{G as a,Y as c,X as d,z as f,H as i,$ as l,b as n,Z as o,U as r,W as s,A as t,Q as u};