agent-device 0.21.30 → 0.21.31

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 (304) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.30.apk → agent-device-android-ime-helper-0.21.31.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.31.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.30.manifest.json → agent-device-android-ime-helper-0.21.31.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.31.apk +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.31.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.30.manifest.json → agent-device-android-snapshot-helper-0.21.31.manifest.json} +7 -7
  7. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/BackgroundInteraction.swift +20 -6
  8. package/apple/snapshot-bridge/README.md +16 -3
  9. package/apple/snapshot-bridge/SnapshotBridgeRuntime.m +33 -1
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +110 -8
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAppScreenCapture.swift +20 -0
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +4 -4
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +1 -1
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +30 -4
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +14 -4
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +81 -41
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +40 -6
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotAcquisition.swift +5 -0
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +74 -10
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotTiming.swift +33 -4
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedCommitDeadline.swift +2 -2
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +23 -2
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +158 -6
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +165 -70
  25. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryConfirmation.swift +2 -3
  26. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +49 -27
  27. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryReadiness.swift +17 -9
  28. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +30 -28
  29. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +87 -87
  30. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +4 -3
  31. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.h +13 -0
  32. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.m +45 -0
  33. package/dist/src/absence-observation-errors.js +1 -1
  34. package/dist/src/adapter.js +1 -1
  35. package/dist/src/adb-executor.js +1 -1
  36. package/dist/src/adb-failure.js +2 -2
  37. package/dist/src/agent-browser-lifecycle.js +1 -1
  38. package/dist/src/agent-browser-process-record.js +1 -1
  39. package/dist/src/agent-browser-provider.js +1 -1
  40. package/dist/src/agent-browser-tool.js +1 -1
  41. package/dist/src/agent-device-client.js +1 -1
  42. package/dist/src/alert-tree-driver.js +1 -1
  43. package/dist/src/alert.js +1 -1
  44. package/dist/src/alert2.js +1 -1
  45. package/dist/src/android.js +1 -1
  46. package/dist/src/app-backend.js +1 -1
  47. package/dist/src/app-launch.js +1 -1
  48. package/dist/src/app-lifecycle.js +4 -4
  49. package/dist/src/app-log-runtime2.js +3 -3
  50. package/dist/src/app-log-session-resource.js +1 -1
  51. package/dist/src/app-resolution-facade.js +1 -1
  52. package/dist/src/app-resolution.js +2 -2
  53. package/dist/src/apple-runner-platform.js +1 -1
  54. package/dist/src/application-lifecycle-interaction.js +1 -1
  55. package/dist/src/artifact-tracking.js +1 -1
  56. package/dist/src/automation-helper-artifact.js +1 -1
  57. package/dist/src/automation-helper.js +1 -1
  58. package/dist/src/back-mode.js +1 -1
  59. package/dist/src/boot-diagnostics.js +1 -1
  60. package/dist/src/browser-launch.js +1 -1
  61. package/dist/src/cli-config.js +1 -1
  62. package/dist/src/cli-help.js +35 -29
  63. package/dist/src/cli-runner.js +1 -1
  64. package/dist/src/cli.js +3 -3
  65. package/dist/src/client-metro-companion.js +1 -1
  66. package/dist/src/client-metro.js +1 -1
  67. package/dist/src/client-types.d.ts +3 -3
  68. package/dist/src/cloud-artifacts.d.ts +5 -4
  69. package/dist/src/code-signature-cache.js +1 -1
  70. package/dist/src/command-metadata.js +10 -10
  71. package/dist/src/command-tools.js +2 -2
  72. package/dist/src/command.js +1 -1
  73. package/dist/src/composed-inventory-gateways.js +1 -1
  74. package/dist/src/connection-runtime.js +1 -1
  75. package/dist/src/connection.js +5 -5
  76. package/dist/src/contracts.js +1 -1
  77. package/dist/src/daemon-client-ensure.js +1 -1
  78. package/dist/src/daemon-client-lease-beat.js +1 -1
  79. package/dist/src/daemon-client-lifecycle.js +1 -1
  80. package/dist/src/daemon-client-liveness-probe.js +1 -1
  81. package/dist/src/daemon-client.js +1 -1
  82. package/dist/src/daemon-command-registry.js +1 -1
  83. package/dist/src/daemon-composition.js +1 -1
  84. package/dist/src/daemon-policy-file.js +1 -1
  85. package/dist/src/daemon-registration-owner.js +3 -3
  86. package/dist/src/daemon-resolution.js +1 -1
  87. package/dist/src/daemon-startup-diagnostics.js +1 -1
  88. package/dist/src/debug-symbols-facade.js +3 -3
  89. package/dist/src/device-claim-recovery.js +1 -1
  90. package/dist/src/device-claims.js +1 -1
  91. package/dist/src/device-inventory-context.js +1 -1
  92. package/dist/src/device-readiness-runtime.js +1 -1
  93. package/dist/src/device-selection-resolver.js +1 -1
  94. package/dist/src/device.js +1 -1
  95. package/dist/src/devicectl.js +1 -1
  96. package/dist/src/diagnostics.js +1 -1
  97. package/dist/src/display-inventory.js +1 -1
  98. package/dist/src/doctor-facade.js +1 -1
  99. package/dist/src/durable-capture-resource.js +1 -1
  100. package/dist/src/durable-resource.js +1 -1
  101. package/dist/src/engine-eval-script.js +1 -1
  102. package/dist/src/error.js +1 -1
  103. package/dist/src/explicit-session-resolution.js +1 -1
  104. package/dist/src/expo-dev-client-launch.js +1 -1
  105. package/dist/src/file.js +1 -1
  106. package/dist/src/find.js +1 -1
  107. package/dist/src/finders.js +1 -1
  108. package/dist/src/gesture-admission.js +1 -1
  109. package/dist/src/gesture-plan.js +1 -1
  110. package/dist/src/gesture-runtime.js +1 -1
  111. package/dist/src/hdc.js +1 -1
  112. package/dist/src/helper.js +2 -2
  113. package/dist/src/host.js +1 -1
  114. package/dist/src/host2.js +1 -1
  115. package/dist/src/host3.js +1 -1
  116. package/dist/src/host4.js +1 -1
  117. package/dist/src/host5.js +1 -0
  118. package/dist/src/human-control.js +1 -1
  119. package/dist/src/ime-rebind.js +1 -1
  120. package/dist/src/ime-state.js +1 -1
  121. package/dist/src/index.js +1 -1
  122. package/dist/src/input-actions.js +1 -1
  123. package/dist/src/input-actions2.js +1 -1
  124. package/dist/src/install-source-network-transport.js +1 -1
  125. package/dist/src/install-source2.js +1 -1
  126. package/dist/src/interaction-positionals.js +1 -1
  127. package/dist/src/interaction.js +1 -1
  128. package/dist/src/interaction2.js +1 -1
  129. package/dist/src/interactor-operation-catalog.js +1 -1
  130. package/dist/src/interactor.js +5 -5
  131. package/dist/src/interactor2.js +1 -1
  132. package/dist/src/interactor3.js +1 -1
  133. package/dist/src/interactor4.js +1 -1
  134. package/dist/src/interactor5.js +1 -1
  135. package/dist/src/interactors.js +1 -1
  136. package/dist/src/internal/bin.js +1 -1
  137. package/dist/src/internal/daemon.js +1 -1
  138. package/dist/src/internal/png-worker.js +1 -1
  139. package/dist/src/inventory.js +1 -1
  140. package/dist/src/inventory2.js +1 -1
  141. package/dist/src/inventory6.js +1 -1
  142. package/dist/src/ios-node-interpretation.js +1 -1
  143. package/dist/src/ios-settings.js +1 -1
  144. package/dist/src/ios-snapshot-acquisition.js +1 -1
  145. package/dist/src/ios-snapshot-engine.js +1 -1
  146. package/dist/src/ios-snapshot-runtime.js +1 -1
  147. package/dist/src/keyboard-occlusion.js +1 -1
  148. package/dist/src/keyed-lock.js +1 -1
  149. package/dist/src/launch-confirmation.js +1 -1
  150. package/dist/src/launch-services-registration.js +4 -4
  151. package/dist/src/lease.js +1 -1
  152. package/dist/src/legacy.js +1 -1
  153. package/dist/src/limrun-runtime-dependencies.js +1 -1
  154. package/dist/src/local-interactor-operation-set.js +1 -1
  155. package/dist/src/mechanics.js +12 -12
  156. package/dist/src/mobile-snapshot-semantics.js +1 -1
  157. package/dist/src/observability.js +1 -1
  158. package/dist/src/output-path.js +1 -1
  159. package/dist/src/parameterized-recorded-fill.js +1 -1
  160. package/dist/src/perf-facade.js +1 -1
  161. package/dist/src/perf-runtime-operation-builder.js +1 -1
  162. package/dist/src/perf-target.js +1 -1
  163. package/dist/src/physical-device-control.js +1 -1
  164. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  165. package/dist/src/platform-runtime-claim-recovery.js +1 -1
  166. package/dist/src/platform-runtime-daemon-services.js +1 -1
  167. package/dist/src/platform-runtime-host.js +1 -1
  168. package/dist/src/platform-runtime-open-target.js +1 -1
  169. package/dist/src/platform-runtime-operation-host.js +5 -5
  170. package/dist/src/platform-runtime-runtime-hints.js +2 -2
  171. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  172. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  173. package/dist/src/platform-runtime-unavailable.js +1 -1
  174. package/dist/src/platform-runtime.js +1 -1
  175. package/dist/src/platform-runtime2.js +1 -1
  176. package/dist/src/png-resize.js +1 -1
  177. package/dist/src/png-worker-client.js +1 -1
  178. package/dist/src/process-exit.js +1 -1
  179. package/dist/src/provider-device-runtime.d.ts +28 -0
  180. package/dist/src/provider-plugin-catalog.js +2 -0
  181. package/dist/src/provider-plugin.d.ts +1 -1
  182. package/dist/src/provider-webdriver.js +1 -1
  183. package/dist/src/proxy.js +1 -1
  184. package/dist/src/react-native-overlay2.js +1 -1
  185. package/dist/src/react-native.js +1 -1
  186. package/dist/src/react-profile-command.js +1 -1
  187. package/dist/src/record-runtime.js +1 -1
  188. package/dist/src/record-trace.js +1 -1
  189. package/dist/src/recording-scope.js +1 -1
  190. package/dist/src/recording.js +1 -1
  191. package/dist/src/registry.js +1 -1
  192. package/dist/src/remote-config-core.js +1 -1
  193. package/dist/src/replay-backend-host.js +1 -1
  194. package/dist/src/replay-divergence.js +1 -1
  195. package/dist/src/replay-maestro-backend.js +3 -3
  196. package/dist/src/replay-script-selection.js +1 -1
  197. package/dist/src/replay2.js +1 -1
  198. package/dist/src/request-runtime-binding.js +1 -1
  199. package/dist/src/request.js +1 -1
  200. package/dist/src/result-serialization.js +1 -1
  201. package/dist/src/retry.js +1 -1
  202. package/dist/src/runner-cache-retention.js +1 -1
  203. package/dist/src/runner-client.js +1 -1
  204. package/dist/src/runner-dev-tools-security.js +1 -1
  205. package/dist/src/runner-device-readiness.js +1 -1
  206. package/dist/src/runner-device-set.js +1 -1
  207. package/dist/src/runner-error-classification.js +2 -2
  208. package/dist/src/runner-exchange.js +1 -1
  209. package/dist/src/runner-lease.js +1 -1
  210. package/dist/src/runner-operations-facade.js +1 -1
  211. package/dist/src/runner-retention.js +1 -1
  212. package/dist/src/runner-selector-query.js +1 -1
  213. package/dist/src/runner-start-budget.js +1 -1
  214. package/dist/src/runner-startup-transport.js +1 -1
  215. package/dist/src/runner-toolchain-probe.js +1 -1
  216. package/dist/src/runner.js +2 -2
  217. package/dist/src/runtime-admission.js +1 -1
  218. package/dist/src/runtime-deployment.js +1 -1
  219. package/dist/src/runtime-factory.js +1 -1
  220. package/dist/src/runtime-session.js +1 -1
  221. package/dist/src/runtime.js +4 -4
  222. package/dist/src/runtime10.js +2 -2
  223. package/dist/src/runtime2.js +1 -1
  224. package/dist/src/runtime3.js +5 -5
  225. package/dist/src/runtime4.js +1 -1
  226. package/dist/src/runtime5.js +1 -1
  227. package/dist/src/runtime6.js +1 -1
  228. package/dist/src/runtime7.js +1 -1
  229. package/dist/src/runtime8.js +1 -1
  230. package/dist/src/runtime9.js +2 -2
  231. package/dist/src/screen-recording-transport.js +1 -1
  232. package/dist/src/screenshot-density.js +1 -1
  233. package/dist/src/screenshot-runtime.js +1 -1
  234. package/dist/src/screenshot3.js +1 -1
  235. package/dist/src/sdk-batch-runner.js +2 -2
  236. package/dist/src/sdk-batch.js +2 -2
  237. package/dist/src/sdk-contracts.d.ts +9 -0
  238. package/dist/src/sdk-contracts.js +2 -2
  239. package/dist/src/sdk-device.js +1 -1
  240. package/dist/src/sdk-finders.js +1 -1
  241. package/dist/src/sdk-io.js +5 -5
  242. package/dist/src/sdk-remote-config.js +1 -1
  243. package/dist/src/sdk-selectors.js +1 -1
  244. package/dist/src/selection.js +0 -0
  245. package/dist/src/selector-pipeline-policy.js +1 -1
  246. package/dist/src/selector-runtime.js +1 -1
  247. package/dist/src/selectors.js +1 -1
  248. package/dist/src/server-startup.js +1 -1
  249. package/dist/src/session-paths.js +1 -1
  250. package/dist/src/session-replay-vars.js +1 -1
  251. package/dist/src/session-runtime.js +1 -1
  252. package/dist/src/session-store.js +3 -3
  253. package/dist/src/session.js +1 -1
  254. package/dist/src/session2.js +5 -5
  255. package/dist/src/settings-bluetooth.js +1 -1
  256. package/dist/src/settings.js +1 -1
  257. package/dist/src/settings2.js +1 -1
  258. package/dist/src/settle-observation-capture.js +1 -1
  259. package/dist/src/simctl-settings.js +1 -1
  260. package/dist/src/simctl.js +1 -1
  261. package/dist/src/simulator-boot.js +1 -1
  262. package/dist/src/simulator-state.js +1 -1
  263. package/dist/src/simulator.js +1 -1
  264. package/dist/src/snapshot-chrome.js +1 -1
  265. package/dist/src/snapshot-desktop-projection.js +1 -1
  266. package/dist/src/snapshot-helper-install.js +6 -6
  267. package/dist/src/snapshot-node-lookup.js +1 -1
  268. package/dist/src/snapshot-occlusion.js +1 -1
  269. package/dist/src/snapshot-runtime-binding.js +1 -1
  270. package/dist/src/snapshot-runtime-capture-input.js +1 -1
  271. package/dist/src/snapshot-runtime.js +1 -1
  272. package/dist/src/snapshot-state.js +1 -1
  273. package/dist/src/snapshot.js +1 -1
  274. package/dist/src/snapshot3.js +1 -1
  275. package/dist/src/src.js +1 -1
  276. package/dist/src/src3.js +1 -1
  277. package/dist/src/src4.js +1 -1
  278. package/dist/src/store.js +1 -1
  279. package/dist/src/tap-keyboard-occlusion.js +1 -1
  280. package/dist/src/target-evidence-tree.js +1 -1
  281. package/dist/src/target-evidence.js +1 -1
  282. package/dist/src/telephony-runtime.js +1 -1
  283. package/dist/src/text-entry-focus.js +1 -1
  284. package/dist/src/tool-provider.js +3 -3
  285. package/dist/src/tool-provider2.js +1 -1
  286. package/dist/src/tool-provider3.js +1 -1
  287. package/dist/src/toolchain-probe.js +1 -1
  288. package/dist/src/touch-reference-frame.js +1 -1
  289. package/dist/src/touch-runtime.js +1 -1
  290. package/dist/src/touch-runtime2.js +1 -1
  291. package/dist/src/tree.js +1 -1
  292. package/dist/src/tv-remote-runtime.js +1 -1
  293. package/dist/src/tv-remote.js +2 -2
  294. package/dist/src/type-text-runtime.js +1 -1
  295. package/dist/src/update-check.js +1 -1
  296. package/dist/src/vega-executable.js +1 -1
  297. package/dist/src/video.js +1 -1
  298. package/dist/src/webdriver-source.js +1 -1
  299. package/package.json +7 -6
  300. package/server.json +2 -2
  301. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.30.apk.sha256 +0 -1
  302. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk +0 -0
  303. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk.sha256 +0 -1
  304. package/dist/src/physical-device-apps.js +0 -1
