agent-device 0.21.2 → 0.21.4

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 (164) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.2.apk → agent-device-android-ime-helper-0.21.4.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.4.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.2.manifest.json → agent-device-android-ime-helper-0.21.4.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.2.apk → agent-device-android-snapshot-helper-0.21.4.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.4.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.4.manifest.json +16 -0
  7. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +39 -0
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSystemSurfaceHostPolicy.swift +9 -1
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +2 -1
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +10 -1
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +26 -124
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +46 -0
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +36 -4
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+MainThreadWork.swift +229 -0
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +15 -0
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +4 -40
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +6 -40
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +30 -9
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +22 -6
  20. package/dist/src/adapter.js +1 -1
  21. package/dist/src/adb-executor.js +2 -2
  22. package/dist/src/adb-failure.js +1 -1
  23. package/dist/src/agent-browser-process-record.js +1 -1
  24. package/dist/src/agent-device-client.js +2 -2
  25. package/dist/src/api.js +3 -11
  26. package/dist/src/app-launch.js +1 -1
  27. package/dist/src/app-lifecycle.js +1 -1
  28. package/dist/src/app-log-reconnect.js +1 -1
  29. package/dist/src/archive.js +2 -2
  30. package/dist/src/auth.js +1 -1
  31. package/dist/src/back-mode.js +1 -1
  32. package/dist/src/cli-help.js +2 -2
  33. package/dist/src/cli.js +4 -4
  34. package/dist/src/client-metro-companion.js +1 -1
  35. package/dist/src/client-metro.js +1 -1
  36. package/dist/src/client-types.d.ts +70 -5
  37. package/dist/src/code-signature-cache.js +1 -1
  38. package/dist/src/command-schema.js +1 -1
  39. package/dist/src/command-tools.js +2 -2
  40. package/dist/src/command.js +1 -1
  41. package/dist/src/config.js +1 -1
  42. package/dist/src/connection-runtime.js +1 -1
  43. package/dist/src/connection.js +1 -1
  44. package/dist/src/contracts.js +1 -1
  45. package/dist/src/daemon-client-lifecycle.js +1 -1
  46. package/dist/src/daemon-registration.js +1 -1
  47. package/dist/src/daemon-resolution.js +1 -0
  48. package/dist/src/daemon-shutdown-report.js +1 -1
  49. package/dist/src/daemon.js +1 -1
  50. package/dist/src/device-claim-rule.js +1 -1
  51. package/dist/src/device-input-state.d.ts +10 -8
  52. package/dist/src/device-inventory-context.js +1 -1
  53. package/dist/src/device-session.js +1 -1
  54. package/dist/src/diagnostics.js +1 -1
  55. package/dist/src/error.js +2 -2
  56. package/dist/src/exec.js +1 -1
  57. package/dist/src/file.js +1 -1
  58. package/dist/src/find.js +1 -1
  59. package/dist/src/gesture-runtime.js +1 -1
  60. package/dist/src/harmonyos.js +1 -1
  61. package/dist/src/helper.js +1 -1
  62. package/dist/src/human-control-contract.js +1 -1
  63. package/dist/src/human-control.js +1 -1
  64. package/dist/src/index.js +1 -1
  65. package/dist/src/install-source-network-transport.js +1 -1
  66. package/dist/src/interaction.js +1 -1
  67. package/dist/src/interaction2.js +1 -1
  68. package/dist/src/interactor.js +4 -4
  69. package/dist/src/interactors.js +1 -1
  70. package/dist/src/internal/bin.js +1 -1
  71. package/dist/src/internal/daemon.js +2 -2
  72. package/dist/src/internal/png-worker.js +1 -1
  73. package/dist/src/ios-client.js +121 -7
  74. package/dist/src/ios-snapshot-adapter.js +1 -1
  75. package/dist/src/ios-system-surface.js +1 -1
  76. package/dist/src/lease-scope.js +1 -1
  77. package/dist/src/limrun-delta-sync-omitted.js +1 -0
  78. package/dist/src/limrun.d.ts +0 -1598
  79. package/dist/src/location-coordinates.js +1 -1
  80. package/dist/src/mechanics.js +16 -16
  81. package/dist/src/output-common.js +2 -0
  82. package/dist/src/owner-identity.js +1 -1
  83. package/dist/src/perf-runtime-operation-builder.js +1 -1
  84. package/dist/src/perf-runtime-plan.js +1 -1
  85. package/dist/src/physical-device-control.js +1 -1
  86. package/dist/src/platform-request-scope.js +1 -1
  87. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  88. package/dist/src/platform-runtime-app-log-android-transport.js +1 -1
  89. package/dist/src/platform-runtime-app-log-process.js +1 -1
  90. package/dist/src/platform-runtime-host.js +1 -1
  91. package/dist/src/platform-runtime-operation-host.js +2 -2
  92. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  93. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  94. package/dist/src/platform-runtime-screen-recording-harmony-host.js +1 -1
  95. package/dist/src/platform-runtime-screen-recording-output-host.js +1 -1
  96. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  97. package/dist/src/platform-runtime.js +1 -1
  98. package/dist/src/process.js +1 -1
  99. package/dist/src/provider-webdriver.js +1 -1
  100. package/dist/src/proxy.js +1 -1
  101. package/dist/src/quality-warnings.js +1 -1
  102. package/dist/src/react-native.js +1 -1
  103. package/dist/src/record-runtime.js +1 -1
  104. package/dist/src/recording-stop-observation.js +1 -0
  105. package/dist/src/register-builtins.js +1 -1
  106. package/dist/src/registry.js +35 -36
  107. package/dist/src/replay-divergence.js +1 -1
  108. package/dist/src/reporting.js +11 -9
  109. package/dist/src/request-providers.js +1 -1
  110. package/dist/src/result-serialization.js +1 -1
  111. package/dist/src/runner-cache-metadata.js +2 -2
  112. package/dist/src/runner-client.js +1 -1
  113. package/dist/src/runner-disposal.js +1 -1
  114. package/dist/src/runner-operations-facade.js +1 -1
  115. package/dist/src/runner.js +1 -1
  116. package/dist/src/runtime.js +3 -3
  117. package/dist/src/runtime10.js +1 -1
  118. package/dist/src/runtime2.js +4 -4
  119. package/dist/src/runtime3.js +1 -1
  120. package/dist/src/runtime4.js +5 -5
  121. package/dist/src/runtime5.js +1 -1
  122. package/dist/src/runtime6.js +1 -1
  123. package/dist/src/runtime9.js +1 -1
  124. package/dist/src/screen-recording-completion.js +1 -1
  125. package/dist/src/screen-recording-resource-recovery.js +1 -1
  126. package/dist/src/screen-recording-runtime.js +1 -1
  127. package/dist/src/screenshot-result.js +1 -1
  128. package/dist/src/screenshot-runtime.js +1 -1
  129. package/dist/src/sdk-batch.js +2 -2
  130. package/dist/src/sdk-contracts.js +2 -2
  131. package/dist/src/sdk-remote-config.d.ts +1 -0
  132. package/dist/src/sdk-remote-config.js +1 -1
  133. package/dist/src/sdk-selectors.d.ts +36 -24
  134. package/dist/src/selector-runtime.js +1 -1
  135. package/dist/src/session-observation.js +1 -1
  136. package/dist/src/session-routing.js +1 -1
  137. package/dist/src/session-snapshot.js +1 -1
  138. package/dist/src/session-store.js +2 -2
  139. package/dist/src/session2.js +5 -5
  140. package/dist/src/simulator.js +1 -1
  141. package/dist/src/snapshot-runtime-binding.js +1 -1
  142. package/dist/src/snapshot-runtime.js +1 -1
  143. package/dist/src/snapshot.js +1 -1
  144. package/dist/src/snapshot4.js +1 -1
  145. package/dist/src/src3.js +1 -1
  146. package/dist/src/src4.js +1 -1
  147. package/dist/src/stop-sequence.js +1 -0
  148. package/dist/src/success-text.js +1 -1
  149. package/dist/src/text-entry-focus.js +1 -0
  150. package/dist/src/tool-provider.js +1 -1
  151. package/dist/src/tool-provider2.js +1 -1
  152. package/dist/src/tool-provider3.js +1 -1
  153. package/dist/src/type-text-runtime.js +1 -1
  154. package/dist/src/video.js +2 -2
  155. package/dist/src/yauzl.js +1 -0
  156. package/package.json +2 -2
  157. package/server.json +2 -2
  158. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.2.apk.sha256 +0 -1
  159. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk.sha256 +0 -1
  160. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.manifest.json +0 -17
  161. package/dist/src/audio-probe-support.js +0 -1
  162. package/dist/src/config2.js +0 -1
  163. package/dist/src/provider-device-runtime.js +0 -1
  164. package/dist/src/screen-recording-live-handle.js +0 -1
