agent-device 0.21.7 → 0.21.9

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 (204) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.7.apk → agent-device-android-ime-helper-0.21.9.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.9.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.7.manifest.json → agent-device-android-ime-helper-0.21.9.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.7.apk → agent-device-android-snapshot-helper-0.21.9.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.9.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.7.manifest.json → agent-device-android-snapshot-helper-0.21.9.manifest.json} +6 -6
  7. package/apple/macos-helper/Package.swift +16 -1
  8. package/apple/macos-helper/Sources/AgentDeviceMacOSDeviceHub/DeviceHubPose.swift +47 -0
  9. package/apple/macos-helper/Sources/AgentDeviceMacOSDeviceHub/DeviceHubWindowInventory.swift +65 -0
  10. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/DeviceHubPose.swift +225 -0
  11. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/DeviceHubSidebar.swift +57 -0
  12. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/DeviceHubWindowDiscovery.swift +108 -0
  13. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift +66 -13
  14. package/apple/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickDelivery.swift +116 -0
  15. package/apple/macos-helper/Sources/AgentDeviceMacOSInput/MouseClickSchedule.swift +61 -0
  16. package/apple/macos-helper/Tests/AgentDeviceMacOSDeviceHubTests/DeviceHubPoseTests.swift +30 -0
  17. package/apple/macos-helper/Tests/AgentDeviceMacOSDeviceHubTests/DeviceHubWindowInventoryTests.swift +65 -0
  18. package/apple/macos-helper/Tests/AgentDeviceMacOSInputTests/MouseClickScheduleTests.swift +58 -0
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h +1 -0
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAppScreenCapture.swift +175 -0
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +10 -2
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +42 -15
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +8 -0
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +45 -22
  25. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +39 -734
  26. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +20 -4
  27. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +63 -1
  28. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +13 -0
  29. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +25 -10
  30. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +5 -562
  31. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotAcquisition.swift +566 -0
  32. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +5 -1
  33. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +594 -0
  34. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.h +35 -1
  35. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.m +160 -0
  36. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/RecordingExportSupport.swift +3 -0
  37. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-frames.swift +203 -0
  38. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotCoordinateSpace.swift +5 -0
  39. package/dist/src/absence-observation-errors.js +1 -1
  40. package/dist/src/adapter.js +1 -1
  41. package/dist/src/agent-browser-lifecycle.js +1 -1
  42. package/dist/src/agent-browser-process-record.js +1 -1
  43. package/dist/src/agent-device-client.js +2 -2
  44. package/dist/src/alert-runtime.js +1 -1
  45. package/dist/src/android-adb.js +1 -1
  46. package/dist/src/android-input-ownership.js +1 -1
  47. package/dist/src/android.js +1 -1
  48. package/dist/src/app-launch.js +1 -1
  49. package/dist/src/app-log-runtime2.js +3 -3
  50. package/dist/src/app-resolution.js +2 -2
  51. package/dist/src/apple-runner-platform.js +1 -1
  52. package/dist/src/application-lifecycle-interaction.js +1 -1
  53. package/dist/src/artifact-paths.js +1 -0
  54. package/dist/src/back-mode.js +1 -1
  55. package/dist/src/cli-config.js +1 -1
  56. package/dist/src/cli-help.js +15 -11
  57. package/dist/src/cli.js +4 -4
  58. package/dist/src/client-types.d.ts +51 -1
  59. package/dist/src/command-tools.js +3 -3
  60. package/dist/src/config.js +1 -1
  61. package/dist/src/connection-runtime.js +1 -1
  62. package/dist/src/device-claim-inspection.js +1 -1
  63. package/dist/src/device-claim-rule.js +2 -2
  64. package/dist/src/device-input-state.d.ts +1 -1
  65. package/dist/src/device-rotation.js +1 -1
  66. package/dist/src/device-selection-resolver.js +1 -1
  67. package/dist/src/device-session.js +1 -1
  68. package/dist/src/device.js +1 -1
  69. package/dist/src/device2.js +1 -1
  70. package/dist/src/devicectl.js +1 -1
  71. package/dist/src/dispatch-resolve.js +1 -1
  72. package/dist/src/display-inventory.js +1 -1
  73. package/dist/src/doctor-facade.js +1 -1
  74. package/dist/src/durable-resource.js +1 -1
  75. package/dist/src/exec.js +1 -1
  76. package/dist/src/find.js +1 -1
  77. package/dist/src/finders.js +1 -1
  78. package/dist/src/fold-runtime.js +1 -0
  79. package/dist/src/gesture-admission.js +1 -1
  80. package/dist/src/gesture-runtime.js +1 -1
  81. package/dist/src/harmonyos.js +1 -1
  82. package/dist/src/helper.js +2 -2
  83. package/dist/src/host.js +1 -0
  84. package/dist/src/interaction-positionals.js +1 -1
  85. package/dist/src/interaction-ref-policy.js +1 -1
  86. package/dist/src/interaction.js +1 -1
  87. package/dist/src/interaction2.js +1 -1
  88. package/dist/src/interactor-operation-binding.js +1 -0
  89. package/dist/src/interactor-operation-catalog.js +1 -1
  90. package/dist/src/interactor.js +4 -5
  91. package/dist/src/interactor2.js +1 -1
  92. package/dist/src/interactors.js +1 -1
  93. package/dist/src/internal/bin.js +1 -1
  94. package/dist/src/internal/daemon.js +2 -2
  95. package/dist/src/internal/png-worker.d.ts +5 -0
  96. package/dist/src/internal/png-worker.js +1 -1
  97. package/dist/src/inventory2.js +1 -1
  98. package/dist/src/ios-snapshot-acquisition.js +1 -1
  99. package/dist/src/ios-snapshot-runtime.js +1 -1
  100. package/dist/src/lease.js +1 -1
  101. package/dist/src/linux.js +1 -1
  102. package/dist/src/local-interactor-operation-set.js +1 -1
  103. package/dist/src/location-coordinates.js +1 -1
  104. package/dist/src/macos-facade.js +1 -1
  105. package/dist/src/managed-device-scope.js +1 -1
  106. package/dist/src/mechanics.js +17 -16
  107. package/dist/src/mobile-snapshot-semantics.js +1 -1
  108. package/dist/src/mp4-duration.js +1 -0
  109. package/dist/src/multitouch-support.js +1 -1
  110. package/dist/src/owner-identity.js +1 -1
  111. package/dist/src/parameterized-recorded-fill.js +1 -1
  112. package/dist/src/perf-facade.js +2 -2
  113. package/dist/src/perf-runtime-plan.js +1 -1
  114. package/dist/src/physical-device-control.js +1 -1
  115. package/dist/src/platform-request-scope.js +1 -1
  116. package/dist/src/platform-runtime-managed-owner.js +1 -1
  117. package/dist/src/platform-runtime-open-target.js +1 -1
  118. package/dist/src/platform-runtime-operation-host.js +2 -2
  119. package/dist/src/platform-runtime-runtime-hints.js +1 -1
  120. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  121. package/dist/src/platform-runtime-unavailable.js +1 -1
  122. package/dist/src/platform-runtime.js +1 -1
  123. package/dist/src/platform-runtime2.js +1 -1
  124. package/dist/src/png-crop-bytes.js +1 -1
  125. package/dist/src/png-encode.js +1 -0
  126. package/dist/src/png-size.js +1 -0
  127. package/dist/src/png-worker-client.js +1 -1
  128. package/dist/src/provider-webdriver.js +1 -1
  129. package/dist/src/quality-warnings.js +1 -1
  130. package/dist/src/react-native.js +1 -1
  131. package/dist/src/record-runtime.js +1 -1
  132. package/dist/src/recording-export-quality.js +1 -1
  133. package/dist/src/recording-scope.js +1 -0
  134. package/dist/src/recording.js +3 -0
  135. package/dist/src/registry.js +35 -35
  136. package/dist/src/replay.js +1 -1
  137. package/dist/src/request-admission.js +1 -1
  138. package/dist/src/request-runtime-binding.js +1 -1
  139. package/dist/src/result-serialization.js +1 -1
  140. package/dist/src/runner-cache-metadata.js +2 -2
  141. package/dist/src/runner-client.js +1 -1
  142. package/dist/src/runner-contract.js +3 -0
  143. package/dist/src/runner-dev-tools-security.js +1 -0
  144. package/dist/src/runner-device-readiness.js +1 -0
  145. package/dist/src/runner-disposal.js +1 -1
  146. package/dist/src/runner-operations-facade.js +1 -1
  147. package/dist/src/runner-presentation.js +1 -1
  148. package/dist/src/runner.js +1 -1
  149. package/dist/src/runtime.js +2 -2
  150. package/dist/src/runtime10.js +2 -1
  151. package/dist/src/runtime2.js +4 -4
  152. package/dist/src/runtime4.js +5 -5
  153. package/dist/src/runtime5.js +1 -1
  154. package/dist/src/runtime6.js +1 -1
  155. package/dist/src/runtime7.js +1 -1
  156. package/dist/src/runtime8.js +1 -1
  157. package/dist/src/runtime9.js +1 -1
  158. package/dist/src/screen-recording-admission-ledger.js +1 -1
  159. package/dist/src/screen-recording-resource-recovery.js +1 -1
  160. package/dist/src/screen-recording-transport.js +1 -1
  161. package/dist/src/screenshot-density.js +1 -1
  162. package/dist/src/screenshot-image.js +1 -0
  163. package/dist/src/screenshot-overlay-draw.js +1 -0
  164. package/dist/src/screenshot-runtime.js +1 -1
  165. package/dist/src/script.js +1 -1
  166. package/dist/src/scroll-gesture.js +1 -1
  167. package/dist/src/sdk-batch.js +2 -2
  168. package/dist/src/sdk-contracts.d.ts +7 -5
  169. package/dist/src/sdk-contracts.js +2 -2
  170. package/dist/src/sdk-device.js +1 -1
  171. package/dist/src/sdk-finders.js +1 -1
  172. package/dist/src/sdk-selectors.d.ts +58 -6
  173. package/dist/src/sdk-selectors.js +1 -1
  174. package/dist/src/selection.js +0 -0
  175. package/dist/src/selector-runtime.js +1 -1
  176. package/dist/src/selectors.js +1 -1
  177. package/dist/src/semantic-index.js +1 -1
  178. package/dist/src/session-routing.js +1 -1
  179. package/dist/src/session-snapshot.js +1 -1
  180. package/dist/src/session-store.js +3 -3
  181. package/dist/src/session2.js +3 -3
  182. package/dist/src/simctl.js +1 -1
  183. package/dist/src/simulator-boot.js +1 -1
  184. package/dist/src/simulator-facade.js +1 -1
  185. package/dist/src/simulator.js +1 -1
  186. package/dist/src/snapshot-runtime-binding.js +1 -1
  187. package/dist/src/snapshot-runtime.js +1 -1
  188. package/dist/src/snapshot-state.js +1 -1
  189. package/dist/src/snapshot4.js +1 -1
  190. package/dist/src/src.js +1 -1
  191. package/dist/src/src7.js +1 -1
  192. package/dist/src/src8.js +1 -1
  193. package/dist/src/stop-sequence.js +1 -1
  194. package/dist/src/text-entry-focus.js +1 -1
  195. package/dist/src/touch-runtime.js +1 -1
  196. package/dist/src/tree.js +1 -1
  197. package/dist/src/type-text-runtime.js +1 -1
  198. package/dist/src/video.js +2 -2
  199. package/dist/src/web2.js +1 -1
  200. package/package.json +3 -1
  201. package/server.json +2 -2
  202. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.7.apk.sha256 +0 -1
  203. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.7.apk.sha256 +0 -1
  204. package/dist/src/png-transcode.js +0 -1