@@ -1 +1 @@
1
- import{C as e,ut as t}from"./sdk-contracts.js";import"./sdk-batch-runner.js";import{G as n,Y as r,m as i}from"./back-mode.js";import{V as a,ht as o}from"./sdk-io.js";import"./diagnostics.js";import{Cn as s,Tn as c,Zn as l,mr as u,xn as d}from"./sdk-batch.js";import{i as f}from"./target-evidence.js";import{n as p,t as m}from"./target-evidence-tree.js";import{t as h}from"./android-snapshot-quality.js";import"./retry.js";import{a as g,n as ee,t as _}from"./replay-divergence.js";import{h as v}from"./replay-script-selection.js";import{n as y}from"./snapshot-chrome.js";import{t as b}from"./snapshot-quality-verdict.js";import x from"node:fs";import S from"node:path";function C(e){if(e.length===0)return{selectorExpression:null,selectorTimeout:null};let t=e.at(-1),n=t!==void 0&&/^\d+$/.test(t)?t:null,r=n===null?e.slice():e.slice(0,-1),i=s(`positional`,r);return i.kind!==`expression`||i.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:i.expression,selectorTimeout:n}}function w(e){let t=[],n=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];if(t.push(...n),r(e.command)){let n=te(e),r=n[0]??``;r&&!r.startsWith(`@`)&&t.push(n.join(` `))}if(e.command===`fill`){let n=e.positionals?.[0]??``;n&&!n.startsWith(`@`)&&Number.isNaN(Number(n))&&t.push(n)}if(e.command===`get`){let n=e.positionals?.[1]??``;n&&!n.startsWith(`@`)&&t.push(e.positionals.slice(1).join(` `))}if(e.command===`is`){let n=s(`is`,[...e.positionals]);n.kind===`expression`&&t.push(n.expression)}if(e.command===`wait`){let{selectorExpression:n}=C([...e.positionals]);n&&t.push(n)}return u(t).filter(e=>e.trim().length>0)}function te(e){let t=e.positionals;if(e.command!==`longpress`)return t;let n=t.at(-1);return t.length>1&&ne(n)?t.slice(0,-1):t}function ne(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}function T(e){let t=S.dirname(e),n=S.basename(e,S.extname(e));return S.join(t,`${n}.healed.ad`)}function E(e){let t=re({failedIndex:e.failedIndex,actions:e.actions,planDigest:e.planDigest,repairHint:e.repairHint,sessionExists:e.resumeStamper.sessionExists()});return e.resumeStamper.stampCorrectiveWatermark({resume:t,repairHint:e.repairHint,failedIndex:e.failedIndex,actions:e.actions}),t}function re(e){let{failedIndex:t,actions:n,planDigest:r,repairHint:i,sessionExists:a}=e,o=i===`record-and-heal`?t+1:t,s=ie({failedIndex:t,actions:n,repairHint:i,sessionExists:a});return{allowed:!0,from:o,planDigest:r,...s===void 0?{}:{alternateFrom:s}}}function ie(e){let{failedIndex:t,actions:n,repairHint:r,sessionExists:i}=e;if(r!==`caution`&&r!==`manual`)return;let a=t+1;if(!(a>n.length&&!i))return a}function D(e){let{kind:t,targetEvidence:n,capture:r}=e;if(t===`identity-mismatch`)return`caution`;if(t===`identity-unverifiable`||!n||r.state!==`available`||!ae(n))return`manual`;let i=O(n,r.nodes);return t===`selector-miss`?i?`record-and-heal`:`state-repair`:i?`record-and-heal`:`manual`}function ae(e){return e.ancestry.length>0||e.scrollRegion!==void 0&&k(e.scrollRegion)}function O(e,t){let n=p(t),r=j(e.ancestry,n,t),i=e.scrollRegion;return i&&k(i)?r&&A(i,n,t):r}function k(e){return e.id!==void 0||e.label!==void 0}function A(e,t,n){return n.some(n=>f(n,t,e))}function j(e,t,n){return e.length===0?n.length>0:n.some(n=>{let r=m(n,t,e.length);return!r.broken&&l(r.chain,e)})}function M(e){let{sessionStore:n,observationStore:r,divergence:i,responseLevel:a}=e,o,s,c=_({divergence:i,level:a,writeOverflowArtifact:e=>{let r=t(e),i=oe(n,r);return`artifactPath`in i&&(o=r,s=i.artifactPath),i}}),l=(o??c).screen;if(l.state!==`available`||l.refs.length===0)return e.evidence&&r.bindAuthority(e.signal).finalize(e.evidence,{refsGeneration:l.state===`available`?l.refsGeneration:void 0,refs:[]}),c;if(!e.evidence)return P(s),N(c,`missing-evidence`);let u=r.bindAuthority(e.signal).finalize(e.evidence,{refsGeneration:l.refsGeneration,refs:l.refs.map(e=>e.ref)});return u.published===!0?c:(P(s),N(c,u.reason))}function N(e,t){let{overflow:n,...r}=e;return{...r,screen:{state:`unavailable`,reason:`ref-publication-${t}`,hint:`The replay observation changed before its refs could be published. Take a new snapshot before targeting an element.`},suggestions:e.suggestions.map(({ref:e,...t})=>t),...e.targetBinding?{targetBinding:{...e.targetBinding,candidates:e.targetBinding.candidates.map(({ref:e,...t})=>t)}}:{}}}function P(e){if(e)try{x.unlinkSync(e)}catch{}}function oe(e,t){try{let n=S.join(e.ensureSessionDir(),`replay-divergence`);x.mkdirSync(n,{recursive:!0});let r=`${Date.now()}-step${t.step.index}.json`,i=S.join(n,r);return x.writeFileSync(i,`${JSON.stringify(t,null,2)}\n`),{artifactPath:i}}catch{return{artifactUnavailable:!0}}}const se={id:0,"role-label":1,label:2,other:3};function F(e,t=new Set){let n=new Map;for(let t of e){let e=n.get(t.nodeIndex);(!e||I(t.basis)<I(e.basis))&&n.set(t.nodeIndex,t)}return[...n.values()].sort((e,n)=>I(e.basis)-I(n.basis)||Number(t.has(n.nodeIndex))-Number(t.has(e.nodeIndex))||e.nodeIndex-n.nodeIndex)}function I(e){return se[e]}async function L(e){let{error:t,action:r,index:i,sourcePath:a,sourceLine:o,session:s,sessionStore:c,observationStore:l,resumeStamper:u,logPath:d,responseLevel:f,scrubVars:p=[],planActions:m,planDigest:h,signal:g}=e,_=ee(p),v={code:t.code,message:_(t.message),...t.hint?{hint:_(t.hint)}:{}},y=s?await B({session:s,observationStore:l,logPath:d,action:r}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`},b=W(y,_),x=y.state===`available`&&s?ue({action:r,session:s,nodes:y.nodes,sanitize:_}):[],S=D({kind:`action-failure`,targetEvidence:r.targetEvidence,capture:R(y)}),C=E({failedIndex:i+1,actions:m,planDigest:h,repairHint:S,resumeStamper:u});return M({sessionStore:c,observationStore:l,divergence:{version:1,kind:`action-failure`,step:{index:i+1,source:{path:_(a),line:o}},action:_(n(r)),cause:v,screen:b,suggestions:x.slice(0,5),suggestionCount:x.length,resume:C,repairHint:S},responseLevel:f,evidence:y.state===`available`?y.evidence:void 0,...g?{signal:g}:{}})}function R(e){return e.state===`available`?{state:`available`,nodes:e.nodes}:{state:`unavailable`}}const z=[300,500,800,1200,2e3,3e3,4e3];async function B(e){let{session:t,observationStore:n,logPath:r,action:i,retryLaunchRace:o=!1}=e,s=H(i),c=Date.now()+12e3,l=n.bindAuthority(),u=await V({session:t,observation:l,logPath:r,flags:s});if(!o)return u.observation;for(let e of z){if(u.observation.state===`available`||!u.retryable)break;let n=c-Date.now();if(n<=0)break;await a(Math.min(e,n)),u=await V({session:t,observation:l,logPath:r,flags:s})}return u.observation}async function V(e){let{session:t,observation:n,logPath:r,flags:i}=e;try{let e=(await n.capture({flags:i,logPath:r})).snapshot;if(b(e.snapshotQuality))return{observation:{state:`unavailable`,reason:`sparse-snapshot`,hint:`The post-failure snapshot was sparse or unavailable; run snapshot -i to observe the current screen.`},retryable:!0};let a=n.store(e);return{observation:{state:`available`,nodes:e.nodes,refsGeneration:a.refsGeneration,evidence:a.evidence,appBundleId:t.appBundleId},retryable:!1}}catch(e){return{observation:{state:`unavailable`,reason:`capture-failed`,hint:`Post-failure snapshot capture failed (${e instanceof Error?e.message:String(e)}); the original replay failure is unaffected.`},retryable:h(e)}}}function H(e){return{snapshotInteractiveOnly:U(e)}}function U(e){return!q(e.command)||J(e).requiresRect}function W(e,t){if(e.state===`unavailable`)return{state:`unavailable`,reason:t(e.reason),hint:t(e.hint)};let{refs:n,truncated:r}=le(e.nodes,t,e.appBundleId);return{state:`available`,refsGeneration:e.refsGeneration,refs:n,...r?{truncated:!0}:{}}}function G(t){return!!i(t,e(t.type??`Element`))||t.hittable===!0}function K(e,t){return t!==void 0&&e.bundleId!==void 0&&e.bundleId!==t&&e.hittable===!0}function ce(e,t){let n=y(e,t),r=e.filter(e=>e.ref&&!n.has(e.ref)&&G(e)),i=r.length>0?r:e.filter(e=>e.ref&&e.hittable===!0),a=i.filter(e=>e.interactionBlocked!==`covered`),o=a.length>0?a:i,s=[...o.filter(e=>K(e,t)),...o.filter(e=>!K(e,t))],c=s.slice(0,20);return{nodes:c,truncated:s.length>c.length}}function le(t,n,r){let{nodes:a,truncated:o}=ce(t,r);return{refs:a.map(t=>{let r=e(t.type??`Element`),a=i(t,r);return{ref:t.ref,role:n(r),...a?{label:n(a)}:{}}}),truncated:o}}function ue(e){let{action:t,session:n,nodes:r,sanitize:i}=e;if(!q(t.command))return[];let a=w(t);return a.length===0?[]:de({candidates:a,nodes:r,session:n,action:t,matching:J(t),sanitize:i})}function q(e){return r(e)||[`fill`,`get`,`is`,`wait`].includes(e)}function J(e){let t=r(e.command);return{requiresRect:t||e.command===`fill`,allowDisambiguation:t||e.command===`fill`||e.command===`get`&&e.positionals?.[0]===`text`}}function de(e){let{candidates:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,s=[];for(let e of t){let t=fe({candidate:e,nodes:n,session:r,action:i,matching:a,sanitize:o});t&&s.push(t)}let c,l=i.targetEvidence;if(l?.verification===`verified`){let e=p(n);c=new Set;for(let{nodeIndex:t}of s){let n=e.get(t);n&&f(n,e,l.scrollRegion)&&c.add(t)}}return F(s,c).map(e=>e.suggestion)}function fe(e){let{candidate:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,s=c(t,n,{platform:r.device.platform,requireRect:a.requiresRect,allowDisambiguation:a.allowDisambiguation});if(s)return{suggestion:Y({node:s.node,nodes:n,session:r,action:i,basis:s.basis,sanitize:o}),basis:s.basis,nodeIndex:s.node.index}}function Y(t){let{node:n,nodes:a,session:o,action:s,basis:c,sanitize:l}=t,u=d(n,o.device.platform,{action:s.command===`fill`?`fill`:r(s.command)?`click`:`get`,nodes:a}),f=e(n.type??`Element`),p=i(n,f);return{selector:l(u.join(` || `)),basis:c,...n.ref?{ref:n.ref}:{},role:l(f),...p?{label:l(p)}:{}}}function pe(e){return me({...e,hint:e.hint??Z(e.details,`hint`),diagnosticId:e.diagnosticId??Z(e.details,`diagnosticId`),logPath:e.logPath??Z(e.details,`logPath`)})}function me(e){return e.details?.reason===`android_shell_text_unsupported`?{...e,hint:"On emulators the test IME activates automatically; on real devices pass `--test-ime` to this test/replay run to enable it for the sessions the flow opens (see `agent-device doctor` for the current IME state)."}:e}function he(e){let{error:t,action:r,step:i,replayPath:a,artifactPaths:o,snapshotDiagnostics:s,divergence:c,scrubVars:l}=e;return X({error:t,actionLabel:n(r),action:r.command,positionals:v(r)??[],step:i,replayPath:a,artifactPaths:o,snapshotDiagnostics:s,divergence:c,scrubVars:l})}function X(e){let{error:t,actionLabel:n,action:r,positionals:i,step:a,replayPath:o,artifactPaths:s,snapshotDiagnostics:c,divergence:l,scrubVars:u,warnings:d}=e;return{ok:!1,error:{code:`REPLAY_DIVERGENCE`,message:g(`Replay failed at step ${a} (${n}): ${t.message}`,u),hint:t.hint===void 0?void 0:g(t.hint,u),diagnosticId:t.diagnosticId,logPath:t.logPath,...t.retriable===void 0?{}:{retriable:t.retriable},...t.supportedOn===void 0?{}:{supportedOn:t.supportedOn},details:{..._e(t.details),replayPath:o,step:a,action:r,positionals:i,artifactPaths:s,...c?{snapshotDiagnostics:c}:{},...d&&d.length>0?{warnings:d.map(e=>g(e,u))}:{},divergence:l}}}}function Z(e,t){let n=e?.[t];return typeof n==`string`&&n.length>0?n:void 0}const ge=[`reason`,`recovery`,`retriable`,`snapshotQuality`,`supportedOn`,`systemSurface`];function _e(e){if(!e)return{};let t={};for(let n of ge)e[n]!==void 0&&(t[n]=e[n]);return t}function ve(e,n){if(e)try{x.appendFileSync(e,`${JSON.stringify(t(n))}\n`)}catch(t){o({level:`warn`,phase:`replay_trace_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}}function ye(e){let{req:t,sessionName:n,metadata:r,resolvedPath:i,hostCwd:a}=e,o=t.flags??{},s={AD_SESSION:n,AD_FILENAME:be(t,i,a)};return Q(s,`AD_PLATFORM`,o.platform??r.platform),Q(s,`AD_TARGET`,o.target??r.target),Q(s,`AD_DEVICE`,o.device),Q(s,`AD_DEVICE_ID`,xe(o)),$(s,`AD_SHARD_INDEX`,o.shardIndex),$(s,`AD_SHARD_COUNT`,o.shardCount),Q(s,`AD_ARTIFACTS`,o.artifactsDir),s}function be(e,t,n){let r=e.meta?.cwd??n;return S.relative(r,t)||t}function xe(e){return typeof e.serial==`string`?e.serial:e.udid}function Q(e,t,n){typeof n==`string`&&n.length>0&&(e[t]=n)}function $(e,t,n){typeof n==`number`&&(e[t]=String(n))}export{pe as a,L as c,R as d,F as f,T as g,E as h,X as i,B as l,D as m,ve as n,W as o,M as p,he as r,Y as s,ye as t,J as u};
1
+ import{C as e,dt as t}from"./sdk-contracts.js";import"./sdk-batch-runner.js";import{G as n,Y as r,m as i}from"./back-mode.js";import{H as a,_t as o}from"./sdk-io.js";import"./diagnostics.js";import{Fn as s,Nn as c,jn as l,sr as u,wr as d}from"./sdk-batch.js";import{i as f}from"./target-evidence.js";import{n as p,t as m}from"./target-evidence-tree.js";import{t as h}from"./android-snapshot-quality.js";import"./retry.js";import{a as g,n as ee,t as _}from"./replay-divergence.js";import{h as v}from"./replay-script-selection.js";import{n as y}from"./snapshot-chrome.js";import{t as b}from"./snapshot-quality-verdict.js";import x from"node:fs";import S from"node:path";function C(e){if(e.length===0)return{selectorExpression:null,selectorTimeout:null};let t=e.at(-1),n=t!==void 0&&/^\d+$/.test(t)?t:null,r=n===null?e.slice():e.slice(0,-1),i=c(`positional`,r);return i.kind!==`expression`||i.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:i.expression,selectorTimeout:n}}function w(e){let t=[],n=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];if(t.push(...n),r(e.command)){let n=T(e),r=n[0]??``;r&&!r.startsWith(`@`)&&t.push(n.join(` `))}if(e.command===`fill`){let n=e.positionals?.[0]??``;n&&!n.startsWith(`@`)&&Number.isNaN(Number(n))&&t.push(n)}if(e.command===`get`){let n=e.positionals?.[1]??``;n&&!n.startsWith(`@`)&&t.push(e.positionals.slice(1).join(` `))}if(e.command===`is`){let n=c(`is`,[...e.positionals]);n.kind===`expression`&&t.push(n.expression)}if(e.command===`wait`){let{selectorExpression:n}=C([...e.positionals]);n&&t.push(n)}return d(t).filter(e=>e.trim().length>0)}function T(e){let t=e.positionals;if(e.command!==`longpress`)return t;let n=t.at(-1);return t.length>1&&te(n)?t.slice(0,-1):t}function te(e){return e===void 0||e.trim()===``?!1:Number.isFinite(Number(e))}function E(e){let t=S.dirname(e),n=S.basename(e,S.extname(e));return S.join(t,`${n}.healed.ad`)}function D(e){let t=ne({failedIndex:e.failedIndex,actions:e.actions,planDigest:e.planDigest,repairHint:e.repairHint,sessionExists:e.resumeStamper.sessionExists()});return e.resumeStamper.stampCorrectiveWatermark({resume:t,repairHint:e.repairHint,failedIndex:e.failedIndex,actions:e.actions}),t}function ne(e){let{failedIndex:t,actions:n,planDigest:r,repairHint:i,sessionExists:a}=e,o=i===`record-and-heal`?t+1:t,s=re({failedIndex:t,actions:n,repairHint:i,sessionExists:a});return{allowed:!0,from:o,planDigest:r,...s===void 0?{}:{alternateFrom:s}}}function re(e){let{failedIndex:t,actions:n,repairHint:r,sessionExists:i}=e;if(r!==`caution`&&r!==`manual`)return;let a=t+1;if(!(a>n.length&&!i))return a}function O(e){let{kind:t,targetEvidence:n,capture:r}=e;if(t===`identity-mismatch`)return`caution`;if(t===`identity-unverifiable`||!n||r.state!==`available`||!ie(n))return`manual`;let i=k(n,r.nodes);return t===`selector-miss`?i?`record-and-heal`:`state-repair`:i?`record-and-heal`:`manual`}function ie(e){return e.ancestry.length>0||e.scrollRegion!==void 0&&A(e.scrollRegion)}function k(e,t){let n=p(t),r=M(e.ancestry,n,t),i=e.scrollRegion;return i&&A(i)?r&&j(i,n,t):r}function A(e){return e.id!==void 0||e.label!==void 0}function j(e,t,n){return n.some(n=>f(n,t,e))}function M(e,t,n){return e.length===0?n.length>0:n.some(n=>{let r=m(n,t,e.length);return!r.broken&&u(r.chain,e)})}function N(e){let{sessionStore:n,observationStore:r,divergence:i,responseLevel:a}=e,o,s,c=_({divergence:i,level:a,writeOverflowArtifact:e=>{let r=t(e),i=ae(n,r);return`artifactPath`in i&&(o=r,s=i.artifactPath),i}}),l=(o??c).screen;if(l.state!==`available`||l.refs.length===0)return e.evidence&&r.bindAuthority(e.signal).finalize(e.evidence,{refsGeneration:l.state===`available`?l.refsGeneration:void 0,refs:[]}),c;if(!e.evidence)return F(s),P(c,`missing-evidence`);let u=r.bindAuthority(e.signal).finalize(e.evidence,{refsGeneration:l.refsGeneration,refs:l.refs.map(e=>e.ref)});return u.published===!0?c:(F(s),P(c,u.reason))}function P(e,t){let{overflow:n,...r}=e;return{...r,screen:{state:`unavailable`,reason:`ref-publication-${t}`,hint:`The replay observation changed before its refs could be published. Take a new snapshot before targeting an element.`},suggestions:e.suggestions.map(({ref:e,...t})=>t),...e.targetBinding?{targetBinding:{...e.targetBinding,candidates:e.targetBinding.candidates.map(({ref:e,...t})=>t)}}:{}}}function F(e){if(e)try{x.unlinkSync(e)}catch{}}function ae(e,t){try{let n=S.join(e.ensureSessionDir(),`replay-divergence`);x.mkdirSync(n,{recursive:!0});let r=`${Date.now()}-step${t.step.index}.json`,i=S.join(n,r);return x.writeFileSync(i,`${JSON.stringify(t,null,2)}\n`),{artifactPath:i}}catch{return{artifactUnavailable:!0}}}const oe={id:0,"role-label":1,label:2,other:3};function I(e,t=new Set){let n=new Map;for(let t of e){let e=n.get(t.nodeIndex);(!e||L(t.basis)<L(e.basis))&&n.set(t.nodeIndex,t)}return[...n.values()].sort((e,n)=>L(e.basis)-L(n.basis)||Number(t.has(n.nodeIndex))-Number(t.has(e.nodeIndex))||e.nodeIndex-n.nodeIndex)}function L(e){return oe[e]}async function se(e){let{error:t,action:r,index:i,sourcePath:a,sourceLine:o,session:s,sessionStore:c,observationStore:l,resumeStamper:u,logPath:d,responseLevel:f,scrubVars:p=[],planActions:m,planDigest:h,signal:g}=e,_=ee(p),v={code:t.code,message:_(t.message),...t.hint?{hint:_(t.hint)}:{}},y=s?await B({session:s,observationStore:l,logPath:d,action:r,signal:g}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a post-failure screen could be captured.`},b=G(y,_),x=y.state===`available`&&s?de({action:r,session:s,nodes:y.nodes,sanitize:_}):[],S=O({kind:`action-failure`,targetEvidence:r.targetEvidence,capture:R(y)}),C=D({failedIndex:i+1,actions:m,planDigest:h,repairHint:S,resumeStamper:u});return N({sessionStore:c,observationStore:l,divergence:{version:1,kind:`action-failure`,step:{index:i+1,source:{path:_(a),line:o}},action:_(n(r)),cause:v,screen:b,suggestions:x.slice(0,5),suggestionCount:x.length,resume:C,repairHint:S},responseLevel:f,evidence:y.state===`available`?y.evidence:void 0,...g?{signal:g}:{}})}function R(e){return e.state===`available`?{state:`available`,nodes:e.nodes}:{state:`unavailable`}}const z=[300,500,800,1200,2e3,3e3,4e3];async function B(e){let{session:t,observationStore:n,logPath:r,action:i,retryLaunchRace:o=!1,signal:s}=e;if(s?.aborted)return V();let c=U(i),l=Date.now()+12e3,u=n.bindAuthority(s),d=await H({session:t,observation:u,logPath:r,flags:c});if(!o)return d.observation;for(let e of z){if(d.observation.state===`available`||!d.retryable)break;let n=l-Date.now();if(n<=0)break;if(await a(Math.min(e,n)),s?.aborted)return V();d=await H({session:t,observation:u,logPath:r,flags:c})}return d.observation}function V(){return{state:`unavailable`,reason:`request-canceled`,hint:`Post-failure snapshot skipped after request cancellation; the original replay failure is unaffected.`}}async function H(e){let{session:t,observation:n,logPath:r,flags:i}=e;try{let e=(await n.capture({flags:i,logPath:r})).snapshot;if(b(e.snapshotQuality))return{observation:{state:`unavailable`,reason:`sparse-snapshot`,hint:`The post-failure snapshot was sparse or unavailable; run snapshot -i to observe the current screen.`},retryable:!0};let a=n.store(e);return{observation:{state:`available`,nodes:e.nodes,refsGeneration:a.refsGeneration,evidence:a.evidence,appBundleId:t.appBundleId},retryable:!1}}catch(e){return{observation:{state:`unavailable`,reason:`capture-failed`,hint:`Post-failure snapshot capture failed (${e instanceof Error?e.message:String(e)}); the original replay failure is unaffected.`},retryable:h(e)}}}function U(e){return{snapshotInteractiveOnly:W(e)}}function W(e){return!q(e.command)||J(e).requiresRect}function G(e,t){if(e.state===`unavailable`)return{state:`unavailable`,reason:t(e.reason),hint:t(e.hint)};let{refs:n,truncated:r}=ue(e.nodes,t,e.appBundleId);return{state:`available`,refsGeneration:e.refsGeneration,refs:n,...r?{truncated:!0}:{}}}function ce(t){return!!i(t,e(t.type??`Element`))||t.hittable===!0}function K(e,t){return t!==void 0&&e.bundleId!==void 0&&e.bundleId!==t&&e.hittable===!0}function le(e,t){let n=y(e,t),r=e.filter(e=>e.ref&&!n.has(e.ref)&&ce(e)),i=r.length>0?r:e.filter(e=>e.ref&&e.hittable===!0),a=i.filter(e=>e.interactionBlocked!==`covered`),o=a.length>0?a:i,s=[...o.filter(e=>K(e,t)),...o.filter(e=>!K(e,t))],c=s.slice(0,20);return{nodes:c,truncated:s.length>c.length}}function ue(t,n,r){let{nodes:a,truncated:o}=le(t,r);return{refs:a.map(t=>{let r=e(t.type??`Element`),a=i(t,r);return{ref:t.ref,role:n(r),...a?{label:n(a)}:{}}}),truncated:o}}function de(e){let{action:t,session:n,nodes:r,sanitize:i}=e;if(!q(t.command))return[];let a=w(t);return a.length===0?[]:fe({candidates:a,nodes:r,session:n,action:t,matching:J(t),sanitize:i})}function q(e){return r(e)||[`fill`,`get`,`is`,`wait`].includes(e)}function J(e){let t=r(e.command);return{requiresRect:t||e.command===`fill`,allowDisambiguation:t||e.command===`fill`||e.command===`get`&&e.positionals?.[0]===`text`}}function fe(e){let{candidates:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,s=[];for(let e of t){let t=pe({candidate:e,nodes:n,session:r,action:i,matching:a,sanitize:o});t&&s.push(t)}let c,l=i.targetEvidence;if(l?.verification===`verified`){let e=p(n);c=new Set;for(let{nodeIndex:t}of s){let n=e.get(t);n&&f(n,e,l.scrollRegion)&&c.add(t)}}return I(s,c).map(e=>e.suggestion)}function pe(e){let{candidate:t,nodes:n,session:r,action:i,matching:a,sanitize:o}=e,c=s(t,n,{platform:r.device.platform,requireRect:a.requiresRect,allowDisambiguation:a.allowDisambiguation});if(c)return{suggestion:Y({node:c.node,nodes:n,session:r,action:i,basis:c.basis,sanitize:o}),basis:c.basis,nodeIndex:c.node.index}}function Y(t){let{node:n,nodes:a,session:o,action:s,basis:c,sanitize:u}=t,d=l(n,o.device.platform,{action:s.command===`fill`?`fill`:r(s.command)?`click`:`get`,nodes:a}),f=e(n.type??`Element`),p=i(n,f);return{selector:u(d.join(` || `)),basis:c,...n.ref?{ref:n.ref}:{},role:u(f),...p?{label:u(p)}:{}}}function me(e){return he({...e,hint:e.hint??Z(e.details,`hint`),diagnosticId:e.diagnosticId??Z(e.details,`diagnosticId`),logPath:e.logPath??Z(e.details,`logPath`)})}function he(e){return e.details?.reason===`android_shell_text_unsupported`?{...e,hint:"On emulators the test IME activates automatically; on real devices pass `--test-ime` to this test/replay run to enable it for the sessions the flow opens (see `agent-device doctor` for the current IME state)."}:e}function ge(e){let{error:t,action:r,step:i,replayPath:a,artifactPaths:o,snapshotDiagnostics:s,divergence:c,scrubVars:l}=e;return X({error:t,actionLabel:n(r),action:r.command,positionals:v(r)??[],step:i,replayPath:a,artifactPaths:o,snapshotDiagnostics:s,divergence:c,scrubVars:l})}function X(e){let{error:t,actionLabel:n,action:r,positionals:i,step:a,replayPath:o,artifactPaths:s,snapshotDiagnostics:c,divergence:l,scrubVars:u,warnings:d}=e;return{ok:!1,error:{code:`REPLAY_DIVERGENCE`,message:g(`Replay failed at step ${a} (${n}): ${t.message}`,u),hint:t.hint===void 0?void 0:g(t.hint,u),diagnosticId:t.diagnosticId,logPath:t.logPath,...t.retriable===void 0?{}:{retriable:t.retriable},...t.supportedOn===void 0?{}:{supportedOn:t.supportedOn},details:{...ve(t.details),replayPath:o,step:a,action:r,positionals:i,artifactPaths:s,...c?{snapshotDiagnostics:c}:{},...d&&d.length>0?{warnings:d.map(e=>g(e,u))}:{},divergence:l}}}}function Z(e,t){let n=e?.[t];return typeof n==`string`&&n.length>0?n:void 0}const _e=[`reason`,`recovery`,`retriable`,`snapshotQuality`,`supportedOn`,`systemSurface`];function ve(e){if(!e)return{};let t={};for(let n of _e)e[n]!==void 0&&(t[n]=e[n]);return t}function ye(e,n){if(e)try{x.appendFileSync(e,`${JSON.stringify(t(n))}\n`)}catch(t){o({level:`warn`,phase:`replay_trace_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}}function be(e){let{req:t,sessionName:n,metadata:r,resolvedPath:i,hostCwd:a}=e,o=t.flags??{},s={AD_SESSION:n,AD_FILENAME:xe(t,i,a)};return Q(s,`AD_PLATFORM`,o.platform??r.platform),Q(s,`AD_TARGET`,o.target??r.target),Q(s,`AD_DEVICE`,o.device),Q(s,`AD_DEVICE_ID`,Se(o)),$(s,`AD_SHARD_INDEX`,o.shardIndex),$(s,`AD_SHARD_COUNT`,o.shardCount),Q(s,`AD_ARTIFACTS`,o.artifactsDir),s}function xe(e,t,n){let r=e.meta?.cwd??n;return S.relative(r,t)||t}function Se(e){return typeof e.serial==`string`?e.serial:e.udid}function Q(e,t,n){typeof n==`string`&&n.length>0&&(e[t]=n)}function $(e,t,n){typeof n==`number`&&(e[t]=String(n))}export{me as a,se as c,R as d,I as f,E as g,D as h,X as i,B as l,O as m,ye as n,G as o,N as p,ge as r,Y as s,be as t,J as u};
@@ -1 +1 @@
1
- import{B as e,R as t,l as n,s as r}from"./sdk-contracts.js";import{Z as i,b as a,ht as o}from"./sdk-io.js";import"./diagnostics.js";import{O as s,_ as c,v as l}from"./sdk-device.js";import{o as ee}from"./sdk-batch.js";import"./session-store.js";import{a as te}from"./session.js";import{C as u,S as ne}from"./transport.js";import"./command.js";import{r as d}from"./runtime-transport-hints.js";import{n as re}from"./runtime-slots.js";import{g as ie,o as ae,u as oe}from"./device-claim-recovery.js";import{c as se}from"./artifact-tracking.js";import{a as ce}from"./daemon-command-registry.js";import{a as le,i as ue,n as de}from"./session-capture-binding.js";import{r as fe}from"./application-lifecycle-runtime.js";import pe from"node:crypto";import{rmSync as me}from"node:fs";import f from"node:os";import p from"node:path";import m from"node:fs/promises";function he(e,t){return u(e,t)?t:`${e}:${t}`}function ge(e,t){return!e.partitioned||u(e.tenant,t)}const _e=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/,ve=/^[1-9][0-9]{0,9}$/;function h(e){let n=e?.trim()??``,r=n.lastIndexOf(`@`),i=r<0?n:n.slice(0,r),a=r<0?void 0:n.slice(r+1);if(!_e.test(i)||a!==void 0&&!ve.test(a))throw new t(`INVALID_ARGS`,`A macos-app lease device key must be <bundleId> or <bundleId>@<pid>.`,{deviceKey:n});return a===void 0?{bundleId:i}:{bundleId:i,pid:Number(a)}}const ye=new Set([`open`,`batch`]),be=[`out`,`saveScript`,`sessionSaveScript`,`baseline`,`launchConsole`,`launchArgs`,`launchUrl`,`bundleUrl`,`artifactsDir`,`stepsFile`,`searchPath`,`retainPaths`,`installSource`,`metroProjectRoot`,`metroRuntimeFile`,`iosXctestrunFile`,`iosXctestDerivedDataPath`,`iosXctestEnvDir`],xe=[`device`,`udid`,`serial`,`target`,`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function g(e,n,r={}){return new t(`UNAUTHORIZED`,n,{...r,reason:`MACOS_APP_LEASE_DENIED`,rule:e,retriable:!1,hint:`This lease is limited to one macOS app; retrying will not help. Use an allowed command on the leased app.`})}function Se(e,t,n,r){if(e.backend!==`macos-app`)return;let i=h(e.deviceKey);if(v(r,i,t.command,t.positionals??[],_(t.runtime,{...t.input,...t.flags})),(t.command===`open`||t.command===`batch`)&&t.flags?.platform!==`macos`)throw g(`device`,`A macos-app lease needs platform macos on ${t.command}.`);if(t.command===`batch`)for(let e of t.flags?.batchSteps??[]){let t=Array.isArray(e.positionals)?e.positionals.map(String):[];v(r,i,ee(e.command),t,_(e.runtime,{...e.input,...e.flags}))}if(n)S(i,n);else if(!ye.has(t.command))throw g(`session`,`A macos-app lease runs ${t.command} only in a session of ${i.bundleId}; open it first.`,{command:t.command,bundleId:i.bundleId})}function _(e,t){return{...t,...e?.launchUrl?{launchUrl:e.launchUrl}:{},...e?.bundleUrl?{bundleUrl:e.bundleUrl}:{}}}function v(e,t,n,r,i){if(!ce(n))throw g(`command`,`A macos-app lease does not allow ${n}.`,{command:n});if(Te(i),we(i),n===`screenshot`?Ce(r,i):y(i),n===`open`&&b(e,t,r),n===`close`&&r.length>0&&r[0]!==t.bundleId)throw g(`app`,`A macos-app lease only closes ${t.bundleId}.`,{bundleId:t.bundleId})}function Ce(e,t){if(t.screenshotFullscreen===!0)throw g(`capture`,`A macos-app lease captures only the app window.`);let{out:n,...r}=t;y(r);for(let t of[e[0],n])if(!(t===void 0||typeof t==`string`&&ne(t,`screenshot`,`.png`)))throw g(`host-path`,`A macos-app lease does not write files on the host.`)}function y(e){let t=be.find(t=>e[t]!==void 0&&e[t]!==!1);if(t)throw g(`host-path`,`A macos-app lease does not accept ${t}, which names a host path or launch.`,{field:t})}function we(e){let t=xe.find(t=>e[t]!==void 0&&e[t]!==``);if(t)throw g(`device`,`A macos-app lease does not accept the ${t} device selector.`,{field:t})}function Te(e){if(e.surface!==void 0&&e.surface!==`app`)throw g(`surface`,`A macos-app lease is limited to the app surface, not ${String(e.surface)}.`,{surface:e.surface});if(e.platform!==void 0&&e.platform!==`macos`)throw g(`app`,`A macos-app lease only drives a macOS app.`,{platform:e.platform})}function b(e,t,n){if(n.length!==1||n[0]!==t.bundleId)throw g(`app`,`A macos-app lease only opens ${t.bundleId}.`,{bundleId:t.bundleId});x(e)}function x(e){if(te(t=>e[t])!==`native`)throw g(`backend`,`A macos-app lease needs the native macOS app backend (AGENT_DEVICE_MACOS_APP_BACKEND=native).`)}function S(e,t){if(!l(t.device)||(t.surface??`app`)!==`app`||t.appBundleId!==e.bundleId)throw g(`app`,`This session is not the leased app ${e.bundleId}.`,{bundleId:e.bundleId})}const C=/bundleID="([^"]+)"/,w=async e=>{if(!a(e))return;let t=await i(`/usr/bin/lsappinfo`,[`info`,`-only`,`bundleid`,String(e)],{allowFailure:!0,timeoutMs:5e3});return C.exec(t.stdout)?.[1]};async function T(e,t=w){if(e.backend!==`macos-app`)return;let n=h(e.deviceKey);if(n.pid!==void 0&&await t(n.pid)!==n.bundleId)throw g(`process`,`The leased app process ${n.bundleId}@${n.pid} is no longer running.`,{bundleId:n.bundleId,pid:n.pid})}const E=[`sessionStateDir`,`runnerLogPath`,`requestLogPath`,`eventLogPath`,`device`,`id`,`kind`,`serial`,`device_udid`,`ios_simulator_device_set`],D=/(?<![\p{L}\p{N}_./])\/(?:Users|home|private|var|tmp|Volumes|Library|Applications|opt|System|usr|etc|Network|cores)(?:\/[\p{L}\p{N}_.@%+~-]+)*\/?/gu;function O(){return{hostName:f.hostname(),homeDirectory:f.homedir()}}function Ee(e,t,n=O()){return t.ok?{ok:!0,data:k(e,t.data,n)}:{ok:!1,error:A(t.error,n)}}function k(e,t,n){if(!t)return t;let{fallbackScreenshotPath:r,...i}=t;if(e!==`open`)return i;for(let e of E)delete i[e];let{snapshot:a,initialSnapshotError:o,warnings:s,...c}=i;return{...c,...a===void 0?{}:{snapshot:k(`snapshot`,a,n)},...o===void 0?{}:{initialSnapshotError:A(o,n)},...s===void 0?{}:{warnings:j(s,n)}}}function A(e,t){let{logPath:n,diagnosticsRecord:r,...i}=e;return j(i,t)}function j(e,t){return typeof e==`string`?De(e,t):Array.isArray(e)?e.map(e=>j(e,t)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,j(n,t)]))}function De(e,t){let n=e;if(t.homeDirectory.length>1){let e=t.homeDirectory.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);n=n.replaceAll(RegExp(`${e}[\\w.@%+~/-]*`,`g`),`<host-path>`)}for(let e of new Set([t.hostName,t.hostName.split(`.`)[0]]))e.length>=4&&(n=n.replaceAll(e,`<host>`));return n.replace(D,`<host-path>`)}function Oe(e,t){if(!(t===void 0||!e.hasHeldMacOsAppLease(t)))throw g(`diagnostics`,`A macos-app lease does not serve request diagnostics.`)}const ke={label:`Materialized paths`,plural:!0,expiredHint:`Materialized paths are released automatically when their TTL expires; re-run the command that materialized them if the paths are still needed.`},Ae=Symbol(`materializedPaths`),M=()=>re(Ae,()=>new Map,e=>{for(let t of e.values()){clearTimeout(t.timer);try{me(t.rootPath,{recursive:!0,force:!0})}catch{}}});async function je(e){let t=await m.mkdtemp(p.join(f.tmpdir(),`agent-device-materialized-`));try{let n=await I(e.installablePath,p.join(t,`installable`)),r=e.archivePath?await I(e.archivePath,p.join(t,`archive`)):void 0,i=pe.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{Me(i)},a);return M().set(i,{rootPath:t,installablePath:n,archivePath:r,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:o,timer:s}),{materializationId:i,installablePath:n,...r?{archivePath:r}:{},expiresAt:new Date(o).toISOString()}}catch(e){throw await m.rm(t,{recursive:!0,force:!0}),e}}async function N(e,t){await F(e,se(M(),e,t,ke))}async function P(e){let t=Array.from(M().entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await F(e,t)}))}async function Me(e){let t=M().get(e);if(t)try{await F(e,t)}catch{}}async function F(e,t){clearTimeout(t.timer),M().delete(e),await m.rm(t.rootPath,{recursive:!0,force:!0})}async function I(e,t){let n=await m.stat(e);await m.mkdir(t,{recursive:!0});let r=p.join(t,p.basename(e));return n.isDirectory()?(await m.cp(e,r,{recursive:!0}),r):(await m.copyFile(e,r),r)}function Ne(e){return e.device.platform===`web`}function L(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function R(e){let t=e.sessionStore.refresh(e.ref);if(!t.session.appLog)return;let{forceCleanupSessionAppLog:n}=await import(`./app-log-session-resource.js`).then(e=>e.n);await n({...e,ref:t})}async function z(e){let t=ue(e.sessionStore,e.ref);t.read()&&await oe({binding:t,intent:`disposal`})}async function B(e,t){await t.stopSnapshotHelper(e.device)}async function Pe(e){let{ref:t,sessionStore:n,platformCleanup:r}=e,i=n.resolveCurrent(t)??t.session,a=t.address;await r.closeManagedBrowser({device:i.device,sessionName:a,stateDir:n.resolveDaemonStateDir(),openSessionNames:()=>L(n)})}async function Fe(e){let t=[];for(let{step:n,run:r}of e)try{await r()}catch(e){t.push({step:n,error:e})}return t}function V(e){if(e.failures.length===0)return;let n=e.failures.map(({step:e})=>e),r=e.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return o({level:`error`,phase:e.phase,data:{session:e.sessionName,failedSteps:n,errors:r}}),new t(`COMMAND_FAILED`,`Session cleanup left ${e.failures.length} resource(s) unreleased: ${r.join(`; `)}`,{reason:`session_cleanup_incomplete`,session:e.sessionName,failedSteps:n,hint:`Some session resources failed to release; inspect the session log for per-resource diagnostics. The session was still deleted, so retrying is safe.`})}async function Ie(e){let{ref:n,sessionStore:r}=e,i=r.resolveCurrent(n)??n.session,a=n.address;if(!e.platformCleanup)throw new t(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let o=e.platformCleanup,s=[{step:`recording`,run:()=>H({ref:n,sessionStore:r})},...e.appLog===`run`?[{step:`app_log`,run:()=>R({ref:n,sessionStore:r})}]:[],{step:`audio_probe`,run:()=>U({ref:n,sessionStore:r})},{step:`perf_capture`,run:()=>z({ref:n,sessionStore:r})},{step:`platform_snapshot_helper`,run:()=>B(i,o)},{step:`web_browser`,run:()=>Pe({ref:n,sessionStore:r,platformCleanup:o})}];s.push({step:`materialized_paths`,run:()=>P(a)});let c=V({sessionName:a,phase:`session_teardown_cleanup_failed`,failures:await Fe(s)});if(c)throw c}async function H(e){let t=le(e.sessionStore,e.ref);t.read()&&await ae({binding:t,intent:`disposal`})}async function U(e){let t=de(e.sessionStore,e.ref);t.read()&&await ie({binding:t,intent:`disposal`})}function Le(e){return c(e)&&e.kind===`simulator`}function Re(e){return e.platform===`android`&&e.kind===`emulator`}const W=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function G(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function K(e){if(!e)return{};let t={};return e.metroHost!==void 0&&(t.metroHost=e.metroHost),e.metroPort!==void 0&&(t.metroPort=String(e.metroPort)),e.bundleUrl!==void 0&&(t.bundleUrl=e.bundleUrl),e.launchUrl!==void 0&&(t.launchUrl=e.launchUrl),t}function q(e){return fe(K(e))}function J(e,n){if(e!==void 0){if(typeof e!=`string`)throw new t(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return d(e)}}function Y(e){if(e!==void 0){if(!Number.isInteger(e)||e<1||e>65535)throw new t(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function ze(e){if(e!==void 0){if(typeof e!=`number`)throw new t(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Y(e)}}function Be(e,r,i){if(e===void 0)return i;if(!n(e))throw new t(`INVALID_ARGS`,`Invalid open runtime platform: ${String(e)}. Use "ios", "android", or "harmonyos".`);if(i&&e!==i)throw new t(`INVALID_ARGS`,`open runtime targets ${e}, but session "${r}" is bound to ${i}.`);return e}function X(e){if(n(e))return e}function Ve(e,t){return{platform:t,metroHost:d(e?.metroHost),metroPort:Y(e?.metroPort),bundleUrl:d(e?.bundleUrl),launchUrl:d(e?.launchUrl)}}function He(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function Ue(e){if(Re(e))return`10.0.2.2`;if(Le(e))return`127.0.0.1`}function Z(e,t){if(!e||d(e.metroHost)||d(e.bundleUrl)||e.metroPort===void 0)return e;let n=Ue(t);return n?{...e,metroHost:n}:e}function We(e){let{runtime:n,sessionName:r,platform:i}=e;if(n===void 0)return;if(!n||typeof n!=`object`||Array.isArray(n))throw new t(`INVALID_ARGS`,`open runtime must be an object.`);let a=n,o=Object.keys(a).find(e=>!W.includes(e));if(o)throw new t(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${W.join(`, `)}.`);return{platform:Be(a.platform,r,i),metroHost:J(a.metroHost,`metroHost`),metroPort:ze(a.metroPort),bundleUrl:J(a.bundleUrl,`bundleUrl`),launchUrl:J(a.launchUrl,`launchUrl`)}}function Ge(e,t,n){if(n){if(G(n)===0){e.setRuntimeHints(t,void 0);return}return e.setRuntimeHints(t,n),n}}function Ke(e,n,r,i){let a=e.getRuntimeHints(n);if(!a)return;let o=r?s(r):void 0,c=X(o)??i;if(a.platform&&r&&!c)throw new t(`INVALID_ARGS`,`Session runtime hints are only supported on iOS, Android, and HarmonyOS sessions, but session "${n}" is bound to ${o}.`);if(a.platform&&c&&a.platform!==c)throw new t(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${n}" is bound to ${o}. Clear the runtime hints or use a different session.`);return c&&a.platform!==c?{...a,platform:c}:a}function Q(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?X(s(i)):e.platform,o=n.getRuntimeHints(r),c=We({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=Ke(n,r,i,a);return{runtime:i?Z(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let l=c&&G(c)>0?c:void 0;return{runtime:i?Z(l,i):l,previousRuntime:o,replacedStoredRuntime:!0}}function qe(e){return Q(e).runtime}function Je(t){try{return{ok:!0,data:Q(t)}}catch(t){let n=e(t);return r(n.code,n.message,n.details)}}async function Ye(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!$(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:K(t)})}function $(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&q(e.previousRuntime)&&!q(e.runtime)}export{he as A,je as C,h as D,Oe as E,Ee as O,P as S,T,B as _,He as a,L as b,Ge as c,Je as d,U as f,z as g,R as h,Ye as i,ge as k,$ as l,V as m,G as n,qe as o,H as p,q as r,K as s,Ve as t,X as u,Ie as v,Se as w,N as x,Ne as y};
1
+ import{R as e,V as t,l as n,s as r}from"./sdk-contracts.js";import{Q as i,_t as a,b as o}from"./sdk-io.js";import"./diagnostics.js";import{E as s,I as c,T as l,w as ee}from"./sdk-device.js";import{o as te}from"./sdk-batch.js";import"./session-store.js";import{o as ne}from"./session.js";import{C as u,S as re}from"./transport.js";import"./command.js";import{r as d}from"./runtime-transport-hints.js";import{n as ie}from"./runtime-slots.js";import{_ as ae,d as oe,s as f}from"./device-claim-recovery.js";import{c as se}from"./artifact-tracking.js";import{a as ce}from"./daemon-command-registry.js";import{a as le,i as ue,n as de}from"./session-capture-binding.js";import{r as fe}from"./application-lifecycle-runtime.js";import pe from"node:crypto";import{rmSync as me}from"node:fs";import p from"node:os";import m from"node:path";import h from"node:fs/promises";function he(e,t){return u(e,t)?t:`${e}:${t}`}function ge(e,t){return!e.partitioned||u(e.tenant,t)}const _e=/^[1-9][0-9]{0,9}$/;function g(t){let n=t?.trim()??``,r=n.lastIndexOf(`@`),i=r<0?n:n.slice(0,r),a=r<0?void 0:n.slice(r+1);if(!s(i)||a!==void 0&&!_e.test(a))throw new e(`INVALID_ARGS`,`A macos-app lease device key must be <bundleId> or <bundleId>@<pid>.`,{deviceKey:n});return a===void 0?{bundleId:i}:{bundleId:i,pid:Number(a)}}const ve=new Set([`open`,`batch`]),ye=[`out`,`saveScript`,`sessionSaveScript`,`baseline`,`launchConsole`,`launchArgs`,`launchUrl`,`bundleUrl`,`artifactsDir`,`stepsFile`,`searchPath`,`retainPaths`,`installSource`,`metroProjectRoot`,`metroRuntimeFile`,`iosXctestrunFile`,`iosXctestDerivedDataPath`,`iosXctestEnvDir`],be=[`device`,`udid`,`serial`,`target`,`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function _(t,n,r={}){return new e(`UNAUTHORIZED`,n,{...r,reason:`MACOS_APP_LEASE_DENIED`,rule:t,retriable:!1,hint:`This lease is limited to one macOS app; retrying will not help. Use an allowed command on the leased app.`})}function xe(e,t,n,r){if(e.backend!==`macos-app`)return;let i=g(e.deviceKey);if(y(r,i,t.command,t.positionals??[],v(t.runtime,{...t.input,...t.flags})),(t.command===`open`||t.command===`batch`)&&t.flags?.platform!==`macos`)throw _(`device`,`A macos-app lease needs platform macos on ${t.command}.`);if(t.command===`batch`)for(let e of t.flags?.batchSteps??[]){let t=Array.isArray(e.positionals)?e.positionals.map(String):[];y(r,i,te(e.command),t,v(e.runtime,{...e.input,...e.flags}))}if(n)C(i,n);else if(!ve.has(t.command))throw _(`session`,`A macos-app lease runs ${t.command} only in a session of ${i.bundleId}; open it first.`,{command:t.command,bundleId:i.bundleId})}function v(e,t){return{...t,...e?.launchUrl?{launchUrl:e.launchUrl}:{},...e?.bundleUrl?{bundleUrl:e.bundleUrl}:{}}}function y(e,t,n,r,i){if(!ce(n))throw _(`command`,`A macos-app lease does not allow ${n}.`,{command:n});if(we(i),Ce(i),n===`screenshot`?Se(r,i):b(i),n===`open`&&x(e,t,r),n===`close`&&r.length>0&&r[0]!==t.bundleId)throw _(`app`,`A macos-app lease only closes ${t.bundleId}.`,{bundleId:t.bundleId})}function Se(e,t){if(t.screenshotFullscreen===!0)throw _(`capture`,`A macos-app lease captures only the app window.`);let{out:n,...r}=t;b(r);for(let t of[e[0],n])if(!(t===void 0||typeof t==`string`&&re(t,`screenshot`,`.png`)))throw _(`host-path`,`A macos-app lease does not write files on the host.`)}function b(e){let t=ye.find(t=>e[t]!==void 0&&e[t]!==!1);if(t)throw _(`host-path`,`A macos-app lease does not accept ${t}, which names a host path or launch.`,{field:t})}function Ce(e){let t=be.find(t=>e[t]!==void 0&&e[t]!==``);if(t)throw _(`device`,`A macos-app lease does not accept the ${t} device selector.`,{field:t})}function we(e){if(e.surface!==void 0&&e.surface!==`app`)throw _(`surface`,`A macos-app lease is limited to the app surface, not ${String(e.surface)}.`,{surface:e.surface});if(e.platform!==void 0&&e.platform!==`macos`)throw _(`app`,`A macos-app lease only drives a macOS app.`,{platform:e.platform})}function x(e,t,n){if(n.length!==1||n[0]!==t.bundleId)throw _(`app`,`A macos-app lease only opens ${t.bundleId}.`,{bundleId:t.bundleId});S(e)}function S(e){if(ne(t=>e[t])!==`native`)throw _(`backend`,`A macos-app lease needs the native macOS app backend (AGENT_DEVICE_MACOS_APP_BACKEND=native).`)}function C(e,t){if(!l(t.device)||(t.surface??`app`)!==`app`||t.appBundleId!==e.bundleId)throw _(`app`,`This session is not the leased app ${e.bundleId}.`,{bundleId:e.bundleId})}const w=/bundleID="([^"]+)"/,T=async e=>{if(!o(e))return;let t=await i(`/usr/bin/lsappinfo`,[`info`,`-only`,`bundleid`,String(e)],{allowFailure:!0,timeoutMs:5e3});return w.exec(t.stdout)?.[1]};async function E(e,t=T){if(e.backend!==`macos-app`)return;let n=g(e.deviceKey);if(n.pid!==void 0&&await t(n.pid)!==n.bundleId)throw _(`process`,`The leased app process ${n.bundleId}@${n.pid} is no longer running.`,{bundleId:n.bundleId,pid:n.pid})}const D=[`sessionStateDir`,`runnerLogPath`,`requestLogPath`,`eventLogPath`,`device`,`id`,`kind`,`serial`,`device_udid`,`ios_simulator_device_set`],O=/(?<![\p{L}\p{N}_./])\/(?:Users|home|private|var|tmp|Volumes|Library|Applications|opt|System|usr|etc|Network|cores)(?:\/[\p{L}\p{N}_.@%+~-]+)*\/?/gu;function k(){return{hostName:p.hostname(),homeDirectory:p.homedir()}}function Te(e,t,n=k()){return t.ok?{ok:!0,data:A(e,t.data,n)}:{ok:!1,error:j(t.error,n)}}function A(e,t,n){if(!t)return t;let{fallbackScreenshotPath:r,...i}=t;if(e!==`open`)return i;for(let e of D)delete i[e];let{snapshot:a,initialSnapshotError:o,warnings:s,...c}=i;return{...c,...a===void 0?{}:{snapshot:A(`snapshot`,a,n)},...o===void 0?{}:{initialSnapshotError:j(o,n)},...s===void 0?{}:{warnings:M(s,n)}}}function j(e,t){if(e.code===`DEVICE_IN_USE`)return Ee(e);let{logPath:n,diagnosticsRecord:r,...i}=e;return M(i,t)}function Ee(e){let t=e.details?.reason;return{code:`DEVICE_IN_USE`,message:`The leased app is in use by another session.`,hint:`Retry once the other session ends.`,...typeof t==`string`?{details:{reason:t}}:{},...e.retriable===void 0?{}:{retriable:e.retriable}}}function M(e,t){return typeof e==`string`?De(e,t):Array.isArray(e)?e.map(e=>M(e,t)):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,M(n,t)]))}function De(e,t){let n=e;if(t.homeDirectory.length>1){let e=t.homeDirectory.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);n=n.replaceAll(RegExp(`${e}[\\w.@%+~/-]*`,`g`),`<host-path>`)}for(let e of new Set([t.hostName,t.hostName.split(`.`)[0]]))e.length>=4&&(n=n.replaceAll(e,`<host>`));return n.replace(O,`<host-path>`)}function Oe(e,t){if(!(t===void 0||!e.hasHeldMacOsAppLease(t)))throw _(`diagnostics`,`A macos-app lease does not serve request diagnostics.`)}const ke={label:`Materialized paths`,plural:!0,expiredHint:`Materialized paths are released automatically when their TTL expires; re-run the command that materialized them if the paths are still needed.`},Ae=Symbol(`materializedPaths`),N=()=>ie(Ae,()=>new Map,e=>{for(let t of e.values()){clearTimeout(t.timer);try{me(t.rootPath,{recursive:!0,force:!0})}catch{}}});async function je(e){let t=await h.mkdtemp(m.join(p.tmpdir(),`agent-device-materialized-`));try{let n=await I(e.installablePath,m.join(t,`installable`)),r=e.archivePath?await I(e.archivePath,m.join(t,`archive`)):void 0,i=pe.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{Ne(i)},a);return N().set(i,{rootPath:t,installablePath:n,archivePath:r,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:o,timer:s}),{materializationId:i,installablePath:n,...r?{archivePath:r}:{},expiresAt:new Date(o).toISOString()}}catch(e){throw await h.rm(t,{recursive:!0,force:!0}),e}}async function Me(e,t){await F(e,se(N(),e,t,ke))}async function P(e){let t=Array.from(N().entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await F(e,t)}))}async function Ne(e){let t=N().get(e);if(t)try{await F(e,t)}catch{}}async function F(e,t){clearTimeout(t.timer),N().delete(e),await h.rm(t.rootPath,{recursive:!0,force:!0})}async function I(e,t){let n=await h.stat(e);await h.mkdir(t,{recursive:!0});let r=m.join(t,m.basename(e));return n.isDirectory()?(await h.cp(e,r,{recursive:!0}),r):(await h.copyFile(e,r),r)}function Pe(e){return e.device.platform===`web`}function L(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function R(e){let t=e.sessionStore.refresh(e.ref);if(!t.session.appLog)return;let{forceCleanupSessionAppLog:n}=await import(`./app-log-session-resource.js`).then(e=>e.n);await n({...e,ref:t})}async function z(e){let t=ue(e.sessionStore,e.ref);t.read()&&await oe({binding:t,intent:`disposal`})}async function B(e,t){await t.stopSnapshotHelper(e.device)}async function Fe(e){let{ref:t,sessionStore:n,platformCleanup:r}=e,i=n.resolveCurrent(t)??t.session,a=t.address;await r.closeManagedBrowser({device:i.device,sessionName:a,stateDir:n.resolveDaemonStateDir(),openSessionNames:()=>L(n)})}async function Ie(e){let t=[];for(let{step:n,run:r}of e)try{await r()}catch(e){t.push({step:n,error:e})}return t}function V(t){if(t.failures.length===0)return;let n=t.failures.map(({step:e})=>e),r=t.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return a({level:`error`,phase:t.phase,data:{session:t.sessionName,failedSteps:n,errors:r}}),new e(`COMMAND_FAILED`,`Session cleanup left ${t.failures.length} resource(s) unreleased: ${r.join(`; `)}`,{reason:`session_cleanup_incomplete`,session:t.sessionName,failedSteps:n,hint:`Some session resources failed to release; inspect the session log for per-resource diagnostics. The session was still deleted, so retrying is safe.`})}async function Le(t){let{ref:n,sessionStore:r}=t,i=r.resolveCurrent(n)??n.session,a=n.address;if(!t.platformCleanup)throw new e(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let o=t.platformCleanup,s=[{step:`recording`,run:()=>H({ref:n,sessionStore:r})},...t.appLog===`run`?[{step:`app_log`,run:()=>R({ref:n,sessionStore:r})}]:[],{step:`audio_probe`,run:()=>U({ref:n,sessionStore:r})},{step:`perf_capture`,run:()=>z({ref:n,sessionStore:r})},{step:`platform_snapshot_helper`,run:()=>B(i,o)},{step:`web_browser`,run:()=>Fe({ref:n,sessionStore:r,platformCleanup:o})}];s.push({step:`materialized_paths`,run:()=>P(a)});let c=V({sessionName:a,phase:`session_teardown_cleanup_failed`,failures:await Ie(s)});if(c)throw c}async function H(e){let t=le(e.sessionStore,e.ref);t.read()&&await f({binding:t,intent:`disposal`})}async function U(e){let t=de(e.sessionStore,e.ref);t.read()&&await ae({binding:t,intent:`disposal`})}function Re(e){return ee(e)&&e.kind===`simulator`}function ze(e){return e.platform===`android`&&e.kind===`emulator`}const W=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function G(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function K(e){if(!e)return{};let t={};return e.metroHost!==void 0&&(t.metroHost=e.metroHost),e.metroPort!==void 0&&(t.metroPort=String(e.metroPort)),e.bundleUrl!==void 0&&(t.bundleUrl=e.bundleUrl),e.launchUrl!==void 0&&(t.launchUrl=e.launchUrl),t}function q(e){return fe(K(e))}function J(t,n){if(t!==void 0){if(typeof t!=`string`)throw new e(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return d(t)}}function Y(t){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(t)}. Use an integer between 1 and 65535.`);return t}}function Be(t){if(t!==void 0){if(typeof t!=`number`)throw new e(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Y(t)}}function Ve(t,r,i){if(t===void 0)return i;if(!n(t))throw new e(`INVALID_ARGS`,`Invalid open runtime platform: ${String(t)}. Use "ios", "android", or "harmonyos".`);if(i&&t!==i)throw new e(`INVALID_ARGS`,`open runtime targets ${t}, but session "${r}" is bound to ${i}.`);return t}function X(e){if(n(e))return e}function He(e,t){return{platform:t,metroHost:d(e?.metroHost),metroPort:Y(e?.metroPort),bundleUrl:d(e?.bundleUrl),launchUrl:d(e?.launchUrl)}}function Ue(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function We(e){if(ze(e))return`10.0.2.2`;if(Re(e))return`127.0.0.1`}function Z(e,t){if(!e||d(e.metroHost)||d(e.bundleUrl)||e.metroPort===void 0)return e;let n=We(t);return n?{...e,metroHost:n}:e}function Ge(t){let{runtime:n,sessionName:r,platform:i}=t;if(n===void 0)return;if(!n||typeof n!=`object`||Array.isArray(n))throw new e(`INVALID_ARGS`,`open runtime must be an object.`);let a=n,o=Object.keys(a).find(e=>!W.includes(e));if(o)throw new e(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${W.join(`, `)}.`);return{platform:Ve(a.platform,r,i),metroHost:J(a.metroHost,`metroHost`),metroPort:Be(a.metroPort),bundleUrl:J(a.bundleUrl,`bundleUrl`),launchUrl:J(a.launchUrl,`launchUrl`)}}function Ke(e,t,n){if(n){if(G(n)===0){e.setRuntimeHints(t,void 0);return}return e.setRuntimeHints(t,n),n}}function qe(t,n,r,i){let a=t.getRuntimeHints(n);if(!a)return;let o=r?c(r):void 0,s=X(o)??i;if(a.platform&&r&&!s)throw new e(`INVALID_ARGS`,`Session runtime hints are only supported on iOS, Android, and HarmonyOS sessions, but session "${n}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new e(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${n}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function Q(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?X(c(i)):e.platform,o=n.getRuntimeHints(r),s=Ge({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=qe(n,r,i,a);return{runtime:i?Z(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let l=s&&G(s)>0?s:void 0;return{runtime:i?Z(l,i):l,previousRuntime:o,replacedStoredRuntime:!0}}function Je(e){return Q(e).runtime}function Ye(e){try{return{ok:!0,data:Q(e)}}catch(e){let n=t(e);return r(n.code,n.message,n.details)}}async function Xe(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!$(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:K(t)})}function $(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&q(e.previousRuntime)&&!q(e.runtime)}export{he as A,je as C,g as D,Oe as E,Te as O,P as S,E as T,B as _,Ue as a,L as b,Ke as c,Ye as d,U as f,z as g,R as h,Xe as i,ge as k,$ as l,V as m,G as n,Je as o,H as p,q as r,K as s,He as t,X as u,Le as v,xe as w,Me as x,Pe as y};
@@ -1,4 +1,4 @@
1
- import{R as e,ut as t}from"./sdk-contracts.js";import{v as n}from"./sdk-batch-runner.js";import{B as r,E as i,H as a,J as o,K as s,L as c,U as l,V as ee,W as te,X as u,Y as d,et as f,q as ne,w as re,z as ie}from"./back-mode.js";import{_t as p,ht as m,lt as ae}from"./sdk-io.js";import"./diagnostics.js";import{O as oe}from"./sdk-device.js";import{ar as se,fn as ce,mn as h,or as le,x as g}from"./sdk-batch.js";import{A as ue,C as _,D as de,E as fe,I as pe,M as me,O as he,P as ge,S as _e,T as ve,_ as v,a as ye,b as be,c as xe,j as y,n as Se,o as Ce,r as we,t as Te,u as Ee,v as De,w as Oe,x as ke,y as Ae}from"./parameterized-recorded-fill.js";import{r as je}from"./success-text.js";import"./file.js";import{n as Me,r as b,t as x}from"./session-paths.js";import{a as Ne,i as Pe,r as Fe}from"./session-artifact-paths.js";import{a as Ie}from"./daemon-resolution.js";import{g as Le,h as Re,m as ze}from"./daemon-registration-owner.js";import{_ as Be,m as Ve,p as He}from"./replay-script-selection.js";import{createHash as Ue}from"node:crypto";import S from"node:fs";import C from"node:path";import{StringDecoder as We}from"node:string_decoder";function Ge(e,t={}){let n=[e.command];return e.command===`snapshot`?te(n,e):e.command===`open`?c(n,e):e.command===`runtime`?ee(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?r(n,e):e.command===`screenshot`?a(n,e):ie(n,e),n.join(` `)}function Ke(e){return e.targetEvidences?[se(e.targetEvidences)]:e.targetEvidence?[le(e.targetEvidence)]:[]}function w(e){return e?.scriptPublication??v}function qe(e,t,n){let r=w(e),i=typeof t.saveScript==`string`?x(t.saveScript,n):r.kind===`repair`?void 0:t.healedSiblingPath;e.scriptPublication=Ae(r,{requested:{path:i,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function Je(e){e.scriptPublication=ke(w(e))}function Ye(e){e.scriptPublication=ve(w(e))}function Xe(e,t){e.scriptPublication=fe(w(e),t)}function Ze(e){e.scriptPublication=De(w(e))}function Qe(e,t){let n=w(e);return n.kind===`repair`&&n.closeReceipt===t}function T(e){return w(e).kind===`repair`}function E(e){return Oe(w(e))}function D(e){return de(w(e))}function O(e){return he(w(e))}function $e(e,t,n){if(t.flags?.noRecord||me(t.flags)&&t.flags.recordAs===void 0||ct(e,t))return;t.flags&&xe(e,t.flags,n);let r=tt(t),i=it(e,nt(t,r));r&&rt(e,r);let a={ts:Date.now(),command:i.command,positionals:i.positionals,runtime:i.runtime,flags:ut(i.flags),result:i.result,...A.has(i.command)?i.interactiveObservation===!1?{publicationIntent:`authored`}:i.flags.record===!0?{publicationIntent:`explicit-record`}:{}:{},...i.targetEvidence?{targetEvidence:i.targetEvidence}:{},...i.targetEvidences?{targetEvidences:i.targetEvidences}:{}};return e.actions.push(a),m({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),a}function et(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 tt(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return;let t=pe(e.flags.recordAs),n=ge(t);return{literal:y({ts:0,command:e.command,positionals:e.positionals,flags:e.flags}),placeholder:n}}function nt(e,t){if(!t)return e;let{literal:n,placeholder:r}=t;return{...e,positionals:ot(e.positionals,r),result:Te(e.result,n,r),targetEvidence:Se(e.targetEvidence,n,r)}}function rt(e,t){t.literal.trim()&&(e.recordedFillLiterals??=new Map,!e.recordedFillLiterals.has(t.literal)&&e.recordedFillLiterals.set(t.literal,t.placeholder))}function it(e,t){let n=e.recordedFillLiterals;if(!n||n.size===0)return t;let r=we(t.result,n),i=(t.targetEvidenceMode??`action`)===`landmark`?at(t.targetEvidence,n):k(t.targetEvidence,n),a=t.targetEvidences?{source:k(t.targetEvidences.source,n),destination:k(t.targetEvidences.destination,n)}:t.targetEvidences;return{...t,result:r,targetEvidence:i,targetEvidences:a}}function at(e,t){return e&&(Ce(e,t)?void 0:e)}function k(e,t){return!e||!Ce(e,t)?e:{...ye(e,t),verification:`unverifiable`}}function ot(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 A=new Set([`snapshot`,`get`,`is`,`find`]);function st(e){return e.internal?.replayPlanStep!==!0&&A.has(e.command)}function ct(e,t){return!t.interactiveObservation||D(e)===void 0?!1:t.flags.record!==!0}const lt=re();function ut(e){if(!e)return{};let t={};for(let n of lt){let r=e[n];r!==void 0&&(t[n]=r)}return t}function j(e){return C.join(e,`idle-expiry.json`)}function dt(e){let t;try{t=S.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`&&!(!M(n.expiredAtMs)||!M(n.idleExpiryMs))&&(n.deviceKey===void 0||typeof n.deviceKey==`string`))return n}function M(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0}function ft(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())g({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=e);if(!t.slice(r+1).some(_t))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 pt(t){for(let n of t){if(mt(n)){ht(n);continue}let t=vt(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`&&g(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||!h(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 mt(e){return N(e)!==void 0}function ht(t){let n=N(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||!h(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 N(e){return e.command===`gesture`?f(e.positionals):void 0}function gt(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 _t(e){if(e.command!==`wait`)return!1;let t=ce(e.positionals);return t?.kind!==`selector`||!h(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function vt(e){if(e.command===`get`)return e.positionals[1];if(d(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&P(t)&&P(n)?void 0:t}}function P(e){return e.trim().length>0&&Number.isFinite(Number(e))}function yt(e){let t=e.scriptPublication??v;return t.kind===`repair`?t.status===`committed`||!_(t):!1}function bt(e){return!_e(e.scriptPublication??v)||yt(e)}var xt=class{sessionsDir;hostCwd;constructor(e,t){this.sessionsDir=e,this.hostCwd=t}write(e,t){let n=T(e),r=t?.publication===`active`,i;try{if(bt(e))return{written:!1};let a=St(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=C.dirname(i);return S.existsSync(o)||S.mkdirSync(o,{recursive:!0}),Tt({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=be(e.scriptPublication??v)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return Ct({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=ue(e.scriptPublication??v);if(t)return x(t,this.hostCwd);let n=b(e.name),r=new Date(e.createdAt).toISOString().replaceAll(/[:.]/g,`-`);return C.join(this.sessionsDir,`${n}-${r}.ad`)}};function St(e,t){let n=Et(e,{strictPortableRefs:t.activePublication});return t.activePublication&&ft(n),{script:It(e,n,t.appendCompleteSentinel),actionCount:n.length}}function Ct(t){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=t;if(m({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:wt(r,i)};if(o)return{written:!1,error:gt(r,i)};if(r instanceof e)throw r;return{written:!1}}function wt(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 Tt(t){let{scriptPath:n,script:r,force:i}=t;try{ae({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 Et(e,t={}){let n=D(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`&&n.publicationIntent!==`authored`&&!(r&&n.publicationIntent===`explicit-record`))continue;let i=kt(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&Dt(n);let o=Ft(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&pt(a),a}function Dt(t){let n=t.command===`gesture`?f(t.positionals??[]):void 0;if(n){Ot(n);return}if(!F(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 Ot(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 kt(e){let t=At(e);if(!(!t||!F(e.command)))return o(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?Mt(e,t):e.command===`fill`?jt(e,t):Nt(e,t)}function At(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 F(e){return d(e)||e===`fill`||e===`get`}function jt(e,t){let n=y(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function Mt(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):Pt(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Nt(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function Pt(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function Ft(e,t){if(!F(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 It(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${oe(e.device)} device=${ne(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...Ke(e)),r.push(Lt(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
2
- `)}\n`}function Lt(e){return Rt([e.command],e)||Ge(e)}function Rt(e,t){if(o(t.command))return zt(e,t);if(t.command===`fill`)return Bt(e,t);if(t.command===`get`)return Vt(e,t)}function zt(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(s(u(n))),I(e,t),l(e,t),e.join(` `);if(t.positionals.length===1)return e.push(s(n)),l(e,t),e.join(` `)}}function Bt(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(s(u(n))),I(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(s(r)),l(e,t),e.join(` `)}function Vt(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(s(n)),e.push(s(u(r))),r.startsWith(`@`)&&I(e,t),e.join(` `)}function I(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(s(n))}const L=65536;function R(e){return Ue(`sha256`).update(e,`utf8`).digest(`hex`).slice(0,32)}function z(e,t){let n=Ut(e);if(n===void 0)return!1;try{let e=V(t),r=Buffer.allocUnsafe(L),i=0;do if(i=S.readSync(n,r,0,r.length,null),!e.push(r.subarray(0,i)))return!0;while(i>0);return e.end(),!0}finally{S.closeSync(n)}}async function Ht(e){let t=await Wt(e);if(t===void 0)return{lineCount:0,firstLineDigest:void 0};let n={lineCount:0,firstLineDigest:void 0};try{let e=V(e=>{n.lineCount===0&&(n.firstLineDigest=R(e)),n.lineCount+=1}),r=Buffer.allocUnsafe(L);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 B(e){let t;return z(e,e=>(t=R(e),!1)),t}function V(e){let t=new We(`utf8`),n=``,r=!1;return{push(i){if(r)return!1;let a=`${n}${t.write(i)}`,o=0;for(let t=a.indexOf(`
1
+ import{R as e,dt as t}from"./sdk-contracts.js";import{v as n}from"./sdk-batch-runner.js";import{B as r,E as i,H as a,J as o,K as s,L as c,U as l,V as ee,W as te,X as u,Y as d,et as f,q as ne,w as re,z as ie}from"./back-mode.js";import{_t as p,dt as ae,yt as m}from"./sdk-io.js";import"./diagnostics.js";import{I as oe,f as se}from"./sdk-device.js";import{Sn as ce,gr as le,hr as ue,wn as h,x as g}from"./sdk-batch.js";import{A as de,C as _,D as fe,E as pe,I as me,M as he,O as ge,P as _e,S as ve,T as ye,_ as v,a as be,b as xe,c as Se,j as y,n as Ce,o as we,r as Te,t as Ee,u as De,v as Oe,w as ke,x as Ae,y as je}from"./parameterized-recorded-fill.js";import{r as Me}from"./success-text.js";import"./file.js";import{n as Ne,r as b,t as x}from"./session-paths.js";import{a as Pe,i as Fe,r as Ie}from"./session-artifact-paths.js";import{a as Le}from"./daemon-resolution.js";import{g as Re,h as ze,m as Be}from"./daemon-registration-owner.js";import{_ as Ve,m as He,p as Ue}from"./replay-script-selection.js";import{createHash as We}from"node:crypto";import S from"node:fs";import C from"node:path";import{StringDecoder as Ge}from"node:string_decoder";function Ke(e,t={}){let n=[e.command];return e.command===`snapshot`?te(n,e):e.command===`open`?c(n,e):e.command===`runtime`?ee(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?r(n,e):e.command===`screenshot`?a(n,e):ie(n,e),n.join(` `)}function qe(e){return e.targetEvidences?[ue(e.targetEvidences)]:e.targetEvidence?[le(e.targetEvidence)]:[]}function w(e){return e?.scriptPublication??v}function Je(e,t,n){let r=w(e),i=typeof t.saveScript==`string`?x(t.saveScript,n):r.kind===`repair`?void 0:t.healedSiblingPath;e.scriptPublication=je(r,{requested:{path:i,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function Ye(e){e.scriptPublication=Ae(w(e))}function Xe(e){e.scriptPublication=ye(w(e))}function Ze(e,t){e.scriptPublication=pe(w(e),t)}function Qe(e){e.scriptPublication=Oe(w(e))}function $e(e,t){let n=w(e);return n.kind===`repair`&&n.closeReceipt===t}function T(e){return w(e).kind===`repair`}function E(e){return ke(w(e))}function D(e){return fe(w(e))}function O(e){return ge(w(e))}function et(e,t,n){if(t.flags?.noRecord||he(t.flags)&&t.flags.recordAs===void 0||lt(e,t))return;t.flags&&Se(e,t.flags,n);let r=nt(t),i=at(e,rt(t,r));r&&it(e,r);let a={ts:Date.now(),command:i.command,positionals:i.positionals,runtime:i.runtime,flags:dt(i.flags),result:i.result,...A.has(i.command)?i.interactiveObservation===!1?{publicationIntent:`authored`}:i.flags.record===!0?{publicationIntent:`explicit-record`}:{}:{},...i.targetEvidence?{targetEvidence:i.targetEvidence}:{},...i.targetEvidences?{targetEvidences:i.targetEvidences}:{}};return e.actions.push(a),p({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),a}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 nt(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return;let t=me(e.flags.recordAs),n=_e(t);return{literal:y({ts:0,command:e.command,positionals:e.positionals,flags:e.flags}),placeholder:n}}function rt(e,t){if(!t)return e;let{literal:n,placeholder:r}=t;return{...e,positionals:st(e.positionals,r),result:Ee(e.result,n,r),targetEvidence:Ce(e.targetEvidence,n,r)}}function it(e,t){t.literal.trim()&&(e.recordedFillLiterals??=new Map,!e.recordedFillLiterals.has(t.literal)&&e.recordedFillLiterals.set(t.literal,t.placeholder))}function at(e,t){let n=e.recordedFillLiterals;if(!n||n.size===0)return t;let r=Te(t.result,n),i=(t.targetEvidenceMode??`action`)===`landmark`?ot(t.targetEvidence,n):k(t.targetEvidence,n),a=t.targetEvidences?{source:k(t.targetEvidences.source,n),destination:k(t.targetEvidences.destination,n)}:t.targetEvidences;return{...t,result:r,targetEvidence:i,targetEvidences:a}}function ot(e,t){return e&&(we(e,t)?void 0:e)}function k(e,t){return!e||!we(e,t)?e:{...be(e,t),verification:`unverifiable`}}function st(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 A=new Set([`snapshot`,`get`,`is`,`find`]);function ct(e){return e.internal?.replayPlanStep!==!0&&A.has(e.command)}function lt(e,t){return!t.interactiveObservation||D(e)===void 0?!1:t.flags.record!==!0}const ut=re();function dt(e){if(!e)return{};let t={};for(let n of ut){let r=e[n];r!==void 0&&(t[n]=r)}return t}function j(e){return C.join(e,`idle-expiry.json`)}function ft(e){let t;try{t=S.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`&&!(!M(n.expiredAtMs)||!M(n.idleExpiryMs))&&(n.deviceKey===void 0||typeof n.deviceKey==`string`))return n}function M(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0}function pt(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())g({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=e);if(!t.slice(r+1).some(vt))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 mt(t){for(let n of t){if(ht(n)){gt(n);continue}let t=yt(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`&&g(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||!h(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 ht(e){return N(e)!==void 0}function gt(t){let n=N(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||!h(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 N(e){return e.command===`gesture`?f(e.positionals):void 0}function _t(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 vt(e){if(e.command!==`wait`)return!1;let t=ce(e.positionals);return t?.kind!==`selector`||!h(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function yt(e){if(e.command===`get`)return e.positionals[1];if(d(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&P(t)&&P(n)?void 0:t}}function P(e){return e.trim().length>0&&Number.isFinite(Number(e))}function bt(e){let t=e.scriptPublication??v;return t.kind===`repair`?t.status===`committed`||!_(t):!1}function xt(e){return!ve(e.scriptPublication??v)||bt(e)}var St=class{sessionsDir;hostCwd;constructor(e,t){this.sessionsDir=e,this.hostCwd=t}write(e,t){let n=T(e),r=t?.publication===`active`,i;try{if(xt(e))return{written:!1};let a=Ct(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=C.dirname(i);return S.existsSync(o)||S.mkdirSync(o,{recursive:!0}),Et({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=xe(e.scriptPublication??v)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return wt({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=de(e.scriptPublication??v);if(t)return x(t,this.hostCwd);let n=b(e.name),r=new Date(e.createdAt).toISOString().replaceAll(/[:.]/g,`-`);return C.join(this.sessionsDir,`${n}-${r}.ad`)}};function Ct(e,t){let n=Dt(e,{strictPortableRefs:t.activePublication});return t.activePublication&&pt(n),{script:Lt(e,n,t.appendCompleteSentinel),actionCount:n.length}}function wt(t){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=t;if(p({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:Tt(r,i)};if(o)return{written:!1,error:_t(r,i)};if(r instanceof e)throw r;return{written:!1}}function Tt(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 Et(t){let{scriptPath:n,script:r,force:i}=t;try{ae({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 Dt(e,t={}){let n=D(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`&&n.publicationIntent!==`authored`&&!(r&&n.publicationIntent===`explicit-record`))continue;let i=At(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&Ot(n);let o=It(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&mt(a),a}function Ot(t){let n=t.command===`gesture`?f(t.positionals??[]):void 0;if(n){kt(n);return}if(!F(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 kt(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 At(e){let t=jt(e);if(!(!t||!F(e.command)))return o(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?Nt(e,t):e.command===`fill`?Mt(e,t):Pt(e,t)}function jt(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 F(e){return d(e)||e===`fill`||e===`get`}function Mt(e,t){let n=y(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function Nt(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):Ft(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Pt(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function Ft(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function It(e,t){if(!F(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 Lt(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${oe(e.device)} device=${ne(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...qe(e)),r.push(Rt(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
2
+ `)}\n`}function Rt(e){return zt([e.command],e)||Ke(e)}function zt(e,t){if(o(t.command))return Bt(e,t);if(t.command===`fill`)return Vt(e,t);if(t.command===`get`)return Ht(e,t)}function Bt(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(s(u(n))),I(e,t),l(e,t),e.join(` `);if(t.positionals.length===1)return e.push(s(n)),l(e,t),e.join(` `)}}function Vt(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(s(u(n))),I(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(s(r)),l(e,t),e.join(` `)}function Ht(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(s(n)),e.push(s(u(r))),r.startsWith(`@`)&&I(e,t),e.join(` `)}function I(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(s(n))}const L=65536;function R(e){return We(`sha256`).update(e,`utf8`).digest(`hex`).slice(0,32)}function z(e,t){let n=Wt(e);if(n===void 0)return!1;try{let e=V(t),r=Buffer.allocUnsafe(L),i=0;do if(i=S.readSync(n,r,0,r.length,null),!e.push(r.subarray(0,i)))return!0;while(i>0);return e.end(),!0}finally{S.closeSync(n)}}async function Ut(e){let t=await Gt(e);if(t===void 0)return{lineCount:0,firstLineDigest:void 0};let n={lineCount:0,firstLineDigest:void 0};try{let e=V(e=>{n.lineCount===0&&(n.firstLineDigest=R(e)),n.lineCount+=1}),r=Buffer.allocUnsafe(L);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 B(e){let t;return z(e,e=>(t=R(e),!1)),t}function V(e){let t=new Ge(`utf8`),n=``,r=!1;return{push(i){if(r)return!1;let a=`${n}${t.write(i)}`,o=0;for(let t=a.indexOf(`
3
3
  `);t!==-1;t=a.indexOf(`
4
- `,o)){if(H(a.slice(o,t),e)===!1)return r=!0,!1;o=t+1}return n=a.slice(o),!0},end(){r||H(`${n}${t.end()}`,e)}}}function H(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0)return t(n)}function Ut(e){try{return S.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Wt(e){try{return await S.promises.open(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}const U=5242880;function Gt(e){let t=e.AGENT_DEVICE_EVENT_LOG_MAX_BYTES?.trim();if(t===void 0||!/^\d+$/.test(t))return U;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:U}function W(e){return`${e}.1`}function G(e){return`${e}.window.json`}function Kt(e){let t;for(let n=0;n<3;n+=1){let n=q(e);try{let t=qt(e);if(q(e)===n)return t}catch(r){if(t=r,q(e)===n)throw r}}throw t??K(e,`the window did not settle while reading`)}function qt(e){let t=W(e),n=Y(e);if(n===`unverifiable`)throw K(e,`window file is invalid`);if(n===void 0)return Jt(e,t);let r=n.at(-1);if(!r)throw K(e,`window file records no generation`);let i=X(e),a=Yt(e,r),o=[],s=Xt({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 Jt(e,t){if(B(t)!==void 0)throw K(e,`a rotated event log exists with no window record`);return{files:X(e)?[{path:e,firstLineIndex:0}]:[],earliestCursor:0}}function Yt(e,t){let n=B(e);return n!==void 0&&n===t.firstLineDigest?t.firstLineIndex:t.firstLineIndex+t.lineCount}function Xt(e){let{eventLogPath:t,rotatedPath:n,sidecar:r,activeStart:i,activeExists:a}=e,o=B(n);if(o===void 0)return;let s=r.find(e=>e.firstLineDigest===o);if(!s)throw K(t,`the rotated event log matches no window record`);let c=$t(n);if(c!==s.lineCount)throw K(t,`the rotated event log holds ${c} lines, the window recorded ${s.lineCount}`);if(a&&s.firstLineIndex+s.lineCount!==i)throw K(t,`retained event log generations are not contiguous`);return s.firstLineIndex}async function Zt(e,t){let n=Z(e);if(!n||n.size<t)return!1;let r=Y(e);if(r===`unverifiable`)return await S.promises.rename(e,W(e)),!0;let i=await Ht(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 tn(e,(a===n?t:[...t,a]).slice(-2))}return await S.promises.rename(e,W(e)),!0}function Qt(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 K(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}, ${W(t)}, and ${G(t)} to restart the timeline, or read the files directly.`})}function $t(e){let t=0;return z(e,()=>{t+=1}),t}function q(e){return[J(G(e)),J(e),J(W(e))].join(`|`)}function J(e){try{let t=S.lstatSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return`absent`}}function Y(e){let t;try{t=S.readFileSync(G(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(en);return i.every(e=>e!==void 0)?i:`unverifiable`}catch{return`unverifiable`}}function en(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 tn(e,t){let n=G(e),r=`${n}.${process.pid}.tmp`;await S.promises.writeFile(r,JSON.stringify({version:2,generations:t}),`utf8`),await S.promises.rename(r,n)}function X(e){return Z(e)!==void 0}function Z(t){try{let n=S.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 Q=new Map,$=new Set;function nn(e){return C.join(e,`events.ndjson`)}function rn(e){return e.command!==i.events}function an(e,n,r,i){let a=t({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});sn(e,`${JSON.stringify(a)}\n`,i)}async function on(e){await(e?Q.get(e):Promise.all(Q.values()))}function sn(e,t,n){let r=(Q.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await cn(e),await Zt(e,Gt(n)),await S.promises.appendFile(e,t,`utf8`)}).catch(t=>{m({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{Q.get(e)===r&&Q.delete(e)});Q.set(e,r)}async function cn(e){let t=C.dirname(e);if(!$.has(t))try{await S.promises.mkdir(t,{recursive:!0}),$.add(t)}catch(t){throw m({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function ln(e,t,n,r){an(e,t,{kind:`action.recorded`,requestId:p().requestId,command:n.command,summary:Ve(n),details:He(n)},r)}function un(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??p().requestId,command:t.command,summary:`Started ${t.command}`}}function dn(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=Be(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??p().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??p().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function fn(e,t={}){let n=mn(t.cursor),r=hn(t.limit),i=Kt(e);Qt(n,i.earliestCursor);let a=pn(i.files,n,r),o=a.lines.flatMap(e=>{let t=gn(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:o,...a.nextCursor===void 0?{}:{nextCursor:String(a.nextCursor)}}}function pn(e,t,n){let r=[],i;for(let a of e){let e=a.firstLineIndex;if(z(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 mn(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 hn(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 gn(e){try{let t=_n(JSON.parse(e));return t?vn(t):void 0}catch{return}}function _n(e){if(n(e)&&e.version===1&&typeof e.ts==`string`&&typeof e.session==`string`&&yn(e.kind))return e}function vn(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}:{},...bn(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function yn(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function bn(e){return e===`ok`||e===`error`}const xn=36e5;var Sn=class{sessions=new Map;acceptingSessions=!0;runtimeHints=new Map;sessionsDir;scriptWriter;host;constructor(e,t){this.sessionsDir=e,this.host=t,this.scriptWriter=new xt(e,t.cwd)}get(e){return this.sessions.get(e)?.current}closeAdmission(){this.acceptingSessions=!1}assertAdmissionOpen(t){if(!this.acceptingSessions)throw new e(`COMMAND_FAILED`,`Daemon is shutting down`,{reason:Ie,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=$e(this.requireCurrent(e),t,this.host.cwd);n&&ln(this.resolveEventLogPath(e.address),e.address,n,this.host.env)}recordEvent(e,t){an(this.resolveEventLogPath(e),e,t,this.host.env)}readEvents(e,t={}){return fn(this.resolveEventLogPath(e),t)}async flushEvents(e){await on(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.requireCurrent(e),r=this.scriptWriter.write(n,t);return r.written&&m({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:Ee(t,void 0)});E(t)&&(!n.written&&n.error?this.writeRepairTombstone(e,xn,{code:String(n.error.code),message:n.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){let t=this.requireCurrent(e),n=t.scriptPublication??v;_(n)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:t.name,...je(`Closed: ${t.name}`)}})}writeRepairTombstone(e,t=xn,n){let r=this.resolveCurrent(e);if(r)try{let i=this.resolveSessionDir(e.address);S.mkdirSync(i,{recursive:!0});let a={owner:e.address,reapedAt:Date.now(),expiresAt:Date.now()+t,...O(r)?{sourcePath:O(r)}:{},...n?{commitFailure:n}:{}};S.writeFileSync(this.repairTombstonePath(e.address),`${JSON.stringify(a)}\n`)}catch(t){m({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.address,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return Re(this.repairTombstonePath(e),e)}clearRepairTombstone(e){ze(this.repairTombstonePath(e),e)}noteSessionActivity(e,t=Date.now()){let n=this.get(e);n&&(n.lastActivityAtMs=t)}writeIdleExpiryTombstone(e,t){try{S.mkdirSync(this.resolveSessionDir(e),{recursive:!0}),S.writeFileSync(j(this.resolveSessionDir(e)),`${JSON.stringify(t)}\n`)}catch(t){m({level:`warn`,phase:`idle_expiry_tombstone_write_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}readIdleExpiryTombstone(e){if(!Me(e))return;let t=dt(j(this.resolveSessionDir(e)));return t?.owner===e?t:void 0}clearIdleExpiryTombstone(e){try{S.rmSync(j(this.resolveSessionDir(e)),{force:!0})}catch(t){m({level:`warn`,phase:`idle_expiry_tombstone_clear_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}repairTombstonePath(e){return Le(this.resolveSessionDir(e))}defaultTracePath(e){let t=b(e.name),n=new Date().toISOString().replaceAll(/[:.]/g,`-`);return C.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(e){return Ne(this.sessionsDir,e)}resolveDaemonStateDir(){return C.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return S.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return Fe(this.sessionsDir,e)}resolveAppLogPidPath(e){return Pe(this.sessionsDir,e)}resolveEventLogPath(e){return nn(this.resolveSessionDir(e))}};export{st as a,qe as c,E as d,Ye as f,Je as h,rn as i,Qe as l,D as m,dn as n,et as o,Xe as p,un as r,Ze as s,Sn as t,T as u};
4
+ `,o)){if(H(a.slice(o,t),e)===!1)return r=!0,!1;o=t+1}return n=a.slice(o),!0},end(){r||H(`${n}${t.end()}`,e)}}}function H(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0)return t(n)}function Wt(e){try{return S.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Gt(e){try{return await S.promises.open(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}const U=5242880;function Kt(e){let t=e.AGENT_DEVICE_EVENT_LOG_MAX_BYTES?.trim();if(t===void 0||!/^\d+$/.test(t))return U;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:U}function W(e){return`${e}.1`}function G(e){return`${e}.window.json`}function qt(e){let t;for(let n=0;n<3;n+=1){let n=q(e);try{let t=Jt(e);if(q(e)===n)return t}catch(r){if(t=r,q(e)===n)throw r}}throw t??K(e,`the window did not settle while reading`)}function Jt(e){let t=W(e),n=Y(e);if(n===`unverifiable`)throw K(e,`window file is invalid`);if(n===void 0)return Yt(e,t);let r=n.at(-1);if(!r)throw K(e,`window file records no generation`);let i=X(e),a=Xt(e,r),o=[],s=Zt({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 Yt(e,t){if(B(t)!==void 0)throw K(e,`a rotated event log exists with no window record`);return{files:X(e)?[{path:e,firstLineIndex:0}]:[],earliestCursor:0}}function Xt(e,t){let n=B(e);return n!==void 0&&n===t.firstLineDigest?t.firstLineIndex:t.firstLineIndex+t.lineCount}function Zt(e){let{eventLogPath:t,rotatedPath:n,sidecar:r,activeStart:i,activeExists:a}=e,o=B(n);if(o===void 0)return;let s=r.find(e=>e.firstLineDigest===o);if(!s)throw K(t,`the rotated event log matches no window record`);let c=en(n);if(c!==s.lineCount)throw K(t,`the rotated event log holds ${c} lines, the window recorded ${s.lineCount}`);if(a&&s.firstLineIndex+s.lineCount!==i)throw K(t,`retained event log generations are not contiguous`);return s.firstLineIndex}async function Qt(e,t){let n=Z(e);if(!n||n.size<t)return!1;let r=Y(e);if(r===`unverifiable`)return await S.promises.rename(e,W(e)),!0;let i=await Ut(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 nn(e,(a===n?t:[...t,a]).slice(-2))}return await S.promises.rename(e,W(e)),!0}function $t(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 K(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}, ${W(t)}, and ${G(t)} to restart the timeline, or read the files directly.`})}function en(e){let t=0;return z(e,()=>{t+=1}),t}function q(e){return[J(G(e)),J(e),J(W(e))].join(`|`)}function J(e){try{let t=S.lstatSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return`absent`}}function Y(e){let t;try{t=S.readFileSync(G(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(tn);return i.every(e=>e!==void 0)?i:`unverifiable`}catch{return`unverifiable`}}function tn(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 nn(e,t){let n=G(e),r=`${n}.${process.pid}.tmp`;await S.promises.writeFile(r,JSON.stringify({version:2,generations:t}),`utf8`),await S.promises.rename(r,n)}function X(e){return Z(e)!==void 0}function Z(t){try{let n=S.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 Q=new Map,$=new Set;function rn(e){return C.join(e,`events.ndjson`)}function an(e){return e.command!==i.events}function on(e,n,r,i){let a=t({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});cn(e,`${JSON.stringify(a)}\n`,i)}async function sn(e){await(e?Q.get(e):Promise.all(Q.values()))}function cn(e,t,n){let r=(Q.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await ln(e),await Qt(e,Kt(n)),await S.promises.appendFile(e,t,`utf8`)}).catch(t=>{p({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{Q.get(e)===r&&Q.delete(e)});Q.set(e,r)}async function ln(e){let t=C.dirname(e);if(!$.has(t))try{await S.promises.mkdir(t,{recursive:!0}),$.add(t)}catch(t){throw p({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function un(e,t,n,r){on(e,t,{kind:`action.recorded`,requestId:m().requestId,command:n.command,summary:He(n),details:Ue(n)},r)}function dn(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??m().requestId,command:t.command,summary:`Started ${t.command}`}}function fn(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=Ve(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??m().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??m().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function pn(e,t={}){let n=hn(t.cursor),r=gn(t.limit),i=qt(e);$t(n,i.earliestCursor);let a=mn(i.files,n,r),o=a.lines.flatMap(e=>{let t=_n(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:o,...a.nextCursor===void 0?{}:{nextCursor:String(a.nextCursor)}}}function mn(e,t,n){let r=[],i;for(let a of e){let e=a.firstLineIndex;if(z(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 hn(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 gn(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 _n(e){try{let t=vn(JSON.parse(e));return t?yn(t):void 0}catch{return}}function vn(e){if(n(e)&&e.version===1&&typeof e.ts==`string`&&typeof e.session==`string`&&bn(e.kind))return e}function yn(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}:{},...xn(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function bn(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function xn(e){return e===`ok`||e===`error`}const Sn=36e5;var Cn=class{sessions=new Map;acceptingSessions=!0;runtimeHints=new Map;sessionsDir;scriptWriter;host;constructor(e,t){this.sessionsDir=e,this.host=t,this.scriptWriter=new St(e,t.cwd)}get(e){return this.sessions.get(e)?.current}closeAdmission(){this.acceptingSessions=!1}assertAdmissionOpen(t){if(!this.acceptingSessions)throw new e(`COMMAND_FAILED`,`Daemon is shutting down`,{reason:Le,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(se(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=et(this.requireCurrent(e),t,this.host.cwd);n&&un(this.resolveEventLogPath(e.address),e.address,n,this.host.env)}recordEvent(e,t){on(this.resolveEventLogPath(e),e,t,this.host.env)}readEvents(e,t={}){return pn(this.resolveEventLogPath(e),t)}async flushEvents(e){await sn(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.requireCurrent(e),r=this.scriptWriter.write(n,t);return r.written&&p({level:`info`,phase:`session_script_written`,data:{session:n.name,path:r.path}}),r}finalizeRepairTeardown(e){let t=this.resolveCurrent(e);if(!t)return;this.recordRepairFinalizeCloseIfCommitting(e);let n=this.writeSessionLog(e,{force:De(t,void 0)});E(t)&&(!n.written&&n.error?this.writeRepairTombstone(e,Sn,{code:String(n.error.code),message:n.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){let t=this.requireCurrent(e),n=t.scriptPublication??v;_(n)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:t.name,...Me(`Closed: ${t.name}`)}})}writeRepairTombstone(e,t=Sn,n){let r=this.resolveCurrent(e);if(r)try{let i=this.resolveSessionDir(e.address);S.mkdirSync(i,{recursive:!0});let a={owner:e.address,reapedAt:Date.now(),expiresAt:Date.now()+t,...O(r)?{sourcePath:O(r)}:{},...n?{commitFailure:n}:{}};S.writeFileSync(this.repairTombstonePath(e.address),`${JSON.stringify(a)}\n`)}catch(t){p({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.address,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return ze(this.repairTombstonePath(e),e)}clearRepairTombstone(e){Be(this.repairTombstonePath(e),e)}noteSessionActivity(e,t=Date.now()){let n=this.get(e);n&&(n.lastActivityAtMs=t)}writeIdleExpiryTombstone(e,t){try{S.mkdirSync(this.resolveSessionDir(e),{recursive:!0}),S.writeFileSync(j(this.resolveSessionDir(e)),`${JSON.stringify(t)}\n`)}catch(t){p({level:`warn`,phase:`idle_expiry_tombstone_write_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}readIdleExpiryTombstone(e){if(!Ne(e))return;let t=ft(j(this.resolveSessionDir(e)));return t?.owner===e?t:void 0}clearIdleExpiryTombstone(e){try{S.rmSync(j(this.resolveSessionDir(e)),{force:!0})}catch(t){p({level:`warn`,phase:`idle_expiry_tombstone_clear_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}repairTombstonePath(e){return Re(this.resolveSessionDir(e))}defaultTracePath(e){let t=b(e.name),n=new Date().toISOString().replaceAll(/[:.]/g,`-`);return C.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(e){return Pe(this.sessionsDir,e)}resolveDaemonStateDir(){return C.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return S.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return Ie(this.sessionsDir,e)}resolveAppLogPidPath(e){return Fe(this.sessionsDir,e)}resolveEventLogPath(e){return rn(this.resolveSessionDir(e))}};export{ct as a,Je as c,E as d,Xe as f,Ye as h,an as i,$e as l,D as m,fn as n,tt as o,Ze as p,dn as r,Qe as s,Cn as t,T as u};
@@ -1 +1 @@
1
- import{ht as e}from"./tv-remote.js";const t=[`app`,`frontmost-app`,`desktop`,`menubar`],n=e(t,{normalize:e=>e.trim().toLowerCase(),message:e=>`Invalid surface: ${e}. Use ${t.join(`|`)}.`});function r(e){return n.parse(e)}const i=[`xctest`,`native`],a=`AGENT_DEVICE_MACOS_APP_BACKEND`,o=e(i,{normalize:e=>e.trim().toLowerCase(),message:e=>`Invalid ${a}: ${e}. Use ${i.join(`|`)}.`});function s(e){let t=e(a);return t===void 0||t.trim()===``?`xctest`:o.parse(t)}const c={"frontmost-app":`macos-helper`,desktop:`macos-helper`,menubar:`macos-helper`};function l(e,t){let n=e??`app`;return n===`app`?t===`native`?`macos-helper`:`xctest`:c[n]}function u(e,t){let n=e??`app`;return l(n,t)===`macos-helper`?n:void 0}export{s as a,r as i,u as n,l as r,t};
1
+ import{r as e}from"./rolldown-runtime.js";import{_t as t}from"./tv-remote.js";const n=[`app`,`frontmost-app`,`desktop`,`menubar`],r=t(n,{normalize:e=>e.trim().toLowerCase(),message:e=>`Invalid surface: ${e}. Use ${n.join(`|`)}.`});function i(e){return r.parse(e)}const a=[`xctest`,`native`],o=`AGENT_DEVICE_MACOS_APP_BACKEND`,s=t(a,{normalize:e=>e.trim().toLowerCase(),message:e=>`Invalid ${o}: ${e}. Use ${a.join(`|`)}.`});function c(e){let t=e(o);return t===void 0||t.trim()===``?`xctest`:s.parse(t)}const l={"frontmost-app":`macos-helper`,desktop:`macos-helper`,menubar:`macos-helper`};function u(e,t){let n=e??`app`;return n===`app`?t===`native`?`macos-helper`:`xctest`:l[n]}function d(e,t){let n=e??`app`;return u(n,t)===`macos-helper`?n:void 0}var f=e({readMacOsAppBackend:()=>c});export{i as a,u as i,n,c as o,d as r,f as t};