@@ -1 +1 @@
1
- import{C as e,T as t,o as n,w as r}from"./sdk-contracts.js";import"./capture.js";import{r as i}from"./sdk-batch-runner.js";import{p as a}from"./android-input-ownership.js";import{_ as o,c as s,l as c,m as l,o as u,v as d}from"./sdk-device.js";import{d as f,l as p,n as m,r as h}from"./lease-scope.js";import{Mr as ee,Sr as te,Tr as ne,Wt as re,Xt as ie,Yt as g,tr as ae,zr as _}from"./sdk-batch.js";import{a as oe,n as se,r as ce}from"./script.js";import"./session-store.js";import{r as le}from"./format.js";import{r as v}from"./diagnostics.js";import"./diagnostics2.js";import{r as y}from"./command.js";import{a as ue,t as de}from"./config.js";import{n as b}from"./runtime-transport-hints.js";import{n as fe,t as pe,u as me}from"./provider-session-ownership.js";import{a as he,c as ge,d as x,f as _e,g as ve,h as ye,i as be,l as xe,m as Se,n as S,o as Ce,p as we,r as Te,s as C,u as Ee}from"./human-control-contract.js";import{i as w}from"./request-runtime-binding.js";import{r as De}from"./application-lifecycle-runtime.js";import{a as Oe,c as T,l as ke,n as Ae,o as je,r as Me,t as Ne}from"./device-claim-inspection.js";import{b as Pe,c as Fe,g as Ie,i as Le,p as Re,x as E}from"./perf-runtime-plan.js";import{n as ze,r as Be,t as Ve}from"./lease-context.js";import{h as He,l as Ue,u as We}from"./screenshot-runtime.js";import{t as Ge}from"./device-isolation.js";import{a as Ke,c as qe,d as D,l as Je,n as Ye,o as Xe,r as Ze,u as O}from"./src8.js";import{n as Qe,t as $e}from"./compatibility-policy.js";import{o as et}from"./screen-recording-resource-recovery.js";import k from"node:path";import"node:fs";import tt,{createHash as nt}from"node:crypto";import rt from"node:os";import A from"node:fs/promises";function it(t,n){if(n?.replayBackend&&n.replayBackend!==`maestro`)throw new e(`INVALID_ARGS`,`Unsupported replay backend "${n.replayBackend}".`);return{...se(t),metadata:ce(t)}}function at(e,t){return j(e,t)?t:`${e}:${t}`}function j(e,t){return t.startsWith(`${e}:`)}function ot(e,t){return!e.partitioned||j(e.tenant,t)}var st=class{active=new Map;waiters=new Map;async run(e,t){this.active.set(e,(this.active.get(e)??0)+1);try{return await t()}finally{let t=(this.active.get(e)??1)-1;if(t>0)this.active.set(e,t);else{this.active.delete(e);let t=this.waiters.get(e);this.waiters.delete(e);for(let e of t??[])e()}}}async wait(e,t){if(t?.throwIfAborted(),!this.active.has(e))return;let n=this.waiters.get(e)??new Set,r=()=>{},i=()=>{};try{await new Promise((a,o)=>{r=a,i=()=>o(t?.reason),n.add(r),this.waiters.set(e,n),t?.addEventListener(`abort`,i,{once:!0})})}finally{t?.removeEventListener(`abort`,i),n.delete(r),n.size===0&&this.waiters.get(e)===n&&this.waiters.delete(e)}}},ct=class{entriesByLeaseId=new Map;retain(e,t){let n={wanted:t,released:!1},r=this.entriesByLeaseId.get(e)??new Set;return r.add(n),this.entriesByLeaseId.set(e,r),{leaseId:e,release:()=>this.releasePass(e,r,n)}}forget(e){let t=this.entriesByLeaseId.get(e);if(t){for(let e of t)e.released=!0;this.entriesByLeaseId.delete(e)}}isDeferred(e){let t=this.entriesByLeaseId.get(e);if(!t)return!1;for(let e of t)e.wanted()||t.delete(e);return t.size>0||(this.entriesByLeaseId.delete(e),!1)}releasePass(e,t,n){return!n.released&&(n.released=!0,t.delete(n),t.size===0&&this.entriesByLeaseId.delete(e),n.wanted())}},lt=class{holdsByDevice=new Map;mutations=new st;inFlightWork=new ct;leases=new Map;runBindings=new Map;deviceBindings=new Map;maxActiveSimulatorLeases;resolveLeaseTtlMs;now;onLeaseExpired;providerSessionOwnership;constructor(e={}){this.maxActiveSimulatorLeases=Number.isInteger(e.maxActiveSimulatorLeases)?Math.max(0,Number(e.maxActiveSimulatorLeases)):0,this.resolveLeaseTtlMs=xe(e),this.now=e.now??(()=>Date.now()),this.onLeaseExpired=e.onLeaseExpired,this.providerSessionOwnership=new pe({now:this.now,retentionMs:e.providerSessionRetentionMs})}allocateLease(e){let t=we(e);this.cleanupExpiredLeases();let n=this.resolveLeaseTtlMs(t.ttlMs);this.assertHumanControlAdmission(t);let r=this.refreshExistingRunBinding(t,n);if(r)return r;this.assertDeviceAvailable(t),this.enforceCapacity(t.backend);let i=ge(t,n,this.now());return this.leases.set(i.leaseId,i),this.bindLease(i),{...i}}refreshExistingRunBinding(e,t){let n=_e(e),r=this.runBindings.get(n);if(!r)return;let i=this.leases.get(r);if(!i){this.runBindings.delete(n);return}if(i.clientId===e.clientId)return this.refreshLease(i,t);if(i.deviceKey)throw Ee(i);return C(i,e),this.refreshLease(i,t)}heartbeatLease(e){let t=ve(e.leaseId);this.cleanupExpiredLeases();let n=this.getActiveLease(t);Ce(n,e),C(n,e);let r=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(n,r)}retainLeaseWork(e,t){let n=this.inFlightWork.retain(e.leaseId,t);return{leaseId:n.leaseId,release:()=>{let t=n.release();return t&&this.refreshProtectedLease(e.leaseId,this.now()),t}}}releaseLease(e){let t=this.getLease(e);return t?(this.leases.delete(t.leaseId),this.unbindLease(t),this.inFlightWork.forget(t.leaseId),{released:!0,lease:t}):{released:!1}}getLease(e){let t=ve(e.leaseId);this.cleanupExpiredLeases();let n=this.leases.get(t);if(n)return Ce(n,e),C(n,e),{...n}}assertLeaseAdmission(e){let t=Se(e);this.cleanupExpiredLeases(),C(this.getActiveLease(t.leaseId),t)}listActiveLeases(){return this.cleanupExpiredLeases(),Array.from(this.leases.values()).map(e=>({...e}))}recordProviderSession(e,t){this.cleanupExpiredLeases();let n=e.expiresAt<=this.now()?e.expiresAt:void 0;this.providerSessionOwnership.record(e,t),this.leases.has(e.leaseId)||this.providerSessionOwnership.markLeaseReleased(e,n)}resolveProviderSession(e){return this.cleanupExpiredLeases(),this.providerSessionOwnership.resolve(e)}listHumanControlHolds(e){this.cleanupExpiredLeases();let t=e.kind===`lease`?x(this.requireHumanControlLease(e.leaseId)):void 0;return[...this.holdsByDevice.entries()].filter(([e])=>t===void 0||t===e).flatMap(([,e])=>[...e.values()].map(({hold:e})=>S(e))).sort((e,t)=>e.id.localeCompare(t.id))}async putHumanControlHold(t,n,r,i){i?.throwIfAborted();let a=be(n),o=he(r);this.cleanupExpiredLeases();let s=this.resolveHumanControlScope(t,o),c=x(s),l=this.findHumanControlHold(a);if(l&&(this.assertHoldAuthority(t,l),x(l.hold.scope)!==c))throw new e(`INVALID_ARGS`,`Release a hold before changing its device scope.`);let u=this.now(),d={...t.kind===`lease`?{ownerLeaseId:t.leaseId}:{},hold:{id:a,scope:s,state:`activating`,...o.reason?{reason:o.reason}:{},createdAt:l?.hold.createdAt??u,updatedAt:u}},f=this.holdsByDevice.get(c)??new Map;return this.holdsByDevice.set(c,f),f.set(a,d),await this.activateHumanControlHold(c,d,o.ttlMs,i)}async activateHumanControlHold(t,n,r,i){let a=this.holdsByDevice.get(t),{id:o}=n.hold;try{if(await this.mutations.wait(t,i),i?.throwIfAborted(),a.get(o)!==n)throw new e(`COMMAND_FAILED`,`Human-control hold changed before activation completed.`,{holdId:o});let s=this.now();return n.hold={...n.hold,state:`active`,updatedAt:s,...r===void 0?{}:{expiresAt:s+r}},this.refreshHeldLease(t,s),S(n.hold)}catch(e){throw a.get(o)===n&&this.deleteHumanControlHold(t,o),e}}removeHumanControlHold(e,t){let n=be(t);this.cleanupExpiredLeases();let r=this.findHumanControlHold(n);if(!r)return;this.assertHoldAuthority(e,r);let i=x(r.hold.scope);return this.deleteHumanControlHold(i,n),S(r.hold)}deleteHumanControlHold(e,t){let n=this.holdsByDevice.get(e);n.delete(t),n.size===0&&(this.holdsByDevice.delete(e),this.refreshHeldLease(e,this.now()))}assertHumanControlAdmission(e){this.expireHumanControlHolds();let t=x(e),n=t===void 0?void 0:this.holdsByDevice.get(t)?.values().next().value;if(n)throw Te(n.hold)}async runDeviceMutation(e,t){if(!e)return await t();this.cleanupExpiredLeases();let n=this.getActiveLease(e.leaseId);this.assertHumanControlAdmission(n);let r=x(n);return r===void 0?await t():await this.mutations.run(r,t)}requireHumanControlLease(t){let n=this.getActiveLease(t);if(!n.deviceKey)throw new e(`UNSUPPORTED_OPERATION`,`Human control requires a device-scoped remote lease.`);return{...n,deviceKey:n.deviceKey}}resolveHumanControlScope(t,n){if(t.kind===`host`){if(!n.scope)throw new e(`INVALID_ARGS`,`Host human control requires a lease device scope.`);return n.scope}if(n.scope)throw new e(`INVALID_ARGS`,`Lease-owner human control uses the admitted lease device; do not supply scope.`);let r=this.requireHumanControlLease(t.leaseId);return{backend:r.backend,leaseProvider:r.leaseProvider,deviceKey:r.deviceKey}}assertHoldAuthority(t,n){if(t.kind===`host`)return;let r=this.requireHumanControlLease(t.leaseId);if(n.ownerLeaseId!==r.leaseId||x(r)!==x(n.hold.scope))throw new e(`UNAUTHORIZED`,`Human-control hold does not belong to the admitted lease.`,{reason:`LEASE_SCOPE_MISMATCH`})}findHumanControlHold(e){for(let t of this.holdsByDevice.values()){let n=t.get(e);if(n)return n}}hasHumanControl(e){let t=x(e);return t!==void 0&&this.holdsByDevice.has(t)}isLeaseProtected(e,t){return e.expiresAt>t||this.hasHumanControl(e)||this.inFlightWork.isDeferred(e.leaseId)}expireHumanControlHolds(){let e=this.now();for(let[t,n]of this.holdsByDevice){let r=0;for(let[t,{hold:i}]of n)i.expiresAt===void 0||i.expiresAt>e||(r=Math.max(r,i.expiresAt),n.delete(t));n.size===0&&(this.holdsByDevice.delete(t),this.refreshHeldLease(t,r))}}refreshHeldLease(e,t){this.refreshProtectedLease(this.deviceBindings.get(e),t)}refreshProtectedLease(e,t){let n=e?this.leases.get(e):void 0;n&&this.refreshLease(n,n.expiresAt-n.heartbeatAt,Math.max(t,n.heartbeatAt))}consumeExpiredLeases(){this.expireHumanControlHolds();let e=this.now(),t=[];for(let n of this.leases.values()){if(this.isLeaseProtected(n,e))continue;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};t.push(r),this.onLeaseExpired?.(r)}return t}consumeExpiredLease(e){this.expireHumanControlHolds();let t=ye(e);if(!t)return;let n=this.leases.get(t);if(!n||this.isLeaseProtected(n,this.now()))return;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};return this.onLeaseExpired?.(r),r}cleanupExpiredLeases(){this.consumeExpiredLeases()}enforceCapacity(t){if(t!==`ios-simulator`||this.maxActiveSimulatorLeases<=0)return;let n=Array.from(this.leases.values()).filter(e=>e.backend===`ios-simulator`).length;if(!(n<this.maxActiveSimulatorLeases))throw new e(`DEVICE_IN_USE`,`No simulator lease capacity available`,{reason:`LEASE_CAPACITY_EXCEEDED`,activeLeases:n,maxActiveLeases:this.maxActiveSimulatorLeases,backend:t,hint:`Retry after releasing another simulator lease.`})}getActiveLease(t){let n=this.leases.get(t);if(n)return n;throw new e(`UNAUTHORIZED`,`Lease is not active`,{reason:`LEASE_NOT_FOUND`})}refreshLease(e,t,n=this.now()){let r={...e,heartbeatAt:n,expiresAt:n+t};return this.leases.set(r.leaseId,r),this.bindLease(r),{...r}}bindLease(e){this.runBindings.set(_e(e),e.leaseId);let t=x(e);t&&this.deviceBindings.set(t,e.leaseId)}unbindLease(e,t=this.now()){this.runBindings.delete(_e(e));let n=x(e);n&&this.deviceBindings.delete(n),this.providerSessionOwnership.markLeaseReleased(e,t)}assertDeviceAvailable(e){let t=x({backend:e.backend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey});if(!t)return;let n=this.deviceBindings.get(t);if(!n)return;let r=this.leases.get(n);if(!r){this.deviceBindings.delete(t);return}throw Ee(r)}};function ut(t){let n=ue(t.meta?.sessionIsolation??t.flags?.sessionIsolation),r=t.meta?.tenantId??t.flags?.tenant,i=de(r);if(r&&!i)throw new e(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);if(n!==`tenant`)return t;if(!i)throw new e(`INVALID_ARGS`,`session isolation mode tenant requires --tenant (or meta.tenantId).`);let a=t.session||`default`;return j(i,a)?{...t,meta:{...t.meta,tenantId:i,sessionIsolation:n}}:{...t,session:at(i,a),meta:{...t.meta,tenantId:i,sessionIsolation:n}}}function dt(t,n,r,i={}){if(We(t.command))return;let a=ze(t);mt(t,a);let o=r?.lease;if(r===void 0&&!a.leaseId&&ft(t,i.providerAppCatalog))return;if(t.command===`human_control`&&!o&&!a.leaseId)throw new e(`UNSUPPORTED_OPERATION`,`Takeover requires an active remote device lease. Local takeover is not supported.`);if(t.command!==`human_control`&&!o&&t.meta?.sessionIsolation!==`tenant`&&(!a.leaseId||!a.tenantId&&!a.runId))return;ht(a,o);let s=Be(t,r),c={...s,leaseTtlMs:s.leaseTtlMs??(h(s)?3e5:void 0)};n.assertLeaseAdmission(p(s));let l=n.heartbeatLease(p(c));return Ue(t)&&n.assertHumanControlAdmission(l),l}function ft(e,t){let n=He(e);return n?.kind===`unconditional`||n?.kind===`provider-app-catalog`&&t?.supports(n.provider)===!0}function pt(e){We(e.command)||mt(e,ze(e))}function mt(t,n){if(t.command!==`open`)return;let r=m(n);if(r.length!==0)throw new e(`INVALID_ARGS`,`Proxy open requires leaseId, tenantId, runId, clientId, and deviceKey lease metadata.`,{missing:r})}function ht(e,t){t&&(M(`leaseId`,e.leaseId,t.leaseId),M(`tenantId`,e.tenantId,t.tenantId),M(`runId`,e.runId,t.runId),M(`leaseProvider`,e.leaseProvider,t.leaseProvider),M(`clientId`,e.clientId,t.clientId),M(`deviceKey`,e.deviceKey,t.deviceKey))}function M(t,n,r){if(!(!n||!r||n===r))throw new e(`UNAUTHORIZED`,`Lease does not match session owner (${t})`,{reason:`LEASE_SESSION_MISMATCH`,field:t})}async function gt(e,t){if(!t.leaseProvider||!e)return!1;try{return await e(t),v({level:`info`,phase:`provider_lease_expired_released`,data:{leaseId:t.leaseId,provider:t.leaseProvider}}),!0}catch(e){return v({level:`error`,phase:`provider_lease_expiry_release_failed`,data:{leaseId:t.leaseId,provider:t.leaseProvider,error:e instanceof Error?e.message:String(e)}}),!1}}function _t(e){pt(e)}async function vt(e){let t=e.sessionStore.get(e.sessionName),n=t?.lease;return!t||!n||!e.leaseRegistry.consumeExpiredLease(n.leaseId)?!1:(v({level:`info`,phase:`leased_session_expired`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,deviceKey:n.deviceKey}}),await e.teardownSession(t,t.name).catch(e=>{v({level:`debug`,phase:`leased_session_expiry_cleanup_failed`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,error:e instanceof Error?e.message:String(e)}})}),await Pe(t.deviceClaim).catch(e=>{v({level:`warn`,phase:`leased_session_expiry_device_claim_clear_failed`,data:{session:t.name,deviceKey:t.deviceClaim?.deviceKey,error:e instanceof Error?e.message:String(e)}})}),e.sessionStore.delete(t.name),!0)}function yt(e){let{sessionName:t,sessionStore:n,leaseRegistry:r}=e,i=n.get(t),a=dt(e.req,r,i,{providerAppCatalog:e.providerAppCatalog});if(!a)return e.req;let o={...e.req,internal:{...e.req.internal,admittedLease:a}};return i?.lease&&n.set(t,{...i,lease:{...i.lease,leaseBackend:a.backend,expiresAt:a.expiresAt}}),o}function bt(e){return Ve(e.req,e.req.internal?.admittedLease)??e.existingLease}async function xt(e){let t=e.session.lease;if(!t)return;let n=f({leaseId:t.leaseId,tenantId:t.tenantId,runId:t.runId,leaseBackend:t.leaseBackend,leaseProvider:t.leaseProvider,deviceKey:t.deviceKey,clientId:t.clientId}),r=e.leaseRegistry.getLease(n),i=r?await e.leaseLifecycleProvider?.release?.(r):void 0,a=fe(i);r&&a&&e.leaseRegistry.recordProviderSession(r,a);let o=e.leaseRegistry.releaseLease(n);return v({level:`info`,phase:`session_lease_released`,data:{session:e.session.name,leaseId:t.leaseId,released:o.released}}),i}const St=[`platform`,`target`],Ct=[`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function wt(e){return u({deviceName:e?.device,udid:e?.udid,serial:e?.serial})}function Tt(e){return wt(e)||Ot(e,St)}function Et(e){return Tt(e)||Ot(e,Ct)}function Dt(e){return typeof e==`string`&&e.trim().length>0}function Ot(e,t){return e?t.some(t=>Dt(e[t])):!1}function kt(e){return{appleSimulatorAppTarget:At(e)}}function At(e){return e&&!i(e)?e:void 0}function jt(e){return`${e.device.platform} device "${e.device.name.trim()}" (${e.device.id})`}function N(e,t){return e.session.screenRecording?Nt(e.address,t):Pt(e.address,t)}function Mt(e,t){return w(`DEVICE_IN_USE`,`Device is already in use by session "${e.address}".`,{session:e.address,deviceId:t.id,deviceName:t.name,hint:N(e,`device-in-use`)})}function Nt(e,t){let n=y(e),r=`agent-device close --session ${n}`;return`Recording session "${e}" owns this device. Run ${`agent-device record stop --session ${n}`}; if the session still appears in agent-device session list, run ${r}. ${t===`selector-conflict`?`To keep using this device, rerun the command with --session ${n} and remove conflicting device selectors.`:`To keep using this device, reuse --session ${n} for commands that should attach to the recording session.`} Run agent-device session list to inspect active sessions.`}function Pt(e,t){let n=y(e),r=`agent-device close --session ${n}`;return t===`selector-conflict`?`Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session ${n} and remove conflicting device selectors. To switch devices, first run ${r}, then open the desired device with a different --session name.`:`Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session ${n}. To open a new session on this device, first run ${r}.`}function Ft(t,n){let{address:r,session:i}=t,a=It(i,n);if(a.length!==0)throw new e(`INVALID_ARGS`,`Session "${r}" is already bound to ${jt(i)}, but this request selected ${a.map(P).join(`, `)}.`,{session:r,conflicts:a.map(P),hint:N(t,`selector-conflict`)})}function It(e,t){if(!t)return[];let n=[],r=e.device,i=t.platform;if(i&&!o(r,i)&&n.push({key:`platform`,value:t.platform}),t.target&&t.target!==(r.target??`mobile`)&&n.push({key:`target`,value:t.target}),t.udid&&(!c(r)||t.udid!==r.id)&&n.push({key:`udid`,value:t.udid}),t.serial&&(!l(r.platform)||t.serial!==r.id)&&n.push({key:`serial`,value:t.serial}),t.device&&t.device.trim().toLowerCase()!==r.name.trim().toLowerCase()&&n.push({key:`device`,value:t.device}),t.iosSimulatorDeviceSet){let e=t.iosSimulatorDeviceSet.trim(),i=r.simulatorSetPath?.trim();(!c(r)||r.kind!==`simulator`||e!==i)&&n.push({key:`iosSimulatorDeviceSet`,value:t.iosSimulatorDeviceSet})}if(t.androidDeviceAllowlist){let e=Ge(t.androidDeviceAllowlist);(r.platform!==`android`||!e.has(r.id))&&n.push({key:`androidDeviceAllowlist`,value:t.androidDeviceAllowlist})}return n}function P(e){return`${Lt(e.key)}=${e.value}`}function Lt(e){switch(e){case`iosSimulatorDeviceSet`:return`--ios-simulator-device-set`;case`androidDeviceAllowlist`:return`--android-device-allowlist`;default:return`--${e}`}}function Rt(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return nt(`sha256`).update(ae(t),`utf8`).digest(`hex`)}function zt(e,t,n){return new Jt(Vt(Bt(t.resolve(e))),n).parse()}function Bt(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function Vt(t){let n=[],r=0;for(;r<t.length;){let i=t.slice(r),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){r+=a;continue}let o=Ht(i);if(!o)throw new e(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);n.push(o.value),r+=o.length}return n}function Ht(e){return Ut(e)??Wt(e)??Gt(e)??Kt(e)??qt(e)}function Ut(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function Wt(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function Gt(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function Kt(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function qt(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var Jt=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let t=this.parseOr();if(this.peek())throw new e(`INVALID_ARGS`,`Unsupported trailing runFlow.when.true expression.`);return t}parseOr(){let e=this.parseAnd();for(;this.consumeOperator(`||`);)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator(`&&`);)e=this.parsePrimary()&&e;return e}parsePrimary(){let t=this.peek();if(!t)throw new e(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(t.type===`boolean`)return this.index+=1,t.value;if(t.type===`paren`&&t.value===`(`){this.index+=1;let t=this.parseOr();if(!this.consumeParen(`)`))throw new e(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return t}return this.parsePlatformComparison()}parsePlatformComparison(){this.consumePlatformToken();let e=this.consumeComparisonOperator(),t=this.consumeStringLiteral(),n=this.platform===t.toLowerCase();return e.value===`==`?n:!n}consumePlatformToken(){if(this.peek()?.type!==`platform`)throw new e(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}consumeComparisonOperator(){let t=this.peek();if(t?.type!==`operator`||t.value!==`==`&&t.value!==`!=`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,t}consumeStringLiteral(){let t=this.peek();if(t?.type!==`string`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`);return this.index+=1,t.value}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};function Yt(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function Xt(e,t){return{...L(e,t),source:e.source}}function F(t,n,r){if(t===void 0)return;let i=r??Ke[n]??{},a=Xe(i),o;if(typeof t==`number`)o=t;else{let r=t.trim();if(r===``)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);o=Number(r)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||i.integer&&!Number.isSafeInteger(o)||i.nonNegative&&o<0||i.positive&&o<=0)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);return o}function Zt(e,t,n,r){return F(e===void 0?t:n.resolve(String(e)),r)}function I(e){if(e?.aborted)throw t()}async function Qt(t,n){if(t.include.kind===`commands`)return{kind:`program`,source:t.source,config:{},commands:t.include.commands};if(!n.loadProgram)throw new e(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return I(n.signal),n.signal?await n.loadProgram(t.include.path,t.source.path,n.signal):await n.loadProgram(t.include.path,t.source.path)}function $t(e,t){if(e.include.kind===`file`)return k.resolve(t?k.dirname(t):process.cwd(),e.include.path)}function en(e){return e===void 0?void 0:k.resolve(e)}function tn(t,n){let r=$t(t,t.source.path);if(r&&n.has(r))throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function nn(t,n,r,i){let a=t.include.kind===`file`?en(n.source.path):void 0,o=new Set([r,a].filter(e=>e!==void 0)),s=[...o].find(e=>i.has(e));if(s)throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function rn(e,t,n){return e.platform&&e.platform!==n.platform?!1:e.true===void 0?!0:typeof e.true==`boolean`?e.true:zt(e.true,t,n.platform)}function an(e){return[...e.visible?[{kind:`visible`,selector:e.visible}]:[],...e.notVisible?[{kind:`notVisible`,selector:e.notVisible}]:[]]}function L(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>L(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,L(n,t)])):e}async function on(e,t){I(t.signal);let n=en(e.source.path),r={options:t,context:qe(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await sn(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function sn(e,t,n,r,i){I(i.options.signal);let a=_n(t,e.config.env),o=e.config.appId??n,s=i.context.enter(e.config.env);try{let t=[...e.config.onFlowStart??[],...e.commands,...e.config.onFlowComplete??[]],n=[];for(let s of t)n.push(...await ln(s,a,o,e.source.path??r,i));return n}finally{s()}}async function cn(e,t,n,r,i){let a=[];for(let o of e)a.push(...await ln(o,t,n,r,i));return a}async function ln(e,t,n,r,i){I(i.options.signal);let a=vn(e,r);switch(a.kind){case`runFlow`:{let e=dn(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await un(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[R(a,t,n,o)]}case`repeat`:return[R(a,t,n,await cn(a.commands,t,n,r,i))];case`retry`:return[R(a,t,n,await cn(a.commands,t,n,r,i))];default:return[hn(a,t,n)]}}async function un(e,t,n,r,i){let a=pn(e,i.context),o=tn(a,i.activeIncludePaths),s=await Qt(a,i.options);I(i.options.signal);let c=nn(a,s,o,i.activeIncludePaths),l=_n(t,e.env),u=i.context.enter(e.env);try{return await sn(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function dn(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:fn(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function fn(e,t){if(e===!1)return`omit`;if(typeof e==`string`)return mn(t.context.resolveDeferred(e))?`opaque`:zt(e,t.context,t.options.platform)?void 0:`omit`}function pn(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function mn(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function hn(e,t,n){return D({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function R(e,t,n,r){return D({kind:`opaque`,command:gn(e),source:e.source,scopes:t,body:r,appId:n})}function gn(e){switch(e.kind){case`runFlow`:return D({kind:e.kind,source:e.source,when:e.when,label:e.label,...e.include.kind===`file`?{includePath:e.include.path}:{}});case`repeat`:return{kind:e.kind,source:e.source,times:e.times};case`retry`:return D({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function _n(e,t){return t===void 0?e:[...e,t]}function vn(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function yn(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await on(e,t),a=bn(t.runtimeHints),o=D({kind:`maestroReplayPlan`,platform:t.platform,target:t.target,runtimeHints:a,initialStaticEnv:structuredClone({...t.defaults??{},...e.config.env??{},...t.env??{}}),steps:structuredClone(n),total:n.length,compatibility:{staticallyExecutedControls:r,staticallySkippedControls:i}}),s=Rt(o);return xn({...o,digest:s})}function bn(e){if(!e)return;let t=Object.entries(e).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}function xn(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))xn(t);return Object.freeze(e)}function Sn(e,t={}){let{from:n,planDigest:r}=t;if(n===void 0&&r===void 0)return{allowed:!0,startIndex:0};if(n===void 0||r===void 0)return{allowed:!1,reason:`replay --from requires --plan-digest (and --plan-digest requires --from).`};if(!Number.isInteger(n)||n<1||n>e.total)return{allowed:!1,reason:`replay --from ${n} is out of range for a ${e.total}-step plan.`};if(r!==e.digest)return{allowed:!1,reason:`replay --plan-digest does not match the current plan digest.`};if(n===1)return{allowed:!0,startIndex:0};for(let t=0;t<n-1;t+=1){let n=e.steps[t];if(n.kind===`opaque`)return{allowed:!1,reason:`step ${t+1} is opaque runtime control flow (${n.command.kind}) and cannot be skipped safely.`};if(n.command.kind===`runScript`||n.command.kind===`evalScript`)return{allowed:!1,reason:`step ${t+1} (${n.command.kind}) can produce outputEnv values and cannot be skipped safely.`}}let i=e.steps[n-1];return i.kind===`opaque`?{allowed:!1,reason:`step ${n} is opaque runtime control flow (${i.command.kind}) and cannot be resumed into.`}:{allowed:!0,startIndex:n-1}}function Cn(t,n={}){let r=Sn(t,n);if(!r.allowed)throw new e(`INVALID_ARGS`,r.reason);return r.startIndex}function wn(t,n){if(!Number.isInteger(n)||n<0||n>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${n} is out of range for a ${t.total}-step plan.`);return n}const Tn=`maestro-test-failure`;function z(t,n={}){return new e(`COMMAND_FAILED`,t,{...n,reason:Tn})}function En(t){return t instanceof e&&t.code===`COMMAND_FAILED`&&t.details?.reason===Tn}const Dn=new Set([``,`false`,`0`,`null`,`undefined`]);function On(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!Dn.has(e)}async function kn(e,t){I(t.options.signal);try{return await Hn(e,t.context,async()=>await An(e,t))}catch(t){throw H(t,e)}}async function An(e,t){if(e.kind===`command`)return await jn(e.command,e.appId,t);await Ln(e,t)}async function jn(e,t,n){if(e.kind===`evalScript`)return await Pn(e,n);let r=Xt(e,n.context);try{return await Fn(r,t,n)}catch(e){if(I(n.options.signal),Nn(r)&&En(e)){n.warnings.push(Mn(r,e)),n.skipped+=1;return}throw Un(e,r)}}function Mn(t,n){let r=`${t.source.path?`${t.source.path}:`:``}line ${t.source.line}`,i=n instanceof e?n.message:String(n);return`Optional Maestro ${t.kind} skipped at ${r}: ${i}`}function Nn(e){return`optional`in e&&e.optional===!0}async function Pn(t,n){let{evaluateMaestroEvalScript:r}=await import(`./engine-eval-script.js`);if(n.options.trustedScripts===!1)throw new e(`UNAUTHORIZED`,`Maestro evalScript is not permitted for flows received over the remote daemon surface: node:vm is not a security sandbox, so an untrusted expression can escape to the host.`);let i=await r(t.script,n.context.values);n.context.replaceOutput(i),n.executed+=1}async function Fn(e,t,n){switch(e.kind){case`assertVisible`:await V({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await V({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!On(e.condition))throw z(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await V(Vn(e),F(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await In(e,t,n)}}async function In(e,t,n){let r=D({command:e,env:n.context.values,appId:t===void 0?void 0:n.context.resolve(t),generation:n.context.generation,invalidateObservation:n.context.invalidateObservation,cachedObservation:n.context.observation,signal:n.options.signal}),i=await n.port.execute(r);return I(n.options.signal),i.observation&&n.context.recordObservation(i.observation),i.outputEnv&&n.context.merge(i.outputEnv),i.artifactPaths?.forEach(e=>n.artifacts.add(e)),n.executed+=1,i}async function Ln(e,t){let n=Xt(e.command,t.context);switch(n.kind){case`runFlow`:if(n.when&&!await zn(n.when,t)){t.skipped+=1;return}t.executed+=1,await B(e.body,t);return;case`repeat`:{let r=Zt(n.times,0,t.context,`repeat.times`);t.executed+=1;for(let n=0;n<r;n+=1)I(t.options.signal),await B(e.body,t);return}case`retry`:{let r=Math.min(Zt(n.maxRetries,1,t.context,`retry.maxRetries`),Qe.control.retryMaxRetries);t.executed+=1,await Rn(e.body,r,t);return}}}async function B(e,t){for(let n of e)await kn(n,t)}async function Rn(t,n,r){let i;for(let e=0;e<=n;e+=1){I(r.options.signal);try{await B(t,r);return}catch(e){if(I(r.options.signal),!En(Gn(e)))throw e;i=H(e,t[0])}}throw i||new e(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function zn(e,t){if(!rn(e,t.context,t.options))return!1;for(let n of an(e))if(I(t.options.signal),!(await Bn(n,t.timing.runFlowConditionTimeoutMs,t)).matched)return!1;return!0}async function V(e,t,n){if(!(await Bn(e,t,n)).matched)throw z(`Maestro ${e.kind} condition did not match.`)}async function Bn(e,t,n){let r={condition:e,timeoutMs:t,generation:n.context.generation,env:n.context.values,...n.context.observation?{cachedObservation:n.context.observation}:{},...n.options.signal?{signal:n.options.signal}:{}},i=await n.port.observe(r);return I(n.options.signal),n.context.recordObservation(i),i}function Vn(t){if(t.visible)return{kind:`visible`,selector:t.visible};if(t.notVisible)return{kind:`notVisible`,selector:t.notVisible};throw new e(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function Hn(e,t,n){let r=e.scopes.map(e=>t.enter({...e}));try{return await n()}finally{for(let e=r.length-1;e>=0;--e)r[e]()}}function H(e,t){if(Wn(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Kn(e,t?.command),source:n,...t?{command:t.command}:{}}}function Un(e,t){return{kind:`maestroPlanStepFailure`,error:Kn(e,t),source:t.source,command:t}}function Wn(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Gn(e){return Wn(e)?e.error:e}function Kn(t,n){if(!(t instanceof e)||!n||/\bline \d+\b/.test(t.message))return t;let r=n.source.path?`${n.source.path}:`:``;return new e(t.code,`${t.message} (${r}line ${n.source.line})`,t.details)}async function qn(t,n,r={}){I(r.signal);let i=r.startIndex??0;if(!Number.isInteger(i)||i<0||i>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${t.total}-step plan.`);let a={plan:t,port:n,options:r,context:qe(r.defaults,r.env?{...r.env}:{}),timing:$e,artifacts:new Set,warnings:[],executed:t.compatibility.staticallyExecutedControls,skipped:t.compatibility.staticallySkippedControls};for(let e=i;e<t.steps.length;e+=1)try{await Jn(t.steps[e],e,a)}catch(e){throw Gn(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function Jn(e,t,n){I(n.options.signal);let r=n.options.now??Date.now,i=r(),a=n.port.readMetrics?.(),o=n.context.generation,s={command:e.command,source:e.source,generation:o,stepIndex:t+1,stepTotal:n.plan.total};U(()=>n.options.observer?.commandStarted?.(s));try{let t=await kn(e,n);I(n.options.signal),U(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...Yn(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=H(t,e);throw U(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...Yn(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts]})),o}}function Yn(e,t){return!e||!t?{}:{runtimeMetrics:{hierarchyCaptures:t.hierarchyCaptures-e.hierarchyCaptures,screenshotCaptures:t.screenshotCaptures-e.screenshotCaptures,tapRetries:t.tapRetries-e.tapRetries,settleLatches:t.settleLatches-e.settleLatches,settleTimeouts:t.settleTimeouts-e.settleTimeouts}}}function U(e){try{e?.()}catch{}}async function Xn(e,t,n={}){let r=Zn(e,n);return await qn(e,t,{...n,startIndex:r})}function Zn(e,t){return t.from!==void 0||t.planDigest!==void 0?Cn(e,{from:t.from,planDigest:t.planDigest}):wn(e,t.startIndex??0)}function Qn(e){return Yt(e)?{command:e.kind,...e.kind===`runFlow`?G(e.label??e.includePath):{}}:{command:e.kind,...$n(e)}}function $n(e){return`label`in e&&e.label?G(e.label):er(e)?G(sr(e.target)):tr(e)?nr(e):e.kind===`inputText`?G(`<text>`):rr(e)}function er(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function tr(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function nr(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return G(W(e.target));case`extendedWaitUntil`:return G(W(e.visible??e.notVisible));case`scrollUntilVisible`:return G(W(e.element))}}function rr(e){return ir(e)?ar(e):e.kind===`swipe`?or(e):e.kind===`runFlow`?G(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?G(String(e.condition)):{}}function ir(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function ar(e){switch(e.kind){case`openLink`:return G(e.link);case`takeScreenshot`:return G(e.path);case`runScript`:return G(e.file);case`pressKey`:return G(e.key)}}function or(e){return G(e.gesture.kind===`coordinates`?`${cr(e.gesture.start)} to ${cr(e.gesture.end)}`:e.gesture.direction)}function sr(e){return e.space===`target`?W(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function W(e){return e?.id??e?.text}function cr(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function G(e){return e?{value:e}:{}}const lr=new Set(String.raw`^$\.*+?()[]{}|`);function ur(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function dr(e){try{new RegExp(e)}catch{return e}let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`\\`){if(lr.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!lr.has(i))return;t+=i,n+=1}return t}function fr(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(_(e.rect))return t.isVisibleInEffectiveViewport(e);if(e.rect)return!1;if(n!==`android`&&e.hittable===!0)return!0;let r=t.findAncestor(e,e=>ne(e,n)?e:null);return r?_(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function pr(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function mr(e,t){let n=[t.id===void 0?void 0:gr(e.identifier,t.id),t.text===void 0?void 0:_r(e,t.text)].filter(e=>e!==void 0);return!(n.length===0&&t.enabled===void 0&&t.selected===void 0||n.some(e=>!e)||t.enabled!==void 0&&e.enabled!==!1!==t.enabled||t.selected!==void 0&&e.selected===!0!==t.selected)}function hr(e){return e.matches.filter(t=>fr(t,e.visibility,e.platform))}function gr(e,t){let n=e??``;return O(n)===O(t)||ur(n,t)}function _r(e,t){return[e.label,Je(e),e.identifier].filter(e=>!!e).some(e=>gr(e,t))}function vr(e){return e.index!==void 0||e.childOf!==void 0||e.below!==void 0||e.above!==void 0||e.leftOf!==void 0||e.rightOf!==void 0||e.containsChild!==void 0||e.containsDescendants!==void 0}function yr(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function br(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=Sr(a.rect,e.rect);n===void 0||!xr(t,a.rect,e.rect)||r.push({node:a,distance:n,order:i++})}return r.sort((e,t)=>e.distance-t.distance||e.order-t.order),r.map(({node:e})=>e)}function xr(e,t,n){switch(e){case`below`:return t.y>n.y;case`above`:return t.y<n.y;case`leftOf`:return t.x<n.x;case`rightOf`:return t.x>n.x}}function Sr(e,t){if(!(!Cr(e)||!Cr(t)))return Math.fround(Math.hypot(K(e.x,e.width)-K(t.x,t.width),K(e.y,e.height)-K(t.y,t.height)))}function Cr(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function K(e,t){return e+Math.trunc(t/2)}function wr(t,n={},r={}){let i=te(t.nodes,n);n.onVisibilityContextCreated?.();let a=new WeakMap,o=new WeakSet,s=new WeakMap,c=new Map,l=e=>e.parentIndex===void 0?void 0:i.nodeByIndex.get(e.parentIndex)??t.nodes[e.parentIndex],u=e=>{let t=s.get(e);if(t)return t;let n=new Set,r=new Set,i=l(e);for(;i&&!r.has(i.index);)r.add(i.index),n.add(i.index),i=l(i);return s.set(e,n),n},d=(e,r)=>{let i=c.get(e);i||(i=new WeakMap,c.set(e,i));let a=i.get(r);if(a)return a;n.onPositionComputed?.(e,r);let o=br(t.nodes,e,m(r).indexed),s={ordered:o,candidateIndexes:new Set(o.map(e=>e.index))};return i.set(r,s),s},f=(e,t)=>d(e,t).ordered,p=(e,t)=>d(e,t).candidateIndexes,m=i=>{let s=a.get(i);if(s)return s;if(o.has(i))throw new e(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(i),n.onSelectorComputed?.(i);try{let e=Tr(t,i,l,u,m,p),n={matches:e,indexed:kr(e,i.index,r.orderUnindexed)};return a.set(i,n),n}finally{o.delete(i)}};return{visibility:i,resolve:m,resolvePosition:f}}function Tr(e,t,n,r,i,a){let{index:o,childOf:s,below:c,above:l,leftOf:u,rightOf:d,containsChild:f,containsDescendants:p,...m}=t,h=yr(m)?e.nodes.filter(e=>mr(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>Dr(r(t),e))}if(f){let e=new Set(i(f).indexed.map(n).filter(e=>e!==void 0).map(e=>e.index));h=h.filter(t=>e.has(t.index))}if(p){let e=p.map(e=>Er(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of Or(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function Er(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function Dr(e,t){for(let n of e)if(t.has(n))return!0;return!1}function Or(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function kr(e,t,n){if(t===void 0)return n?n(e):[...e];let r=jr(e)[Mr(t)];return r?[r]:[]}function Ar(e,t){return t===void 0?e[0]:jr(e)[Mr(t)]}function jr(e){return[...e].sort((e,t)=>{let n=q(e.rect?.y),r=q(t.rect?.y);return n===r?q(e.rect?.x)-q(t.rect?.x):n-r})}function q(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function Mr(t){let n=typeof t==`number`?t:Number(t.trim());if(!Number.isSafeInteger(n)||n<0)throw new e(`INVALID_ARGS`,`Maestro selector.index must be a non-negative integer.`);return n}const Nr={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Pr(e,t){let n=Nr[t];if(n.kind===`divergence`)return n;let r=a(e);return r?r.kind!==`exact`||r.provider!==n.provider?{kind:`divergence`,provider:n.provider,reason:`unregistered-provider-evidence`}:r:{kind:`divergence`,provider:n.provider,reason:`exact-evidence-not-retained`}}function J(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:Fr(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Fr(e){return e===!0?2:+(e===!1)}function Ir(e,t,n,r={}){let i=Pr(e,n),a=Rr(e,i,r),o=Lr(t,a),s=hr({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:zr(s,t,n,a.visibility,i)}}function Lr(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Rr(e,t,n={}){return wr(e,n,t?{orderUnindexed:e=>J(e,t)}:{})}function zr(e,t,n,r,i){let a=n!==`ios`||!Ur(t)?e:e.filter(n=>{if(Kr(n))return!0;let i=e.filter(e=>e!==n&&Wr(n,e,t));return!i.some(e=>Kr(e)&&pr(n,e,r))&&!i.some(e=>pr(e,n,r))});return t.index===void 0&&i?J(a,i):a}function Br(e,t){let n=t===void 0?e.find(Y):Vr(e,t);return!n||!Y(n)?null:{node:n,rect:n.rect}}function Vr(e,t){return Ar(e,t)}function Hr(e){return Y(e)?e.rect:void 0}function Y(e){return _(e.rect)}function Ur(e){return e.id!==void 0||e.text!==void 0}function Wr(e,t,n){if(n.id!==void 0&&X(e.identifier)!==X(t.identifier))return!1;if(n.text!==void 0){let n=Gr(e),r=new Set(Gr(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Gr(e){return[e.label,e.value,e.identifier].map(X).filter(e=>e!==void 0)}function X(e){if(e)return O(e)||void 0}function Kr(e){let t=ee(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const qr=Symbol(`maestroFlowProgram`),Jr=Symbol(`maestroFailureCommand`),Yr=Symbol(`maestroFailurePlan`);function Xr(e,t){let n=Ze(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:ei(n),[qr]:n}}async function Zr(e,t,n){let r;try{let i=Ye(k.dirname(e.sourcePath),n.readSource),a=await yn(e[qr],{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:i,signal:n.signal}),o=Cn(a,{from:n.from,planDigest:n.planDigest}),s=await Xn(a,t,{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,loadProgram:i,signal:n.signal,startIndex:o,trustedScripts:n.trustedScripts,observer:$r(a,n.observer,e=>{r=e})});return{ok:!0,replayed:a.total-o,planDigest:a.digest,startIndex:o,artifactPaths:s.artifactPaths,...s.warnings?{warnings:s.warnings}:{}}}catch(e){return{ok:!1,error:r?.error??e,...r?{failure:r}:{}}}}function Qr(e,t){let n=ni(e[Jr]),r=e[Yr].platform;return!n||r!==`android`&&r!==`ios`?[]:Ir(t,n.selector,r).ranked.map(e=>({node:e,basis:ri(n.selector,e)}))}function $r(e,t,n){return{commandStarted:e=>t?.actionStarted?.(Z(e)),commandCompleted:e=>t?.actionCompleted?.({...Z(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=Sn(e,{from:r.stepIndex,planDigest:e.digest}),a={...Z(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,isControl:Yt(r.command),redactions:r.command.kind===`inputText`&&r.command.text.length>0?[{name:`inputText.text`,value:r.command.text}]:[],resume:i.allowed?{allowed:!0,from:r.stepIndex,planDigest:e.digest}:{allowed:!1,from:r.stepIndex,planDigest:e.digest,reason:i.reason},[Jr]:r.command,[Yr]:e};n(a),t?.actionFailed?.(a)}}}function Z(e){let t=Qn(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function ei(e){return[e.config.appId,...[...e.config.onFlowStart??[],...e.commands].filter(e=>e.kind===`launchApp`).map(e=>e.kind===`launchApp`?e.appId:void 0)].find(ti)}function ti(e){return!!(e?.trim()&&!e.includes(`$`)&&!i(e))}function ni(e){switch(e.kind){case`tapOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`doubleTapOn`:case`longPressOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`assertVisible`:case`assertNotVisible`:return{selector:e.target};case`extendedWaitUntil`:return e.visible?{selector:e.visible}:e.notVisible?{selector:e.notVisible}:void 0;case`scrollUntilVisible`:return{selector:e.element};case`swipe`:return e.gesture.kind===`target`?{selector:e.gesture.from}:void 0;default:return}}function ri(e,t){return e.id!==void 0||e.text!==void 0&&mr({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}const ii=`This replay request carries no script sources. Replay scripts are read by the client and sent with the request; upgrade the agent-device client that issued it to a version that sends script sources.`;function ai(t,n){let r=t.files[n];if(r===void 0)throw new e(`INVALID_ARGS`,`replay script source is missing ${n}; it was not part of the script sources sent with this request.`,{path:n,entry:t.entry});return r}function oi(e){if(e.command!==`replay`||e.flags?.replayFrom!==void 0)return;let t=e.flags?.replayScriptSource;if(t)try{let n=t.entry,r=ai(t,n);if(le(n,e.flags?.replayBackend)===`maestro`){let t=Xr(r,n);return{flags:e.flags??{},options:si(t.appTarget,e.flags?.platform)}}let i=it(r,e.flags),a=ci(i.actions);if(!a.appTarget)return;let o=li(e.flags,i.actions),s=o.platform??i.metadata.platform;return{flags:s&&o.platform===void 0?{...o,platform:s}:o,options:s===`ios`?di(a.appTarget):void 0}}catch{return}}function si(e,t){return t===`ios`?di(e)??{}:{}}function ci(e){let t=oe(e);for(let n of e){if(n.command!==`open`)continue;let e=n.positionals?.[0];return ui(e)?{appTarget:e,platform:t}:{appTarget:void 0,platform:t}}return{appTarget:void 0,platform:t}}function li(e,t){let n=ci(t);return e?.platform!==void 0||!n.platform?e??{}:{...e,platform:n.platform}}function ui(e){return!!(e&&e.trim()&&!e.includes(`$`)&&!i(e))}function di(e){let t=At(e);return t?{appleSimulatorAppTarget:t}:void 0}const fi={label:`Materialized paths`,plural:!0,expiredHint:`Materialized paths are released automatically when their TTL expires; re-run the command that materialized them if the paths are still needed.`},Q=new Map;async function pi(e){let t=await A.mkdtemp(k.join(rt.tmpdir(),`agent-device-materialized-`));try{let n=await _i(e.installablePath,k.join(t,`installable`)),r=e.archivePath?await _i(e.archivePath,k.join(t,`archive`)):void 0,i=tt.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{gi(i)},a);return Q.set(i,{rootPath:t,installablePath:n,archivePath:r,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:o,timer:s}),{materializationId:i,installablePath:n,...r?{archivePath:r}:{},expiresAt:new Date(o).toISOString()}}catch(e){throw await A.rm(t,{recursive:!0,force:!0}),e}}async function mi(e,t){await $(e,me(Q,e,t,fi))}async function hi(e){let t=Array.from(Q.entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await $(e,t)}))}async function gi(e){let t=Q.get(e);if(t)try{await $(e,t)}catch{}}async function $(e,t){clearTimeout(t.timer),Q.delete(e),await A.rm(t.rootPath,{recursive:!0,force:!0})}async function _i(e,t){let n=await A.stat(e);await A.mkdir(t,{recursive:!0});let r=k.join(t,k.basename(e));return n.isDirectory()?(await A.cp(e,r,{recursive:!0}),r):(await A.copyFile(e,r),r)}function vi(e){return e.device.platform===`web`}function yi(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function bi(e){let{session:t,sessionName:n,sessionStore:r}=e;t.appLog&&await Re({session:t,sessionName:n,sessionStore:r,resourcePath:Ie.resolvePath(r.resolveSessionDir(n))})}async function xi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.perfCapture&&await Le({...e,session:t})}async function Si(e,t){await t.stopSnapshotHelper(e.device)}async function Ci(e){let{session:t,sessionName:n,sessionStore:r,platformCleanup:i}=e;await i.closeManagedBrowser({device:t.device,sessionName:n,stateDir:r.resolveDaemonStateDir(),openSessionNames:()=>yi(r)})}async function wi(e){let t=[];for(let{step:n,run:r}of e)try{await r()}catch(e){t.push({step:n,error:e})}return t}function Ti(t){if(t.failures.length===0)return;let n=t.failures.map(({step:e})=>e),r=t.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return v({level:`error`,phase:t.phase,data:{session:t.sessionName,failedSteps:n,errors:r}}),new e(`COMMAND_FAILED`,`Session cleanup left ${t.failures.length} resource(s) unreleased: ${r.join(`; `)}`,{reason:`session_cleanup_incomplete`,session:t.sessionName,failedSteps:n,hint:`Some session resources failed to release; inspect the session log for per-resource diagnostics. The session was still deleted, so retrying is safe.`})}async function Ei(t){let{session:n,sessionName:r,sessionStore:i}=t;if(!t.platformCleanup)throw new e(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let a=t.platformCleanup,o=[{step:`recording`,run:()=>Di({session:n,sessionName:r,sessionStore:i})},...t.appLog===`run`?[{step:`app_log`,run:()=>bi({session:n,sessionName:r,sessionStore:i})}]:[],{step:`audio_probe`,run:()=>Oi({session:n,sessionName:r,sessionStore:i})},{step:`perf_capture`,run:()=>xi({session:n,sessionName:r,sessionStore:i})},{step:`platform_snapshot_helper`,run:()=>Si(n,a)},{step:`web_browser`,run:()=>Ci({session:n,sessionName:r,sessionStore:i,platformCleanup:a})}];o.push({step:`materialized_paths`,run:()=>hi(r)});let s=Ti({sessionName:r,phase:`session_teardown_cleanup_failed`,failures:await wi(o)});if(s)throw s}async function Di(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.screenRecording&&await et({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}async function Oi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.audioProbe&&await Fe({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}function ki(e){return c(e)&&e.kind===`simulator`}function Ai(e){return e.platform===`android`&&e.kind===`emulator`}const ji=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function Mi(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function Ni(e){if(!e)return{};let t={};return e.metroHost!==void 0&&(t.metroHost=e.metroHost),e.metroPort!==void 0&&(t.metroPort=String(e.metroPort)),e.bundleUrl!==void 0&&(t.bundleUrl=e.bundleUrl),e.launchUrl!==void 0&&(t.launchUrl=e.launchUrl),t}function Pi(e){return De(Ni(e))}function Fi(t,n){if(t!==void 0){if(typeof t!=`string`)throw new e(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return b(t)}}function Ii(t){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(t)}. Use an integer between 1 and 65535.`);return t}}function Li(t){if(t!==void 0){if(typeof t!=`number`)throw new e(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Ii(t)}}function Ri(t,r,i){if(t===void 0)return i;if(!n(t))throw new e(`INVALID_ARGS`,`Invalid open runtime platform: ${String(t)}. Use "ios", "android", or "harmonyos".`);if(i&&t!==i)throw new e(`INVALID_ARGS`,`open runtime targets ${t}, but session "${r}" is bound to ${i}.`);return t}function zi(e){if(n(e))return e}function Bi(e,t){return{platform:t,metroHost:b(e?.metroHost),metroPort:Ii(e?.metroPort),bundleUrl:b(e?.bundleUrl),launchUrl:b(e?.launchUrl)}}function Vi(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function Hi(e){if(Ai(e))return`10.0.2.2`;if(ki(e))return`127.0.0.1`}function Ui(e,t){if(!e||b(e.metroHost)||b(e.bundleUrl)||e.metroPort===void 0)return e;let n=Hi(t);return n?{...e,metroHost:n}:e}function Wi(t){let{runtime:n,sessionName:r,platform:i}=t;if(n===void 0)return;if(!n||typeof n!=`object`||Array.isArray(n))throw new e(`INVALID_ARGS`,`open runtime must be an object.`);let a=n,o=Object.keys(a).find(e=>!ji.includes(e));if(o)throw new e(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${ji.join(`, `)}.`);return{platform:Ri(a.platform,r,i),metroHost:Fi(a.metroHost,`metroHost`),metroPort:Li(a.metroPort),bundleUrl:Fi(a.bundleUrl,`bundleUrl`),launchUrl:Fi(a.launchUrl,`launchUrl`)}}function Gi(e,t,n){if(n){if(Mi(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function Ki(t,n,r,i){let a=t.getRuntimeHints(n);if(!a)return;let o=r?d(r):void 0,s=zi(o)??i;if(a.platform&&r&&!s)throw new e(`INVALID_ARGS`,`Session runtime hints are only supported on iOS, Android, and HarmonyOS sessions, but session "${n}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new e(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${n}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function qi(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?zi(d(i)):e.platform,o=n.getRuntimeHints(r),s=Wi({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=Ki(n,r,i,a);return{runtime:i?Ui(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&Mi(s)>0?s:void 0;return{runtime:i?Ui(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function Ji(e){return qi(e).runtime}function Yi(e){try{return{ok:!0,data:qi(e)}}catch(e){let t=r(e);return w(t.code,t.message,t.details)}}async function Xi(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!Zi(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:Ni(t)})}function Zi(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&Pi(e.previousRuntime)&&!Pi(e.runtime)}function Qi(e){let{device:t,owner:n,stateDir:r,intent:i}=e,a=i.kind===`exact-owner`&&ie(i.owner,n)?re(i.fence):null;if(!a)return{status:`binding-invalid`};let o=T(E(t)),s=Me(ke(o));if(!s)return{status:`missing`};let c=s.allocatorClaim;return!c||!ea(c.stateDir,r)||!ie(je(c),n)?{status:`conflict`,conflict:s}:c.allocator.identityIncarnationId===a.identityIncarnationId?{status:`covered`}:{status:`incarnation-stale`,heldIncarnationId:c.allocator.identityIncarnationId}}function $i(e){let t=T(E(e));return Oe(ke(t))}function ea(e,t){return k.resolve(e)===k.resolve(t)}const ta=new Set([`DEVICE_CLAIM_LIVE_OWNER`,`DEVICE_CLAIM_RECOVERY_PENDING`,`DEVICE_CLAIM_OWNER_UNCERTAIN`]);function na(e){return ta.has(e)}function ra(e,t,n=`status`){let r=t.claim??t.allocatorClaim,i=d(r?{platform:r.device.family,appleOs:r.device.appleOs}:e),a=s(e.platform)?`--udid`:`--serial`;return[`agent-device device ${n}`,`--platform ${y(i)}`,`${a} ${y(e.id)}`,...n===`release`||Ae(t.classification)?[`--stale`]:[]].join(` `)}function ia(t,n){if(n.classification===`allocator-held`)return oa(t,n);let r=n.claim,i=ra(t,n,Ne(n.classification)?`release`:`status`),a=d(r?{platform:r.device.family,appleOs:r.device.appleOs}:t);return new e(`DEVICE_IN_USE`,r?`${a} device ${t.id} is owned by session "${r.session}" in workspace "${r.workspace}".`:`${t.name} has an ownership claim that could not be verified.`,{reason:pa(n.classification),classification:n.classification,deviceKey:n.deviceKey,...r?{owner:{session:r.session,workspace:r.workspace,stateDir:r.stateDir}}:{},recovery:{command:i},hint:Ne(n.classification)?`The recorded owner can no longer release this device; settle its resources and release the claim with: ${i}`:`Inspect the owner with: ${i}`,retriable:!1})}function aa(e,t){return fa(ia(e,t))}function oa(t,n){let r=n.allocatorClaim,i=d({platform:r.device.family,appleOs:r.device.appleOs}),a=ra(t,n);return new e(`DEVICE_IN_USE`,`${i} device ${t.id} is held by managed-device allocator "${r.allocator.instanceId}" for installation "${r.stateDir}".`,{reason:`DEVICE_CLAIM_ALLOCATOR_HELD`,classification:n.classification,deviceKey:n.deviceKey,owner:{kind:`allocator`,stateDir:r.stateDir,allocator:r.allocator},recovery:{command:a},hint:`This device belongs to a managed pool and is released only after its allocator proves the identity removed; inspect with: ${a}`,retriable:!1})}function sa(t,n){return new e(`COMMAND_FAILED`,`${d(t)} device ${t.id} is a managed identity with no allocator-held execution claim for this installation.`,{reason:`allocator-claim-missing`,owner:g(n),deviceKey:T(E(t)),retriable:!1,hint:`A managed identity becomes executable only after its allocator activates it and this installation holds its allocator-held claim.`})}function ca(t,n,r){return new e(`COMMAND_FAILED`,`${d(t)} device ${t.id} is held for identity incarnation "${r}", which is not the incarnation this binding fences.`,{reason:`allocator-claim-incarnation-stale`,owner:g(n),deviceKey:T(E(t)),heldIncarnationId:r,retriable:!1,hint:`The managed identity was re-provisioned; obtain a new grant from the allocator.`})}function la(t,n){return new e(`COMMAND_FAILED`,`A managed local owner executes only under an exact-owner binding that carries a managed binding fence.`,{reason:`runtime-contract-invalid`,owner:g(n),deviceKey:T(E(t)),retriable:!1})}function ua(e,t,n){switch(n.status){case`binding-invalid`:return{admitted:!1,error:la(e,t)};case`missing`:return{admitted:!1,error:sa(e,t)};case`covered`:return{admitted:!0};case`incarnation-stale`:return{admitted:!1,error:ca(e,t,n.heldIncarnationId)};case`conflict`:return{admitted:!1,error:ia(e,n.conflict)}}}function da(e,t,n){let r=ua(e,t,n);return r.admitted?void 0:fa(r.error)}function fa(e){let{hint:t,retriable:n,...r}=e.details??{};return w(e.code,e.message,r,{hint:t,retriable:n})}function pa(e){switch(e){case`live`:return`DEVICE_CLAIM_LIVE_OWNER`;case`owner-process-dead`:case`owner-daemon-superseded`:return`DEVICE_CLAIM_RECOVERY_PENDING`;case`owner-process-reused`:case`owner-state-dir-gone`:case`unknown`:case`inconsistent`:case`allocator-inconsistent`:return`DEVICE_CLAIM_OWNER_UNCERTAIN`}}function ma(e){switch(e.kind){case`local-family`:return`ordinary`;case`managed-local`:return`allocator-held`;case`provider-runtime`:return`none`}}export{dr as $,hi as A,Rr as B,bi as C,vi as D,Ei as E,ii as F,Vr as G,Ir as H,ai as I,Pr as J,Hr as K,Qr as L,si as M,li as N,yi as O,oi as P,fr as Q,Zr as R,Ti as S,Si as T,zr as U,Lr as V,Br as W,vr as X,wr as Y,hr as Z,Zi as _,xt as _t,ia as a,Mt as at,Oi as b,lt as bt,Qi as c,kt as ct,Pi as d,Et as dt,z as et,Xi as f,Dt as ft,Gi as g,gt,Ni as h,vt as ht,ua as i,It as it,pi as j,mi as k,Bi as l,Tt as lt,Ji as m,_t as mt,da as n,Ft as nt,na as o,N as ot,Vi as p,yt as pt,J as q,aa as r,P as rt,$i as s,jt as st,ma as t,F as tt,Mi as u,wt as ut,zi as v,bt as vt,xi as w,Di as x,ot as xt,Yi as y,ut as yt,Xr as z};
1
+ import{C as e,T as t,o as n,w as r}from"./sdk-contracts.js";import"./capture.js";import{r as i}from"./sdk-batch-runner.js";import{p as a}from"./android-input-ownership.js";import{c as o,l as s,o as c,v as l}from"./sdk-device.js";import{d as u,l as d,n as f,r as p}from"./lease-scope.js";import{Mr as m,Sr as h,Tr as ee,Wt as te,Xt as ne,Yt as re,tr as ie,zr as g}from"./sdk-batch.js";import{a as ae,n as oe,r as se}from"./script.js";import"./session-store.js";import{r as ce}from"./format.js";import{r as _}from"./diagnostics.js";import"./diagnostics2.js";import{r as le}from"./command.js";import{n as v}from"./runtime-transport-hints.js";import{_ as ue,a as de,c as fe,d as y,f as b,g as pe,h as me,i as he,l as ge,m as _e,n as x,o as ve,p as ye,r as be,s as S,u as xe,v as Se}from"./human-control-contract.js";import{n as Ce,t as we,u as Te}from"./provider-session-ownership.js";import{i as Ee}from"./request-runtime-binding.js";import{r as De}from"./application-lifecycle-runtime.js";import{a as Oe,c as C,l as ke,n as Ae,o as je,r as Me,t as Ne}from"./device-claim-inspection.js";import{b as Pe,c as Fe,g as Ie,i as Le,p as Re,x as w}from"./perf-runtime-plan.js";import{n as ze,r as Be,t as Ve}from"./lease-context.js";import{d as He,g as Ue,u as We}from"./screenshot-runtime.js";import{a as Ge,c as Ke,d as T,l as qe,n as Je,o as Ye,r as Xe,u as E}from"./src8.js";import{n as Ze,t as Qe}from"./compatibility-policy.js";import{o as $e}from"./screen-recording-resource-recovery.js";import D from"node:path";import"node:fs";import et,{createHash as tt}from"node:crypto";import nt from"node:os";import O from"node:fs/promises";function rt(t,n){if(n?.replayBackend&&n.replayBackend!==`maestro`)throw new e(`INVALID_ARGS`,`Unsupported replay backend "${n.replayBackend}".`);return{...oe(t),metadata:se(t)}}function it(e,t){return k(e,t)?t:`${e}:${t}`}function k(e,t){return t.startsWith(`${e}:`)}function at(e,t){return!e.partitioned||k(e.tenant,t)}var ot=class{active=new Map;waiters=new Map;async run(e,t){this.active.set(e,(this.active.get(e)??0)+1);try{return await t()}finally{let t=(this.active.get(e)??1)-1;if(t>0)this.active.set(e,t);else{this.active.delete(e);let t=this.waiters.get(e);this.waiters.delete(e);for(let e of t??[])e()}}}async wait(e,t){if(t?.throwIfAborted(),!this.active.has(e))return;let n=this.waiters.get(e)??new Set,r=()=>{},i=()=>{};try{await new Promise((a,o)=>{r=a,i=()=>o(t?.reason),n.add(r),this.waiters.set(e,n),t?.addEventListener(`abort`,i,{once:!0})})}finally{t?.removeEventListener(`abort`,i),n.delete(r),n.size===0&&this.waiters.get(e)===n&&this.waiters.delete(e)}}},st=class{entriesByLeaseId=new Map;retain(e,t){let n={wanted:t,released:!1},r=this.entriesByLeaseId.get(e)??new Set;return r.add(n),this.entriesByLeaseId.set(e,r),{leaseId:e,release:()=>this.releasePass(e,r,n)}}forget(e){let t=this.entriesByLeaseId.get(e);if(t){for(let e of t)e.released=!0;this.entriesByLeaseId.delete(e)}}isDeferred(e){let t=this.entriesByLeaseId.get(e);if(!t)return!1;for(let e of t)e.wanted()||t.delete(e);return t.size>0||(this.entriesByLeaseId.delete(e),!1)}releasePass(e,t,n){return!n.released&&(n.released=!0,t.delete(n),t.size===0&&this.entriesByLeaseId.delete(e),n.wanted())}},ct=class{holdsByDevice=new Map;mutations=new ot;inFlightWork=new st;leases=new Map;runBindings=new Map;deviceBindings=new Map;maxActiveSimulatorLeases;resolveLeaseTtlMs;now;onLeaseExpired;providerSessionOwnership;constructor(e={}){this.maxActiveSimulatorLeases=Number.isInteger(e.maxActiveSimulatorLeases)?Math.max(0,Number(e.maxActiveSimulatorLeases)):0,this.resolveLeaseTtlMs=ge(e),this.now=e.now??(()=>Date.now()),this.onLeaseExpired=e.onLeaseExpired,this.providerSessionOwnership=new we({now:this.now,retentionMs:e.providerSessionRetentionMs})}allocateLease(e){let t=ye(e);this.cleanupExpiredLeases();let n=this.resolveLeaseTtlMs(t.ttlMs);this.assertHumanControlAdmission(t);let r=this.refreshExistingRunBinding(t,n);if(r)return r;this.assertDeviceAvailable(t),this.enforceCapacity(t.backend);let i=fe(t,n,this.now());return this.leases.set(i.leaseId,i),this.bindLease(i),{...i}}refreshExistingRunBinding(e,t){let n=b(e),r=this.runBindings.get(n);if(!r)return;let i=this.leases.get(r);if(!i){this.runBindings.delete(n);return}if(i.clientId===e.clientId)return this.refreshLease(i,t);if(i.deviceKey)throw xe(i);return S(i,e),this.refreshLease(i,t)}heartbeatLease(e){let t=pe(e.leaseId);this.cleanupExpiredLeases();let n=this.getActiveLease(t);ve(n,e),S(n,e);let r=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(n,r)}retainLeaseWork(e,t){let n=this.inFlightWork.retain(e.leaseId,t);return{leaseId:n.leaseId,release:()=>{let t=n.release();return t&&this.refreshProtectedLease(e.leaseId,this.now()),t}}}releaseLease(e){let t=this.getLease(e);return t?(this.leases.delete(t.leaseId),this.unbindLease(t),this.inFlightWork.forget(t.leaseId),{released:!0,lease:t}):{released:!1}}getLease(e){let t=pe(e.leaseId);this.cleanupExpiredLeases();let n=this.leases.get(t);if(n)return ve(n,e),S(n,e),{...n}}assertLeaseAdmission(e){let t=_e(e);this.cleanupExpiredLeases(),S(this.getActiveLease(t.leaseId),t)}listActiveLeases(){return this.cleanupExpiredLeases(),Array.from(this.leases.values()).map(e=>({...e}))}recordProviderSession(e,t){this.cleanupExpiredLeases();let n=e.expiresAt<=this.now()?e.expiresAt:void 0;this.providerSessionOwnership.record(e,t),this.leases.has(e.leaseId)||this.providerSessionOwnership.markLeaseReleased(e,n)}resolveProviderSession(e){return this.cleanupExpiredLeases(),this.providerSessionOwnership.resolve(e)}listHumanControlHolds(e){this.cleanupExpiredLeases();let t=e.kind===`lease`?y(this.requireHumanControlLease(e.leaseId)):void 0;return[...this.holdsByDevice.entries()].filter(([e])=>t===void 0||t===e).flatMap(([,e])=>[...e.values()].map(({hold:e})=>x(e))).sort((e,t)=>e.id.localeCompare(t.id))}async putHumanControlHold(t,n,r,i){i?.throwIfAborted();let a=he(n),o=de(r);this.cleanupExpiredLeases();let s=this.resolveHumanControlScope(t,o),c=y(s),l=this.findHumanControlHold(a);if(l&&(this.assertHoldAuthority(t,l),y(l.hold.scope)!==c))throw new e(`INVALID_ARGS`,`Release a hold before changing its device scope.`);let u=this.now(),d={...t.kind===`lease`?{ownerLeaseId:t.leaseId}:{},hold:{id:a,scope:s,state:`activating`,...o.reason?{reason:o.reason}:{},createdAt:l?.hold.createdAt??u,updatedAt:u}},f=this.holdsByDevice.get(c)??new Map;return this.holdsByDevice.set(c,f),f.set(a,d),await this.activateHumanControlHold(c,d,o.ttlMs,i)}async activateHumanControlHold(t,n,r,i){let a=this.holdsByDevice.get(t),{id:o}=n.hold;try{if(await this.mutations.wait(t,i),i?.throwIfAborted(),a.get(o)!==n)throw new e(`COMMAND_FAILED`,`Human-control hold changed before activation completed.`,{holdId:o});let s=this.now();return n.hold={...n.hold,state:`active`,updatedAt:s,...r===void 0?{}:{expiresAt:s+r}},this.refreshHeldLease(t,s),x(n.hold)}catch(e){throw a.get(o)===n&&this.deleteHumanControlHold(t,o),e}}removeHumanControlHold(e,t){let n=he(t);this.cleanupExpiredLeases();let r=this.findHumanControlHold(n);if(!r)return;this.assertHoldAuthority(e,r);let i=y(r.hold.scope);return this.deleteHumanControlHold(i,n),x(r.hold)}deleteHumanControlHold(e,t){let n=this.holdsByDevice.get(e);n.delete(t),n.size===0&&(this.holdsByDevice.delete(e),this.refreshHeldLease(e,this.now()))}assertHumanControlAdmission(e){this.expireHumanControlHolds();let t=y(e),n=t===void 0?void 0:this.holdsByDevice.get(t)?.values().next().value;if(n)throw be(n.hold)}async runDeviceMutation(e,t){if(!e)return await t();this.cleanupExpiredLeases();let n=this.getActiveLease(e.leaseId);this.assertHumanControlAdmission(n);let r=y(n);return r===void 0?await t():await this.mutations.run(r,t)}requireHumanControlLease(t){let n=this.getActiveLease(t);if(!n.deviceKey)throw new e(`UNSUPPORTED_OPERATION`,`Human control requires a device-scoped remote lease.`);return{...n,deviceKey:n.deviceKey}}resolveHumanControlScope(t,n){if(t.kind===`host`){if(!n.scope)throw new e(`INVALID_ARGS`,`Host human control requires a lease device scope.`);return n.scope}if(n.scope)throw new e(`INVALID_ARGS`,`Lease-owner human control uses the admitted lease device; do not supply scope.`);let r=this.requireHumanControlLease(t.leaseId);return{backend:r.backend,leaseProvider:r.leaseProvider,deviceKey:r.deviceKey}}assertHoldAuthority(t,n){if(t.kind===`host`)return;let r=this.requireHumanControlLease(t.leaseId);if(n.ownerLeaseId!==r.leaseId||y(r)!==y(n.hold.scope))throw new e(`UNAUTHORIZED`,`Human-control hold does not belong to the admitted lease.`,{reason:`LEASE_SCOPE_MISMATCH`})}findHumanControlHold(e){for(let t of this.holdsByDevice.values()){let n=t.get(e);if(n)return n}}hasHumanControl(e){let t=y(e);return t!==void 0&&this.holdsByDevice.has(t)}isLeaseProtected(e,t){return e.expiresAt>t||this.hasHumanControl(e)||this.inFlightWork.isDeferred(e.leaseId)}expireHumanControlHolds(){let e=this.now();for(let[t,n]of this.holdsByDevice){let r=0;for(let[t,{hold:i}]of n)i.expiresAt===void 0||i.expiresAt>e||(r=Math.max(r,i.expiresAt),n.delete(t));n.size===0&&(this.holdsByDevice.delete(t),this.refreshHeldLease(t,r))}}refreshHeldLease(e,t){this.refreshProtectedLease(this.deviceBindings.get(e),t)}refreshProtectedLease(e,t){let n=e?this.leases.get(e):void 0;n&&this.refreshLease(n,n.expiresAt-n.heartbeatAt,Math.max(t,n.heartbeatAt))}consumeExpiredLeases(){this.expireHumanControlHolds();let e=this.now(),t=[];for(let n of this.leases.values()){if(this.isLeaseProtected(n,e))continue;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};t.push(r),this.onLeaseExpired?.(r)}return t}consumeExpiredLease(e){this.expireHumanControlHolds();let t=me(e);if(!t)return;let n=this.leases.get(t);if(!n||this.isLeaseProtected(n,this.now()))return;this.leases.delete(n.leaseId),this.unbindLease(n,n.expiresAt);let r={...n};return this.onLeaseExpired?.(r),r}cleanupExpiredLeases(){this.consumeExpiredLeases()}enforceCapacity(t){if(t!==`ios-simulator`||this.maxActiveSimulatorLeases<=0)return;let n=Array.from(this.leases.values()).filter(e=>e.backend===`ios-simulator`).length;if(!(n<this.maxActiveSimulatorLeases))throw new e(`DEVICE_IN_USE`,`No simulator lease capacity available`,{reason:`LEASE_CAPACITY_EXCEEDED`,activeLeases:n,maxActiveLeases:this.maxActiveSimulatorLeases,backend:t,hint:`Retry after releasing another simulator lease.`})}getActiveLease(t){let n=this.leases.get(t);if(n)return n;throw new e(`UNAUTHORIZED`,`Lease is not active`,{reason:`LEASE_NOT_FOUND`})}refreshLease(e,t,n=this.now()){let r={...e,heartbeatAt:n,expiresAt:n+t};return this.leases.set(r.leaseId,r),this.bindLease(r),{...r}}bindLease(e){this.runBindings.set(b(e),e.leaseId);let t=y(e);t&&this.deviceBindings.set(t,e.leaseId)}unbindLease(e,t=this.now()){this.runBindings.delete(b(e));let n=y(e);n&&this.deviceBindings.delete(n),this.providerSessionOwnership.markLeaseReleased(e,t)}assertDeviceAvailable(e){let t=y({backend:e.backend,leaseProvider:e.leaseProvider,deviceKey:e.deviceKey});if(!t)return;let n=this.deviceBindings.get(t);if(!n)return;let r=this.leases.get(n);if(!r){this.deviceBindings.delete(t);return}throw xe(r)}};function lt(t){let n=Se(t.meta?.sessionIsolation??t.flags?.sessionIsolation),r=t.meta?.tenantId??t.flags?.tenant,i=ue(r);if(r&&!i)throw new e(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);if(n!==`tenant`)return t;if(!i)throw new e(`INVALID_ARGS`,`session isolation mode tenant requires --tenant (or meta.tenantId).`);let a=t.session||`default`;return k(i,a)?{...t,meta:{...t.meta,tenantId:i,sessionIsolation:n}}:{...t,session:it(i,a),meta:{...t.meta,tenantId:i,sessionIsolation:n}}}function ut(t,n,r,i={}){if(He(t.command))return;let a=ze(t);pt(t,a);let o=r?.lease;if(r===void 0&&!a.leaseId&&dt(t,i.providerAppCatalog))return;if(t.command===`human_control`&&!o&&!a.leaseId)throw new e(`UNSUPPORTED_OPERATION`,`Takeover requires an active remote device lease. Local takeover is not supported.`);if(t.command!==`human_control`&&!o&&t.meta?.sessionIsolation!==`tenant`&&(!a.leaseId||!a.tenantId&&!a.runId))return;mt(a,o);let s=Be(t,r),c={...s,leaseTtlMs:s.leaseTtlMs??(p(s)?3e5:void 0)};n.assertLeaseAdmission(d(s));let l=n.heartbeatLease(d(c));return We(t)&&n.assertHumanControlAdmission(l),l}function dt(e,t){let n=Ue(e);return n?.kind===`unconditional`||n?.kind===`provider-app-catalog`&&t?.supports(n.provider)===!0}function ft(e){He(e.command)||pt(e,ze(e))}function pt(t,n){if(t.command!==`open`)return;let r=f(n);if(r.length!==0)throw new e(`INVALID_ARGS`,`Proxy open requires leaseId, tenantId, runId, clientId, and deviceKey lease metadata.`,{missing:r})}function mt(e,t){t&&(A(`leaseId`,e.leaseId,t.leaseId),A(`tenantId`,e.tenantId,t.tenantId),A(`runId`,e.runId,t.runId),A(`leaseProvider`,e.leaseProvider,t.leaseProvider),A(`clientId`,e.clientId,t.clientId),A(`deviceKey`,e.deviceKey,t.deviceKey))}function A(t,n,r){if(!(!n||!r||n===r))throw new e(`UNAUTHORIZED`,`Lease does not match session owner (${t})`,{reason:`LEASE_SESSION_MISMATCH`,field:t})}async function ht(e,t){if(!t.leaseProvider||!e)return!1;try{return await e(t),_({level:`info`,phase:`provider_lease_expired_released`,data:{leaseId:t.leaseId,provider:t.leaseProvider}}),!0}catch(e){return _({level:`error`,phase:`provider_lease_expiry_release_failed`,data:{leaseId:t.leaseId,provider:t.leaseProvider,error:e instanceof Error?e.message:String(e)}}),!1}}function gt(e){ft(e)}async function _t(e){let t=e.sessionStore.get(e.sessionName),n=t?.lease;return!t||!n||!e.leaseRegistry.consumeExpiredLease(n.leaseId)?!1:(_({level:`info`,phase:`leased_session_expired`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,deviceKey:n.deviceKey}}),await e.teardownSession(t,t.name).catch(e=>{_({level:`debug`,phase:`leased_session_expiry_cleanup_failed`,data:{reason:`LEASE_EXPIRED`,leaseId:n.leaseId,session:t.name,error:e instanceof Error?e.message:String(e)}})}),await Pe(t.deviceClaim).catch(e=>{_({level:`warn`,phase:`leased_session_expiry_device_claim_clear_failed`,data:{session:t.name,deviceKey:t.deviceClaim?.deviceKey,error:e instanceof Error?e.message:String(e)}})}),e.sessionStore.delete(t.name),!0)}function vt(e){let{sessionName:t,sessionStore:n,leaseRegistry:r}=e,i=n.get(t),a=ut(e.req,r,i,{providerAppCatalog:e.providerAppCatalog});if(!a)return e.req;let o={...e.req,internal:{...e.req.internal,admittedLease:a}};return i?.lease&&n.set(t,{...i,lease:{...i.lease,leaseBackend:a.backend,expiresAt:a.expiresAt}}),o}function yt(e){return Ve(e.req,e.req.internal?.admittedLease)??e.existingLease}async function bt(e){let t=e.session.lease;if(!t)return;let n=u({leaseId:t.leaseId,tenantId:t.tenantId,runId:t.runId,leaseBackend:t.leaseBackend,leaseProvider:t.leaseProvider,deviceKey:t.deviceKey,clientId:t.clientId}),r=e.leaseRegistry.getLease(n),i=r?await e.leaseLifecycleProvider?.release?.(r):void 0,a=Ce(i);r&&a&&e.leaseRegistry.recordProviderSession(r,a);let o=e.leaseRegistry.releaseLease(n);return _({level:`info`,phase:`session_lease_released`,data:{session:e.session.name,leaseId:t.leaseId,released:o.released}}),i}const xt=[`platform`,`target`],St=[`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function Ct(e){return c({deviceName:e?.device,udid:e?.udid,serial:e?.serial})}function wt(e){return Ct(e)||Dt(e,xt)}function Tt(e){return wt(e)||Dt(e,St)}function Et(e){return typeof e==`string`&&e.trim().length>0}function Dt(e,t){return e?t.some(t=>Et(e[t])):!1}function Ot(e){return{appleSimulatorAppTarget:kt(e)}}function kt(e){return e&&!i(e)?e:void 0}function At(e){let t={version:2,platform:e.platform??null,target:e.target??null,runtimeHints:e.runtimeHints??null,initialStaticEnv:e.initialStaticEnv,steps:e.steps};return tt(`sha256`).update(ie(t),`utf8`).digest(`hex`)}function jt(e,t,n){return new Bt(Nt(Mt(t.resolve(e))),n).parse()}function Mt(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function Nt(t){let n=[],r=0;for(;r<t.length;){let i=t.slice(r),a=/^\s+/.exec(i)?.[0].length??0;if(a>0){r+=a;continue}let o=Pt(i);if(!o)throw new e(`INVALID_ARGS`,`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`);n.push(o.value),r+=o.length}return n}function Pt(e){return Ft(e)??It(e)??Lt(e)??Rt(e)??zt(e)}function Ft(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function It(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function Lt(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function Rt(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function zt(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var Bt=class{index=0;tokens;platform;constructor(e,t){this.tokens=e,this.platform=t}parse(){let t=this.parseOr();if(this.peek())throw new e(`INVALID_ARGS`,`Unsupported trailing runFlow.when.true expression.`);return t}parseOr(){let e=this.parseAnd();for(;this.consumeOperator(`||`);)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator(`&&`);)e=this.parsePrimary()&&e;return e}parsePrimary(){let t=this.peek();if(!t)throw new e(`INVALID_ARGS`,`Incomplete runFlow.when.true expression.`);if(t.type===`boolean`)return this.index+=1,t.value;if(t.type===`paren`&&t.value===`(`){this.index+=1;let t=this.parseOr();if(!this.consumeParen(`)`))throw new e(`INVALID_ARGS`,`Unclosed runFlow.when.true parenthesis.`);return t}return this.parsePlatformComparison()}parsePlatformComparison(){this.consumePlatformToken();let e=this.consumeComparisonOperator(),t=this.consumeStringLiteral(),n=this.platform===t.toLowerCase();return e.value===`==`?n:!n}consumePlatformToken(){if(this.peek()?.type!==`platform`)throw new e(`INVALID_ARGS`,`runFlow.when.true supports maestro.platform comparisons.`);this.index+=1}consumeComparisonOperator(){let t=this.peek();if(t?.type!==`operator`||t.value!==`==`&&t.value!==`!=`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires == or !=.`);return this.index+=1,t}consumeStringLiteral(){let t=this.peek();if(t?.type!==`string`)throw new e(`INVALID_ARGS`,`runFlow.when.true comparison requires a string literal.`);return this.index+=1,t.value}consumeOperator(e){let t=this.peek();return t?.type!==`operator`||t.value!==e?!1:(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type!==`paren`||t.value!==e?!1:(this.index+=1,!0)}peek(){return this.tokens[this.index]}};function Vt(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function Ht(e,t){return{...N(e,t),source:e.source}}function j(t,n,r){if(t===void 0)return;let i=r??Ge[n]??{},a=Ye(i),o;if(typeof t==`number`)o=t;else{let r=t.trim();if(r===``)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);o=Number(r)}if(!Number.isFinite(o)||Math.abs(o)>2**53-1||i.integer&&!Number.isSafeInteger(o)||i.nonNegative&&o<0||i.positive&&o<=0)throw new e(`INVALID_ARGS`,`Maestro ${n} must be ${a}.`);return o}function Ut(e,t,n,r){return j(e===void 0?t:n.resolve(String(e)),r)}function M(e){if(e?.aborted)throw t()}async function Wt(t,n){if(t.include.kind===`commands`)return{kind:`program`,source:t.source,config:{},commands:t.include.commands};if(!n.loadProgram)throw new e(`INVALID_ARGS`,`Maestro file runFlow requires a program loader.`);return M(n.signal),n.signal?await n.loadProgram(t.include.path,t.source.path,n.signal):await n.loadProgram(t.include.path,t.source.path)}function Gt(e,t){if(e.include.kind===`file`)return D.resolve(t?D.dirname(t):process.cwd(),e.include.path)}function Kt(e){return e===void 0?void 0:D.resolve(e)}function qt(t,n){let r=Gt(t,t.source.path);if(r&&n.has(r))throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function Jt(t,n,r,i){let a=t.include.kind===`file`?Kt(n.source.path):void 0,o=new Set([r,a].filter(e=>e!==void 0)),s=[...o].find(e=>i.has(e));if(s)throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${s}.`);return o.forEach(e=>i.add(e)),o}function Yt(e,t,n){return e.platform&&e.platform!==n.platform?!1:e.true===void 0?!0:typeof e.true==`boolean`?e.true:jt(e.true,t,n.platform)}function Xt(e){return[...e.visible?[{kind:`visible`,selector:e.visible}]:[],...e.notVisible?[{kind:`notVisible`,selector:e.notVisible}]:[]]}function N(e,t){return typeof e==`string`?t.resolve(e):Array.isArray(e)?e.map(e=>N(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,N(n,t)])):e}async function Zt(e,t){M(t.signal);let n=Kt(e.source.path),r={options:t,context:Ke(t.defaults,t.env),activeIncludePaths:new Set(n===void 0?[]:[n]),staticallyExecutedControls:0,staticallySkippedControls:0};return{steps:await Qt(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function Qt(e,t,n,r,i){M(i.options.signal);let a=ln(t,e.config.env),o=e.config.appId??n,s=i.context.enter(e.config.env);try{let t=[...e.config.onFlowStart??[],...e.commands,...e.config.onFlowComplete??[]],n=[];for(let s of t)n.push(...await en(s,a,o,e.source.path??r,i));return n}finally{s()}}async function $t(e,t,n,r,i){let a=[];for(let o of e)a.push(...await en(o,t,n,r,i));return a}async function en(e,t,n,r,i){M(i.options.signal);let a=un(e,r);switch(a.kind){case`runFlow`:{let e=nn(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await tn(a,t,n,r,i);return e===`flatten`?(i.staticallyExecutedControls+=1,o):[P(a,t,n,o)]}case`repeat`:return[P(a,t,n,await $t(a.commands,t,n,r,i))];case`retry`:return[P(a,t,n,await $t(a.commands,t,n,r,i))];default:return[sn(a,t,n)]}}async function tn(e,t,n,r,i){let a=an(e,i.context),o=qt(a,i.activeIncludePaths),s=await Wt(a,i.options);M(i.options.signal);let c=Jt(a,s,o,i.activeIncludePaths),l=ln(t,e.env),u=i.context.enter(e.env);try{return await Qt(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function nn(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:rn(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function rn(e,t){if(e===!1)return`omit`;if(typeof e==`string`)return on(t.context.resolveDeferred(e))?`opaque`:jt(e,t.context,t.options.platform)?void 0:`omit`}function an(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function on(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function sn(e,t,n){return T({kind:`command`,command:e,source:e.source,scopes:t,appId:n})}function P(e,t,n,r){return T({kind:`opaque`,command:cn(e),source:e.source,scopes:t,body:r,appId:n})}function cn(e){switch(e.kind){case`runFlow`:return T({kind:e.kind,source:e.source,when:e.when,label:e.label,...e.include.kind===`file`?{includePath:e.include.path}:{}});case`repeat`:return{kind:e.kind,source:e.source,times:e.times};case`retry`:return T({kind:e.kind,source:e.source,maxRetries:e.maxRetries})}}function ln(e,t){return t===void 0?e:[...e,t]}function un(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function dn(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await Zt(e,t),a=fn(t.runtimeHints),o=T({kind:`maestroReplayPlan`,platform:t.platform,target:t.target,runtimeHints:a,initialStaticEnv:structuredClone({...t.defaults??{},...e.config.env??{},...t.env??{}}),steps:structuredClone(n),total:n.length,compatibility:{staticallyExecutedControls:r,staticallySkippedControls:i}}),s=At(o);return pn({...o,digest:s})}function fn(e){if(!e)return;let t=Object.entries(e).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}function pn(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))pn(t);return Object.freeze(e)}function mn(e,t={}){let{from:n,planDigest:r}=t;if(n===void 0&&r===void 0)return{allowed:!0,startIndex:0};if(n===void 0||r===void 0)return{allowed:!1,reason:`replay --from requires --plan-digest (and --plan-digest requires --from).`};if(!Number.isInteger(n)||n<1||n>e.total)return{allowed:!1,reason:`replay --from ${n} is out of range for a ${e.total}-step plan.`};if(r!==e.digest)return{allowed:!1,reason:`replay --plan-digest does not match the current plan digest.`};if(n===1)return{allowed:!0,startIndex:0};for(let t=0;t<n-1;t+=1){let n=e.steps[t];if(n.kind===`opaque`)return{allowed:!1,reason:`step ${t+1} is opaque runtime control flow (${n.command.kind}) and cannot be skipped safely.`};if(n.command.kind===`runScript`||n.command.kind===`evalScript`)return{allowed:!1,reason:`step ${t+1} (${n.command.kind}) can produce outputEnv values and cannot be skipped safely.`}}let i=e.steps[n-1];return i.kind===`opaque`?{allowed:!1,reason:`step ${n} is opaque runtime control flow (${i.command.kind}) and cannot be resumed into.`}:{allowed:!0,startIndex:n-1}}function hn(t,n={}){let r=mn(t,n);if(!r.allowed)throw new e(`INVALID_ARGS`,r.reason);return r.startIndex}function gn(t,n){if(!Number.isInteger(n)||n<0||n>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${n} is out of range for a ${t.total}-step plan.`);return n}const _n=`maestro-test-failure`;function F(t,n={}){return new e(`COMMAND_FAILED`,t,{...n,reason:_n})}function vn(t){return t instanceof e&&t.code===`COMMAND_FAILED`&&t.details?.reason===_n}const yn=new Set([``,`false`,`0`,`null`,`undefined`]);function bn(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!yn.has(e)}async function xn(e,t){M(t.options.signal);try{return await Pn(e,t.context,async()=>await Sn(e,t))}catch(t){throw R(t,e)}}async function Sn(e,t){if(e.kind===`command`)return await Cn(e.command,e.appId,t);await kn(e,t)}async function Cn(e,t,n){if(e.kind===`evalScript`)return await En(e,n);let r=Ht(e,n.context);try{return await Dn(r,t,n)}catch(e){if(M(n.options.signal),Tn(r)&&vn(e)){n.warnings.push(wn(r,e)),n.skipped+=1;return}throw Fn(e,r)}}function wn(t,n){let r=`${t.source.path?`${t.source.path}:`:``}line ${t.source.line}`,i=n instanceof e?n.message:String(n);return`Optional Maestro ${t.kind} skipped at ${r}: ${i}`}function Tn(e){return`optional`in e&&e.optional===!0}async function En(t,n){let{evaluateMaestroEvalScript:r}=await import(`./engine-eval-script.js`);if(n.options.trustedScripts===!1)throw new e(`UNAUTHORIZED`,`Maestro evalScript is not permitted for flows received over the remote daemon surface: node:vm is not a security sandbox, so an untrusted expression can escape to the host.`);let i=await r(t.script,n.context.values);n.context.replaceOutput(i),n.executed+=1}async function Dn(e,t,n){switch(e.kind){case`assertVisible`:await L({kind:`visible`,selector:e.target},n.timing.assertVisibleTimeoutMs,n),n.executed+=1;return;case`assertNotVisible`:await L({kind:`notVisible`,selector:e.target},n.timing.assertNotVisibleTimeoutMs,n),n.executed+=1;return;case`assertTrue`:if(!bn(e.condition))throw F(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await L(Nn(e),j(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await On(e,t,n)}}async function On(e,t,n){let r=T({command:e,env:n.context.values,appId:t===void 0?void 0:n.context.resolve(t),generation:n.context.generation,invalidateObservation:n.context.invalidateObservation,cachedObservation:n.context.observation,signal:n.options.signal}),i=await n.port.execute(r);return M(n.options.signal),i.observation&&n.context.recordObservation(i.observation),i.outputEnv&&n.context.merge(i.outputEnv),i.artifactPaths?.forEach(e=>n.artifacts.add(e)),n.executed+=1,i}async function kn(e,t){let n=Ht(e.command,t.context);switch(n.kind){case`runFlow`:if(n.when&&!await jn(n.when,t)){t.skipped+=1;return}t.executed+=1,await I(e.body,t);return;case`repeat`:{let r=Ut(n.times,0,t.context,`repeat.times`);t.executed+=1;for(let n=0;n<r;n+=1)M(t.options.signal),await I(e.body,t);return}case`retry`:{let r=Math.min(Ut(n.maxRetries,1,t.context,`retry.maxRetries`),Ze.control.retryMaxRetries);t.executed+=1,await An(e.body,r,t);return}}}async function I(e,t){for(let n of e)await xn(n,t)}async function An(t,n,r){let i;for(let e=0;e<=n;e+=1){M(r.options.signal);try{await I(t,r);return}catch(e){if(M(r.options.signal),!vn(Ln(e)))throw e;i=R(e,t[0])}}throw i||new e(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function jn(e,t){if(!Yt(e,t.context,t.options))return!1;for(let n of Xt(e))if(M(t.options.signal),!(await Mn(n,t.timing.runFlowConditionTimeoutMs,t)).matched)return!1;return!0}async function L(e,t,n){if(!(await Mn(e,t,n)).matched)throw F(`Maestro ${e.kind} condition did not match.`)}async function Mn(e,t,n){let r={condition:e,timeoutMs:t,generation:n.context.generation,env:n.context.values,...n.context.observation?{cachedObservation:n.context.observation}:{},...n.options.signal?{signal:n.options.signal}:{}},i=await n.port.observe(r);return M(n.options.signal),n.context.recordObservation(i),i}function Nn(t){if(t.visible)return{kind:`visible`,selector:t.visible};if(t.notVisible)return{kind:`notVisible`,selector:t.notVisible};throw new e(`INVALID_ARGS`,`Maestro extendedWaitUntil requires one condition.`)}async function Pn(e,t,n){let r=e.scopes.map(e=>t.enter({...e}));try{return await n()}finally{for(let e=r.length-1;e>=0;--e)r[e]()}}function R(e,t){if(In(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Rn(e,t?.command),source:n,...t?{command:t.command}:{}}}function Fn(e,t){return{kind:`maestroPlanStepFailure`,error:Rn(e,t),source:t.source,command:t}}function In(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Ln(e){return In(e)?e.error:e}function Rn(t,n){if(!(t instanceof e)||!n||/\bline \d+\b/.test(t.message))return t;let r=n.source.path?`${n.source.path}:`:``;return new e(t.code,`${t.message} (${r}line ${n.source.line})`,t.details)}async function zn(t,n,r={}){M(r.signal);let i=r.startIndex??0;if(!Number.isInteger(i)||i<0||i>t.total)throw new e(`INVALID_ARGS`,`Maestro replay startIndex ${i} is out of range for a ${t.total}-step plan.`);let a={plan:t,port:n,options:r,context:Ke(r.defaults,r.env?{...r.env}:{}),timing:Qe,artifacts:new Set,warnings:[],executed:t.compatibility.staticallyExecutedControls,skipped:t.compatibility.staticallySkippedControls};for(let e=i;e<t.steps.length;e+=1)try{await Bn(t.steps[e],e,a)}catch(e){throw Ln(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function Bn(e,t,n){M(n.options.signal);let r=n.options.now??Date.now,i=r(),a=n.port.readMetrics?.(),o=n.context.generation,s={command:e.command,source:e.source,generation:o,stepIndex:t+1,stepTotal:n.plan.total};z(()=>n.options.observer?.commandStarted?.(s));try{let t=await xn(e,n);M(n.options.signal),z(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...Vn(a,n.port.readMetrics?.()),...t?.data?{data:t.data}:{}}))}catch(t){let o=R(t,e);throw z(()=>n.options.observer?.commandFailed?.({...s,...o.command?{command:o.command}:{},source:o.source,durationMs:r()-i,...Vn(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts],warnings:[...n.warnings]})),o}}function Vn(e,t){return!e||!t?{}:{runtimeMetrics:{hierarchyCaptures:t.hierarchyCaptures-e.hierarchyCaptures,screenshotCaptures:t.screenshotCaptures-e.screenshotCaptures,tapRetries:t.tapRetries-e.tapRetries,settleLatches:t.settleLatches-e.settleLatches,settleTimeouts:t.settleTimeouts-e.settleTimeouts}}}function z(e){try{e?.()}catch{}}async function Hn(e,t,n={}){let r=Un(e,n);return await zn(e,t,{...n,startIndex:r})}function Un(e,t){return t.from!==void 0||t.planDigest!==void 0?hn(e,{from:t.from,planDigest:t.planDigest}):gn(e,t.startIndex??0)}function Wn(e){return Vt(e)?{command:e.kind,...e.kind===`runFlow`?V(e.label??e.includePath):{}}:{command:e.kind,...Gn(e)}}function Gn(e){return`label`in e&&e.label?V(e.label):Kn(e)?V($n(e.target)):qn(e)?Jn(e):e.kind===`inputText`?V(`<text>`):Yn(e)}function Kn(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function qn(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function Jn(e){switch(e.kind){case`assertVisible`:case`assertNotVisible`:return V(B(e.target));case`extendedWaitUntil`:return V(B(e.visible??e.notVisible));case`scrollUntilVisible`:return V(B(e.element))}}function Yn(e){return Xn(e)?Zn(e):e.kind===`swipe`?Qn(e):e.kind===`runFlow`?V(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?V(String(e.condition)):{}}function Xn(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function Zn(e){switch(e.kind){case`openLink`:return V(e.link);case`takeScreenshot`:return V(e.path);case`runScript`:return V(e.file);case`pressKey`:return V(e.key)}}function Qn(e){return V(e.gesture.kind===`coordinates`?`${er(e.gesture.start)} to ${er(e.gesture.end)}`:e.gesture.direction)}function $n(e){return e.space===`target`?B(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function B(e){return e?.id??e?.text}function er(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function V(e){return e?{value:e}:{}}const tr=new Set(String.raw`^$\.*+?()[]{}|`);function nr(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function rr(e){try{new RegExp(e)}catch{return e}let t=``;for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==`\\`){if(tr.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!tr.has(i))return;t+=i,n+=1}return t}function ir(e,t,n){if(n===`android`&&e.visibleToUser===!1)return!1;if(g(e.rect))return t.isVisibleInEffectiveViewport(e);if(e.rect)return!1;if(n!==`android`&&e.hittable===!0)return!0;let r=t.findAncestor(e,e=>ee(e,n)?e:null);return r?g(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function ar(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function or(e,t){let n=[t.id===void 0?void 0:cr(e.identifier,t.id),t.text===void 0?void 0:lr(e,t.text)].filter(e=>e!==void 0);return!(n.length===0&&t.enabled===void 0&&t.selected===void 0||n.some(e=>!e)||t.enabled!==void 0&&e.enabled!==!1!==t.enabled||t.selected!==void 0&&e.selected===!0!==t.selected)}function sr(e){return e.matches.filter(t=>ir(t,e.visibility,e.platform))}function cr(e,t){let n=e??``;return E(n)===E(t)||nr(n,t)}function lr(e,t){return[e.label,qe(e),e.identifier].filter(e=>!!e).some(e=>cr(e,t))}function ur(e){return e.index!==void 0||e.childOf!==void 0||e.below!==void 0||e.above!==void 0||e.leftOf!==void 0||e.rightOf!==void 0||e.containsChild!==void 0||e.containsDescendants!==void 0}function dr(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function fr(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=mr(a.rect,e.rect);n===void 0||!pr(t,a.rect,e.rect)||r.push({node:a,distance:n,order:i++})}return r.sort((e,t)=>e.distance-t.distance||e.order-t.order),r.map(({node:e})=>e)}function pr(e,t,n){switch(e){case`below`:return t.y>n.y;case`above`:return t.y<n.y;case`leftOf`:return t.x<n.x;case`rightOf`:return t.x>n.x}}function mr(e,t){if(!(!hr(e)||!hr(t)))return Math.fround(Math.hypot(H(e.x,e.width)-H(t.x,t.width),H(e.y,e.height)-H(t.y,t.height)))}function hr(e){return!!(e&&[e.x,e.y,e.width,e.height].every(Number.isFinite))}function H(e,t){return e+Math.trunc(t/2)}function gr(t,n={},r={}){let i=h(t.nodes,n);n.onVisibilityContextCreated?.();let a=new WeakMap,o=new WeakSet,s=new WeakMap,c=new Map,l=e=>e.parentIndex===void 0?void 0:i.nodeByIndex.get(e.parentIndex)??t.nodes[e.parentIndex],u=e=>{let t=s.get(e);if(t)return t;let n=new Set,r=new Set,i=l(e);for(;i&&!r.has(i.index);)r.add(i.index),n.add(i.index),i=l(i);return s.set(e,n),n},d=(e,r)=>{let i=c.get(e);i||(i=new WeakMap,c.set(e,i));let a=i.get(r);if(a)return a;n.onPositionComputed?.(e,r);let o=fr(t.nodes,e,m(r).indexed),s={ordered:o,candidateIndexes:new Set(o.map(e=>e.index))};return i.set(r,s),s},f=(e,t)=>d(e,t).ordered,p=(e,t)=>d(e,t).candidateIndexes,m=i=>{let s=a.get(i);if(s)return s;if(o.has(i))throw new e(`INVALID_ARGS`,`Maestro selector relations cannot contain cycles.`);o.add(i),n.onSelectorComputed?.(i);try{let e=_r(t,i,l,u,m,p),n={matches:e,indexed:xr(e,i.index,r.orderUnindexed)};return a.set(i,n),n}finally{o.delete(i)}};return{visibility:i,resolve:m,resolvePosition:f}}function _r(e,t,n,r,i,a){let{index:o,childOf:s,below:c,above:l,leftOf:u,rightOf:d,containsChild:f,containsDescendants:p,...m}=t,h=dr(m)?e.nodes.filter(e=>or(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>yr(r(t),e))}if(f){let e=new Set(i(f).indexed.map(n).filter(e=>e!==void 0).map(e=>e.index));h=h.filter(t=>e.has(t.index))}if(p){let e=p.map(e=>vr(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of br(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function vr(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function yr(e,t){for(let n of e)if(t.has(n))return!0;return!1}function br(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function xr(e,t,n){if(t===void 0)return n?n(e):[...e];let r=Cr(e)[wr(t)];return r?[r]:[]}function Sr(e,t){return t===void 0?e[0]:Cr(e)[wr(t)]}function Cr(e){return[...e].sort((e,t)=>{let n=U(e.rect?.y),r=U(t.rect?.y);return n===r?U(e.rect?.x)-U(t.rect?.x):n-r})}function U(e){return e!==void 0&&Number.isFinite(e)?e:2**53-1}function wr(t){let n=typeof t==`number`?t:Number(t.trim());if(!Number.isSafeInteger(n)||n<0)throw new e(`INVALID_ARGS`,`Maestro selector.index must be a non-negative integer.`);return n}const Tr={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Er(e,t){let n=Tr[t];if(n.kind===`divergence`)return n;let r=a(e);return r?r.kind!==`exact`||r.provider!==n.provider?{kind:`divergence`,provider:n.provider,reason:`unregistered-provider-evidence`}:r:{kind:`divergence`,provider:n.provider,reason:`exact-evidence-not-retained`}}function W(e,t){return t.kind===`exact`?e.map((e,n)=>({node:e,order:n,rank:Dr(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Dr(e){return e===!0?2:+(e===!1)}function Or(e,t,n,r={}){let i=Er(e,n),a=Ar(e,i,r),o=kr(t,a),s=sr({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:jr(s,t,n,a.visibility,i)}}function kr(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Ar(e,t,n={}){return gr(e,n,t?{orderUnindexed:e=>W(e,t)}:{})}function jr(e,t,n,r,i){let a=n!==`ios`||!Fr(t)?e:e.filter(n=>{if(Rr(n))return!0;let i=e.filter(e=>e!==n&&Ir(n,e,t));return!i.some(e=>Rr(e)&&ar(n,e,r))&&!i.some(e=>ar(e,n,r))});return t.index===void 0&&i?W(a,i):a}function Mr(e,t){let n=t===void 0?e.find(G):Nr(e,t);return!n||!G(n)?null:{node:n,rect:n.rect}}function Nr(e,t){return Sr(e,t)}function Pr(e){return G(e)?e.rect:void 0}function G(e){return g(e.rect)}function Fr(e){return e.id!==void 0||e.text!==void 0}function Ir(e,t,n){if(n.id!==void 0&&K(e.identifier)!==K(t.identifier))return!1;if(n.text!==void 0){let n=Lr(e),r=new Set(Lr(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Lr(e){return[e.label,e.value,e.identifier].map(K).filter(e=>e!==void 0)}function K(e){if(e)return E(e)||void 0}function Rr(e){let t=m(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const zr=Symbol(`maestroFlowProgram`),Br=Symbol(`maestroFailureCommand`),Vr=Symbol(`maestroFailurePlan`);function Hr(e,t){let n=Xe(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:Kr(n),[zr]:n}}async function Ur(e,t,n){let r;try{let i=Je(D.dirname(e.sourcePath),n.readSource),a=await dn(e[zr],{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:i,signal:n.signal}),o=hn(a,{from:n.from,planDigest:n.planDigest}),s=await Hn(a,t,{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,loadProgram:i,signal:n.signal,startIndex:o,trustedScripts:n.trustedScripts,observer:Gr(a,n.observer,e=>{r=e})});return{ok:!0,replayed:a.total-o,planDigest:a.digest,startIndex:o,artifactPaths:s.artifactPaths,...s.warnings?{warnings:s.warnings}:{}}}catch(e){return{ok:!1,error:r?.error??e,...r?{failure:r}:{}}}}function Wr(e,t){let n=Jr(e[Br]),r=e[Vr].platform;return!n||r!==`android`&&r!==`ios`?[]:Or(t,n.selector,r).ranked.map(e=>({node:e,basis:Yr(n.selector,e)}))}function Gr(e,t,n){return{commandStarted:e=>t?.actionStarted?.(q(e)),commandCompleted:e=>t?.actionCompleted?.({...q(e),durationMs:e.durationMs,runtimeMetrics:e.runtimeMetrics,data:e.data}),commandFailed:r=>{let i=mn(e,{from:r.stepIndex,planDigest:e.digest}),a={...q(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,warnings:[...r.warnings],isControl:Vt(r.command),redactions:r.command.kind===`inputText`&&r.command.text.length>0?[{name:`inputText.text`,value:r.command.text}]:[],resume:i.allowed?{allowed:!0,from:r.stepIndex,planDigest:e.digest}:{allowed:!1,from:r.stepIndex,planDigest:e.digest,reason:i.reason},[Br]:r.command,[Vr]:e};n(a),t?.actionFailed?.(a)}}}function q(e){let t=Wn(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function Kr(e){return[e.config.appId,...[...e.config.onFlowStart??[],...e.commands].filter(e=>e.kind===`launchApp`).map(e=>e.kind===`launchApp`?e.appId:void 0)].find(qr)}function qr(e){return!!(e?.trim()&&!e.includes(`$`)&&!i(e))}function Jr(e){switch(e.kind){case`tapOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`doubleTapOn`:case`longPressOn`:return e.target.space===`target`?{selector:e.target.selector}:void 0;case`assertVisible`:case`assertNotVisible`:return{selector:e.target};case`extendedWaitUntil`:return e.visible?{selector:e.visible}:e.notVisible?{selector:e.notVisible}:void 0;case`scrollUntilVisible`:return{selector:e.element};case`swipe`:return e.gesture.kind===`target`?{selector:e.gesture.from}:void 0;default:return}}function Yr(e,t){return e.id!==void 0||e.text!==void 0&&or({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}const Xr=`This replay request carries no script sources. Replay scripts are read by the client and sent with the request; upgrade the agent-device client that issued it to a version that sends script sources.`;function Zr(t,n){let r=t.files[n];if(r===void 0)throw new e(`INVALID_ARGS`,`replay script source is missing ${n}; it was not part of the script sources sent with this request.`,{path:n,entry:t.entry});return r}function Qr(e){if(e.command!==`replay`||e.flags?.replayFrom!==void 0)return;let t=e.flags?.replayScriptSource;if(t)try{let n=t.entry,r=Zr(t,n);if(ce(n,e.flags?.replayBackend)===`maestro`){let t=Hr(r,n);return{flags:e.flags??{},options:$r(t.appTarget,e.flags?.platform)}}let i=rt(r,e.flags),a=ei(i.actions);if(!a.appTarget)return;let o=ti(e.flags,i.actions),s=o.platform??i.metadata.platform;return{flags:s&&o.platform===void 0?{...o,platform:s}:o,options:s===`ios`?ri(a.appTarget):void 0}}catch{return}}function $r(e,t){return t===`ios`?ri(e)??{}:{}}function ei(e){let t=ae(e);for(let n of e){if(n.command!==`open`)continue;let e=n.positionals?.[0];return ni(e)?{appTarget:e,platform:t}:{appTarget:void 0,platform:t}}return{appTarget:void 0,platform:t}}function ti(e,t){let n=ei(t);return e?.platform!==void 0||!n.platform?e??{}:{...e,platform:n.platform}}function ni(e){return!!(e&&e.trim()&&!e.includes(`$`)&&!i(e))}function ri(e){let t=kt(e);return t?{appleSimulatorAppTarget:t}:void 0}const ii={label:`Materialized paths`,plural:!0,expiredHint:`Materialized paths are released automatically when their TTL expires; re-run the command that materialized them if the paths are still needed.`},J=new Map;async function ai(e){let t=await O.mkdtemp(D.join(nt.tmpdir(),`agent-device-materialized-`));try{let n=await li(e.installablePath,D.join(t,`installable`)),r=e.archivePath?await li(e.archivePath,D.join(t,`archive`)):void 0,i=et.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{ci(i)},a);return J.set(i,{rootPath:t,installablePath:n,archivePath:r,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:o,timer:s}),{materializationId:i,installablePath:n,...r?{archivePath:r}:{},expiresAt:new Date(o).toISOString()}}catch(e){throw await O.rm(t,{recursive:!0,force:!0}),e}}async function oi(e,t){await Y(e,Te(J,e,t,ii))}async function si(e){let t=Array.from(J.entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await Y(e,t)}))}async function ci(e){let t=J.get(e);if(t)try{await Y(e,t)}catch{}}async function Y(e,t){clearTimeout(t.timer),J.delete(e),await O.rm(t.rootPath,{recursive:!0,force:!0})}async function li(e,t){let n=await O.stat(e);await O.mkdir(t,{recursive:!0});let r=D.join(t,D.basename(e));return n.isDirectory()?(await O.cp(e,r,{recursive:!0}),r):(await O.copyFile(e,r),r)}function ui(e){return e.device.platform===`web`}function di(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function fi(e){let{session:t,sessionName:n,sessionStore:r}=e;t.appLog&&await Re({session:t,sessionName:n,sessionStore:r,resourcePath:Ie.resolvePath(r.resolveSessionDir(n))})}async function pi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.perfCapture&&await Le({...e,session:t,intent:`disposal`})}async function mi(e,t){await t.stopSnapshotHelper(e.device)}async function hi(e){let{session:t,sessionName:n,sessionStore:r,platformCleanup:i}=e;await i.closeManagedBrowser({device:t.device,sessionName:n,stateDir:r.resolveDaemonStateDir(),openSessionNames:()=>di(r)})}async function gi(e){let t=[];for(let{step:n,run:r}of e)try{await r()}catch(e){t.push({step:n,error:e})}return t}function _i(t){if(t.failures.length===0)return;let n=t.failures.map(({step:e})=>e),r=t.failures.map(({step:e,error:t})=>`${e}: ${t instanceof Error?t.message:String(t)}`);return _({level:`error`,phase:t.phase,data:{session:t.sessionName,failedSteps:n,errors:r}}),new e(`COMMAND_FAILED`,`Session cleanup left ${t.failures.length} resource(s) unreleased: ${r.join(`; `)}`,{reason:`session_cleanup_incomplete`,session:t.sessionName,failedSteps:n,hint:`Some session resources failed to release; inspect the session log for per-resource diagnostics. The session was still deleted, so retrying is safe.`})}async function vi(t){let{session:n,sessionName:r,sessionStore:i}=t;if(!t.platformCleanup)throw new e(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let a=t.platformCleanup,o=[{step:`recording`,run:()=>yi({session:n,sessionName:r,sessionStore:i})},...t.appLog===`run`?[{step:`app_log`,run:()=>fi({session:n,sessionName:r,sessionStore:i})}]:[],{step:`audio_probe`,run:()=>bi({session:n,sessionName:r,sessionStore:i})},{step:`perf_capture`,run:()=>pi({session:n,sessionName:r,sessionStore:i})},{step:`platform_snapshot_helper`,run:()=>mi(n,a)},{step:`web_browser`,run:()=>hi({session:n,sessionName:r,sessionStore:i,platformCleanup:a})}];o.push({step:`materialized_paths`,run:()=>si(r)});let s=_i({sessionName:r,phase:`session_teardown_cleanup_failed`,failures:await gi(o)});if(s)throw s}async function yi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.screenRecording&&await $e({intent:`disposal`,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}async function bi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.audioProbe&&await Fe({intent:`disposal`,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}function xi(e){return s(e)&&e.kind===`simulator`}function Si(e){return e.platform===`android`&&e.kind===`emulator`}const Ci=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function X(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function Z(e){if(!e)return{};let t={};return e.metroHost!==void 0&&(t.metroHost=e.metroHost),e.metroPort!==void 0&&(t.metroPort=String(e.metroPort)),e.bundleUrl!==void 0&&(t.bundleUrl=e.bundleUrl),e.launchUrl!==void 0&&(t.launchUrl=e.launchUrl),t}function Q(e){return De(Z(e))}function $(t,n){if(t!==void 0){if(typeof t!=`string`)throw new e(`INVALID_ARGS`,`Invalid open runtime ${n}: expected string.`);return v(t)}}function wi(t){if(t!==void 0){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid runtime metroPort: ${String(t)}. Use an integer between 1 and 65535.`);return t}}function Ti(t){if(t!==void 0){if(typeof t!=`number`)throw new e(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return wi(t)}}function Ei(t,r,i){if(t===void 0)return i;if(!n(t))throw new e(`INVALID_ARGS`,`Invalid open runtime platform: ${String(t)}. Use "ios", "android", or "harmonyos".`);if(i&&t!==i)throw new e(`INVALID_ARGS`,`open runtime targets ${t}, but session "${r}" is bound to ${i}.`);return t}function Di(e){if(n(e))return e}function Oi(e,t){return{platform:t,metroHost:v(e?.metroHost),metroPort:wi(e?.metroPort),bundleUrl:v(e?.bundleUrl),launchUrl:v(e?.launchUrl)}}function ki(e,t){return{platform:t.platform??e?.platform,metroHost:t.metroHost??e?.metroHost,metroPort:t.metroPort??e?.metroPort,bundleUrl:t.bundleUrl??e?.bundleUrl,launchUrl:t.launchUrl??e?.launchUrl}}function Ai(e){if(Si(e))return`10.0.2.2`;if(xi(e))return`127.0.0.1`}function ji(e,t){if(!e||v(e.metroHost)||v(e.bundleUrl)||e.metroPort===void 0)return e;let n=Ai(t);return n?{...e,metroHost:n}:e}function Mi(t){let{runtime:n,sessionName:r,platform:i}=t;if(n===void 0)return;if(!n||typeof n!=`object`||Array.isArray(n))throw new e(`INVALID_ARGS`,`open runtime must be an object.`);let a=n,o=Object.keys(a).find(e=>!Ci.includes(e));if(o)throw new e(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${Ci.join(`, `)}.`);return{platform:Ei(a.platform,r,i),metroHost:$(a.metroHost,`metroHost`),metroPort:Ti(a.metroPort),bundleUrl:$(a.bundleUrl,`bundleUrl`),launchUrl:$(a.launchUrl,`launchUrl`)}}function Ni(e,t,n){if(n){if(X(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function Pi(t,n,r,i){let a=t.getRuntimeHints(n);if(!a)return;let o=r?l(r):void 0,s=Di(o)??i;if(a.platform&&r&&!s)throw new e(`INVALID_ARGS`,`Session runtime hints are only supported on iOS, Android, and HarmonyOS sessions, but session "${n}" is bound to ${o}.`);if(a.platform&&s&&a.platform!==s)throw new e(`INVALID_ARGS`,`Session runtime hints target ${a.platform}, but session "${n}" is bound to ${o}. Clear the runtime hints or use a different session.`);return s&&a.platform!==s?{...a,platform:s}:a}function Fi(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?Di(l(i)):e.platform,o=n.getRuntimeHints(r),s=Mi({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=Pi(n,r,i,a);return{runtime:i?ji(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&X(s)>0?s:void 0;return{runtime:i?ji(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function Ii(e){return Fi(e).runtime}function Li(e){try{return{ok:!0,data:Fi(e)}}catch(e){let t=r(e);return Ee(t.code,t.message,t.details)}}async function Ri(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!zi(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:Z(t)})}function zi(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&Q(e.previousRuntime)&&!Q(e.runtime)}function Bi(e){let{device:t,owner:n,stateDir:r,intent:i}=e,a=i.kind===`exact-owner`&&ne(i.owner,n)?te(i.fence):null;if(!a)return{status:`binding-invalid`};let o=C(w(t)),s=Me(ke(o));if(!s)return{status:`missing`};let c=s.allocatorClaim;return!c||!Hi(c.stateDir,r)||!ne(je(c),n)?{status:`conflict`,conflict:s}:c.allocator.identityIncarnationId===a.identityIncarnationId?{status:`covered`}:{status:`incarnation-stale`,heldIncarnationId:c.allocator.identityIncarnationId}}function Vi(e){let t=C(w(e));return Oe(ke(t))}function Hi(e,t){return D.resolve(e)===D.resolve(t)}const Ui=new Set([`DEVICE_CLAIM_LIVE_OWNER`,`DEVICE_CLAIM_RECOVERY_PENDING`,`DEVICE_CLAIM_OWNER_UNCERTAIN`]);function Wi(e){return Ui.has(e)}function Gi(e,t,n=`status`){let r=t.claim??t.allocatorClaim,i=l(r?{platform:r.device.family,appleOs:r.device.appleOs}:e),a=o(e.platform)?`--udid`:`--serial`;return[`agent-device device ${n}`,`--platform ${le(i)}`,`${a} ${le(e.id)}`,...n===`release`||Ae(t.classification)?[`--stale`]:[]].join(` `)}function Ki(t,n){if(n.classification===`allocator-held`)return Ji(t,n);let r=n.claim,i=Gi(t,n,Ne(n.classification)?`release`:`status`),a=l(r?{platform:r.device.family,appleOs:r.device.appleOs}:t);return new e(`DEVICE_IN_USE`,r?`${a} device ${t.id} is owned by session "${r.session}" in workspace "${r.workspace}".`:`${t.name} has an ownership claim that could not be verified.`,{reason:ta(n.classification),classification:n.classification,deviceKey:n.deviceKey,...r?{owner:{session:r.session,workspace:r.workspace,stateDir:r.stateDir}}:{},recovery:{command:i},hint:Ne(n.classification)?`The recorded owner can no longer release this device; settle its resources and release the claim with: ${i}`:`Inspect the owner with: ${i}`,retriable:!1})}function qi(e,t){return ea(Ki(e,t))}function Ji(t,n){let r=n.allocatorClaim,i=l({platform:r.device.family,appleOs:r.device.appleOs}),a=Gi(t,n);return new e(`DEVICE_IN_USE`,`${i} device ${t.id} is held by managed-device allocator "${r.allocator.instanceId}" for installation "${r.stateDir}".`,{reason:`DEVICE_CLAIM_ALLOCATOR_HELD`,classification:n.classification,deviceKey:n.deviceKey,owner:{kind:`allocator`,stateDir:r.stateDir,allocator:r.allocator},recovery:{command:a},hint:`This device belongs to a managed pool and is released only after its allocator proves the identity removed; inspect with: ${a}`,retriable:!1})}function Yi(t,n){return new e(`COMMAND_FAILED`,`${l(t)} device ${t.id} is a managed identity with no allocator-held execution claim for this installation.`,{reason:`allocator-claim-missing`,owner:re(n),deviceKey:C(w(t)),retriable:!1,hint:`A managed identity becomes executable only after its allocator activates it and this installation holds its allocator-held claim.`})}function Xi(t,n,r){return new e(`COMMAND_FAILED`,`${l(t)} device ${t.id} is held for identity incarnation "${r}", which is not the incarnation this binding fences.`,{reason:`allocator-claim-incarnation-stale`,owner:re(n),deviceKey:C(w(t)),heldIncarnationId:r,retriable:!1,hint:`The managed identity was re-provisioned; obtain a new grant from the allocator.`})}function Zi(t,n){return new e(`COMMAND_FAILED`,`A managed local owner executes only under an exact-owner binding that carries a managed binding fence.`,{reason:`runtime-contract-invalid`,owner:re(n),deviceKey:C(w(t)),retriable:!1})}function Qi(e,t,n){switch(n.status){case`binding-invalid`:return{admitted:!1,error:Zi(e,t)};case`missing`:return{admitted:!1,error:Yi(e,t)};case`covered`:return{admitted:!0};case`incarnation-stale`:return{admitted:!1,error:Xi(e,t,n.heldIncarnationId)};case`conflict`:return{admitted:!1,error:Ki(e,n.conflict)}}}function $i(e,t,n){let r=Qi(e,t,n);return r.admitted?void 0:ea(r.error)}function ea(e){let{hint:t,retriable:n,...r}=e.details??{};return Ee(e.code,e.message,r,{hint:t,retriable:n})}function ta(e){switch(e){case`live`:return`DEVICE_CLAIM_LIVE_OWNER`;case`owner-process-dead`:case`owner-daemon-superseded`:return`DEVICE_CLAIM_RECOVERY_PENDING`;case`owner-process-reused`:case`owner-state-dir-gone`:case`unknown`:case`inconsistent`:case`allocator-inconsistent`:return`DEVICE_CLAIM_OWNER_UNCERTAIN`}}function na(e){switch(e.kind){case`local-family`:return`ordinary`;case`managed-local`:return`allocator-held`;case`provider-runtime`:return`none`}}export{rr as $,si as A,Ar as B,fi as C,ui as D,vi as E,Xr as F,Nr as G,Or as H,Zr as I,Er as J,Pr as K,Wr as L,$r as M,ti as N,di as O,Qr as P,ir as Q,Ur as R,_i as S,mi as T,jr as U,kr as V,Mr as W,ur as X,gr as Y,sr as Z,zi as _,Ki as a,Tt as at,bi as b,Bi as c,gt as ct,Q as d,bt as dt,F as et,Ri as f,yt as ft,Ni as g,Z as h,at as ht,Qi as i,Ct as it,ai as j,oi as k,Oi as l,_t as lt,Ii as m,ct as mt,$i as n,Ot as nt,Wi as o,Et as ot,ki as p,lt as pt,W as q,qi as r,wt as rt,Vi as s,vt as st,na as t,j as tt,X as u,ht as ut,Di as v,pi as w,yi as x,Li as y,Hr as z};
@@ -1,5 +1,5 @@
1
1
  import { O as Rect } from "./sdk-contracts.js";
2
- import { D as PointerTrajectorySample, E as PointerTrajectory, O as SinglePointerGesturePlan, T as MultiTouchGesturePlan } from "./sdk-selectors.js";
2
+ import { A as PointerTrajectory, M as SinglePointerGesturePlan, j as PointerTrajectorySample, k as MultiTouchGesturePlan } from "./sdk-selectors.js";
3
3
  import { Readable, Stream, Writable } from "node:stream";
4
4
  //#region packages/platform-android/src/helper-artifacts.d.ts
5
5
  type AndroidImeHelperManifest = {
@@ -31,7 +31,6 @@ type AndroidSnapshotHelperManifest = {
31
31
  targetSdk?: number;
32
32
  outputFormat: 'uiautomator-xml';
33
33
  statusProtocol: 'android-snapshot-helper-v1';
34
- installArgs: string[];
35
34
  };
36
35
  type AndroidSnapshotHelperArtifact = {
37
36
  apkPath: string;
@@ -81,7 +80,13 @@ type AndroidAdbExecutorResult = {
81
80
  };
82
81
  /** Structural mirror of node's StdioOptions; R13 bars the child_process import that names it. */
83
82
  type AndroidAdbStdioOption = 'overlapped' | 'pipe' | 'ignore' | 'inherit';
84
- type AndroidAdbSpawnOptions = AndroidAdbExecutorOptions & {
83
+ /**
84
+ * A spawned adb process is long-lived — the snapshot helper session rides it for
85
+ * the whole session — so `timeoutMs` is not part of its options: background
86
+ * spawns arm no deadline, and a field that looked like one invited callers to
87
+ * kill their own helper.
88
+ */
89
+ type AndroidAdbSpawnOptions = Omit<AndroidAdbExecutorOptions, 'timeoutMs'> & {
85
90
  cwd?: string;
86
91
  detached?: boolean;
87
92
  /** Max stdout/stderr bytes for synchronous runs (default Node ~1MB). */
@@ -131,14 +136,11 @@ type AndroidPortReverseProvider = {
131
136
  type AndroidAdbTransferOptions = AndroidAdbExecutorOptions;
132
137
  type AndroidAdbInstallOptions = AndroidAdbTransferOptions & {
133
138
  replace?: boolean;
134
- allowTestPackages?: boolean;
135
- allowDowngrade?: boolean;
136
- grantPermissions?: boolean;
137
139
  };
138
140
  type AndroidAdbPuller = (remotePath: string, localPath: string, options?: AndroidAdbTransferOptions) => Promise<AndroidAdbExecutorResult>;
139
141
  /**
140
- * Installs an APK path. Implementations are responsible for honoring semantic
141
- * install options such as replace/test/downgrade/grant-permissions.
142
+ * Installs an APK path. Implementations are responsible for honoring the
143
+ * semantic `replace` option (`adb install -r`).
142
144
  */
143
145
  type AndroidAdbInstaller = (apkPath: string, options?: AndroidAdbInstallOptions) => Promise<AndroidAdbExecutorResult>;
144
146
  type AndroidBundleInstaller = (bundlePath: string, options: Readonly<{
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{A as t,C as n}from"./sdk-contracts.js";import{AsyncLocalStorage as r}from"node:async_hooks";var i=e({listDeviceInventory:()=>l,listLocalDeviceInventory:()=>d,readDeviceInventory:()=>u,readInstalledAppProbe:()=>c,shouldPropagateDeviceInventoryProbeError:()=>m,withDeviceInventoryContext:()=>s});const a=`device_inventory_context_unavailable`,o=new r;async function s(e,t){return await o.run(e,t)}function c(){return o.getStore()?.findInstalledApp}async function l(e){return await f(`providerFirst`,e)}async function u(e){let t=p(),n=await t.providerFirst.discoverWithSource(e,t.requestScope);return{devices:n.devices.map(e=>({...e})),source:n.source}}async function d(e){return await f(`localOnly`,e)}async function f(e,t){let n=p();return(await n[e].discover(t,n.requestScope)).map(e=>({...e}))}function p(){let e=o.getStore();if(!e)throw new n(`COMMAND_FAILED`,`Device inventory gateway is unavailable outside request execution`,{reason:a});return e}function m(e){return t(e)||e instanceof n&&e.code===`COMMAND_FAILED`&&e.details?.reason===a?!0:e instanceof Error&&e.name===`AbortError`}export{m as a,u as i,l as n,s as o,d as r,i as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{C as t,j as n}from"./sdk-contracts.js";import{AsyncLocalStorage as r}from"node:async_hooks";var i=e({listDeviceInventory:()=>l,listLocalDeviceInventory:()=>d,readDeviceInventory:()=>u,readInstalledAppProbe:()=>c,shouldPropagateDeviceInventoryProbeError:()=>m,withDeviceInventoryContext:()=>s});const a=`device_inventory_context_unavailable`,o=new r;async function s(e,t){return await o.run(e,t)}function c(){return o.getStore()?.findInstalledApp}async function l(e){return await f(`providerFirst`,e)}async function u(e){let t=p(),n=await t.providerFirst.discoverWithSource(e,t.requestScope);return{devices:n.devices.map(e=>({...e})),source:n.source}}async function d(e){return await f(`localOnly`,e)}async function f(e,t){let n=p();return(await n[e].discover(t,n.requestScope)).map(e=>({...e}))}function p(){let e=o.getStore();if(!e)throw new t(`COMMAND_FAILED`,`Device inventory gateway is unavailable outside request execution`,{reason:a});return e}function m(e){return n(e)||e instanceof t&&e.code===`COMMAND_FAILED`&&e.details?.reason===a?!0:e instanceof Error&&e.name===`AbortError`}export{m as a,u as i,l as n,s as o,d as r,i as t};
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";import{r as t}from"./sdk-batch-runner.js";import{n}from"./app-inventory.js";import"./device.js";import{t as r}from"./request-cancellation.js";import{n as i,t as a}from"./ios-client.js";import{n as o,r as s}from"./snapshot.js";import c from"node:path";import l from"node:fs";import u from"node:os";import{setTimeout as d}from"node:timers/promises";function f(e){return e?.trim()||void 0}async function p(e,t){let n=await i({apiUrl:e.apiUrl,adbUrl:e.adbUrl,token:e.token,logLevel:`warn`}),r={platform:`android`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t},a={exec:async(e,t)=>await y(r,e,t),text:async e=>{await n.setText(e.target,e.text)}};return a.reverse=await t.android.createPortReverse(a.exec),Object.assign(r,{adbProvider:a})}function m(e){return e.dependencies.android.createInteractor(e.device,e.adbProvider)}async function h(e,t,n,i,a,o){a?.throwIfAborted();let s=f(i?.packageNameHint);i?.relaunch&&s&&await y(t,[`shell`,`am`,`force-stop`,s],{allowFailure:!0,signal:a});let c=await r(o,e.assets.getOrUpload({path:n,name:T(s,n)},{signal:a}),a);await r(o,t.client.sendAsset(c.signedDownloadUrl),a),a?.throwIfAborted();let l=s?await t.dependencies.android.inferAppName(s):void 0;return{...s?{packageName:s,launchTarget:s}:{},...l?{appName:l}:{}}}async function g(e,t){await e.adbProvider.reverse?.ensure({local:w(t.devicePort),remote:w(t.hostPort),ownerId:t.name})}async function _(e){await e.adbTunnelPromise?.catch(()=>{});let t=e.adbSerial;t&&(await v(e),await e.dependencies.host.runAdb([`disconnect`,t],{allowFailure:!0,timeoutMs:1e4}).catch(()=>{})),e.adbTunnel?.close(),e.adbTunnel=void 0,e.adbSerial=void 0,e.adbTunnelPromise=void 0}async function v(e){let t=e.adbProvider.reverse;if(!t?.list)return;let n=await t.list().catch(()=>[]),r=new Set,i=[];for(let e of n)e.ownerId?r.add(e.ownerId):i.push(e.local);await Promise.allSettled([...[...r].map(async e=>await t.removeAllOwned(e)),...i.map(async e=>await t.remove(e))])}async function y(e,t,n){let{adbArgs:r,result:i}=await b(e,t,n);return await x(r,i,n?.allowFailure,e.dependencies)}async function b(e,t,n){let r=[`-s`,await S(e),...t];return{adbArgs:r,result:await e.dependencies.host.runAdb(r,{allowFailure:n?.allowFailure,binaryStdout:n?.binaryStdout,stdin:n?.stdin,timeoutMs:n?.timeoutMs??3e4,signal:n?.signal})}}async function x(e,t,n,r){if(t.exitCode!==0&&n!==!0)throw await r.android.adbError(`Limrun Android ADB command failed`,t,{command:[`adb`,...e].join(` `)});return t}async function S(e){if(e.adbSerial)return e.adbSerial;let t=e.adbTunnelPromise??C(e);e.adbTunnelPromise=t;try{return await t}catch(n){throw e.adbTunnelPromise===t&&(e.adbTunnelPromise=void 0),n}}async function C(e){let t=await e.client.startAdbTunnel(),n=`${t.address.address}:${t.address.port}`;return e.adbTunnel=t,e.adbSerial=n,n}function w(t){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid Android tcp reverse port: ${t}`);return`tcp:${t}`}function T(e,t){let n=c.extname(t)||`.apk`;return`${e?.replaceAll(/[^a-zA-Z0-9_.-]+/g,`-`)||`android-app`}${n}`}async function E(e,t){let n=await a({apiUrl:e.apiUrl,token:e.token,logLevel:`warn`});return{platform:`ios`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t}}async function D(e,t,n,i,a,o){a?.throwIfAborted();let s=await j(n,t.dependencies);try{a?.throwIfAborted();let n=await r(o,e.assets.getOrUpload({path:s.uploadPath,name:s.assetName},{signal:a}),a),c=(await O(t,n.signedDownloadUrl,{md5:n.md5,relaunch:i?.relaunch,appIdentifierHint:i?.appIdentifierHint},a,o)).appId;return{...c?{bundleId:c,launchTarget:c}:{},...s.appName?{appName:s.appName}:{}}}finally{await s.cleanup()}}async function O(t,n,i,a,o){a?.throwIfAborted();let s=await r(o,t.client.listApps(),a).catch(e=>{if(a?.aborted)throw e}),c=f((await r(o,t.client.installApp(n,{md5:i?.md5,launchMode:i?.relaunch?`RelaunchIfRunning`:`ForegroundIfRunning`}),a)).bundleId),l=f(i?.appIdentifierHint),u=[];for(let e of N){e>0&&await d(e,void 0,{signal:a}),u=await r(o,t.client.listApps(),a);let n=P({resultBundleId:c,requestedBundleId:l,beforeInstallApps:s,afterInstallApps:u});if(n)return{appId:n}}throw new e(`COMMAND_FAILED`,`Limrun iOS app installation could not be verified.`,{resultBundleId:c,requestedBundleId:l,installedUserApps:u.filter(I).map(e=>e.bundleId).sort()})}function k(e){return new A(e)}var A=class{session;constructor(e){this.session=e}async open(e,n){if(n?.url){await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e)),await this.session.client.openUrl(n.url);return}if(t(e)){await this.session.client.openUrl(e);return}await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e))}async openDevice(){}async close(e){e&&await this.session.client.terminateApp(await this.session.dependencies.ios.resolveAppAlias(e)).catch(()=>{})}async tap(e,t){await this.session.client.tap(e,t)}async tapElementSelector(e){await this.session.client.tapElement(o(e))}async doubleTap(e,t){await this.tap(e,t),await this.tap(e,t)}async longPress(){throw R(`longpress`,`Limrun iOS direct sessions do not expose long press yet.`)}async focus(e,t){await this.tap(e,t)}async type(e,t){if(t&&t>0){for(let n of Array.from(e))await this.session.client.typeText(n),await d(t);return}await this.session.client.typeText(e)}async fill(e,t,n){await this.tap(e,t),await this.session.client.typeText(n)}async scroll(e,t){await this.session.client.scroll(e,t?.pixels??300)}async screenshot(e){let t=await this.session.client.screenshot();await s(e,t.base64)}async snapshot(){let{captureLimrunIosSnapshot:e}=await import(`./ios-snapshot-adapter.js`);return await e(this.session)}async back(){await this.session.client.pressKey(`escape`)}async home(){throw R(`home`,`Limrun iOS direct sessions do not expose home yet.`)}async setOrientation(e){if(e===`portrait-upside-down`)throw R(`orientation`,`Limrun iOS direct sessions support portrait and landscape orientation, not portrait upside-down.`);await this.session.client.setOrientation(e===`portrait`?`Portrait`:`Landscape`)}async performGesture(){throw R(`gesture`,`Limrun iOS direct sessions do not expose portable gesture execution yet.`)}async appSwitcher(){throw R(`app-switcher`,`Limrun iOS direct sessions do not expose app switcher yet.`)}async tvRemote(){throw R(`tv-remote`,`Limrun iOS direct sessions do not expose tv remote control.`)}async readAlert(){throw R(`alert`,L)}async awaitAlert(){throw R(`alert`,L)}async acceptAlert(){throw R(`alert`,L)}async dismissAlert(){throw R(`alert`,L)}async readClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard read yet.`)}async writeClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard write yet.`)}async setSetting(){throw R(`settings`,`Limrun iOS direct sessions do not expose settings changes yet.`)}};async function j(e,t){if(!(await l.promises.stat(e)).isDirectory())return{uploadPath:e,assetName:c.basename(e),appName:M(e),cleanup:async()=>{}};let n=await l.promises.mkdtemp(c.join(u.tmpdir(),`agent-device-limrun-ios-app-`)),r=c.join(n,`${c.basename(e)}.zip`);try{await t.host.archiveDirectory({sourceDirectory:c.dirname(e),entryName:c.basename(e),archivePath:r})}catch(e){throw await l.promises.rm(n,{recursive:!0,force:!0}),e}return{uploadPath:r,assetName:c.basename(r),appName:await t.ios.readBundleAppName(e)??M(e),cleanup:async()=>{await l.promises.rm(n,{recursive:!0,force:!0})}}}function M(e){return c.basename(e).replace(/\.(?:app|ipa|apk|aab|zip)$/i,``)||void 0}const N=[0,250];function P(e){let t=new Set(e.afterInstallApps.map(e=>e.bundleId));return(e.resultBundleId&&t.has(e.resultBundleId)?e.resultBundleId:void 0)??(e.requestedBundleId&&t.has(e.requestedBundleId)?e.requestedBundleId:void 0)??F(e.beforeInstallApps,e.afterInstallApps)}function F(e,t){if(!e)return;let n=new Set(e.map(e=>e.bundleId)),r=t.filter(e=>I(e)&&!n.has(e.bundleId));return r.length===1?r[0]?.bundleId:void 0}function I(e){return!e.bundleId.startsWith(`com.apple.`)&&!e.installType.toLowerCase().includes(`system`)}const L=`Limrun iOS direct sessions do not expose alert inspection yet.`;function R(t,n){throw new e(`UNSUPPORTED_OPERATION`,n,{command:t})}function z(e){return e.platform===`android`?B(e):V(e)}function B(e){let t=e.adbProvider.exec;return{platform:`android`,device:e.device,interactor:m(e),adb:e.adbProvider,listApps:async r=>await e.dependencies.android.listApps(t,n(r)),getForegroundApp:async n=>await e.dependencies.android.getForegroundApp(e.device,t,n),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},getKeyboardState:async()=>await e.dependencies.android.getKeyboardState(t),dismissKeyboard:async()=>await e.dependencies.android.dismissKeyboard(t),readLogs:async n=>await e.dependencies.android.readLogs(t,n),...H(e.client),installRemoteApp:async t=>{await e.client.sendAsset(t)}}}function V(e){return{platform:`ios`,device:e.device,interactor:k(e),viewport:{width:e.client.deviceInfo.screenWidth,height:e.client.deviceInfo.screenHeight},listApps:async t=>(await e.client.listApps()).filter(e=>n(t)===`all`||I(e)).map(e=>({id:e.bundleId,name:e.name,installType:e.installType})).sort((e,t)=>e.id.localeCompare(t.id)),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},readLogs:async(t,n)=>await e.client.appLogTail(t,n),...H(e.client),installRemoteApp:async(t,n)=>await O(e,t,n),runSimctl:t=>e.client.simctl(t)}}function H(e){return{startRecording:async t=>{await e.startRecording(t)},stopRecording:async({outPath:t})=>await e.stopRecording({localPath:t})}}export{_ as a,p as c,D as i,h as l,k as n,g as o,E as r,m as s,z as t};
1
+ import{C as e}from"./sdk-contracts.js";import{r as t}from"./sdk-batch-runner.js";import{n}from"./app-inventory.js";import"./device.js";import{t as r}from"./request-cancellation.js";import{n as i,t as a}from"./ios-client.js";import{a as o,i as s}from"./snapshot.js";import c from"node:path";import l from"node:fs";import u from"node:os";import{setTimeout as d}from"node:timers/promises";function f(e){return e?.trim()||void 0}async function p(e,t){let n=await i({apiUrl:e.apiUrl,adbUrl:e.adbUrl,token:e.token,logLevel:`warn`}),r={platform:`android`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t},a={exec:async(e,t)=>await y(r,e,t),text:async e=>{await n.setText(e.target,e.text)}};return a.reverse=await t.android.createPortReverse(a.exec),Object.assign(r,{adbProvider:a})}function m(e){return e.dependencies.android.createInteractor(e.device,e.adbProvider)}async function h(e,t,n,i,a,o){a?.throwIfAborted();let s=f(i?.packageNameHint);i?.relaunch&&s&&await y(t,[`shell`,`am`,`force-stop`,s],{allowFailure:!0,signal:a});let c=await r(o,e.assets.getOrUpload({path:n,name:T(s,n)},{signal:a}),a);await r(o,t.client.sendAsset(c.signedDownloadUrl),a),a?.throwIfAborted();let l=s?await t.dependencies.android.inferAppName(s):void 0;return{...s?{packageName:s,launchTarget:s}:{},...l?{appName:l}:{}}}async function g(e,t){await e.adbProvider.reverse?.ensure({local:w(t.devicePort),remote:w(t.hostPort),ownerId:t.name})}async function _(e){await e.adbTunnelPromise?.catch(()=>{});let t=e.adbSerial;t&&(await v(e),await e.dependencies.host.runAdb([`disconnect`,t],{allowFailure:!0,timeoutMs:1e4}).catch(()=>{})),e.adbTunnel?.close(),e.adbTunnel=void 0,e.adbSerial=void 0,e.adbTunnelPromise=void 0}async function v(e){let t=e.adbProvider.reverse;if(!t?.list)return;let n=await t.list().catch(()=>[]),r=new Set,i=[];for(let e of n)e.ownerId?r.add(e.ownerId):i.push(e.local);await Promise.allSettled([...[...r].map(async e=>await t.removeAllOwned(e)),...i.map(async e=>await t.remove(e))])}async function y(e,t,n){let{adbArgs:r,result:i}=await b(e,t,n);return await x(r,i,n?.allowFailure,e.dependencies)}async function b(e,t,n){let r=[`-s`,await S(e),...t];return{adbArgs:r,result:await e.dependencies.host.runAdb(r,{allowFailure:n?.allowFailure,binaryStdout:n?.binaryStdout,stdin:n?.stdin,timeoutMs:n?.timeoutMs??3e4,signal:n?.signal})}}async function x(e,t,n,r){if(t.exitCode!==0&&n!==!0)throw await r.android.adbError(`Limrun Android ADB command failed`,t,{command:[`adb`,...e].join(` `)});return t}async function S(e){if(e.adbSerial)return e.adbSerial;let t=e.adbTunnelPromise??C(e);e.adbTunnelPromise=t;try{return await t}catch(n){throw e.adbTunnelPromise===t&&(e.adbTunnelPromise=void 0),n}}async function C(e){let t=await e.client.startAdbTunnel(),n=`${t.address.address}:${t.address.port}`;return e.adbTunnel=t,e.adbSerial=n,n}function w(t){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid Android tcp reverse port: ${t}`);return`tcp:${t}`}function T(e,t){let n=c.extname(t)||`.apk`;return`${e?.replaceAll(/[^a-zA-Z0-9_.-]+/g,`-`)||`android-app`}${n}`}async function E(e,t){let n=await a({apiUrl:e.apiUrl,token:e.token,logLevel:`warn`});return{platform:`ios`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t}}async function D(e,t,n,i,a,o){a?.throwIfAborted();let s=await j(n,t.dependencies);try{a?.throwIfAborted();let n=await r(o,e.assets.getOrUpload({path:s.uploadPath,name:s.assetName},{signal:a}),a),c=(await O(t,n.signedDownloadUrl,{md5:n.md5,relaunch:i?.relaunch,appIdentifierHint:i?.appIdentifierHint},a,o)).appId;return{...c?{bundleId:c,launchTarget:c}:{},...s.appName?{appName:s.appName}:{}}}finally{await s.cleanup()}}async function O(t,n,i,a,o){a?.throwIfAborted();let s=await r(o,t.client.listApps(),a).catch(e=>{if(a?.aborted)throw e}),c=f((await r(o,t.client.installApp(n,{md5:i?.md5,launchMode:i?.relaunch?`RelaunchIfRunning`:`ForegroundIfRunning`}),a)).bundleId),l=f(i?.appIdentifierHint),u=[];for(let e of N){e>0&&await d(e,void 0,{signal:a}),u=await r(o,t.client.listApps(),a);let n=P({resultBundleId:c,requestedBundleId:l,beforeInstallApps:s,afterInstallApps:u});if(n)return{appId:n}}throw new e(`COMMAND_FAILED`,`Limrun iOS app installation could not be verified.`,{resultBundleId:c,requestedBundleId:l,installedUserApps:u.filter(I).map(e=>e.bundleId).sort()})}function k(e){return new A(e)}var A=class{session;constructor(e){this.session=e}async open(e,n){if(n?.url){await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e)),await this.session.client.openUrl(n.url);return}if(t(e)){await this.session.client.openUrl(e);return}await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e))}async openDevice(){}async close(e){e&&await this.session.client.terminateApp(await this.session.dependencies.ios.resolveAppAlias(e)).catch(()=>{})}async tap(e,t){await this.session.client.tap(e,t)}async tapElementSelector(e){await this.session.client.tapElement(s(e))}async doubleTap(e,t){await this.tap(e,t),await this.tap(e,t)}async longPress(){throw R(`longpress`,`Limrun iOS direct sessions do not expose long press yet.`)}async focus(e,t){await this.tap(e,t)}async type(e,t){await this.enterText(e,t)}async fill(e,t,n,r){let{awaitLimrunTextEntryFocus:i,readLimrunUnambiguousTapTargets:a,readLimrunTextEntryFocus:o}=await import(`./text-entry-focus.js`),s=a(await this.session.client.elementTree(),e,t);await this.tap(e,t);let c=await i({targetsAtPoint:s,readFocus:async()=>o(await this.session.client.elementTree()),sleep:e=>d(e),x:e,y:t});return await this.session.client.pressKey(`a`,[`command`]),n.length===0?(await this.session.client.pressKey(`delete`),{textEntryReadiness:c}):(await this.enterText(n,r),{textEntryReadiness:c})}async enterText(e,t){if(t&&t>0){for(let n of Array.from(e))await this.session.client.typeText(n,!1,{requireFocus:!1}),await d(t);return}await this.session.client.typeText(e,!1,{requireFocus:!1})}async scroll(e,t){await this.session.client.scroll(e,t?.pixels??300)}async screenshot(e){let t=await this.session.client.screenshot();await o(e,t.base64)}async snapshot(){let{captureLimrunIosSnapshot:e}=await import(`./ios-snapshot-adapter.js`);return await e(this.session)}async back(){await this.session.client.pressKey(`escape`)}async home(){throw R(`home`,`Limrun iOS direct sessions do not expose home yet.`)}async setOrientation(e){if(e===`portrait-upside-down`)throw R(`orientation`,`Limrun iOS direct sessions support portrait and landscape orientation, not portrait upside-down.`);await this.session.client.setOrientation(e===`portrait`?`Portrait`:`Landscape`)}async performGesture(){throw R(`gesture`,`Limrun iOS direct sessions do not expose portable gesture execution yet.`)}async appSwitcher(){throw R(`app-switcher`,`Limrun iOS direct sessions do not expose app switcher yet.`)}async tvRemote(){throw R(`tv-remote`,`Limrun iOS direct sessions do not expose tv remote control.`)}async readAlert(){throw R(`alert`,L)}async awaitAlert(){throw R(`alert`,L)}async acceptAlert(){throw R(`alert`,L)}async dismissAlert(){throw R(`alert`,L)}async readClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard read yet.`)}async writeClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard write yet.`)}async setSetting(){throw R(`settings`,`Limrun iOS direct sessions do not expose settings changes yet.`)}};async function j(e,t){if(!(await l.promises.stat(e)).isDirectory())return{uploadPath:e,assetName:c.basename(e),appName:M(e),cleanup:async()=>{}};let n=await l.promises.mkdtemp(c.join(u.tmpdir(),`agent-device-limrun-ios-app-`)),r=c.join(n,`${c.basename(e)}.zip`);try{await t.host.archiveDirectory({sourceDirectory:c.dirname(e),entryName:c.basename(e),archivePath:r})}catch(e){throw await l.promises.rm(n,{recursive:!0,force:!0}),e}return{uploadPath:r,assetName:c.basename(r),appName:await t.ios.readBundleAppName(e)??M(e),cleanup:async()=>{await l.promises.rm(n,{recursive:!0,force:!0})}}}function M(e){return c.basename(e).replace(/\.(?:app|ipa|apk|aab|zip)$/i,``)||void 0}const N=[0,250];function P(e){let t=new Set(e.afterInstallApps.map(e=>e.bundleId));return(e.resultBundleId&&t.has(e.resultBundleId)?e.resultBundleId:void 0)??(e.requestedBundleId&&t.has(e.requestedBundleId)?e.requestedBundleId:void 0)??F(e.beforeInstallApps,e.afterInstallApps)}function F(e,t){if(!e)return;let n=new Set(e.map(e=>e.bundleId)),r=t.filter(e=>I(e)&&!n.has(e.bundleId));return r.length===1?r[0]?.bundleId:void 0}function I(e){return!e.bundleId.startsWith(`com.apple.`)&&!e.installType.toLowerCase().includes(`system`)}const L=`Limrun iOS direct sessions do not expose alert inspection yet.`;function R(t,n){throw new e(`UNSUPPORTED_OPERATION`,n,{command:t})}function z(e){return e.platform===`android`?B(e):V(e)}function B(e){let t=e.adbProvider.exec;return{platform:`android`,device:e.device,interactor:m(e),adb:e.adbProvider,listApps:async r=>await e.dependencies.android.listApps(t,n(r)),getForegroundApp:async n=>await e.dependencies.android.getForegroundApp(e.device,t,n),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},getKeyboardState:async()=>await e.dependencies.android.getKeyboardState(t),dismissKeyboard:async()=>await e.dependencies.android.dismissKeyboard(t),readLogs:async n=>await e.dependencies.android.readLogs(t,n),...H(e.client),installRemoteApp:async t=>{await e.client.sendAsset(t)}}}function V(e){return{platform:`ios`,device:e.device,interactor:k(e),viewport:{width:e.client.deviceInfo.screenWidth,height:e.client.deviceInfo.screenHeight},listApps:async t=>(await e.client.listApps()).filter(e=>n(t)===`all`||I(e)).map(e=>({id:e.bundleId,name:e.name,installType:e.installType})).sort((e,t)=>e.id.localeCompare(t.id)),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},readLogs:async(t,n)=>await e.client.appLogTail(t,n),...H(e.client),installRemoteApp:async(t,n)=>await O(e,t,n),runSimctl:t=>e.client.simctl(t)}}function H(e){return{startRecording:async t=>{await e.startRecording(t)},stopRecording:async({outPath:t})=>await e.stopRecording({localPath:t})}}export{_ as a,p as c,D as i,h as l,k as n,g as o,E as r,m as s,z as t};
@@ -1,3 +1,3 @@
1
- import{z as e}from"./sdk-contracts.js";import t from"node:path";import n from"node:fs";import r from"node:crypto";import{AsyncLocalStorage as i}from"node:async_hooks";import a from"node:os";const o=new i;function s(){return r.randomBytes(8).toString(`hex`)}function c(){return`${Date.now().toString(36)}-${r.randomBytes(4).toString(`hex`)}`}async function l(e,t){let n={...e,diagnosticId:c(),events:[],liveWrittenEventCount:0,phaseCounts:new Map,sensitiveValues:new Set,ensuredDirectories:new Set};return await o.run(n,t)}function u(e){let t=o.getStore();t&&Object.assign(t,e)}function d(){let e=o.getStore();if(!e)return{};let{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}=e;return{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}}function f(e){if(!e)return;let t=o.getStore();t&&(t.sensitiveValues.add(e),t.sortedSensitiveValues=void 0)}function p(e){let t=o.getStore();if(!t)return 0;let n=0;for(let r of e)n+=t.phaseCounts.get(r)??0;return n}function m(e){let t=o.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??`info`,phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?v(t,e.data):void 0};if(t.events.push(n),t.phaseCounts.set(e.phase,(t.phaseCounts.get(e.phase)??0)+1),!t.debug&&!t.traceLogPath)return;let r=`${JSON.stringify(n)}\n`;try{t.debug&&t.logPath&&(x(t,t.logPath,r),t.liveWrittenEventCount=t.events.length),t.traceLogPath&&x(t,t.traceLogPath,r),t.debug&&!t.logPath&&!t.traceLogPath&&process.stderr.write(`[agent-device][diag] ${r}`)}catch{}}async function h(e,t,n){let r=Date.now();try{let i=await t();return m({level:`info`,phase:e,durationMs:Date.now()-r,data:n}),i}catch(t){throw m({level:`error`,phase:e,durationMs:Date.now()-r,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function g(e={}){let r=o.getStore();if(!r||!e.force&&!r.debug&&!r.flushOnSuccess||r.events.length===0)return null;let i=_(r);try{if(r.logPath){let e=r.events.slice(r.liveWrittenEventCount);if(e.length>0){let t=e.map(e=>JSON.stringify(y(e,i)));x(r,r.logPath,`${t.join(`
1
+ import{B as e}from"./sdk-contracts.js";import t from"node:path";import n from"node:fs";import r from"node:crypto";import{AsyncLocalStorage as i}from"node:async_hooks";import a from"node:os";const o=new i;function s(){return r.randomBytes(8).toString(`hex`)}function c(){return`${Date.now().toString(36)}-${r.randomBytes(4).toString(`hex`)}`}async function l(e,t){let n={...e,diagnosticId:c(),events:[],liveWrittenEventCount:0,phaseCounts:new Map,sensitiveValues:new Set,ensuredDirectories:new Set};return await o.run(n,t)}function u(e){let t=o.getStore();t&&Object.assign(t,e)}function d(){let e=o.getStore();if(!e)return{};let{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}=e;return{diagnosticId:t,requestId:n,session:r,command:i,debug:a,flushOnSuccess:s}}function f(e){if(!e)return;let t=o.getStore();t&&(t.sensitiveValues.add(e),t.sortedSensitiveValues=void 0)}function p(e){let t=o.getStore();if(!t)return 0;let n=0;for(let r of e)n+=t.phaseCounts.get(r)??0;return n}function m(e){let t=o.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??`info`,phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?v(t,e.data):void 0};if(t.events.push(n),t.phaseCounts.set(e.phase,(t.phaseCounts.get(e.phase)??0)+1),!t.debug&&!t.traceLogPath)return;let r=`${JSON.stringify(n)}\n`;try{t.debug&&t.logPath&&(x(t,t.logPath,r),t.liveWrittenEventCount=t.events.length),t.traceLogPath&&x(t,t.traceLogPath,r),t.debug&&!t.logPath&&!t.traceLogPath&&process.stderr.write(`[agent-device][diag] ${r}`)}catch{}}async function h(e,t,n){let r=Date.now();try{let i=await t();return m({level:`info`,phase:e,durationMs:Date.now()-r,data:n}),i}catch(t){throw m({level:`error`,phase:e,durationMs:Date.now()-r,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function g(e={}){let r=o.getStore();if(!r||!e.force&&!r.debug&&!r.flushOnSuccess||r.events.length===0)return null;let i=_(r);try{if(r.logPath){let e=r.events.slice(r.liveWrittenEventCount);if(e.length>0){let t=e.map(e=>JSON.stringify(y(e,i)));x(r,r.logPath,`${t.join(`
2
2
  `)}\n`)}let t=r.logRecord;return r.events=[],r.liveWrittenEventCount=0,{path:r.logPath,...t?{ref:t}:{}}}let e=b(r.session??`default`),o=new Date().toISOString().slice(0,10),s=t.join(a.homedir(),`.agent-device`,`logs`,e,o);n.mkdirSync(s,{recursive:!0});let c=new Date().toISOString().replaceAll(/[:.]/g,`-`),l=t.join(s,`${c}-${r.diagnosticId}.ndjson`),u=r.events.map(e=>JSON.stringify(y(e,i)));return n.writeFileSync(l,`${u.join(`
3
3
  `)}\n`),r.events=[],{path:l}}catch{return null}}function _(e){return e.sortedSensitiveValues??=[...e.sensitiveValues].sort((e,t)=>t.length-e.length),e.sortedSensitiveValues}function v(t,n){return y(e(n),_(t))}function y(e,t){return typeof e==`string`?t.reduce((e,t)=>e.replaceAll(t,`[REDACTED]`),e):Array.isArray(e)?e.map(e=>y(e,t)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,y(n,t)]))}function b(e){return e.replaceAll(/[^a-zA-Z0-9._-]/g,`_`)}function x(e,r,i){let a=t.dirname(r);e.ensuredDirectories.has(a)||(n.mkdirSync(a,{recursive:!0}),e.ensuredDirectories.add(a)),n.appendFileSync(r,i,`utf8`)}export{d as a,h as c,g as i,l,s as n,f as o,m as r,u as s,p as t};
package/dist/src/error.js CHANGED
@@ -1,2 +1,2 @@
1
- import{C as e,F as t,M as n}from"./sdk-contracts.js";import{r}from"./replay-divergence.js";function i(i,o={}){let s=i instanceof e?n(i):i;if(process.stderr.write(`Error (${s.code}): ${s.message}\n`),s.cause){let e=s.cause.code?`${s.cause.code} `:``;process.stderr.write(`Cause: ${e}${s.cause.message}\n`)}s.hint&&process.stderr.write(`Hint: ${s.hint}\n`);let c=a(t(s.details));c.length>0&&process.stderr.write(`${c.join(`
2
- `)}\n`),s.diagnosticId&&process.stderr.write(`Diagnostic ID: ${s.diagnosticId}\n`),s.logPath&&process.stderr.write(`Diagnostics Log: ${s.logPath}\n`),s.logPathUnavailable&&process.stderr.write(`Remote Diagnostics: unavailable (${s.logPathUnavailable})\n`);let l=r(s.details);l&&process.stderr.write(`${l}\n`),o.showDetails&&s.details&&process.stderr.write(`${JSON.stringify(s.details,null,2)}\n`)}function a(e){return e.flatMap(e=>{if(e.kind===`element-match`){let t=e.matches-e.candidates.length;return[`Candidates:`,...e.candidates.map(t=>` ${o(t,e.refsGeneration)}`),...t>0?[` +${t} more`]:[]]}return[`Devices:`,...e.devices.map(e=>` ${e.id} ${e.name}`)]})}function o(e,t){return t===void 0?e:e.replace(/^@(e\d+)(?=\s|$)/,`@$1~s${t}`)}export{i as printHumanError};
1
+ import{r as e}from"./rolldown-runtime.js";import{C as t,I as n,N as r}from"./sdk-contracts.js";import{n as i}from"./success-text.js";import{t as a}from"./output-common.js";import{r as o}from"./replay-divergence.js";var s=e({formatErrorCandidateViews:()=>l,printHumanError:()=>c});function c(e,s={}){let c=e instanceof t?r(e):e;if(process.stderr.write(`Error (${c.code}): ${c.message}\n`),c.cause){let e=c.cause.code?`${c.cause.code} `:``;process.stderr.write(`Cause: ${e}${c.cause.message}\n`)}c.hint&&process.stderr.write(`Hint: ${c.hint}\n`);for(let e of i(c.details))process.stderr.write(`Warning: ${a(e)}\n`);let u=l(n(c.details));u.length>0&&process.stderr.write(`${u.join(`
2
+ `)}\n`),c.diagnosticId&&process.stderr.write(`Diagnostic ID: ${c.diagnosticId}\n`),c.logPath&&process.stderr.write(`Diagnostics Log: ${c.logPath}\n`),c.logPathUnavailable&&process.stderr.write(`Remote Diagnostics: unavailable (${c.logPathUnavailable})\n`);let d=o(c.details);d&&process.stderr.write(`${d}\n`),s.showDetails&&c.details&&process.stderr.write(`${JSON.stringify(c.details,null,2)}\n`)}function l(e){return e.flatMap(e=>{if(e.kind===`element-match`){let t=e.matches-e.candidates.length;return[`Candidates:`,...e.candidates.map(t=>` ${u(t,e.refsGeneration)}`),...t>0?[` +${t} more`]:[]]}return[`Devices:`,...e.devices.map(e=>` ${e.id} ${e.name}`)]})}function u(e,t){return t===void 0?e:e.replace(/^@(e\d+)(?=\s|$)/,`@$1~s${t}`)}export{l as n,s as t};
package/dist/src/exec.js CHANGED
@@ -1 +1 @@
1
- import{C as e,T as t}from"./sdk-contracts.js";import{o as n}from"./sdk-remote-config.js";import{a as r,r as i,s as a}from"./diagnostics.js";import o from"node:path";import{constants as s}from"node:fs";import{AsyncLocalStorage as c}from"node:async_hooks";import{access as l,stat as u}from"node:fs/promises";import{spawn as d,spawnSync as f}from"node:child_process";import{Readable as p}from"node:stream";import{pipeline as m}from"node:stream/promises";const h=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,g=[`.com`,`.exe`,`.bat`,`.cmd`],_=new c;async function v(e,t){return e?await _.run(e,t):await t()}async function y(e){return await _.run(void 0,e)}async function b(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}async function x(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}function S(e){let t=typeof e.stdout==`string`?e.stdout:String(e.stdout??``),n=typeof e.stderr==`string`?e.stderr:String(e.stderr??``),r=typeof e.exitCode==`number`?e.exitCode:1;return t===e.stdout&&n===e.stderr&&r===e.exitCode?e:{...e,stdout:t,stderr:n,exitCode:r}}function C(e,t,n={}){let r=N(e),i=A();return new Promise((a,o)=>{let s=d(r,t,{cwd:n.cwd,env:n.env,stdio:[`pipe`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});n.onSpawn?.(s);let c=``,l=n.binaryStdout?[]:void 0,u=``,f=!1,p=Z(n.timeoutMs),m=p?setTimeout(()=>{f=!0,$(s,n.detached)},p):null,h=Q(s,n);n.binaryStdout||s.stdout.setEncoding(`utf8`),s.stderr.setEncoding(`utf8`),ne(s,n.stdin).catch(i=>{h.didAbort||f||re(i)||(o(te(r,e,t,i)),$(s,n.detached))}),s.stdout.on(`data`,e=>{if(n.binaryStdout){l?.push(Buffer.isBuffer(e)?e:Buffer.from(e));return}let t=String(e);c+=t,n.onStdoutChunk?.(t)}),s.stderr.on(`data`,e=>{let t=String(e);u+=t,n.onStderrChunk?.(t)}),s.on(`error`,n=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t),o(U(h,r,e,t,n))}),s.on(`close`,s=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t);let d=s??1;if(!h.didAbort&&f&&p){o(R(r,e,t,p,d,c,u));return}let g=W(h,r,e,t,d,n.allowFailure,c,u);if(g){o(g);return}a({stdout:c,stderr:u,exitCode:d,stdoutBuffer:l?Buffer.concat(l):void 0})})})}async function w(e){let t=K(e);if(!t)return!1;if(o.isAbsolute(t))return Y(t);let n=process.env.PATH;if(!n)return!1;let r=q();for(let e of n.split(o.delimiter)){let n=e.trim();if(n){for(let e of J(t,r))if(await Y(o.join(n,e)))return!0}}return!1}async function ee(t,n){let r=G(t,n,`executable`);if(r){if(!await Y(r))throw new e(`TOOL_MISSING`,`${n} points to a missing or non-executable file: ${r}`,{envName:n,path:r});return r}}async function T(t,n){let r=G(t,n,`file`);if(r){if(!await X(r))throw new e(`TOOL_MISSING`,`${n} points to a missing or non-file path: ${r}`,{envName:n,path:r});return r}}function E(t,n,r={}){let i=N(t),a=f(i,n,{cwd:r.cwd,env:r.env,stdio:[`pipe`,`pipe`,`pipe`],encoding:r.binaryStdout?void 0:`utf8`,input:r.stdin,timeout:Z(r.timeoutMs),windowsHide:!0,shell:!1,...r.maxBuffer===void 0?{}:{maxBuffer:r.maxBuffer}});if(a.error){let o=a.error.code;throw o===`ETIMEDOUT`?new e(`COMMAND_FAILED`,`${i} timed out after ${Z(r.timeoutMs)}ms`,{cmd:t,args:n,timeoutMs:Z(r.timeoutMs)},a.error):o===`ENOENT`?F(i,t,a.error):I(i,t,n,a.error)}let o=r.binaryStdout?Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(a.stdout??``):void 0,s=r.binaryStdout?``:typeof a.stdout==`string`?a.stdout:(a.stdout??``).toString(),c=typeof a.stderr==`string`?a.stderr:(a.stderr??``).toString(),l=a.status??1;if(l!==0&&!r.allowFailure)throw B(i,t,n,l,s,c);return{stdout:s,stderr:c,exitCode:l,stdoutBuffer:o}}function D(e,t,n={}){return O(e,t,n).pid}function O(e,t,n={}){let r=N(e),i=d(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??`ignore`,detached:!0,windowsHide:!0,shell:!1}),a=i.pid??0,o=new Promise(e=>{i.once(`error`,t=>{e({pid:a,error:t.message})}),i.once(`exit`,(t,n)=>{e({pid:a,...typeof t==`number`?{exitCode:t}:{},...n?{signal:n}:{}})})});return i.unref(),{pid:a,exited:o}}function k(e,t,n={}){let r=N(e),i=A(),a=d(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??[`ignore`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});i.emitBackgroundSpawn(e,t);let o=``,s=``,c=n.captureOutput??!0,l=Q(a,n);return c&&(a.stdout?.setEncoding(`utf8`),a.stderr?.setEncoding(`utf8`),a.stdout?.on(`data`,e=>{o+=e}),a.stderr?.on(`data`,e=>{s+=e})),{child:a,wait:new Promise((c,u)=>{a.on(`error`,n=>{l.dispose(),i.emitBackgroundCompletion(e,t,`error`),u(U(l,r,e,t,n))}),a.on(`close`,a=>{l.dispose(),i.emitBackgroundCompletion(e,t,`exit`);let d=a??1,f=W(l,r,e,t,d,n.allowFailure,o,s);if(f){u(f);return}c({stdout:o,stderr:s,exitCode:d})})})}}function A(){let e=r(),t=e.debug===!0,i=n(process.env.AGENT_DEVICE_EXEC_TRACE??``)===!0;if(!t&&!i)return j();i&&e.flushOnSuccess!==!0&&a({flushOnSuccess:!0});let o=Date.now(),s=!1;return{emitForegroundCompletion:(e,t)=>{s||(s=!0,M({cmd:e,args:t,startedAtMs:o}))},emitBackgroundSpawn:(e,t)=>{M({cmd:e,args:t,data:{event:`spawn`}})},emitBackgroundCompletion:(e,t,n)=>{s||(s=!0,M({cmd:e,args:t,startedAtMs:o,data:{event:n}}))}}}function j(){return{emitForegroundCompletion:()=>{},emitBackgroundSpawn:()=>{},emitBackgroundCompletion:()=>{}}}function M(e){let t=e.args.slice(0,6);i({level:`debug`,phase:`exec_command`,durationMs:e.startedAtMs===void 0?void 0:Math.max(0,Date.now()-e.startedAtMs),data:{command:e.cmd,argsPrefix:t,...e.args.length>t.length?{omittedArgCount:e.args.length-t.length}:{},...e.data??{}}})}function N(t){let n=K(t);if(!n)throw new e(`INVALID_ARGS`,`Invalid executable command: ${JSON.stringify(t)}`,{cmd:t,hint:`Use a bare command name from PATH or an absolute executable path.`});return n}function P(e,t,n,r){return r.code===`ENOENT`?F(e,t,r):I(e,t,n,r)}function F(t,n,r){return new e(`TOOL_MISSING`,`${t} not found in PATH`,{cmd:n},r)}function I(t,n,r,i){return new e(`COMMAND_FAILED`,`Failed to run ${t}`,{cmd:n,args:r},i)}function te(t,n,r,i){return new e(`COMMAND_FAILED`,`Failed to write stdin for ${t}`,{cmd:n,args:r},i instanceof Error?i:void 0)}function L(e,n,r){return t({cmd:n,args:r,executable:e})}function R(t,n,r,i,a,o,s){return new e(`COMMAND_FAILED`,`${t} timed out after ${i}ms`,{cmd:n,args:r,stdout:o,stderr:s,exitCode:a,timeoutMs:i})}function z(t){return t instanceof e&&t.code===`COMMAND_FAILED`&&typeof t.details?.timeoutMs==`number`}function B(t,n,r,i,a,o){return new e(`COMMAND_FAILED`,`${t} exited with code ${i}`,H({stdout:a,stderr:o,exitCode:i},{cmd:n,args:r}))}function V(t,n,r){if(t.exitCode===0)return t;throw new e(`COMMAND_FAILED`,n,H(t,typeof r==`function`?r(t):r))}function H(e,t){return{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,processExitError:!0,...t}}function U(e,t,n,r,i){return e.didAbort?L(t,n,r):P(t,n,r,i)}function W(e,t,n,r,i,a,o,s){return e.didAbort?L(t,n,r):i!==0&&!a?B(t,n,r,i,o,s):null}function G(t,n,r){let i=t?.trim();if(i){if(!o.isAbsolute(i)||i.includes(`\0`))throw new e(`INVALID_ARGS`,`${n} must be an absolute ${r} path, not ${JSON.stringify(t)}`,{envName:n,path:t});return i}}function K(e){let t=e.trim();return!t||t.includes(`\0`)?null:o.isAbsolute(t)?t:t.includes(`/`)||t.includes(`\\`)?null:h.test(t)?t:null}function q(){if(process.platform!==`win32`)return[``];let e=process.env.PATHEXT;if(!e)return g;let t=e.split(`;`).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:g}function J(e,t){if(process.platform!==`win32`)return[e];let n=e.toLowerCase();return t.some(e=>n.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}async function Y(e){try{return await X(e)?(await l(e,process.platform===`win32`?s.F_OK:s.X_OK),!0):!1}catch{return!1}}async function X(e){try{return(await u(e)).isFile()}catch{return!1}}function Z(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function Q(e,t){let n=!1,r=()=>{n=!0,$(e,t.detached)};return t.signal?.aborted?r():t.signal?.addEventListener(`abort`,r,{once:!0}),{get didAbort(){return n},dispose:()=>{t.signal?.removeEventListener(`abort`,r)}}}function $(e,t){if(t&&e.pid&&process.platform!==`win32`)try{process.kill(-e.pid,`SIGKILL`);return}catch{}e.kill(`SIGKILL`)}async function ne(e,t){if(e.stdin){if(t===void 0){e.stdin?.end();return}await m(p.from([t]),e.stdin)}}function re(e){return e instanceof Error&&`code`in e&&e.code===`EPIPE`}export{V as a,b as c,O as d,x as f,y as g,v as h,Y as i,k as l,w as m,H as n,ee as o,E as p,z as r,T as s,S as t,D as u};
1
+ import{C as e,T as t}from"./sdk-contracts.js";import{o as n}from"./sdk-remote-config.js";import{a as r,r as i,s as a}from"./diagnostics.js";import o from"node:path";import{constants as s}from"node:fs";import{AsyncLocalStorage as c}from"node:async_hooks";import{access as l,stat as u}from"node:fs/promises";import{spawn as d,spawnSync as f}from"node:child_process";import{Readable as p}from"node:stream";import{pipeline as m}from"node:stream/promises";const h=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,g=[`.com`,`.exe`,`.bat`,`.cmd`],_=new c;async function v(e,t){return e?await _.run(e,t):await t()}async function y(e){return await _.run(void 0,e)}async function b(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}async function x(e,t,n={}){let r=_.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}function S(e){let t=typeof e.stdout==`string`?e.stdout:String(e.stdout??``),n=typeof e.stderr==`string`?e.stderr:String(e.stderr??``),r=typeof e.exitCode==`number`?e.exitCode:1;return t===e.stdout&&n===e.stderr&&r===e.exitCode?e:{...e,stdout:t,stderr:n,exitCode:r}}function C(e,t,n={}){let r=M(e),i=k();return new Promise((a,o)=>{let s=d(r,t,{cwd:n.cwd,env:n.env,stdio:[`pipe`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});n.onSpawn?.(s);let c=``,l=n.binaryStdout?[]:void 0,u=``,f=!1,p=J(n.timeoutMs),m=null,h=!1;function g(){return!h&&(h=!0,m&&clearTimeout(m),b.dispose(),$(s),i.emitForegroundCompletion(e,t),!0)}function _(e){g()&&o(e)}function v(i){if(!g())return;let s=i??1;if(!b.didAbort&&f&&p){o(ne(r,e,t,p,s,c,u));return}let d=V(b,r,e,t,s,n.allowFailure,c,u);if(d){o(d);return}a({stdout:c,stderr:u,exitCode:s,stdoutBuffer:l?Buffer.concat(l):void 0})}let y=Y({killProcessTree:()=>Q(s,n.detached),settle:v}),b=X(n,y.requestKill);m=p?setTimeout(()=>{f=!0,y.requestKill()},p):null,n.binaryStdout||s.stdout.setEncoding(`utf8`),s.stderr.setEncoding(`utf8`),ae(s,n.stdin).catch(i=>{b.didAbort||f||oe(i)||(_(I(r,e,t,i)),Q(s,n.detached))}),s.stdout.on(`data`,e=>{if(n.binaryStdout){l?.push(Buffer.isBuffer(e)?e:Buffer.from(e));return}let t=String(e);c+=t,n.onStdoutChunk?.(t)}),s.stderr.on(`data`,e=>{let t=String(e);u+=t,n.onStderrChunk?.(t)}),s.on(`error`,n=>{_(B(b,r,e,t,n))}),s.once(`exit`,y.recordExit),s.once(`close`,v)})}async function ee(e){let t=U(e);if(!t)return!1;if(o.isAbsolute(t))return K(t);let n=process.env.PATH;if(!n)return!1;let r=W();for(let e of n.split(o.delimiter)){let n=e.trim();if(n){for(let e of G(t,r))if(await K(o.join(n,e)))return!0}}return!1}async function w(t,n){let r=H(t,n,`executable`);if(r){if(!await K(r))throw new e(`TOOL_MISSING`,`${n} points to a missing or non-executable file: ${r}`,{envName:n,path:r});return r}}async function T(t,n){let r=H(t,n,`file`);if(r){if(!await q(r))throw new e(`TOOL_MISSING`,`${n} points to a missing or non-file path: ${r}`,{envName:n,path:r});return r}}function E(t,n,r={}){let i=M(t),a=f(i,n,{cwd:r.cwd,env:r.env,stdio:[`pipe`,`pipe`,`pipe`],encoding:r.binaryStdout?void 0:`utf8`,input:r.stdin,timeout:J(r.timeoutMs),windowsHide:!0,shell:!1,...r.maxBuffer===void 0?{}:{maxBuffer:r.maxBuffer}});if(a.error){let o=a.error.code;throw o===`ETIMEDOUT`?new e(`COMMAND_FAILED`,`${i} timed out after ${J(r.timeoutMs)}ms`,{cmd:t,args:n,timeoutMs:J(r.timeoutMs)},a.error):o===`ENOENT`?P(i,t,a.error):F(i,t,n,a.error)}let o=r.binaryStdout?Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(a.stdout??``):void 0,s=r.binaryStdout?``:typeof a.stdout==`string`?a.stdout:(a.stdout??``).toString(),c=typeof a.stderr==`string`?a.stderr:(a.stderr??``).toString(),l=a.status??1;if(l!==0&&!r.allowFailure)throw R(i,t,n,l,s,c);return{stdout:s,stderr:c,exitCode:l,stdoutBuffer:o}}function D(e,t,n={}){return O(e,t,n).pid}function O(e,t,n={}){let r=M(e),i=d(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??`ignore`,detached:!0,windowsHide:!0,shell:!1}),a=i.pid??0,o=new Promise(e=>{i.once(`error`,t=>{e({pid:a,error:t.message})}),i.once(`exit`,(t,n)=>{e({pid:a,...typeof t==`number`?{exitCode:t}:{},...n?{signal:n}:{}})})});return i.unref(),{pid:a,exited:o}}function te(e,t,n={}){let r=M(e),i=k(),a=d(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??[`ignore`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});i.emitBackgroundSpawn(e,t);let o=``,s=``;return(n.captureOutput??!0)&&(a.stdout?.setEncoding(`utf8`),a.stderr?.setEncoding(`utf8`),a.stdout?.on(`data`,e=>{o+=e}),a.stderr?.on(`data`,e=>{s+=e})),{child:a,wait:new Promise((c,l)=>{let u=!1;function d(n){return!u&&(u=!0,m.dispose(),$(a),i.emitBackgroundCompletion(e,t,n),!0)}function f(i){if(!d(`exit`))return;let a=i??1,u=V(m,r,e,t,a,n.allowFailure,o,s);if(u){l(u);return}c({stdout:o,stderr:s,exitCode:a})}let p=Y({killProcessTree:()=>Q(a,n.detached),settle:f}),m=X(n,p.requestKill);a.on(`error`,n=>{d(`error`)&&l(B(m,r,e,t,n))}),a.once(`exit`,p.recordExit),a.once(`close`,f)})}}function k(){let e=r(),t=e.debug===!0,i=n(process.env.AGENT_DEVICE_EXEC_TRACE??``)===!0;if(!t&&!i)return A();i&&e.flushOnSuccess!==!0&&a({flushOnSuccess:!0});let o=Date.now(),s=!1;return{emitForegroundCompletion:(e,t)=>{s||(s=!0,j({cmd:e,args:t,startedAtMs:o}))},emitBackgroundSpawn:(e,t)=>{j({cmd:e,args:t,data:{event:`spawn`}})},emitBackgroundCompletion:(e,t,n)=>{s||(s=!0,j({cmd:e,args:t,startedAtMs:o,data:{event:n}}))}}}function A(){return{emitForegroundCompletion:()=>{},emitBackgroundSpawn:()=>{},emitBackgroundCompletion:()=>{}}}function j(e){let t=e.args.slice(0,6);i({level:`debug`,phase:`exec_command`,durationMs:e.startedAtMs===void 0?void 0:Math.max(0,Date.now()-e.startedAtMs),data:{command:e.cmd,argsPrefix:t,...e.args.length>t.length?{omittedArgCount:e.args.length-t.length}:{},...e.data??{}}})}function M(t){let n=U(t);if(!n)throw new e(`INVALID_ARGS`,`Invalid executable command: ${JSON.stringify(t)}`,{cmd:t,hint:`Use a bare command name from PATH or an absolute executable path.`});return n}function N(e,t,n,r){return r.code===`ENOENT`?P(e,t,r):F(e,t,n,r)}function P(t,n,r){return new e(`TOOL_MISSING`,`${t} not found in PATH`,{cmd:n},r)}function F(t,n,r,i){return new e(`COMMAND_FAILED`,`Failed to run ${t}`,{cmd:n,args:r},i)}function I(t,n,r,i){return new e(`COMMAND_FAILED`,`Failed to write stdin for ${t}`,{cmd:n,args:r},i instanceof Error?i:void 0)}function L(e,n,r){return t({cmd:n,args:r,executable:e})}function ne(t,n,r,i,a,o,s){return new e(`COMMAND_FAILED`,`${t} timed out after ${i}ms`,{cmd:n,args:r,stdout:o,stderr:s,exitCode:a,timeoutMs:i})}function re(t){return t instanceof e&&t.code===`COMMAND_FAILED`&&typeof t.details?.timeoutMs==`number`}function R(t,n,r,i,a,o){return new e(`COMMAND_FAILED`,`${t} exited with code ${i}`,z({stdout:a,stderr:o,exitCode:i},{cmd:n,args:r}))}function ie(t,n,r){if(t.exitCode===0)return t;throw new e(`COMMAND_FAILED`,n,z(t,typeof r==`function`?r(t):r))}function z(e,t){return{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,processExitError:!0,...t}}function B(e,t,n,r,i){return e.didAbort?L(t,n,r):N(t,n,r,i)}function V(e,t,n,r,i,a,o,s){return e.didAbort?L(t,n,r):i!==0&&!a?R(t,n,r,i,o,s):null}function H(t,n,r){let i=t?.trim();if(i){if(!o.isAbsolute(i)||i.includes(`\0`))throw new e(`INVALID_ARGS`,`${n} must be an absolute ${r} path, not ${JSON.stringify(t)}`,{envName:n,path:t});return i}}function U(e){let t=e.trim();return!t||t.includes(`\0`)?null:o.isAbsolute(t)?t:t.includes(`/`)||t.includes(`\\`)?null:h.test(t)?t:null}function W(){if(process.platform!==`win32`)return[``];let e=process.env.PATHEXT;if(!e)return g;let t=e.split(`;`).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:g}function G(e,t){if(process.platform!==`win32`)return[e];let n=e.toLowerCase();return t.some(e=>n.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}async function K(e){try{return await q(e)?(await l(e,process.platform===`win32`?s.F_OK:s.X_OK),!0):!1}catch{return!1}}async function q(e){try{return(await u(e)).isFile()}catch{return!1}}function J(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function Y(e){let t=!1,n=!1,r=null,i=()=>{t&&n&&e.settle(r)};return{requestKill:()=>{t=!0,e.killProcessTree(),i()},recordExit:e=>{n=!0,r=e??1,i()}}}function X(e,t){let n=!1,r=()=>{n=!0,t()};return e.signal?.aborted?r():e.signal?.addEventListener(`abort`,r,{once:!0}),{get didAbort(){return n},dispose:()=>{e.signal?.removeEventListener(`abort`,r)}}}function Z(e,t){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(-e,t),!0}catch{return!1}}function Q(e,t){if(t&&e.pid&&process.platform!==`win32`){Z(e.pid,`SIGKILL`);return}e.exitCode===null&&e.signalCode===null&&e.kill(`SIGKILL`)}function $(e){e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()}async function ae(e,t){if(e.stdin){if(t===void 0){e.stdin?.end();return}await m(p.from([t]),e.stdin)}}function oe(e){return e instanceof Error&&`code`in e&&e.code===`EPIPE`}export{y as _,ie as a,b as c,O as d,x as f,v as g,ee as h,K as i,te as l,Z as m,z as n,w as o,E as p,re as r,T as s,S as t,D as u};
package/dist/src/file.js CHANGED
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";import{O as t,t as n}from"./owner-identity.js";import{t as r}from"./timeouts.js";import i from"node:path";import a from"node:fs";async function o(t){let{lockDirPath:n,owner:o}=t,l=i.join(n,`owner.json`),d=Date.now()+(t.timeoutMs??3e4),f=t.pollMs??100,p=t.ownerGraceMs??5e3,m=t.description??`process lock`;for(a.mkdirSync(i.dirname(n),{recursive:!0});Date.now()<d;)try{a.mkdirSync(n),s(l,o);let e=!1;return async()=>{e||(e=!0,a.rmSync(n,{recursive:!0,force:!0}))}}catch(e){let t=e;if(t.code!==`EEXIST`)throw t;if(c(n,l,p))continue;await r(f)}throw new e(`COMMAND_FAILED`,`Timed out waiting for ${m}`,{lockDirPath:n,...u(n,l)})}function s(e,n){t({destination:e,contents:JSON.stringify(n)})}function c(e,t,n){let r=null;try{r=a.statSync(e)}catch{return!0}let i=l(t);return i?!d(i)&&(a.rmSync(e,{recursive:!0,force:!0}),!0):Date.now()-r.mtimeMs<n?!1:(a.rmSync(e,{recursive:!0,force:!0}),!0)}function l(e){try{return JSON.parse(a.readFileSync(e,`utf8`))}catch{return null}}function u(e,t){let r=Date.now(),i=l(t),o;try{o=Math.max(0,Math.round(r-a.statSync(e).mtimeMs))}catch{}return{...o===void 0?{}:{lockAgeMs:o},...i?{ownerPid:i.pid,ownerStartTime:i.startTime,ownerAgeMs:Math.max(0,Math.round(r-i.acquiredAtMs)),ownerLiveness:n({owner:i})}:{}}}function d(e){let t=n({owner:e});return t!==`owner-process-dead`&&t!==`owner-process-reused`}export{o as t};
1
+ import{C as e}from"./sdk-contracts.js";import{D as t,t as n}from"./owner-identity.js";import{t as r}from"./timeouts.js";import i from"node:path";import a from"node:fs";async function o(t){let{lockDirPath:n,owner:o}=t,l=i.join(n,`owner.json`),d=Date.now()+(t.timeoutMs??3e4),f=t.pollMs??100,p=t.ownerGraceMs??5e3,m=t.description??`process lock`;for(a.mkdirSync(i.dirname(n),{recursive:!0});Date.now()<d;)try{a.mkdirSync(n),s(l,o);let e=!1;return async()=>{e||(e=!0,a.rmSync(n,{recursive:!0,force:!0}))}}catch(e){let t=e;if(t.code!==`EEXIST`)throw t;if(c(n,l,p))continue;await r(f)}throw new e(`COMMAND_FAILED`,`Timed out waiting for ${m}`,{lockDirPath:n,...u(n,l)})}function s(e,n){t({destination:e,contents:JSON.stringify(n)})}function c(e,t,n){let r=null;try{r=a.statSync(e)}catch{return!0}let i=l(t);return i?!d(i)&&(a.rmSync(e,{recursive:!0,force:!0}),!0):Date.now()-r.mtimeMs<n?!1:(a.rmSync(e,{recursive:!0,force:!0}),!0)}function l(e){try{return JSON.parse(a.readFileSync(e,`utf8`))}catch{return null}}function u(e,t){let r=Date.now(),i=l(t),o;try{o=Math.max(0,Math.round(r-a.statSync(e).mtimeMs))}catch{}return{...o===void 0?{}:{lockAgeMs:o},...i?{ownerPid:i.pid,ownerStartTime:i.startTime,ownerAgeMs:Math.max(0,Math.round(r-i.acquiredAtMs)),ownerLiveness:n({owner:i})}:{}}}function d(e){let t=n({owner:e});return t!==`owner-process-dead`&&t!==`owner-process-reused`}export{o as t};
package/dist/src/find.js CHANGED
@@ -1 +1 @@
1
- import{p as e}from"./sdk-contracts.js";import{An as t,Ft as n,Nn as r,On as i,ht as a,kn as o}from"./sdk-batch.js";import{c as s}from"./session-store.js";import{C as c,_ as l,g as u,h as d,p as f}from"./runtime.js";import{n as p,t as m}from"./success-text.js";import{f as h}from"./absence-observation-errors.js";import{a as g,i as _}from"./request-runtime-binding.js";import{C as v,E as y,S as b}from"./session-snapshot.js";import{p as x}from"./quality-warnings.js";import{t as S}from"./internal/daemon.js";import{t as C}from"./snapshot-runtime-binding.js";import{l as w,n as T,u as E}from"./selector-runtime.js";import{t as D}from"./type-text-runtime.js";function O(t,n){let r=n[0]?.rect;if(!r)return t;let i=t.filter(t=>{if(!t.rect)return!1;let n=e(t.rect);return n.x>=r.x&&n.x<=r.x+r.width&&n.y>=r.y&&n.y<=r.y+r.height}),a=i.length>0?i:t;return a.length<2?a:k(a,n,u(n))}function k(e,t,n){return e.map((e,r)=>({node:e,index:r,score:A(e,t,n)})).sort((e,t)=>t.score===e.score?M(e.node)-M(t.node)||e.index-t.index:t.score-e.score).map(e=>e.node)}function A(e,t,n){let r=n(e);if(r.reason===`covered`)return 0;let i=j(r,t[0]);return i>0?i:e.hittable&&e.rect&&!l(e,t[0])?3:+!!e.rect}function j(e,t){return e.node.rect?e.reason===`semantic-target`||e.reason===`same-rect-descendant`?4:e.reason===`hittable-ancestor`&&!l(e.node,t)?2:0:0}function M(e){return e.rect?e.rect.width*e.rect.height:1/0}function N(e,t,n){let r={matches:e.length,candidates:e.slice(0,5).map(e=>h(e,0,!1))};return _(`AMBIGUOUS_MATCH`,`find matched ${e.length} elements for ${t} "${n}". Use a more specific locator or selector.`,{locator:t,query:n,...r})}function P(e){if(e.ambiguity!==`reject-candidates`)throw Error(`find's resolution policy must reject candidates, got "${e.ambiguity}"`)}function F(e){let{nodes:t,locator:n,query:r,selectorExpression:i,flags:a,platform:s}=e,u=c.findAct,d=t.filter(e=>!l(e,t[0])),p=u.resolution,m;if(m=i?f(u,d,i,{platform:s}).list?.matchedNodes??[]:o(d,n,r,{requireRect:p.requireRect}).matches,m=O(m,t),m.length>1){P(p);let e=I(m,a);if(!e)return{ok:!1,response:N(m,n,r)};m=e}let h=m[0]??null;return h?{ok:!0,node:h}:{ok:!1,response:_(`COMMAND_FAILED`,`find did not match any element`)}}function I(e,t){return t?.findFirst?[e[0]]:t?.findLast?[e.at(-1)]:null}function L(e){let{device:t,session:n,req:r,logPath:i,locator:a,query:o,sessionStore:s,sessionName:c}=e,l=w({device:t,session:n,sessionStore:s,sessionName:c,req:r,logPath:i,capture:e.capture});return async()=>{let{snapshot:e}=await l.capture({flags:{...r.flags,snapshotInteractiveOnly:!0},recovery:{legacyIosSparse:{query:o,shouldScope:z(a)},sparseVerdictQueryScope:{query:o,shouldScope:z(a)}}});return{nodes:e.nodes,snapshotQuality:e.snapshotQuality,systemSurfaceOnly:e.systemSurfaceOnly,iosSystemSurfaceBundleId:e.iosSystemSurfaceBundleId}}}function R(e){return _(`COMMAND_FAILED`,`find could not read the current accessibility tree`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen.`})}function z(e){return e!==`role`}async function B(e){let{req:o,sessionName:s,logPath:l,sessionStore:u,invoke:f}=e,p=o.command;if(p!==`find`)return null;let m=o.positionals??[],h=i(m,o.flags);if(!h.ok)return _(h.code,h.message);let{locator:v,query:y,action:b,value:S}=h.parsed;if(o.flags?.record&&!t(b))return _(`INVALID_ARGS`,`find ${b} is a mutating action and is always recorded; --record only applies to a read-only find (exists, wait, list, get text, get attrs).`);let w=await T({req:o,sessionName:s,logPath:l,sessionStore:u,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(w)return w;let D=u.get(s);if(!D)return g();let O=D.device,k=await C({command:`find`,device:O,session:D,plan:n({hasActiveApp:D.appBundleId!==void 0,intent:a(b)}),inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(!k.ok)return k.response;let A=r(v,y),j=L({device:O,session:D,req:o,logPath:l,locator:v,query:y,sessionStore:u,sessionName:s,capture:k.capture}),M={req:o,sessionName:s,logPath:l,sessionStore:u,invoke:f,session:D,device:O,command:p,locator:v,query:y,publicFlags:X(o.flags),boundFocusPoint:k.focusPoint,boundTypeText:k.typeText},N=await j();if(x(N.snapshotQuality))return R(N.snapshotQuality);let{nodes:P}=N,I=F({nodes:P,locator:v,query:y,selectorExpression:A,flags:o.flags,platform:O.platform});if(!I.ok)return E(I.response,N);let z=I.node,B=await d(c.findAct,P,z),H=B.node,U=`@${H.ref}`,W={...o.flags??{},noRecord:!0},G=await V(M,{node:z,resolvedNode:H,ref:U,nodes:P,...N.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:N.iosSystemSurfaceBundleId}:{},actionFlags:W,...B.kind===`occluded`?{occludedNode:B.node}:{}},b,S);return G&&E(G,N)}async function V(e,t,n,r){let i={click:()=>U(e,t),fill:()=>W(e,t,r),focus:()=>G(e,t),type:()=>K(e,t,r)}[n];return i?await i():null}function H(e){return{ref:e.ref,node:e.resolvedNode,nodes:e.nodes,...e.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:e.iosSystemSurfaceBundleId}:{}}}async function U(t,n){let{req:r,sessionName:i,sessionStore:a,session:o,invoke:c,command:l,locator:u,query:d,publicFlags:f}=t,h=await c({token:r.token,session:i,command:`click`,positionals:[n.ref],flags:n.actionFlags,internal:{findResolvedTarget:H(n)}});if(!h.ok)return h;let g=n.resolvedNode.rect?e(n.resolvedNode.rect):n.node.rect?e(n.node.rect):null,_={ref:n.ref,locator:u,query:d};g&&(_.x=g.x,_.y=g.y);let v=m(h.data)??`Tapped ${n.ref}${g?` (${g.x}, ${g.y})`:``}`;return Object.assign(_,p(v)),s(a,o,r,l,{ref:n.ref,action:`click`,locator:u,query:d},{flags:f}),{ok:!0,data:_}}async function W(e,t,n){let{req:r,sessionName:i,sessionStore:a,session:o,invoke:c,command:l,publicFlags:u}=e;if(n===void 0)return _(`INVALID_ARGS`,`find fill requires text (use "" to clear the field)`);let d=await c({token:r.token,session:i,command:`fill`,positionals:[t.ref,n],flags:t.actionFlags,internal:{findResolvedTarget:H(t)}});return d.ok&&s(a,o,r,l,{ref:t.ref,action:`fill`},{flags:u}),d}async function G(e,t){let n=await q(e,t);return n.ok&&Y(e,t,`focus`),n}async function K(e,t,n){let{req:r,logPath:i,session:a}=e;if(!n)return _(`INVALID_ARGS`,`find type requires text`);let o=await q(e,t);if(!o.ok)return o;y(a);let s=e.boundTypeText;if(!s)return _(`COMMAND_FAILED`,`find type was admitted without a text-entry operation`);let c=await D({operations:{typeText:s}},[n],v(i,r.flags,a.appBundleId,a.trace?.outPath));return Y(e,t,`type`),{ok:!0,data:c??{ref:t.ref}}}async function q(t,n){let{req:r,logPath:i,session:a}=t,o=J(n,`be focused`);if(o)return o;let s=n.resolvedNode.rect?e(n.resolvedNode.rect):null;if(!s)return _(`COMMAND_FAILED`,`matched element has no bounds`);y(a);let c=t.boundFocusPoint;return c?{ok:!0,data:await S({operations:{focusPoint:c}},s,v(i,r.flags,a.appBundleId,a.trace?.outPath))??{ref:n.ref}}:_(`COMMAND_FAILED`,`find focus was admitted without a focus operation`)}function J(e,t){let n=e.occludedNode;return n?_(`COMMAND_FAILED`,`Matched element ${e.ref} is covered by another visible element and cannot ${t} safely`,{ref:`@${n.ref}`,interactionBlocked:n.interactionBlocked,hint:`Use a different visible target, scroll it clear of the overlay, or inspect with snapshot/screenshot before retrying.`}):null}function Y(e,t,n){let{req:r,sessionStore:i,session:a,command:o,publicFlags:c}=e;s(i,a,r,o,{ref:t.ref,action:n},{flags:c})}function X(e){return{...b(e)??{}}}export{B as handleFindCommands};
1
+ import{p as e}from"./sdk-contracts.js";import{An as t,Ft as n,Nn as r,On as i,ht as a,kn as o}from"./sdk-batch.js";import{c as s}from"./session-store.js";import{C as c,_ as l,g as u,h as d,p as f}from"./runtime.js";import{r as p,t as m}from"./success-text.js";import{f as h}from"./absence-observation-errors.js";import{a as g,i as _}from"./request-runtime-binding.js";import{C as v,E as y,S as b}from"./session-snapshot.js";import{p as x}from"./quality-warnings.js";import{t as S}from"./internal/daemon.js";import{t as C}from"./snapshot-runtime-binding.js";import{l as w,n as T,u as E}from"./selector-runtime.js";import{t as D}from"./type-text-runtime.js";function O(t,n){let r=n[0]?.rect;if(!r)return t;let i=t.filter(t=>{if(!t.rect)return!1;let n=e(t.rect);return n.x>=r.x&&n.x<=r.x+r.width&&n.y>=r.y&&n.y<=r.y+r.height}),a=i.length>0?i:t;return a.length<2?a:k(a,n,u(n))}function k(e,t,n){return e.map((e,r)=>({node:e,index:r,score:A(e,t,n)})).sort((e,t)=>t.score===e.score?M(e.node)-M(t.node)||e.index-t.index:t.score-e.score).map(e=>e.node)}function A(e,t,n){let r=n(e);if(r.reason===`covered`)return 0;let i=j(r,t[0]);return i>0?i:e.hittable&&e.rect&&!l(e,t[0])?3:+!!e.rect}function j(e,t){return e.node.rect?e.reason===`semantic-target`||e.reason===`same-rect-descendant`?4:e.reason===`hittable-ancestor`&&!l(e.node,t)?2:0:0}function M(e){return e.rect?e.rect.width*e.rect.height:1/0}function N(e,t,n){let r={matches:e.length,candidates:e.slice(0,5).map(e=>h(e,0,!1))};return _(`AMBIGUOUS_MATCH`,`find matched ${e.length} elements for ${t} "${n}". Use a more specific locator or selector.`,{locator:t,query:n,...r})}function P(e){if(e.ambiguity!==`reject-candidates`)throw Error(`find's resolution policy must reject candidates, got "${e.ambiguity}"`)}function F(e){let{nodes:t,locator:n,query:r,selectorExpression:i,flags:a,platform:s}=e,u=c.findAct,d=t.filter(e=>!l(e,t[0])),p=u.resolution,m;if(m=i?f(u,d,i,{platform:s}).list?.matchedNodes??[]:o(d,n,r,{requireRect:p.requireRect}).matches,m=O(m,t),m.length>1){P(p);let e=I(m,a);if(!e)return{ok:!1,response:N(m,n,r)};m=e}let h=m[0]??null;return h?{ok:!0,node:h}:{ok:!1,response:_(`COMMAND_FAILED`,`find did not match any element`)}}function I(e,t){return t?.findFirst?[e[0]]:t?.findLast?[e.at(-1)]:null}function L(e){let{device:t,session:n,req:r,logPath:i,locator:a,query:o,sessionStore:s,sessionName:c}=e,l=w({device:t,session:n,sessionStore:s,sessionName:c,req:r,logPath:i,capture:e.capture});return async()=>{let{snapshot:e}=await l.capture({flags:{...r.flags,snapshotInteractiveOnly:!0},recovery:{legacyIosSparse:{query:o,shouldScope:z(a)},sparseVerdictQueryScope:{query:o,shouldScope:z(a)}}});return{nodes:e.nodes,snapshotQuality:e.snapshotQuality,systemSurfaceOnly:e.systemSurfaceOnly,iosSystemSurfaceBundleId:e.iosSystemSurfaceBundleId}}}function R(e){return _(`COMMAND_FAILED`,`find could not read the current accessibility tree`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen.`})}function z(e){return e!==`role`}async function B(e){let{req:o,sessionName:s,logPath:l,sessionStore:u,invoke:f}=e,p=o.command;if(p!==`find`)return null;let m=o.positionals??[],h=i(m,o.flags);if(!h.ok)return _(h.code,h.message);let{locator:v,query:y,action:b,value:S}=h.parsed;if(o.flags?.record&&!t(b))return _(`INVALID_ARGS`,`find ${b} is a mutating action and is always recorded; --record only applies to a read-only find (exists, wait, list, get text, get attrs).`);let w=await T({req:o,sessionName:s,logPath:l,sessionStore:u,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(w)return w;let D=u.get(s);if(!D)return g();let O=D.device,k=await C({command:`find`,device:O,session:D,plan:n({hasActiveApp:D.appBundleId!==void 0,intent:a(b)}),inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(!k.ok)return k.response;let A=r(v,y),j=L({device:O,session:D,req:o,logPath:l,locator:v,query:y,sessionStore:u,sessionName:s,capture:k.capture}),M={req:o,sessionName:s,logPath:l,sessionStore:u,invoke:f,session:D,device:O,command:p,locator:v,query:y,publicFlags:X(o.flags),boundFocusPoint:k.focusPoint,boundTypeText:k.typeText},N=await j();if(x(N.snapshotQuality))return R(N.snapshotQuality);let{nodes:P}=N,I=F({nodes:P,locator:v,query:y,selectorExpression:A,flags:o.flags,platform:O.platform});if(!I.ok)return E(I.response,N);let z=I.node,B=await d(c.findAct,P,z),H=B.node,U=`@${H.ref}`,W={...o.flags??{},noRecord:!0},G=await V(M,{node:z,resolvedNode:H,ref:U,nodes:P,...N.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:N.iosSystemSurfaceBundleId}:{},actionFlags:W,...B.kind===`occluded`?{occludedNode:B.node}:{}},b,S);return G&&E(G,N)}async function V(e,t,n,r){let i={click:()=>U(e,t),fill:()=>W(e,t,r),focus:()=>G(e,t),type:()=>K(e,t,r)}[n];return i?await i():null}function H(e){return{ref:e.ref,node:e.resolvedNode,nodes:e.nodes,...e.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:e.iosSystemSurfaceBundleId}:{}}}async function U(t,n){let{req:r,sessionName:i,sessionStore:a,session:o,invoke:c,command:l,locator:u,query:d,publicFlags:f}=t,h=await c({token:r.token,session:i,command:`click`,positionals:[n.ref],flags:n.actionFlags,internal:{findResolvedTarget:H(n)}});if(!h.ok)return h;let g=n.resolvedNode.rect?e(n.resolvedNode.rect):n.node.rect?e(n.node.rect):null,_={ref:n.ref,locator:u,query:d};g&&(_.x=g.x,_.y=g.y);let v=m(h.data)??`Tapped ${n.ref}${g?` (${g.x}, ${g.y})`:``}`;return Object.assign(_,p(v)),s(a,o,r,l,{ref:n.ref,action:`click`,locator:u,query:d},{flags:f}),{ok:!0,data:_}}async function W(e,t,n){let{req:r,sessionName:i,sessionStore:a,session:o,invoke:c,command:l,publicFlags:u}=e;if(n===void 0)return _(`INVALID_ARGS`,`find fill requires text (use "" to clear the field)`);let d=await c({token:r.token,session:i,command:`fill`,positionals:[t.ref,n],flags:t.actionFlags,internal:{findResolvedTarget:H(t)}});return d.ok&&s(a,o,r,l,{ref:t.ref,action:`fill`},{flags:u}),d}async function G(e,t){let n=await q(e,t);return n.ok&&Y(e,t,`focus`),n}async function K(e,t,n){let{req:r,logPath:i,session:a}=e;if(!n)return _(`INVALID_ARGS`,`find type requires text`);let o=await q(e,t);if(!o.ok)return o;y(a);let s=e.boundTypeText;if(!s)return _(`COMMAND_FAILED`,`find type was admitted without a text-entry operation`);let c=await D({operations:{typeText:s}},[n],v(i,r.flags,a.appBundleId,a.trace?.outPath));return Y(e,t,`type`),{ok:!0,data:c??{ref:t.ref}}}async function q(t,n){let{req:r,logPath:i,session:a}=t,o=J(n,`be focused`);if(o)return o;let s=n.resolvedNode.rect?e(n.resolvedNode.rect):null;if(!s)return _(`COMMAND_FAILED`,`matched element has no bounds`);y(a);let c=t.boundFocusPoint;return c?{ok:!0,data:await S({operations:{focusPoint:c}},s,v(i,r.flags,a.appBundleId,a.trace?.outPath))??{ref:n.ref}}:_(`COMMAND_FAILED`,`find focus was admitted without a focus operation`)}function J(e,t){let n=e.occludedNode;return n?_(`COMMAND_FAILED`,`Matched element ${e.ref} is covered by another visible element and cannot ${t} safely`,{ref:`@${n.ref}`,interactionBlocked:n.interactionBlocked,hint:`Use a different visible target, scroll it clear of the overlay, or inspect with snapshot/screenshot before retrying.`}):null}function Y(e,t,n){let{req:r,sessionStore:i,session:a,command:o,publicFlags:c}=e;s(i,a,r,o,{ref:t.ref,action:n},{flags:c})}function X(e){return{...b(e)??{}}}export{B as handleFindCommands};
@@ -1 +1 @@
1
- import{C as e,M as t}from"./sdk-contracts.js";import{Mt as n,_t as r}from"./sdk-batch.js";import{g as i,h as a,m as o}from"./session-snapshot.js";import{a as s}from"./gesture-admission.js";async function c(e){let t=await i({command:`runtime gesture-viewport`,device:e.device,use:r,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});return t.type===`response`?{ok:!1,response:t.response}:{ok:!0,read:d(t.runtime).gestureViewport}}async function l(r){let i=n(r.input),o=await a({command:`gesture`,device:r.device,required:i.use.required,inspectFacts:r.inspectFacts,bindDevice:r.bindDevice,unavailableResponse:n=>({ok:!1,error:t(new e(`UNSUPPORTED_OPERATION`,s(r.device,i.tier,r.input.intent),{gesture:r.input.intent,...n.hint===void 0?{}:{hint:n.hint}}))})});return o.type===`response`?{ok:!1,response:o.response}:{ok:!0,gestures:await u(o.bind,r.device,i)}}async function u(e,t,n){switch(n.tier){case`plan`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performGesturePlan(f(e,t)),...d(r)}}case`directional-fling`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performDirectionalFlingPlan(f(e,t)),...d(r)}}case`multi-touch`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performMultiTouchGesturePlan(f(e,t)),...d(r)}}case`target-authored-drag`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performTargetAuthoredDrag(f(e,t)),...d(r)}}}}function d(e){let{gestureViewport:t}=e.operations,n=e.operations.captureSnapshot?{operations:{captureSnapshot:e.operations.captureSnapshot}}:void 0,r=t?{operations:{gestureViewport:t}}:void 0;return Object.freeze({...n?{captureSnapshot:async e=>await n.operations.captureSnapshot(e)}:{},...r?{gestureViewport:async e=>await r.operations.gestureViewport(p(e))}:{}})}function f(e,t){return{plan:e,...t.appBundleId===void 0?{}:{options:{appBundleId:t.appBundleId}},execution:o(t)}}function p(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:o(e)}}export{c as n,l as t};
1
+ import{C as e,N as t}from"./sdk-contracts.js";import{Mt as n,_t as r}from"./sdk-batch.js";import{g as i,h as a,m as o}from"./session-snapshot.js";import{a as s}from"./gesture-admission.js";async function c(e){let t=await i({command:`runtime gesture-viewport`,device:e.device,use:r,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});return t.type===`response`?{ok:!1,response:t.response}:{ok:!0,read:d(t.runtime).gestureViewport}}async function l(r){let i=n(r.input),o=await a({command:`gesture`,device:r.device,required:i.use.required,inspectFacts:r.inspectFacts,bindDevice:r.bindDevice,unavailableResponse:n=>({ok:!1,error:t(new e(`UNSUPPORTED_OPERATION`,s(r.device,i.tier,r.input.intent),{gesture:r.input.intent,...n.hint===void 0?{}:{hint:n.hint}}))})});return o.type===`response`?{ok:!1,response:o.response}:{ok:!0,gestures:await u(o.bind,r.device,i)}}async function u(e,t,n){switch(n.tier){case`plan`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performGesturePlan(f(e,t)),...d(r)}}case`directional-fling`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performDirectionalFlingPlan(f(e,t)),...d(r)}}case`multi-touch`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performMultiTouchGesturePlan(f(e,t)),...d(r)}}case`target-authored-drag`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performTargetAuthoredDrag(f(e,t)),...d(r)}}}}function d(e){let{gestureViewport:t}=e.operations,n=e.operations.captureSnapshot?{operations:{captureSnapshot:e.operations.captureSnapshot}}:void 0,r=t?{operations:{gestureViewport:t}}:void 0;return Object.freeze({...n?{captureSnapshot:async e=>await n.operations.captureSnapshot(e)}:{},...r?{gestureViewport:async e=>await r.operations.gestureViewport(p(e))}:{}})}function f(e,t){return{plan:e,...t.appBundleId===void 0?{}:{options:{appBundleId:t.appBundleId}},execution:o(t)}}function p(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:o(e)}}export{c as n,l as t};
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";import{c as t}from"./diagnostics.js";import"./diagnostics2.js";import{_ as n,a as r,c as i,d as a,f as o,g as s,h as c,l,n as u,o as d,p as f,r as p,s as m,t as h,u as g,v as _,x as v,y}from"./src3.js";function b(b,x){let S=t=>async()=>{throw new e(`UNSUPPORTED_OPERATION`,`${t} is not supported on HarmonyOS`)};return{open:(e,t)=>l(b,e,{activity:t?.activity}),openDevice:()=>m(b),close:e=>p(b,e),tap:(e,t)=>a(b,e,t),doubleTap:(e,t)=>r(b,e,t),longPress:(e,t,n)=>i(b,e,t,n),focus:(e,t)=>a(b,e,t),type:(e,t)=>v(b,e,t),fill:(e,t,n,r)=>d(b,e,t,n,r),scroll:(e,t)=>s(b,e,t),performGesture:e=>g(b,e),gestureViewport:()=>f(b),screenshot:e=>c(b,e),snapshot:async e=>({...await t(`snapshot_capture`,async()=>await y(b,e),{backend:`harmonyos-arkui`}),backend:`harmonyos-arkui`,producer:`harmonyos-uitest`}),back:()=>u(b),home:()=>m(b),setOrientation:e=>n(b,e),appSwitcher:()=>h(b),tvRemote:S(`tv-remote`),keyboardDismiss:async()=>(await o(b,`Back`),{kind:`acknowledged`}),keyboardEnter:async()=>(await o(b,`Enter`),{kind:`harmonyos-acknowledged`}),readClipboard:S(`clipboard`),writeClipboard:S(`clipboard`),setSetting:(e,t,n)=>_(b,e,t,n),readAlert:S(`alert`),awaitAlert:S(`alert`),acceptAlert:S(`alert`),dismissAlert:S(`alert`)}}export{b as createHarmonyInteractor};
1
+ import{C as e}from"./sdk-contracts.js";import{c as t}from"./diagnostics.js";import"./diagnostics2.js";import{_ as n,a as r,c as i,d as a,f as o,g as s,h as c,l,n as u,o as d,p as f,r as p,s as m,t as h,u as g,v as _,x as v,y}from"./src4.js";function b(b,x){let S=t=>async()=>{throw new e(`UNSUPPORTED_OPERATION`,`${t} is not supported on HarmonyOS`)};return{open:(e,t)=>l(b,e,{activity:t?.activity}),openDevice:()=>m(b),close:e=>p(b,e),tap:(e,t)=>a(b,e,t),doubleTap:(e,t)=>r(b,e,t),longPress:(e,t,n)=>i(b,e,t,n),focus:(e,t)=>a(b,e,t),type:(e,t)=>v(b,e,t),fill:(e,t,n,r)=>d(b,e,t,n,r),scroll:(e,t)=>s(b,e,t),performGesture:e=>g(b,e),gestureViewport:()=>f(b),screenshot:e=>c(b,e),snapshot:async e=>({...await t(`snapshot_capture`,async()=>await y(b,e),{backend:`harmonyos-arkui`}),backend:`harmonyos-arkui`,producer:`harmonyos-uitest`}),back:()=>u(b),home:()=>m(b),setOrientation:e=>n(b,e),appSwitcher:()=>h(b),tvRemote:S(`tv-remote`),keyboardDismiss:async()=>(await o(b,`Back`),{kind:`acknowledged`}),keyboardEnter:async()=>(await o(b,`Enter`),{kind:`harmonyos-acknowledged`}),readClipboard:S(`clipboard`),writeClipboard:S(`clipboard`),setSetting:(e,t,n)=>_(b,e,t,n),readAlert:S(`alert`),awaitAlert:S(`alert`),acceptAlert:S(`alert`),dismissAlert:S(`alert`)}}export{b as createHarmonyInteractor};
@@ -1,2 +1,2 @@
1
- import{r as e}from"./rolldown-runtime.js";import{C as t}from"./sdk-contracts.js";import{E as n,_ as r,d as i}from"./owner-identity.js";import{l as a,o}from"./exec.js";import"./command.js";import"./process.js";import{D as s,c,f as l,g as u,h as d,n as f,o as p,r as m,t as h,w as g,y as _}from"./host-file.js";import{a as v,i as y,n as b}from"./tool-provider.js";import x from"node:path";import{createHash as S}from"node:crypto";import{fileURLToPath as C}from"node:url";var w=e({quitMacOsApp:()=>W,resolveFrontmostMacOsApp:()=>U,resolveMacOsHelperPackageRootFrom:()=>M,runMacOsAlertAction:()=>K,runMacOsPermissionAction:()=>G,runMacOsPressAction:()=>Y,runMacOsReadTextAction:()=>J,runMacOsScreenshotAction:()=>X,runMacOsSnapshotAction:()=>q,startMacOsAudioProbeProcess:()=>V});const T=`agent-device-macos-helper`,E=`AGENT_DEVICE_MACOS_HELPER_BIN`,D=x.join(l(),`.agent-device`,`macos-helper`,`current`),O=x.join(D,`manifest.json`),k=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/;function A(e){let n=e.trim();if(!k.test(n))throw new t(`INVALID_ARGS`,`macOS bundle id must use reverse-DNS form like com.example.App`,{bundleId:e});return n}function j(e,t){t.bundleId&&e.push(`--bundle-id`,A(t.bundleId)),t.surface&&e.push(`--surface`,t.surface)}function M(e){let n=x.dirname(e);for(;;){let e=x.join(n,`apple`,`macos-helper`);if(c(x.join(e,`Package.swift`)))return e;let t=x.dirname(n);if(t===n)break;n=t}throw new t(`COMMAND_FAILED`,`Unable to locate macOS helper package root`,{modulePath:e})}function N(){return M(C(import.meta.url))}function P(){return x.join(N(),`.build`,`release`,T)}function F(){return x.join(D,T)}async function I(e){let t=await u(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>{let n=x.join(e,t.name);return t.isDirectory()?t.name===`.build`?[]:await I(n):!t.isFile()||!t.name.endsWith(`.swift`)&&t.name!==`Package.swift`?[]:[n]}))).flat().sort()}async function L(e){let t=await I(e),n=S(`sha256`);for(let r of t)n.update(x.relative(e,r)),n.update(`\0`),n.update(await d(r)),n.update(`\0`);let r=await v(`swift`,[`--version`],{allowFailure:!0,cwd:e,timeoutMs:1e4});return n.update(`swift-version`),n.update(`\0`),n.update(r.stdout||r.stderr||`exit:${r.exitCode}`),n.update(`\0`),n.digest(`hex`)}async function R(){try{let e=JSON.parse(await _(O));return typeof e.fingerprint==`string`?e.fingerprint:null}catch{return null}}async function z(){let e=await o(r(E),E);if(e)return e;let t=N(),i=await L(t),a=F();try{if(await R()===i)return await h(a),a}catch{}let c=P();n(`agent-device: building macOS helper (first run or helper update)
1
+ import{r as e}from"./rolldown-runtime.js";import{C as t}from"./sdk-contracts.js";import{T as n,_ as r,d as i}from"./owner-identity.js";import{l as a,o}from"./exec.js";import"./command.js";import"./process.js";import{D as s,c,f as l,g as u,h as d,n as f,o as p,r as m,t as h,w as g,y as _}from"./host-file.js";import{a as v,i as y,n as b}from"./tool-provider.js";import x from"node:path";import{createHash as S}from"node:crypto";import{fileURLToPath as C}from"node:url";var w=e({quitMacOsApp:()=>W,resolveFrontmostMacOsApp:()=>U,resolveMacOsHelperPackageRootFrom:()=>M,runMacOsAlertAction:()=>K,runMacOsPermissionAction:()=>G,runMacOsPressAction:()=>Y,runMacOsReadTextAction:()=>J,runMacOsScreenshotAction:()=>X,runMacOsSnapshotAction:()=>q,startMacOsAudioProbeProcess:()=>V});const T=`agent-device-macos-helper`,E=`AGENT_DEVICE_MACOS_HELPER_BIN`,D=x.join(l(),`.agent-device`,`macos-helper`,`current`),O=x.join(D,`manifest.json`),k=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/;function A(e){let n=e.trim();if(!k.test(n))throw new t(`INVALID_ARGS`,`macOS bundle id must use reverse-DNS form like com.example.App`,{bundleId:e});return n}function j(e,t){t.bundleId&&e.push(`--bundle-id`,A(t.bundleId)),t.surface&&e.push(`--surface`,t.surface)}function M(e){let n=x.dirname(e);for(;;){let e=x.join(n,`apple`,`macos-helper`);if(c(x.join(e,`Package.swift`)))return e;let t=x.dirname(n);if(t===n)break;n=t}throw new t(`COMMAND_FAILED`,`Unable to locate macOS helper package root`,{modulePath:e})}function N(){return M(C(import.meta.url))}function P(){return x.join(N(),`.build`,`release`,T)}function F(){return x.join(D,T)}async function I(e){let t=await u(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>{let n=x.join(e,t.name);return t.isDirectory()?t.name===`.build`?[]:await I(n):!t.isFile()||!t.name.endsWith(`.swift`)&&t.name!==`Package.swift`?[]:[n]}))).flat().sort()}async function L(e){let t=await I(e),n=S(`sha256`);for(let r of t)n.update(x.relative(e,r)),n.update(`\0`),n.update(await d(r)),n.update(`\0`);let r=await v(`swift`,[`--version`],{allowFailure:!0,cwd:e,timeoutMs:1e4});return n.update(`swift-version`),n.update(`\0`),n.update(r.stdout||r.stderr||`exit:${r.exitCode}`),n.update(`\0`),n.digest(`hex`)}async function R(){try{let e=JSON.parse(await _(O));return typeof e.fingerprint==`string`?e.fingerprint:null}catch{return null}}async function z(){let e=await o(r(E),E);if(e)return e;let t=N(),i=await L(t),a=F();try{if(await R()===i)return await h(a),a}catch{}let c=P();n(`agent-device: building macOS helper (first run or helper update)
2
2
  `),await v(`swift`,[`build`,`-c`,`release`,`--package-path`,t],{cwd:t,timeoutMs:12e4}),await p(D);let l=`${a}.tmp`;return await m(c,l),await g(l,a),await f(a,493),await s(O,`${JSON.stringify({fingerprint:i},null,2)}\n`),a}async function B(){let e=r(E)?.trim();if(e){let t=await o(e,E);if(t)return t}if(b())return T;if(i()!==`darwin`)throw new t(`UNSUPPORTED_PLATFORM`,`macOS helper is only available on macOS`);return await z()}async function V(e){let t=await B();return a(t,[`audio-probe`,`--duration-ms`,String(e.durationMs),`--bucket-ms`,String(e.bucketMs),`--out`,e.statusPath],{allowFailure:!0,captureOutput:!0})}async function H(e,n={}){let r={allowFailure:!0,timeoutMs:3e4,signal:n.signal},i=y().macosHelper,a=i?T:await B(),o=i?await i.run(e,r):await v(a,e,r),s=o.stdout.trim(),c=null;if(s)try{c=JSON.parse(s)}catch{c=null}if(o.exitCode===0&&c?.ok)return c.data;let l=c&&!c.ok?c.error?.message??`macOS helper exited with code ${o.exitCode}`:s||o.stderr.trim()||`macOS helper exited with code ${o.exitCode}`;throw new t(`COMMAND_FAILED`,l,{helperPath:a,args:e,stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode,...c&&!c.ok?c.error?.details:{}})}async function U(){return await H([`app`,`frontmost`])}async function W(e){return await H([`app`,`quit`,`--bundle-id`,A(e)])}async function G(e,t){return await H([`permission`,e,t])}async function K(e,t={}){let n=[`alert`,e];return j(n,t),await H(n)}async function q(e,t={}){let n=[`snapshot`,`--surface`,e];return j(n,t),await H(n,{signal:t.signal})}async function J(e,t,n={}){let r=[`read`,`--x`,String(e),`--y`,String(t)];return j(r,n),await H(r)}async function Y(e,t,n={}){let r=[`press`,`--x`,String(e),`--y`,String(t)];return j(r,n),await H(r)}async function X(e,t={}){let n=[`screenshot`,`--out`,e];return j(n,t),t.fullscreen&&n.push(`--fullscreen`),await H(n)}export{G as a,K as i,W as n,X as o,U as r,V as s,w as t};