@@ -1,4 +1,4 @@
1
- import{D as e,W as t}from"./sdk-contracts.js";import{g as n}from"./sdk-batch-runner.js";import{i as r,r as i,t as a,y as o}from"./sdk-device.js";import{Xn as s,Yn as c,an as l,p as ee,rn as te,x as ne}from"./sdk-batch.js";import{o as re,s as ie,t as u}from"./back-mode.js";import{a as ae}from"./scroll-gesture.js";import{_ as d,c as oe,d as se,g as ce,h as le,i as ue,l as de,m as fe,o as pe,p as f,s as me,u as p,y as he}from"./script.js";import{A as ge,C as _e,D as ve,E as ye,M as be,N as xe,S as Se,T as Ce,_ as we,a as Te,b as Ee,g as m,i as De,k as Oe,l as ke,n as Ae,r as je,s as Me,t as Ne,v as Pe,w as Fe,x as Ie,y as Le}from"./parameterized-recorded-fill.js";import{n as h,t as g}from"./catalog.js";import{t as Re}from"./session.js";import{r as ze}from"./success-text.js";import{t as Be}from"./click-button.js";import"./device.js";import{t as _}from"./device-rotation.js";import{a as v,r as y}from"./diagnostics.js";import{D as Ve}from"./owner-identity.js";import"./file.js";import{t as He}from"./tv-remote.js";import"./diagnostics2.js";import{n as Ue,r as We}from"./session-repair-tombstone.js";import{n as Ge,r as b,t as x}from"./session-paths.js";import{t as Ke}from"./keyboard-actions.js";import S from"node:path";import C from"node:fs";import{createHash as qe}from"node:crypto";import{StringDecoder as Je}from"node:string_decoder";function Ye(e,t={}){let n=[e.command];return e.command===`snapshot`?se(n,e):e.command===`open`?ue(n,e):e.command===`runtime`?oe(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?me(n,e):e.command===`screenshot`?de(n,e):pe(n,e),n.join(` `)}function Xe(e){return e.targetEvidences?[c(e.targetEvidences)]:e.targetEvidence?[s(e.targetEvidence)]:[]}function w(e){return e?.scriptPublication??m}function Ze(e,t){let n=w(e),r=typeof t.saveScript==`string`?x(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath;e.scriptPublication=Pe(n,{requested:{path:r,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function Qe(e){e.scriptPublication=Ee(w(e))}function $e(e){e.scriptPublication=Fe(w(e))}function et(e,t){e.scriptPublication=Ce(w(e),t)}function tt(e){e.scriptPublication=we(w(e))}function nt(e,t){let n=w(e);return n.kind===`repair`&&n.closeReceipt===t}function rt(e){return w(e).kind===`repair`}function it(e){return _e(w(e))}function T(e){return ye(w(e))}function at(e){return ve(w(e))}function ot(e,t){if(t.flags?.noRecord||gt(e,t))return;t.flags&&Me(e,t.flags);let n=ct(t),r=dt(e,lt(t,n));n&&ut(e,n);let i={ts:Date.now(),command:r.command,positionals:r.positionals,runtime:r.runtime,flags:vt(r.flags),result:r.result,...r.targetEvidence?{targetEvidence:r.targetEvidence}:{},...r.targetEvidences?{targetEvidences:r.targetEvidences}:{}};return e.actions.push(i),y({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),i}function st(e,t,n,r,i,a){t&&e.recordAction(t,{command:r,positionals:a?.positionals??n.positionals??[],flags:a?.flags??n.flags??{},result:i??{}})}function ct(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return;let t=xe(e.flags.recordAs),n=be(t);return{literal:ge({ts:0,command:e.command,positionals:e.positionals,flags:e.flags}),placeholder:n}}function lt(e,t){if(!t)return e;let{literal:n,placeholder:r}=t;return{...e,positionals:pt(e.positionals,r),result:Ne(e.result,n,r),targetEvidence:Ae(e.targetEvidence,n,r)}}function ut(e,t){t.literal.trim()&&(e.recordedFillLiterals??=new Map,!e.recordedFillLiterals.has(t.literal)&&e.recordedFillLiterals.set(t.literal,t.placeholder))}function dt(e,t){let n=e.recordedFillLiterals;if(!n||n.size===0)return t;let r=je(t.result,n),i=(t.targetEvidenceMode??`action`)===`landmark`?ft(t.targetEvidence,n):E(t.targetEvidence,n),a=t.targetEvidences?{source:E(t.targetEvidences.source,n),destination:E(t.targetEvidences.destination,n)}:t.targetEvidences;return{...t,result:r,targetEvidence:i,targetEvidences:a}}function ft(e,t){return e&&(Te(e,t)?void 0:e)}function E(e,t){return!e||!Te(e,t)?e:{...De(e,t),verification:`unverifiable`}}function pt(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const mt=new Set([`snapshot`,`get`,`is`,`find`]);function ht(e){return e.internal?.replayPlanStep!==!0&&mt.has(e.command)}function gt(e,t){return!t.interactiveObservation||T(e)===void 0?!1:t.flags?.record!==!0}const _t=re();function vt(e){if(!e)return{};let t={};for(let n of _t){let r=e[n];r!==void 0&&(t[n]=r)}return t}function yt(t){let n=t.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new e(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(t.some(e=>e.command===`close`))throw new e(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[e,n]of t.entries())ne({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=e);if(!t.slice(r+1).some(Tt))throw new e(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function bt(t){for(let n of t){if(xt(n)){St(n);continue}let t=Et(n),r=t??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&ne(n)===`mutates-app`)throw new e(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=t;if(!(!i||!l(i)||n.targetEvidence))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function xt(e){return Ct(e)!==void 0}function St(t){let n=Ct(t);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!l(n))&&!t.targetEvidences)throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function Ct(e){return e.command===`gesture`?he(e.positionals):void 0}function wt(t,n){if(t instanceof e){if(t.details?.reason===`script_target_exists`)return new e(t.code,`A file already exists at ${String(t.details.path)}.`,{...t.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=t.details?.retriable===!0;return new e(t.code,t.message,{...t.details,retriable:n,hint:t.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Tt(e){if(e.command!==`wait`)return!1;let t=te(e.positionals);return t?.kind!==`selector`||!l(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function Et(e){if(e.command===`get`)return e.positionals[1];if(ce(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&Dt(t)&&Dt(n)?void 0:t}}function Dt(e){return e.trim().length>0&&Number.isFinite(Number(e))}function Ot(e){let t=e.scriptPublication??m;return t.kind===`repair`?t.status===`committed`||!Se(t):!1}function kt(e){return!Ie(e.scriptPublication??m)||Ot(e)}var At=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=rt(e),r=t?.publication===`active`,i;try{if(kt(e))return{written:!1};let a=jt(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=S.dirname(i);return C.existsSync(o)||C.mkdirSync(o,{recursive:!0}),Pt({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=Le(e.scriptPublication??m)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return Mt({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=Oe(e.scriptPublication??m);if(t)return x(t);let n=b(e.name),r=new Date(e.createdAt).toISOString().replaceAll(/[:.]/g,`-`);return S.join(this.sessionsDir,`${n}-${r}.ad`)}};function jt(e,t){let n=Ft(e,{strictPortableRefs:t.activePublication});return t.activePublication&&yt(n),{script:Gt(e,n,t.appendCompleteSentinel),actionCount:n.length}}function Mt(t){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=t;if(y({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:Nt(r,i)};if(o)return{written:!1,error:wt(r,i)};if(r instanceof e)throw r;return{written:!1}}function Nt(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 Pt(t){let{scriptPath:n,script:r,force:i}=t;try{Ve({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 Ft(e,t={}){let n=T(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=Rt(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&It(n);let o=Wt(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&bt(a),a}function It(t){let n=t.command===`gesture`?he(t.positionals??[]):void 0;if(n){Lt(n);return}if(!D(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 Lt(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 Rt(e){let t=zt(e);if(!(!t||!D(e.command)))return le(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?Vt(e,t):e.command===`fill`?Bt(e,t):Ht(e,t)}function zt(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 D(e){return ce(e)||e===`fill`||e===`get`}function Bt(e,t){let n=ge(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function Vt(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):Ut(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Ht(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function Ut(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function Wt(e,t){if(!D(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 Gt(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${o(e.device)} device=${fe(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...Xe(e)),r.push(Kt(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
2
- `)}\n`}function Kt(e){return qt([e.command],e)||Ye(e)}function qt(e,t){if(le(t.command))return Jt(e,t);if(t.command===`fill`)return Yt(e,t);if(t.command===`get`)return Xt(e,t)}function Jt(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(f(d(n))),O(e,t),p(e,t),e.join(` `);if(t.positionals.length===1)return e.push(f(n)),p(e,t),e.join(` `)}}function Yt(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(f(d(n))),O(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(f(r)),p(e,t),e.join(` `)}function Xt(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(f(n)),e.push(f(d(r))),r.startsWith(`@`)&&O(e,t),e.join(` `)}function O(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(f(n))}const Zt=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],Qt={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function $t(e,t){let n=t??{};switch(e.command){case h.devices:return en(n.devices);case h.apps:return tn(n.apps,e.flags?.appsFilter);case h.boot:return nn(`Booted`,n,!0);case h.shutdown:return nn(`Shut down`,n,!1);case h.install:return k(`Installed`,n);case h.reinstall:return k(`Reinstalled`,n);case h.screenshot:return rn(e,n);default:return{}}}function en(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=on(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:hn(`Found ${t.length} ${gn(`device`,t.length)}`,i.map(e=>pn(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function tn(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=M(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:hn(`Found ${n.length} ${gn(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function nn(e,t,n){let r=sn(t);if(!r)return{};let i={device:r,...fn(t),booted:n};return{summary:`${e} ${pn(i,!1)}`,details:i}}function k(e,t){let n=M(t.appName),r=M(t.bundleId),i=A(t,[`packageName`,`package`]),a=M(t.platform),o=M(t.launchTarget),s=A(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=mn(n,s);if(!c)return{};let l={};return j(l,`appName`,n),j(l,`bundleId`,r),j(l,`packageName`,i),j(l,`platform`,a),o!==s&&j(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function rn(e,t){let n=an(e,t);return n?{details:{requestedFileName:n}}:{}}function an(e,t){let n=R(e.meta?.clientArtifactPaths?.path)??R(t.path);if(n)return L(n)}function on(e){if(!n(e))return;let t=sn(e);if(t)return{name:t,...fn(e)}}function sn(e){let t=A(e,[`name`,`deviceName`,`device`]);return!t||!cn(e,t)?t:un(e)}function cn(e,t){let n=ln(t);return Zt.some(t=>{let r=M(e[t]);return r!==void 0&&ln(r)===n})}function ln(e){return e.toLowerCase()}function un(e){let t=M(e.appleOs),n=M(e.platform),r=M(e.kind),i=dn(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function dn(e,t){let n=e??t;if(!(!n||!Object.hasOwn(Qt,n)))return Qt[n]}function fn(e){let t=M(e.platform),n=M(e.appleOs),r=M(e.kind),i=M(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function pn(e,t){let n=M(e.name)??M(e.device)??`device`,r=M(e.platform),i=M(e.appleOs),a=[r,i===r?void 0:i,M(e.kind),M(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function mn(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function A(e,t){for(let n of t){let t=M(e[n]);if(t)return t}}function j(e,t,n){n&&(e[t]=n)}function hn(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function gn(e,t){return t===1?e:`${e}s`}function M(e){let t=R(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function N(e){return M(e)}function P(e){return typeof e==`boolean`?e:void 0}function F(e,t){let n=N(e);return n&&t.includes(n)?n:void 0}function I(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function L(e){let t=R(e);return t?M(t.split(/[\\/]/).at(-1)):void 0}function R(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function z(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const _n=[`up`,`down`,`left`,`right`],vn=[`top`,`bottom`];function yn(e){return`${e.command===h.reinstall?`Reinstalled`:`Installed`} ${Cn(e.result??{})??`app`}`}function bn(e){let t=e.result??{};switch(e.command){case h.scroll:return Tn(t);case h.screenshot:return On(t);case h.home:return`Went home`;case h.back:return An(t);case h.appSwitcher:return`Opened app switcher`;case h.actionButton:return`Pressed Action Button`;case h.orientation:return jn(t);case h.viewport:return Mn(t);case h.clipboard:return Nn(t);case h.keyboard:return Pn(t);case h.tvRemote:return Ln(t);case h.gesture:return Rn(t);case h.swipe:return zn(t);case h.trace:return Vn(`trace`,e);case h.record:return Vn(`recording`,e);default:return}}function xn(e){let t=e.result??{};switch(e.command){case h.scroll:return I({direction:F(t.direction,_n),edge:F(t.edge,vn),passes:z(t.passes),amount:z(t.amount),pixels:z(t.pixels),durationMs:z(t.durationMs),x1:z(t.x1),y1:z(t.y1),x2:z(t.x2),y2:z(t.y2)});case h.screenshot:return I({requestedFileName:kn(t)});case h.back:return I({mode:F(t.mode,u)});case h.orientation:return I({orientation:F(t.orientation,_)});case h.viewport:return I({width:z(t.width),height:z(t.height)});case h.clipboard:return I({action:F(t.action,[`read`,`write`])});case h.keyboard:return In(t);case h.tvRemote:return I({button:F(t.button,He),durationMs:z(t.durationMs)});case h.gesture:case h.swipe:return Bn(t);case h.trace:case h.record:return I({action:F(t.action,[`start`,`stop`]),fileName:Un(e),showTouches:P(t.showTouches)});default:return{}}}function Sn(e,t){if(e.command!==h.screenshot)return t;let n=an(e,t);return n?{...t,requestedFileName:n}:t}function Cn(e){let t=N(e.appName),n=Wn(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??wn(e)}function wn(e){let t=N(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function Tn(e){let t=F(e.direction,_n),n=F(e.edge,vn),r=z(e.passes);return n?En(n,r):t?Dn(t,e):`Scrolled`}function En(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function Dn(e,t){let n=z(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=z(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function On(e){let t=kn(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function kn(e){return L(e.requestedFileName)??L(e.path)}function An(e){return F(e.mode,u)===`system`?`Went back using system navigation`:`Went back`}function jn(e){let t=F(e.orientation,_);return t?P(e.confirmed)===!1?`Requested ${t} (unconfirmed)`:`Rotated to ${t}`:`Changed orientation`}function Mn(e){let t=z(e.width),n=z(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function Nn(e){let t=F(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function Pn(e){let t=R(e.action);if(!t||!Ke(t))return`Used keyboard`;if(t===`dismiss`)return Fn(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=P(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function Fn(e){return P(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function In(e){let t=R(e.action);return I({action:t&&Ke(t)?t:void 0,platform:F(e.platform,[`ios`,`android`]),visible:P(e.visible),wasVisible:P(e.wasVisible),dismissed:P(e.dismissed),attempts:z(e.attempts),mechanism:F(e.mechanism,[`dismissKey`])})}function Ln(e){let t=F(e.button,He);return t?`Pressed TV remote ${t}`:`Used TV remote`}function Rn(e){let t=F(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function zn(e){let t=z(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function Bn(e){return I({kind:F(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:z(e.durationMs),pointerCount:z(e.pointerCount),x1:z(e.x1),y1:z(e.y1),x2:z(e.x2),y2:z(e.y2),count:z(e.count),pauseMs:z(e.pauseMs),pattern:F(e.pattern,[`one-way`,`ping-pong`]),scale:z(e.scale)})}function Vn(e,t){let n=Hn(e,F(t.result?.action,[`start`,`stop`])),r=Un(t);return r?`${n} ${r}`:n}function Hn(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function Un(e){let t=e.result??{};return L(t.requestedFileName)??L(t.outPath)??L(t.path)??L(e.positionals[1])}function Wn(e,t){for(let n of t){let t=N(e[n]);if(t)return t}}function Gn(e){switch(e.command){case h.open:return`Opened ${B(e)??`session`}`;case h.close:return`Closed ${N(e.result?.session)??`session`}`;case h.click:case h.press:return`Tapped ${B(e)??`target`}`;case h.longPress:return`Long pressed ${B(e)??`target`}`;case h.hover:return`Hovered ${B(e)??`target`}`;case h.fill:return`Filled ${B(e)??`target`}`;case h.type:return`Typed text`;case h.install:case h.reinstall:case g.installSource:return yn(e);default:return bn(e)??`Ran ${e.command}`}}function Kn(e){return I({command:e.command,positionals:tr(e),flags:pr(e),...qn(e),...Jn(e),...Yn(e),...xn(e)})}function qn(e){if(!Xn(e.command))return{};let t=e.result??{};return I({ref:G(t),targetLabel:B(e),selectorChainLength:lr(t.selectorChain)?.length,x:z(t.x),y:z(t.y),x2:z(t.x2),y2:z(t.y2),durationMs:z(t.durationMs)})}function Jn(e){if(!Zn(e.command))return{};let t=e.result??{};return I({platform:F(t.platform,r),target:F(t.target,a),appName:N(t.appName),appBundleId:N(t.appBundleId),bundleId:N(t.bundleId),packageName:N(t.packageName),launchTarget:N(t.launchTarget)})}function Yn(e){let t=e.result??{};return e.command===h.snapshot?Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}:e.command!==h.wait&&e.command!==h.find&&e.command!==h.get&&e.command!==h.is?{}:I({waitedMs:z(t.waitedMs),found:P(t.found)})}function Xn(e){return e===h.click||e===h.press||e===h.longPress||e===h.hover||e===h.focus||e===h.fill}function Zn(e){return e===h.open||e===h.install||e===h.reinstall||e===g.installSource}function B(e){let t=e.result??{};return Qn(t)??$n(t)??er(t)??sr(e.positionals[0])}function Qn(e){let t=G(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function $n(e){let t=z(e.x),n=z(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function er(e){return N(e.appName)??N(e.appBundleId)??N(e.bundleId)??N(e.packageName)}function tr(e){if(e.positionals.length!==0)return e.command===h.type?[H(`text`)]:e.command===h.fill?nr(e):e.command===h.find?rr(e):e.command===h.clipboard?ir(e):e.command===h.push?ar(e,`app`,`payload`):e.command===h.triggerAppEvent?ar(e,`event`,`payload`):e.positionals.map(V)}function nr(e){let t=H(`text`),n=e.result??{},r=G(n);if(r)return[`@${r}`,t];if(N(n.selector))return[H(`target`),t];let i=z(n.x),a=z(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function rr(e){let t=+!!cr(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],H(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,H(`text`)]:[...r,...e.positionals.slice(n).map(or)]:r}function ir(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,H(`text`)]:e.positionals.map(V)}function ar(e,t,n){let[r,i,...a]=e.positionals;return[...r?[H(t)]:[],...i?[H(n)]:[],...a.map(V)]}function or(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:V(e)}function V(e){return sr(e)??H(`arg`)}function sr(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function H(e){return`<${e}>`}function cr(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function lr(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const ur={enums:[{source:`platform`,values:i},{source:`target`,values:a}]},dr={booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}]},fr={[h.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:Re}]},[h.click]:U(),[h.press]:U(),[h.longPress]:U(),[h.hover]:U(),[h.fill]:hr(),[h.type]:hr(),[h.scroll]:{numbers:[{source:`pixels`},{source:`durationMs`}]},[h.gesture]:gr(),[h.swipe]:gr(),[h.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[h.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[h.back]:{enums:[{source:`backMode`,output:`mode`,values:u}]},[h.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:ie}]},[h.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[h.boot]:{booleans:[{source:`headless`}]},[h.close]:{booleans:[{source:`shutdown`}]}};function pr(e){let t=e.flags??{},n={},r=Object.hasOwn(fr,e.command)?fr[e.command]:void 0;return W(n,t,ur),W(n,t,r),W(n,t,mr(e.command)),Object.keys(n).length>0?n:void 0}function mr(e){return ee(e)?dr:void 0}function U(){return{booleans:[{source:`doubleTap`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`}],enums:[{source:`clickButton`,values:Be}]}}function hr(){return{numbers:[{source:`delayMs`}]}}function gr(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:ae}]}}function W(e,t,n){n&&(_r(e,t,n.booleans??[]),vr(e,t,n.numbers??[]),yr(e,t,n.enums??[]))}function _r(e,t,n){for(let r of n)br(e,r.output??r.source,t[r.source])}function vr(e,t,n){for(let r of n)xr(e,r.output??r.source,t[r.source])}function yr(e,t,n){for(let r of n)Sr(e,r.output??r.source,t[r.source],r.values)}function G(e){let t=N(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function br(e,t,n){typeof n==`boolean`&&(e[t]=n)}function xr(e,t,n){let r=z(n);r!==void 0&&(e[t]=r)}function Sr(e,t,n,r){let i=F(n,r);i!==void 0&&(e[t]=i)}const Cr=65536;function wr(e){return qe(`sha256`).update(e,`utf8`).digest(`hex`).slice(0,32)}function K(e,t){let n=Or(e);if(n===void 0)return!1;try{let e=Er(t),r=Buffer.allocUnsafe(Cr),i=0;do if(i=C.readSync(n,r,0,r.length,null),!e.push(r.subarray(0,i)))return!0;while(i>0);return e.end(),!0}finally{C.closeSync(n)}}async function Tr(e){let t=await kr(e);if(t===void 0)return{lineCount:0,firstLineDigest:void 0};let n={lineCount:0,firstLineDigest:void 0};try{let e=Er(e=>{n.lineCount===0&&(n.firstLineDigest=wr(e)),n.lineCount+=1}),r=Buffer.allocUnsafe(Cr);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 q(e){let t;return K(e,e=>(t=wr(e),!1)),t}function Er(e){let t=new Je(`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{D as e,W as t}from"./sdk-contracts.js";import{g as n}from"./sdk-batch-runner.js";import{b as r,i,r as a,t as o}from"./sdk-device.js";import{$n as s,Qn as c,cn as l,on as ee,p as te,x as ne}from"./sdk-batch.js";import{t as re}from"./recording-scope.js";import{a as ie}from"./scroll-gesture.js";import{_ as u,c as ae,d as oe,g as se,h as ce,i as le,l as ue,m as de,o as fe,p as d,s as pe,u as f,y as me}from"./script.js";import{A as p,C as he,D as ge,E as _e,M as ve,N as ye,S as be,T as xe,_ as Se,a as Ce,b as we,g as m,i as Te,k as Ee,l as De,n as Oe,r as ke,s as Ae,t as je,v as Me,w as Ne,x as Pe,y as Fe}from"./parameterized-recorded-fill.js";import{n as h,t as Ie}from"./catalog.js";import{o as Le,t as g}from"./back-mode.js";import{t as Re}from"./session.js";import{r as ze}from"./success-text.js";import{t as Be}from"./click-button.js";import"./device.js";import{r as _,t as v}from"./device-rotation.js";import{a as y,r as b}from"./diagnostics.js";import{D as Ve}from"./owner-identity.js";import"./file.js";import{t as He}from"./tv-remote.js";import"./diagnostics2.js";import{n as Ue,r as We}from"./session-repair-tombstone.js";import{n as Ge,r as x,t as S}from"./session-paths.js";import{t as Ke}from"./keyboard-actions.js";import C from"node:path";import w from"node:fs";import{createHash as qe}from"node:crypto";import{StringDecoder as Je}from"node:string_decoder";function Ye(e,t={}){let n=[e.command];return e.command===`snapshot`?oe(n,e):e.command===`open`?le(n,e):e.command===`runtime`?ae(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?pe(n,e):e.command===`screenshot`?ue(n,e):fe(n,e),n.join(` `)}function Xe(e){return e.targetEvidences?[c(e.targetEvidences)]:e.targetEvidence?[s(e.targetEvidence)]:[]}function T(e){return e?.scriptPublication??m}function Ze(e,t){let n=T(e),r=typeof t.saveScript==`string`?S(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath;e.scriptPublication=Me(n,{requested:{path:r,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function Qe(e){e.scriptPublication=we(T(e))}function $e(e){e.scriptPublication=Ne(T(e))}function et(e,t){e.scriptPublication=xe(T(e),t)}function tt(e){e.scriptPublication=Se(T(e))}function nt(e,t){let n=T(e);return n.kind===`repair`&&n.closeReceipt===t}function rt(e){return T(e).kind===`repair`}function it(e){return he(T(e))}function E(e){return _e(T(e))}function at(e){return ge(T(e))}function ot(e,t){if(t.flags?.noRecord||gt(e,t))return;t.flags&&Ae(e,t.flags);let n=ct(t),r=dt(e,lt(t,n));n&&ut(e,n);let i={ts:Date.now(),command:r.command,positionals:r.positionals,runtime:r.runtime,flags:vt(r.flags),result:r.result,...r.targetEvidence?{targetEvidence:r.targetEvidence}:{},...r.targetEvidences?{targetEvidences:r.targetEvidences}:{}};return e.actions.push(i),b({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),i}function st(e,t,n,r,i,a){t&&e.recordAction(t,{command:r,positionals:a?.positionals??n.positionals??[],flags:a?.flags??n.flags??{},result:i??{}})}function ct(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return;let t=ye(e.flags.recordAs),n=ve(t);return{literal:p({ts:0,command:e.command,positionals:e.positionals,flags:e.flags}),placeholder:n}}function lt(e,t){if(!t)return e;let{literal:n,placeholder:r}=t;return{...e,positionals:pt(e.positionals,r),result:je(e.result,n,r),targetEvidence:Oe(e.targetEvidence,n,r)}}function ut(e,t){t.literal.trim()&&(e.recordedFillLiterals??=new Map,!e.recordedFillLiterals.has(t.literal)&&e.recordedFillLiterals.set(t.literal,t.placeholder))}function dt(e,t){let n=e.recordedFillLiterals;if(!n||n.size===0)return t;let r=ke(t.result,n),i=(t.targetEvidenceMode??`action`)===`landmark`?ft(t.targetEvidence,n):D(t.targetEvidence,n),a=t.targetEvidences?{source:D(t.targetEvidences.source,n),destination:D(t.targetEvidences.destination,n)}:t.targetEvidences;return{...t,result:r,targetEvidence:i,targetEvidences:a}}function ft(e,t){return e&&(Ce(e,t)?void 0:e)}function D(e,t){return!e||!Ce(e,t)?e:{...Te(e,t),verification:`unverifiable`}}function pt(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const mt=new Set([`snapshot`,`get`,`is`,`find`]);function ht(e){return e.internal?.replayPlanStep!==!0&&mt.has(e.command)}function gt(e,t){return!t.interactiveObservation||E(e)===void 0?!1:t.flags?.record!==!0}const _t=Le();function vt(e){if(!e)return{};let t={};for(let n of _t){let r=e[n];r!==void 0&&(t[n]=r)}return t}function yt(t){let n=t.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new e(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(t.some(e=>e.command===`close`))throw new e(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[e,n]of t.entries())ne({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=e);if(!t.slice(r+1).some(Tt))throw new e(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function bt(t){for(let n of t){if(xt(n)){St(n);continue}let t=Et(n),r=t??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&ne(n)===`mutates-app`)throw new e(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=t;if(!(!i||!l(i)||n.targetEvidence))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function xt(e){return Ct(e)!==void 0}function St(t){let n=Ct(t);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!l(n))&&!t.targetEvidences)throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function Ct(e){return e.command===`gesture`?me(e.positionals):void 0}function wt(t,n){if(t instanceof e){if(t.details?.reason===`script_target_exists`)return new e(t.code,`A file already exists at ${String(t.details.path)}.`,{...t.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=t.details?.retriable===!0;return new e(t.code,t.message,{...t.details,retriable:n,hint:t.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Tt(e){if(e.command!==`wait`)return!1;let t=ee(e.positionals);return t?.kind!==`selector`||!l(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function Et(e){if(e.command===`get`)return e.positionals[1];if(se(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&Dt(t)&&Dt(n)?void 0:t}}function Dt(e){return e.trim().length>0&&Number.isFinite(Number(e))}function Ot(e){let t=e.scriptPublication??m;return t.kind===`repair`?t.status===`committed`||!be(t):!1}function kt(e){return!Pe(e.scriptPublication??m)||Ot(e)}var At=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=rt(e),r=t?.publication===`active`,i;try{if(kt(e))return{written:!1};let a=jt(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=C.dirname(i);return w.existsSync(o)||w.mkdirSync(o,{recursive:!0}),Pt({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=Fe(e.scriptPublication??m)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return Mt({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=Ee(e.scriptPublication??m);if(t)return S(t);let n=x(e.name),r=new Date(e.createdAt).toISOString().replaceAll(/[:.]/g,`-`);return C.join(this.sessionsDir,`${n}-${r}.ad`)}};function jt(e,t){let n=Ft(e,{strictPortableRefs:t.activePublication});return t.activePublication&&yt(n),{script:Gt(e,n,t.appendCompleteSentinel),actionCount:n.length}}function Mt(t){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=t;if(b({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:Nt(r,i)};if(o)return{written:!1,error:wt(r,i)};if(r instanceof e)throw r;return{written:!1}}function Nt(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 Pt(t){let{scriptPath:n,script:r,force:i}=t;try{Ve({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 Ft(e,t={}){let n=E(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=Rt(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&It(n);let o=Wt(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&bt(a),a}function It(t){let n=t.command===`gesture`?me(t.positionals??[]):void 0;if(n){Lt(n);return}if(!O(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 Lt(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 Rt(e){let t=zt(e);if(!(!t||!O(e.command)))return ce(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?Vt(e,t):e.command===`fill`?Bt(e,t):Ht(e,t)}function zt(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 O(e){return se(e)||e===`fill`||e===`get`}function Bt(e,t){let n=p(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function Vt(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):Ut(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Ht(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function Ut(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function Wt(e,t){if(!O(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 Gt(e,t,n){let i=[],a=e.device.kind?` kind=${e.device.kind}`:``;i.push(`context platform=${r(e.device)} device=${de(e.device.name)}${a} theme=unknown`);for(let e of t)e.flags?.noRecord||(i.push(...Xe(e)),i.push(Kt(e)));return n&&i.push(`# agent-device:heal-complete`),`${i.join(`
2
+ `)}\n`}function Kt(e){return qt([e.command],e)||Ye(e)}function qt(e,t){if(ce(t.command))return Jt(e,t);if(t.command===`fill`)return Yt(e,t);if(t.command===`get`)return Xt(e,t)}function Jt(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(d(u(n))),k(e,t),f(e,t),e.join(` `);if(t.positionals.length===1)return e.push(d(n)),f(e,t),e.join(` `)}}function Yt(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(d(u(n))),k(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(d(r)),f(e,t),e.join(` `)}function Xt(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(d(n)),e.push(d(u(r))),r.startsWith(`@`)&&k(e,t),e.join(` `)}function k(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(d(n))}const Zt=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],Qt={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function $t(e,t){let n=t??{};switch(e.command){case h.devices:return en(n.devices);case h.apps:return tn(n.apps,e.flags?.appsFilter);case h.boot:return nn(`Booted`,n,!0);case h.shutdown:return nn(`Shut down`,n,!1);case h.install:return rn(`Installed`,n);case h.reinstall:return rn(`Reinstalled`,n);case h.screenshot:return an(e,n);default:return{}}}function en(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=sn(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:gn(`Found ${t.length} ${_n(`device`,t.length)}`,i.map(e=>mn(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function tn(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=M(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:gn(`Found ${n.length} ${_n(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function nn(e,t,n){let r=cn(t);if(!r)return{};let i={device:r,...pn(t),booted:n};return{summary:`${e} ${mn(i,!1)}`,details:i}}function rn(e,t){let n=M(t.appName),r=M(t.bundleId),i=A(t,[`packageName`,`package`]),a=M(t.platform),o=M(t.launchTarget),s=A(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=hn(n,s);if(!c)return{};let l={};return j(l,`appName`,n),j(l,`bundleId`,r),j(l,`packageName`,i),j(l,`platform`,a),o!==s&&j(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function an(e,t){let n=on(e,t);return n?{details:{requestedFileName:n}}:{}}function on(e,t){let n=R(e.meta?.clientArtifactPaths?.path)??R(t.path);if(n)return L(n)}function sn(e){if(!n(e))return;let t=cn(e);if(t)return{name:t,...pn(e)}}function cn(e){let t=A(e,[`name`,`deviceName`,`device`]);return!t||!ln(e,t)?t:dn(e)}function ln(e,t){let n=un(t);return Zt.some(t=>{let r=M(e[t]);return r!==void 0&&un(r)===n})}function un(e){return e.toLowerCase()}function dn(e){let t=M(e.appleOs),n=M(e.platform),r=M(e.kind),i=fn(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function fn(e,t){let n=e??t;if(!(!n||!Object.hasOwn(Qt,n)))return Qt[n]}function pn(e){let t=M(e.platform),n=M(e.appleOs),r=M(e.kind),i=M(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function mn(e,t){let n=M(e.name)??M(e.device)??`device`,r=M(e.platform),i=M(e.appleOs),a=[r,i===r?void 0:i,M(e.kind),M(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function hn(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function A(e,t){for(let n of t){let t=M(e[n]);if(t)return t}}function j(e,t,n){n&&(e[t]=n)}function gn(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function _n(e,t){return t===1?e:`${e}s`}function M(e){let t=R(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function N(e){return M(e)}function P(e){return typeof e==`boolean`?e:void 0}function F(e,t){let n=N(e);return n&&t.includes(n)?n:void 0}function I(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function L(e){let t=R(e);return t?M(t.split(/[\\/]/).at(-1)):void 0}function R(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function z(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const vn=[`up`,`down`,`left`,`right`],yn=[`top`,`bottom`];function bn(e){return`${e.command===h.reinstall?`Reinstalled`:`Installed`} ${wn(e.result??{})??`app`}`}function xn(e){let t=e.result??{};switch(e.command){case h.scroll:return En(t);case h.screenshot:return kn(t);case h.home:return`Went home`;case h.back:return jn(t);case h.appSwitcher:return`Opened app switcher`;case h.actionButton:return`Pressed Action Button`;case h.orientation:return Nn(t);case h.fold:return Mn(t);case h.viewport:return Pn(t);case h.clipboard:return Fn(t);case h.keyboard:return In(t);case h.tvRemote:return zn(t);case h.gesture:return Bn(t);case h.swipe:return Vn(t);case h.trace:return Un(`trace`,e);case h.record:return Un(`recording`,e);default:return}}function Sn(e){let t=e.result??{};switch(e.command){case h.scroll:return I({direction:F(t.direction,vn),edge:F(t.edge,yn),passes:z(t.passes),amount:z(t.amount),pixels:z(t.pixels),durationMs:z(t.durationMs),x1:z(t.x1),y1:z(t.y1),x2:z(t.x2),y2:z(t.y2)});case h.screenshot:return I({requestedFileName:An(t)});case h.back:return I({mode:F(t.mode,g)});case h.orientation:return I({orientation:F(t.orientation,v)});case h.fold:return I({pose:F(t.pose,_)});case h.viewport:return I({width:z(t.width),height:z(t.height)});case h.clipboard:return I({action:F(t.action,[`read`,`write`])});case h.keyboard:return Rn(t);case h.tvRemote:return I({button:F(t.button,He),durationMs:z(t.durationMs)});case h.gesture:case h.swipe:return Hn(t);case h.trace:case h.record:return I({action:F(t.action,[`start`,`stop`]),fileName:Gn(e),showTouches:P(t.showTouches)});default:return{}}}function Cn(e,t){if(e.command!==h.screenshot)return t;let n=on(e,t);return n?{...t,requestedFileName:n}:t}function wn(e){let t=N(e.appName),n=Kn(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??Tn(e)}function Tn(e){let t=N(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function En(e){let t=F(e.direction,vn),n=F(e.edge,yn),r=z(e.passes);return n?Dn(n,r):t?On(t,e):`Scrolled`}function Dn(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function On(e,t){let n=z(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=z(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function kn(e){let t=An(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function An(e){return L(e.requestedFileName)??L(e.path)}function jn(e){return F(e.mode,g)===`system`?`Went back using system navigation`:`Went back`}function Mn(e){let t=F(e.pose,_);return t?`Folded to ${t}`:`Changed fold pose`}function Nn(e){let t=F(e.orientation,v);return t?P(e.confirmed)===!1?`Requested ${t} (unconfirmed)`:`Rotated to ${t}`:`Changed orientation`}function Pn(e){let t=z(e.width),n=z(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function Fn(e){let t=F(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function In(e){let t=R(e.action);if(!t||!Ke(t))return`Used keyboard`;if(t===`dismiss`)return Ln(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=P(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function Ln(e){return P(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function Rn(e){let t=R(e.action);return I({action:t&&Ke(t)?t:void 0,platform:F(e.platform,[`ios`,`android`]),visible:P(e.visible),wasVisible:P(e.wasVisible),dismissed:P(e.dismissed),attempts:z(e.attempts),mechanism:F(e.mechanism,[`dismissKey`])})}function zn(e){let t=F(e.button,He);return t?`Pressed TV remote ${t}`:`Used TV remote`}function Bn(e){let t=F(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function Vn(e){let t=z(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function Hn(e){return I({kind:F(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:z(e.durationMs),pointerCount:z(e.pointerCount),x1:z(e.x1),y1:z(e.y1),x2:z(e.x2),y2:z(e.y2),count:z(e.count),pauseMs:z(e.pauseMs),pattern:F(e.pattern,[`one-way`,`ping-pong`]),scale:z(e.scale)})}function Un(e,t){let n=Wn(e,F(t.result?.action,[`start`,`stop`])),r=Gn(t);return r?`${n} ${r}`:n}function Wn(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function Gn(e){let t=e.result??{};return L(t.requestedFileName)??L(t.outPath)??L(t.path)??L(e.positionals[1])}function Kn(e,t){for(let n of t){let t=N(e[n]);if(t)return t}}function qn(e){switch(e.command){case h.open:return`Opened ${B(e)??`session`}`;case h.close:return`Closed ${N(e.result?.session)??`session`}`;case h.click:case h.press:return`Tapped ${B(e)??`target`}`;case h.longPress:return`Long pressed ${B(e)??`target`}`;case h.hover:return`Hovered ${B(e)??`target`}`;case h.fill:return`Filled ${B(e)??`target`}`;case h.type:return`Typed text`;case h.install:case h.reinstall:case Ie.installSource:return bn(e);default:return xn(e)??`Ran ${e.command}`}}function Jn(e){return I({command:e.command,positionals:rr(e),flags:hr(e),...Yn(e),...Xn(e),...Zn(e),...Sn(e)})}function Yn(e){if(!Qn(e.command))return{};let t=e.result??{};return I({ref:G(t),targetLabel:B(e),selectorChainLength:dr(t.selectorChain)?.length,x:z(t.x),y:z(t.y),x2:z(t.x2),y2:z(t.y2),durationMs:z(t.durationMs)})}function Xn(e){if(!$n(e.command))return{};let t=e.result??{};return I({platform:F(t.platform,i),target:F(t.target,o),appName:N(t.appName),appBundleId:N(t.appBundleId),bundleId:N(t.bundleId),packageName:N(t.packageName),launchTarget:N(t.launchTarget)})}function Zn(e){let t=e.result??{};return e.command===h.snapshot?Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}:e.command!==h.wait&&e.command!==h.find&&e.command!==h.get&&e.command!==h.is?{}:I({waitedMs:z(t.waitedMs),found:P(t.found)})}function Qn(e){return e===h.click||e===h.press||e===h.longPress||e===h.hover||e===h.focus||e===h.fill}function $n(e){return e===h.open||e===h.install||e===h.reinstall||e===Ie.installSource}function B(e){let t=e.result??{};return er(t)??tr(t)??nr(t)??lr(e.positionals[0])}function er(e){let t=G(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function tr(e){let t=z(e.x),n=z(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function nr(e){return N(e.appName)??N(e.appBundleId)??N(e.bundleId)??N(e.packageName)}function rr(e){if(e.positionals.length!==0)return e.command===h.type?[H(`text`)]:e.command===h.fill?ir(e):e.command===h.find?ar(e):e.command===h.clipboard?or(e):e.command===h.push?sr(e,`app`,`payload`):e.command===h.triggerAppEvent?sr(e,`event`,`payload`):e.positionals.map(V)}function ir(e){let t=H(`text`),n=e.result??{},r=G(n);if(r)return[`@${r}`,t];if(N(n.selector))return[H(`target`),t];let i=z(n.x),a=z(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function ar(e){let t=+!!ur(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],H(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,H(`text`)]:[...r,...e.positionals.slice(n).map(cr)]:r}function or(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,H(`text`)]:e.positionals.map(V)}function sr(e,t,n){let[r,i,...a]=e.positionals;return[...r?[H(t)]:[],...i?[H(n)]:[],...a.map(V)]}function cr(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:V(e)}function V(e){return lr(e)??H(`arg`)}function lr(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function H(e){return`<${e}>`}function ur(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function dr(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const fr={enums:[{source:`platform`,values:a},{source:`target`,values:o}]},pr={booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}]},mr={[h.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:Re}]},[h.click]:U(),[h.press]:U(),[h.longPress]:U(),[h.hover]:U(),[h.fill]:_r(),[h.type]:_r(),[h.scroll]:{numbers:[{source:`pixels`},{source:`durationMs`}]},[h.gesture]:vr(),[h.swipe]:vr(),[h.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[h.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[h.back]:{enums:[{source:`backMode`,output:`mode`,values:g}]},[h.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:re}]},[h.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[h.boot]:{booleans:[{source:`headless`}]},[h.close]:{booleans:[{source:`shutdown`}]}};function hr(e){let t=e.flags??{},n={},r=Object.hasOwn(mr,e.command)?mr[e.command]:void 0;return W(n,t,fr),W(n,t,r),W(n,t,gr(e.command)),Object.keys(n).length>0?n:void 0}function gr(e){return te(e)?pr:void 0}function U(){return{booleans:[{source:`doubleTap`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`}],enums:[{source:`clickButton`,values:Be}]}}function _r(){return{numbers:[{source:`delayMs`}]}}function vr(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:ie}]}}function W(e,t,n){n&&(yr(e,t,n.booleans??[]),br(e,t,n.numbers??[]),xr(e,t,n.enums??[]))}function yr(e,t,n){for(let r of n)Sr(e,r.output??r.source,t[r.source])}function br(e,t,n){for(let r of n)Cr(e,r.output??r.source,t[r.source])}function xr(e,t,n){for(let r of n)wr(e,r.output??r.source,t[r.source],r.values)}function G(e){let t=N(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function Sr(e,t,n){typeof n==`boolean`&&(e[t]=n)}function Cr(e,t,n){let r=z(n);r!==void 0&&(e[t]=r)}function wr(e,t,n,r){let i=F(n,r);i!==void 0&&(e[t]=i)}const Tr=65536;function Er(e){return qe(`sha256`).update(e,`utf8`).digest(`hex`).slice(0,32)}function K(e,t){let n=Ar(e);if(n===void 0)return!1;try{let e=Or(t),r=Buffer.allocUnsafe(Tr),i=0;do if(i=w.readSync(n,r,0,r.length,null),!e.push(r.subarray(0,i)))return!0;while(i>0);return e.end(),!0}finally{w.closeSync(n)}}async function Dr(e){let t=await jr(e);if(t===void 0)return{lineCount:0,firstLineDigest:void 0};let n={lineCount:0,firstLineDigest:void 0};try{let e=Or(e=>{n.lineCount===0&&(n.firstLineDigest=Er(e)),n.lineCount+=1}),r=Buffer.allocUnsafe(Tr);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 q(e){let t;return K(e,e=>(t=Er(e),!1)),t}function Or(e){let t=new Je(`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(Dr(a.slice(o,t),e)===!1)return r=!0,!1;o=t+1}return n=a.slice(o),!0},end(){r||Dr(`${n}${t.end()}`,e)}}}function Dr(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0)return t(n)}function Or(e){try{return C.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function kr(e){try{return await C.promises.open(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}const Ar=5242880;function jr(e=process.env){let t=e.AGENT_DEVICE_EVENT_LOG_MAX_BYTES?.trim();if(t===void 0||!/^\d+$/.test(t))return Ar;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:Ar}function J(e){return`${e}.1`}function Y(e){return`${e}.window.json`}function Mr(e){let t;for(let n=0;n<3;n+=1){let n=Z(e);try{let t=Nr(e);if(Z(e)===n)return t}catch(r){if(t=r,Z(e)===n)throw r}}throw t??X(e,`the window did not settle while reading`)}function Nr(e){let t=J(e),n=Br(e);if(n===`unverifiable`)throw X(e,`window file is invalid`);if(n===void 0)return Pr(e,t);let r=n.at(-1);if(!r)throw X(e,`window file records no generation`);let i=Ur(e),a=Fr(e,r),o=[],s=Ir({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 Pr(e,t){if(q(t)!==void 0)throw X(e,`a rotated event log exists with no window record`);return{files:Ur(e)?[{path:e,firstLineIndex:0}]:[],earliestCursor:0}}function Fr(e,t){let n=q(e);return n!==void 0&&n===t.firstLineDigest?t.firstLineIndex:t.firstLineIndex+t.lineCount}function Ir(e){let{eventLogPath:t,rotatedPath:n,sidecar:r,activeStart:i,activeExists:a}=e,o=q(n);if(o===void 0)return;let s=r.find(e=>e.firstLineDigest===o);if(!s)throw X(t,`the rotated event log matches no window record`);let c=zr(n);if(c!==s.lineCount)throw X(t,`the rotated event log holds ${c} lines, the window recorded ${s.lineCount}`);if(a&&s.firstLineIndex+s.lineCount!==i)throw X(t,`retained event log generations are not contiguous`);return s.firstLineIndex}async function Lr(e,t){let n=Wr(e);if(!n||n.size<t)return!1;let r=Br(e);if(r===`unverifiable`)return await C.promises.rename(e,J(e)),!0;let i=await Tr(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 Hr(e,(a===n?t:[...t,a]).slice(-2))}return await C.promises.rename(e,J(e)),!0}function Rr(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 X(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}, ${J(t)}, and ${Y(t)} to restart the timeline, or read the files directly.`})}function zr(e){let t=0;return K(e,()=>{t+=1}),t}function Z(e){return[Q(Y(e)),Q(e),Q(J(e))].join(`|`)}function Q(e){try{let t=C.lstatSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return`absent`}}function Br(e){let t;try{t=C.readFileSync(Y(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(Vr);return i.every(e=>e!==void 0)?i:`unverifiable`}catch{return`unverifiable`}}function Vr(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 Hr(e,t){let n=Y(e),r=`${n}.${process.pid}.tmp`;await C.promises.writeFile(r,JSON.stringify({version:2,generations:t}),`utf8`),await C.promises.rename(r,n)}function Ur(e){return Wr(e)!==void 0}function Wr(t){try{let n=C.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 $=new Map,Gr=new Set;function Kr(e){return S.join(e,`events.ndjson`)}function qr(e){return e.command!==h.events}function Jr(e,n,r){let i=t({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});Xr(e,`${JSON.stringify(i)}\n`)}async function Yr(e){await(e?$.get(e):Promise.all($.values()))}function Xr(e,t){let n=($.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await Zr(e),await Lr(e,jr()),await C.promises.appendFile(e,t,`utf8`)}).catch(t=>{y({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{$.get(e)===n&&$.delete(e)});$.set(e,n)}async function Zr(e){let t=S.dirname(e);if(!Gr.has(t))try{await C.promises.mkdir(t,{recursive:!0}),Gr.add(t)}catch(t){throw y({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function Qr(e,t,n){Jr(e,t,{kind:`action.recorded`,requestId:v().requestId,command:n.command,summary:Gn(n),details:Kn(n)})}function $r(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??v().requestId,command:t.command,summary:`Started ${t.command}`}}function ei(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=$t(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??v().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??v().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 ti(e,t={}){let n=ri(t.cursor),r=ii(t.limit),i=Mr(e);Rr(n,i.earliestCursor);let a=ni(i.files,n,r),o=a.lines.flatMap(e=>{let t=ai(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:o,...a.nextCursor===void 0?{}:{nextCursor:String(a.nextCursor)}}}function ni(e,t,n){let r=[],i;for(let a of e){let e=a.firstLineIndex;if(K(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 ri(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 ii(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 ai(e){try{let t=oi(JSON.parse(e));return t?si(t):void 0}catch{return}}function oi(e){if(n(e)&&e.version===1&&typeof e.ts==`string`&&typeof e.session==`string`&&ci(e.kind))return e}function si(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}:{},...li(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function ci(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function li(e){return e===`ok`||e===`error`}const ui=36e5;var di=class{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new At(e)}get(e){return this.sessions.get(e)}set(e,t){this.sessions.set(e,t)}delete(e){return this.runtimeHints.delete(e),this.sessions.delete(e)}values(){return this.sessions.values()}toArray(){return Array.from(this.sessions.values())}lookup(e){let t=this.sessions.get(e);return t?{address:e,session:t}:void 0}findByDevice(e){for(let[t,n]of this.sessions)if(n.device.id===e)return{address:t,session:n}}listRefs(){return Array.from(this.sessions,([e,t])=>({address:e,session:t}))}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){this.runtimeHints.set(e,t)}clearRuntimeHints(e){return this.runtimeHints.delete(e)}recordAction(e,t){let n=ot(e,t);if(n){let t=this.resolveStoredSessionName(e);Qr(this.resolveEventLogPath(t),t,n)}}recordEvent(e,t){Jr(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return ti(this.resolveEventLogPath(e),t)}async flushEvents(e){await Yr(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.scriptWriter.write(e,t);return n.written&&y({level:`info`,phase:`session_script_written`,data:{session:e.name,path:n.path}}),n}finalizeRepairTeardown(e){this.recordRepairFinalizeCloseIfCommitting(e);let t=this.writeSessionLog(e,{force:ke(e,void 0)});it(e)&&(!t.written&&t.error?this.writeRepairTombstone(e,ui,{code:String(t.error.code),message:t.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){let t=e.scriptPublication??m;Se(t)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:e.name,...ze(`Closed: ${e.name}`)}})}writeRepairTombstone(e,t=ui,n){try{let r=this.resolveSessionDir(e.name);C.mkdirSync(r,{recursive:!0});let i={owner:e.name,reapedAt:Date.now(),expiresAt:Date.now()+t,...at(e)?{sourcePath:at(e)}:{},...n?{commitFailure:n}:{}};C.writeFileSync(this.repairTombstonePath(e.name),`${JSON.stringify(i)}\n`)}catch(t){y({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.name,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return Ue(this.repairTombstonePath(e))}clearRepairTombstone(e){try{C.rmSync(this.repairTombstonePath(e),{force:!0})}catch{}}repairTombstonePath(e){return We(this.resolveSessionDir(e))}defaultTracePath(e){let t=b(e.name),n=new Date().toISOString().replaceAll(/[:.]/g,`-`);return S.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(t){if(!Ge(t))throw new e(`INVALID_ARGS`,`Invalid session name ${JSON.stringify(t)}: a session name cannot be empty, ".", or "..".`);return S.join(this.sessionsDir,b(t))}resolveDaemonStateDir(){return S.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return C.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return S.join(this.resolveSessionDir(e),`app.log`)}resolveAppLogPidPath(e){return S.join(this.resolveSessionDir(e),`app-log.pid`)}resolveEventLogPath(e){return Kr(this.resolveSessionDir(e))}static expandHome(e,t){return x(e,t)}resolveStoredSessionName(e){for(let[t,n]of this.sessions)if(n===e)return t;return e.name}};export{Qe as _,tr as a,st as c,nt as d,rt as f,T as g,et as h,qr as i,tt as l,$e as m,ei as n,Sn as o,it as p,$r as r,ht as s,di as t,Ze as u};
4
+ `,o)){if(kr(a.slice(o,t),e)===!1)return r=!0,!1;o=t+1}return n=a.slice(o),!0},end(){r||kr(`${n}${t.end()}`,e)}}}function kr(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0)return t(n)}function Ar(e){try{return w.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function jr(e){try{return await w.promises.open(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}const Mr=5242880;function Nr(e=process.env){let t=e.AGENT_DEVICE_EVENT_LOG_MAX_BYTES?.trim();if(t===void 0||!/^\d+$/.test(t))return Mr;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:Mr}function J(e){return`${e}.1`}function Y(e){return`${e}.window.json`}function Pr(e){let t;for(let n=0;n<3;n+=1){let n=Z(e);try{let t=Fr(e);if(Z(e)===n)return t}catch(r){if(t=r,Z(e)===n)throw r}}throw t??X(e,`the window did not settle while reading`)}function Fr(e){let t=J(e),n=Hr(e);if(n===`unverifiable`)throw X(e,`window file is invalid`);if(n===void 0)return Ir(e,t);let r=n.at(-1);if(!r)throw X(e,`window file records no generation`);let i=Gr(e),a=Lr(e,r),o=[],s=Rr({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 Ir(e,t){if(q(t)!==void 0)throw X(e,`a rotated event log exists with no window record`);return{files:Gr(e)?[{path:e,firstLineIndex:0}]:[],earliestCursor:0}}function Lr(e,t){let n=q(e);return n!==void 0&&n===t.firstLineDigest?t.firstLineIndex:t.firstLineIndex+t.lineCount}function Rr(e){let{eventLogPath:t,rotatedPath:n,sidecar:r,activeStart:i,activeExists:a}=e,o=q(n);if(o===void 0)return;let s=r.find(e=>e.firstLineDigest===o);if(!s)throw X(t,`the rotated event log matches no window record`);let c=Vr(n);if(c!==s.lineCount)throw X(t,`the rotated event log holds ${c} lines, the window recorded ${s.lineCount}`);if(a&&s.firstLineIndex+s.lineCount!==i)throw X(t,`retained event log generations are not contiguous`);return s.firstLineIndex}async function zr(e,t){let n=Kr(e);if(!n||n.size<t)return!1;let r=Hr(e);if(r===`unverifiable`)return await w.promises.rename(e,J(e)),!0;let i=await Dr(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 Wr(e,(a===n?t:[...t,a]).slice(-2))}return await w.promises.rename(e,J(e)),!0}function Br(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 X(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}, ${J(t)}, and ${Y(t)} to restart the timeline, or read the files directly.`})}function Vr(e){let t=0;return K(e,()=>{t+=1}),t}function Z(e){return[Q(Y(e)),Q(e),Q(J(e))].join(`|`)}function Q(e){try{let t=w.lstatSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return`absent`}}function Hr(e){let t;try{t=w.readFileSync(Y(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(Ur);return i.every(e=>e!==void 0)?i:`unverifiable`}catch{return`unverifiable`}}function Ur(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 Wr(e,t){let n=Y(e),r=`${n}.${process.pid}.tmp`;await w.promises.writeFile(r,JSON.stringify({version:2,generations:t}),`utf8`),await w.promises.rename(r,n)}function Gr(e){return Kr(e)!==void 0}function Kr(t){try{let n=w.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 $=new Map,qr=new Set;function Jr(e){return C.join(e,`events.ndjson`)}function Yr(e){return e.command!==h.events}function Xr(e,n,r){let i=t({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});Qr(e,`${JSON.stringify(i)}\n`)}async function Zr(e){await(e?$.get(e):Promise.all($.values()))}function Qr(e,t){let n=($.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await $r(e),await zr(e,Nr()),await w.promises.appendFile(e,t,`utf8`)}).catch(t=>{b({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{$.get(e)===n&&$.delete(e)});$.set(e,n)}async function $r(e){let t=C.dirname(e);if(!qr.has(t))try{await w.promises.mkdir(t,{recursive:!0}),qr.add(t)}catch(t){throw b({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function ei(e,t,n){Xr(e,t,{kind:`action.recorded`,requestId:y().requestId,command:n.command,summary:qn(n),details:Jn(n)})}function ti(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??y().requestId,command:t.command,summary:`Started ${t.command}`}}function ni(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=$t(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??y().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??y().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 ri(e,t={}){let n=ai(t.cursor),r=oi(t.limit),i=Pr(e);Br(n,i.earliestCursor);let a=ii(i.files,n,r),o=a.lines.flatMap(e=>{let t=si(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:o,...a.nextCursor===void 0?{}:{nextCursor:String(a.nextCursor)}}}function ii(e,t,n){let r=[],i;for(let a of e){let e=a.firstLineIndex;if(K(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 ai(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 oi(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 si(e){try{let t=ci(JSON.parse(e));return t?li(t):void 0}catch{return}}function ci(e){if(n(e)&&e.version===1&&typeof e.ts==`string`&&typeof e.session==`string`&&ui(e.kind))return e}function li(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}:{},...di(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function ui(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function di(e){return e===`ok`||e===`error`}const fi=36e5;var pi=class{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new At(e)}get(e){return this.sessions.get(e)}set(e,t){this.sessions.set(e,t)}delete(e){return this.runtimeHints.delete(e),this.sessions.delete(e)}values(){return this.sessions.values()}toArray(){return Array.from(this.sessions.values())}lookup(e){let t=this.sessions.get(e);return t?{address:e,session:t}:void 0}findByDevice(e){for(let[t,n]of this.sessions)if(n.device.id===e)return{address:t,session:n}}listRefs(){return Array.from(this.sessions,([e,t])=>({address:e,session:t}))}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){this.runtimeHints.set(e,t)}clearRuntimeHints(e){return this.runtimeHints.delete(e)}recordAction(e,t){let n=ot(e,t);if(n){let t=this.resolveStoredSessionName(e);ei(this.resolveEventLogPath(t),t,n)}}recordEvent(e,t){Xr(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return ri(this.resolveEventLogPath(e),t)}async flushEvents(e){await Zr(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.scriptWriter.write(e,t);return n.written&&b({level:`info`,phase:`session_script_written`,data:{session:e.name,path:n.path}}),n}finalizeRepairTeardown(e){this.recordRepairFinalizeCloseIfCommitting(e);let t=this.writeSessionLog(e,{force:De(e,void 0)});it(e)&&(!t.written&&t.error?this.writeRepairTombstone(e,fi,{code:String(t.error.code),message:t.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){let t=e.scriptPublication??m;be(t)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:e.name,...ze(`Closed: ${e.name}`)}})}writeRepairTombstone(e,t=fi,n){try{let r=this.resolveSessionDir(e.name);w.mkdirSync(r,{recursive:!0});let i={owner:e.name,reapedAt:Date.now(),expiresAt:Date.now()+t,...at(e)?{sourcePath:at(e)}:{},...n?{commitFailure:n}:{}};w.writeFileSync(this.repairTombstonePath(e.name),`${JSON.stringify(i)}\n`)}catch(t){b({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.name,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return Ue(this.repairTombstonePath(e))}clearRepairTombstone(e){try{w.rmSync(this.repairTombstonePath(e),{force:!0})}catch{}}repairTombstonePath(e){return We(this.resolveSessionDir(e))}defaultTracePath(e){let t=x(e.name),n=new Date().toISOString().replaceAll(/[:.]/g,`-`);return C.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(t){if(!Ge(t))throw new e(`INVALID_ARGS`,`Invalid session name ${JSON.stringify(t)}: a session name cannot be empty, ".", or "..".`);return C.join(this.sessionsDir,x(t))}resolveDaemonStateDir(){return C.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return w.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return C.join(this.resolveSessionDir(e),`app.log`)}resolveAppLogPidPath(e){return C.join(this.resolveSessionDir(e),`app-log.pid`)}resolveEventLogPath(e){return Jr(this.resolveSessionDir(e))}static expandHome(e,t){return S(e,t)}resolveStoredSessionName(e){for(let[t,n]of this.sessions)if(n===e)return t;return e.name}};export{Qe as _,rr as a,st as c,nt as d,rt as f,E as g,et as h,Yr as i,tt as l,$e as m,ni as n,Cn as o,it as p,ti as r,ht as s,pi as t,Ze as u};