agent-device 0.21.2 → 0.21.3

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 (74) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.2.apk → agent-device-android-ime-helper-0.21.3.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.3.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.3.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.3.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.3.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.2.manifest.json → agent-device-android-snapshot-helper-0.21.3.manifest.json} +7 -7
  7. package/dist/src/agent-device-client.js +1 -1
  8. package/dist/src/app-launch.js +1 -1
  9. package/dist/src/auth.js +1 -1
  10. package/dist/src/back-mode.js +1 -1
  11. package/dist/src/cli.js +2 -2
  12. package/dist/src/client-types.d.ts +1 -1
  13. package/dist/src/command-schema.js +1 -1
  14. package/dist/src/config.js +1 -1
  15. package/dist/src/connection-runtime.js +1 -1
  16. package/dist/src/connection.js +1 -1
  17. package/dist/src/daemon-client-lifecycle.js +1 -1
  18. package/dist/src/daemon-registration.js +1 -1
  19. package/dist/src/daemon-resolution.js +1 -0
  20. package/dist/src/daemon.js +1 -1
  21. package/dist/src/device-claim-rule.js +1 -1
  22. package/dist/src/harmonyos.js +1 -1
  23. package/dist/src/human-control-contract.js +1 -1
  24. package/dist/src/human-control.js +1 -1
  25. package/dist/src/interaction.js +1 -1
  26. package/dist/src/interactor.js +1 -1
  27. package/dist/src/interactors.js +1 -1
  28. package/dist/src/internal/bin.js +1 -1
  29. package/dist/src/internal/daemon.js +2 -2
  30. package/dist/src/lease-scope.js +1 -1
  31. package/dist/src/mechanics.js +16 -16
  32. package/dist/src/perf-runtime-plan.js +1 -1
  33. package/dist/src/physical-device-control.js +1 -1
  34. package/dist/src/platform-request-scope.js +1 -1
  35. package/dist/src/platform-runtime-host.js +1 -1
  36. package/dist/src/platform-runtime-operation-host.js +1 -1
  37. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  38. package/dist/src/platform-runtime-screen-recording-harmony-host.js +1 -1
  39. package/dist/src/platform-runtime.js +1 -1
  40. package/dist/src/provider-webdriver.js +1 -1
  41. package/dist/src/record-runtime.js +1 -1
  42. package/dist/src/register-builtins.js +1 -1
  43. package/dist/src/registry.js +3 -3
  44. package/dist/src/request-providers.js +1 -1
  45. package/dist/src/runner-cache-metadata.js +2 -2
  46. package/dist/src/runner-client.js +1 -1
  47. package/dist/src/runner-disposal.js +1 -1
  48. package/dist/src/runtime.js +1 -1
  49. package/dist/src/runtime2.js +1 -1
  50. package/dist/src/runtime4.js +5 -5
  51. package/dist/src/runtime6.js +1 -1
  52. package/dist/src/runtime9.js +1 -1
  53. package/dist/src/screen-recording-resource-recovery.js +1 -1
  54. package/dist/src/screen-recording-runtime.js +1 -1
  55. package/dist/src/screenshot-runtime.js +1 -1
  56. package/dist/src/sdk-batch.js +2 -2
  57. package/dist/src/sdk-remote-config.d.ts +1 -0
  58. package/dist/src/sdk-remote-config.js +1 -1
  59. package/dist/src/selector-runtime.js +1 -1
  60. package/dist/src/session-routing.js +1 -1
  61. package/dist/src/session-snapshot.js +1 -1
  62. package/dist/src/session2.js +5 -5
  63. package/dist/src/simulator.js +1 -1
  64. package/dist/src/snapshot-runtime-binding.js +1 -1
  65. package/dist/src/snapshot-runtime.js +1 -1
  66. package/dist/src/snapshot4.js +1 -1
  67. package/dist/src/src3.js +1 -1
  68. package/dist/src/src4.js +1 -1
  69. package/package.json +1 -1
  70. package/server.json +2 -2
  71. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.2.apk.sha256 +0 -1
  72. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk.sha256 +0 -1
  73. package/dist/src/config2.js +0 -1
  74. package/dist/src/provider-device-runtime.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]})),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,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 +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 +1 @@
1
- import{C as e}from"./sdk-contracts.js";import{t}from"./config.js";import n from"node:crypto";const r=`default`;function i(t){let n=Number.isInteger(t.defaultLeaseTtlMs)?Math.max(1,Number(t.defaultLeaseTtlMs)):6e4,r=Number.isInteger(t.minLeaseTtlMs)?Math.max(1,Number(t.minLeaseTtlMs)):5e3,i=Number.isInteger(t.maxLeaseTtlMs)?Math.max(r,Number(t.maxLeaseTtlMs)):6e5;return t=>{if(!Number.isInteger(t))return n;let a=Number(t);if(a<r||a>i)throw new e(`INVALID_ARGS`,`Lease ttlMs must be between ${r} and ${i}.`);return a}}function a(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}function o(e){if(!e)return;let t=e.trim();if(t&&/^[a-f0-9]{16,128}$/i.test(t))return t.toLowerCase()}function s(t){let n=o(t);if(!n)throw new e(`INVALID_ARGS`,`Invalid lease id.`);return n}function c(t){let n=(t??``).trim().toLowerCase();if(!n||n===`ios-simulator`)return`ios-simulator`;if(n===`ios-instance`||n===`android-instance`||n===`harmonyos-instance`)return n;throw new e(`INVALID_ARGS`,`Unsupported lease backend: ${t??``}`)}function l(t){if(t===void 0)return;let n=t.trim();if(!n||n.length>256||!/^[\u0020-\u007E]+$/.test(n))throw new e(`INVALID_ARGS`,`Invalid device key. Use 1-256 printable characters.`);return n}function u(e){return f(e,`client id`,128)}function d(e){return f(e,`lease provider`,64)}function f(t,n,r){if(t===void 0)return;let i=t.trim();if(!i||i.length>r||!/^[a-zA-Z0-9._-]+$/.test(i))throw new e(`INVALID_ARGS`,`Invalid ${n}. Use 1-${String(r)} chars: letters, numbers, dot, underscore, hyphen.`);return i}function p(n){let r=t(n);if(!r)throw new e(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);return r}function m(t){let n=a(t);if(!n)throw new e(`INVALID_ARGS`,`Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);return n}function h(e){return{backend:c(e.leaseBackend),leaseProvider:d(e.leaseProvider),deviceKey:l(e.deviceKey),clientId:u(e.clientId),tenantId:p(e.tenantId),runId:m(e.runId),ttlMs:e.ttlMs}}function g(e){return!!(e.leaseProvider??e.deviceKey??e.clientId)}function _(e,t){return!t.tenantId||!t.runId?!1:[[e.leaseProvider,t.leaseProvider],[e.deviceKey,t.deviceKey],[e.clientId,t.clientId]].every(([e,t])=>!e||!!t)}function v(t,n){let r=b(n);if(r.tenantId&&t.tenantId!==r.tenantId||r.runId&&t.runId!==r.runId||r.leaseBackend&&t.backend!==r.leaseBackend||r.leaseProvider&&t.leaseProvider!==r.leaseProvider||r.deviceKey&&t.deviceKey!==r.deviceKey||r.clientId&&t.clientId!==r.clientId)throw new e(`UNAUTHORIZED`,`Lease does not match tenant/run scope`,{reason:`LEASE_SCOPE_MISMATCH`})}function y(n){let r=c(n.leaseBackend),i=t(n.tenantId);if(!i)throw new e(`INVALID_ARGS`,`tenant isolation requires tenant id.`);let s=a(n.runId);if(!s)throw new e(`INVALID_ARGS`,`tenant isolation requires run id.`);let l=o(n.leaseId);if(!l)throw new e(`INVALID_ARGS`,`tenant isolation requires lease id.`);return{...n,tenantId:i,runId:s,leaseId:l,leaseBackend:r}}function b(n){let r=t(n.tenantId),i=a(n.runId);if(n.tenantId&&!r)throw new e(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);if(n.runId&&!i)throw new e(`INVALID_ARGS`,`Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);return{tenantId:r,runId:i,leaseBackend:n.leaseBackend?c(n.leaseBackend):void 0,leaseProvider:d(n.leaseProvider),deviceKey:l(n.deviceKey),clientId:u(n.clientId)}}function x(t,n){if(g(t)&&!_(t,n))throw new e(`UNAUTHORIZED`,`Lease owner scope is required`,{reason:`LEASE_SCOPE_REQUIRED`})}function S(e){if(e.deviceKey)return JSON.stringify([e.backend,e.leaseProvider??r,e.deviceKey])}function C(e){return JSON.stringify([e.tenantId,e.runId,e.backend,e.leaseProvider??r,e.deviceKey??`*`])}function w(e,t,r){return{leaseId:n.randomBytes(16).toString(`hex`),tenantId:e.tenantId,runId:e.runId,backend:e.backend,...e.leaseProvider?{leaseProvider:e.leaseProvider}:{},...e.deviceKey?{deviceKey:e.deviceKey}:{},...e.clientId?{clientId:e.clientId}:{},createdAt:r,heartbeatAt:r,expiresAt:r+t}}function T(t){return new e(`DEVICE_IN_USE`,`Device is already leased`,{reason:`DEVICE_LEASE_BUSY`,deviceKey:t.deviceKey,backend:t.backend,leaseProvider:t.leaseProvider,expiresAt:t.expiresAt,hint:`Retry after the lease expires or close the owning session.`})}const E=`/admin/human-control/holds`;function D(t){let n=k(t,`Human-control request body`),r=n.reason;if(r!==void 0&&(typeof r!=`string`||r.trim().length>512))throw new e(`INVALID_ARGS`,`Human-control reason must be at most 512 characters.`);let i=n.ttlMs;if(i!==void 0&&(typeof i!=`number`||!Number.isInteger(i)||i<1e3||i>864e5))throw new e(`INVALID_ARGS`,`Human-control ttlMs must be between 1000 and 86400000.`);return{...n.scope===void 0?{}:{scope:O(n.scope)},...typeof r==`string`&&r.trim()?{reason:r.trim()}:{},...typeof i==`number`?{ttlMs:i}:{}}}function O(t){let n=k(t,`Host human-control scope`);if(typeof n.backend!=`string`||!n.backend.trim()||typeof n.deviceKey!=`string`)throw new e(`INVALID_ARGS`,`Host human control requires scope.backend and scope.deviceKey.`);if(n.leaseProvider!==void 0&&typeof n.leaseProvider!=`string`)throw new e(`INVALID_ARGS`,`scope.leaseProvider must be a string.`);let r=d(n.leaseProvider);return{backend:c(n.backend),deviceKey:l(n.deviceKey),...r?{leaseProvider:r}:{}}}function k(t,n){if(!t||typeof t!=`object`||Array.isArray(t))throw new e(`INVALID_ARGS`,`${n} must be an object.`);return t}function A(t){let n=typeof t==`string`?t.trim():``;if(!/^[a-zA-Z0-9._-]{1,128}$/.test(n))throw new e(`INVALID_ARGS`,`Invalid human-control hold id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);return n}function j(e){return{...e,scope:{...e.scope}}}function M(t){return new e(`DEVICE_IN_USE`,`A human is interacting with this simulator or device; agent interactions are temporarily disabled.`,{reason:`human_control_active`,blockedBy:`human_control`,holdId:t.id,deviceKey:t.scope.deviceKey,pausedAt:new Date(t.createdAt).toISOString(),...t.expiresAt===void 0?{}:{expiresAt:new Date(t.expiresAt).toISOString()},...t.reason?{humanReason:t.reason}:{},hint:`Wait until the human-control hold is released before retrying.`})}export{D as a,w as c,S as d,C as f,s as g,o as h,A as i,i as l,y as m,j as n,x as o,h as p,M as r,v as s,E as t,T as u};
1
+ import{C as e}from"./sdk-contracts.js";import t from"node:crypto";function n(e){return(e??``).trim().toLowerCase()===`tenant`?`tenant`:`none`}function r(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}const i=`default`;function a(t){let n=Number.isInteger(t.defaultLeaseTtlMs)?Math.max(1,Number(t.defaultLeaseTtlMs)):6e4,r=Number.isInteger(t.minLeaseTtlMs)?Math.max(1,Number(t.minLeaseTtlMs)):5e3,i=Number.isInteger(t.maxLeaseTtlMs)?Math.max(r,Number(t.maxLeaseTtlMs)):6e5;return t=>{if(!Number.isInteger(t))return n;let a=Number(t);if(a<r||a>i)throw new e(`INVALID_ARGS`,`Lease ttlMs must be between ${r} and ${i}.`);return a}}function o(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}function s(e){if(!e)return;let t=e.trim();if(t&&/^[a-f0-9]{16,128}$/i.test(t))return t.toLowerCase()}function c(t){let n=s(t);if(!n)throw new e(`INVALID_ARGS`,`Invalid lease id.`);return n}function l(t){let n=(t??``).trim().toLowerCase();if(!n||n===`ios-simulator`)return`ios-simulator`;if(n===`ios-instance`||n===`android-instance`||n===`harmonyos-instance`)return n;throw new e(`INVALID_ARGS`,`Unsupported lease backend: ${t??``}`)}function u(t){if(t===void 0)return;let n=t.trim();if(!n||n.length>256||!/^[\u0020-\u007E]+$/.test(n))throw new e(`INVALID_ARGS`,`Invalid device key. Use 1-256 printable characters.`);return n}function d(e){return p(e,`client id`,128)}function f(e){return p(e,`lease provider`,64)}function p(t,n,r){if(t===void 0)return;let i=t.trim();if(!i||i.length>r||!/^[a-zA-Z0-9._-]+$/.test(i))throw new e(`INVALID_ARGS`,`Invalid ${n}. Use 1-${String(r)} chars: letters, numbers, dot, underscore, hyphen.`);return i}function m(t){let n=r(t);if(!n)throw new e(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);return n}function h(t){let n=o(t);if(!n)throw new e(`INVALID_ARGS`,`Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);return n}function g(e){return{backend:l(e.leaseBackend),leaseProvider:f(e.leaseProvider),deviceKey:u(e.deviceKey),clientId:d(e.clientId),tenantId:m(e.tenantId),runId:h(e.runId),ttlMs:e.ttlMs}}function _(e){return!!(e.leaseProvider??e.deviceKey??e.clientId)}function v(e,t){return!t.tenantId||!t.runId?!1:[[e.leaseProvider,t.leaseProvider],[e.deviceKey,t.deviceKey],[e.clientId,t.clientId]].every(([e,t])=>!e||!!t)}function y(t,n){let r=x(n);if(r.tenantId&&t.tenantId!==r.tenantId||r.runId&&t.runId!==r.runId||r.leaseBackend&&t.backend!==r.leaseBackend||r.leaseProvider&&t.leaseProvider!==r.leaseProvider||r.deviceKey&&t.deviceKey!==r.deviceKey||r.clientId&&t.clientId!==r.clientId)throw new e(`UNAUTHORIZED`,`Lease does not match tenant/run scope`,{reason:`LEASE_SCOPE_MISMATCH`})}function b(t){let n=l(t.leaseBackend),i=r(t.tenantId);if(!i)throw new e(`INVALID_ARGS`,`tenant isolation requires tenant id.`);let a=o(t.runId);if(!a)throw new e(`INVALID_ARGS`,`tenant isolation requires run id.`);let c=s(t.leaseId);if(!c)throw new e(`INVALID_ARGS`,`tenant isolation requires lease id.`);return{...t,tenantId:i,runId:a,leaseId:c,leaseBackend:n}}function x(t){let n=r(t.tenantId),i=o(t.runId);if(t.tenantId&&!n)throw new e(`INVALID_ARGS`,`Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);if(t.runId&&!i)throw new e(`INVALID_ARGS`,`Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);return{tenantId:n,runId:i,leaseBackend:t.leaseBackend?l(t.leaseBackend):void 0,leaseProvider:f(t.leaseProvider),deviceKey:u(t.deviceKey),clientId:d(t.clientId)}}function S(t,n){if(_(t)&&!v(t,n))throw new e(`UNAUTHORIZED`,`Lease owner scope is required`,{reason:`LEASE_SCOPE_REQUIRED`})}function C(e){if(e.deviceKey)return JSON.stringify([e.backend,e.leaseProvider??i,e.deviceKey])}function w(e){return JSON.stringify([e.tenantId,e.runId,e.backend,e.leaseProvider??i,e.deviceKey??`*`])}function T(e,n,r){return{leaseId:t.randomBytes(16).toString(`hex`),tenantId:e.tenantId,runId:e.runId,backend:e.backend,...e.leaseProvider?{leaseProvider:e.leaseProvider}:{},...e.deviceKey?{deviceKey:e.deviceKey}:{},...e.clientId?{clientId:e.clientId}:{},createdAt:r,heartbeatAt:r,expiresAt:r+n}}function E(t){return new e(`DEVICE_IN_USE`,`Device is already leased`,{reason:`DEVICE_LEASE_BUSY`,deviceKey:t.deviceKey,backend:t.backend,leaseProvider:t.leaseProvider,expiresAt:t.expiresAt,hint:`Retry after the lease expires or close the owning session.`})}const D=`/admin/human-control/holds`;function O(t){let n=A(t,`Human-control request body`),r=n.reason;if(r!==void 0&&(typeof r!=`string`||r.trim().length>512))throw new e(`INVALID_ARGS`,`Human-control reason must be at most 512 characters.`);let i=n.ttlMs;if(i!==void 0&&(typeof i!=`number`||!Number.isInteger(i)||i<1e3||i>864e5))throw new e(`INVALID_ARGS`,`Human-control ttlMs must be between 1000 and 86400000.`);return{...n.scope===void 0?{}:{scope:k(n.scope)},...typeof r==`string`&&r.trim()?{reason:r.trim()}:{},...typeof i==`number`?{ttlMs:i}:{}}}function k(t){let n=A(t,`Host human-control scope`);if(typeof n.backend!=`string`||!n.backend.trim()||typeof n.deviceKey!=`string`)throw new e(`INVALID_ARGS`,`Host human control requires scope.backend and scope.deviceKey.`);if(n.leaseProvider!==void 0&&typeof n.leaseProvider!=`string`)throw new e(`INVALID_ARGS`,`scope.leaseProvider must be a string.`);let r=f(n.leaseProvider);return{backend:l(n.backend),deviceKey:u(n.deviceKey),...r?{leaseProvider:r}:{}}}function A(t,n){if(!t||typeof t!=`object`||Array.isArray(t))throw new e(`INVALID_ARGS`,`${n} must be an object.`);return t}function j(t){let n=typeof t==`string`?t.trim():``;if(!/^[a-zA-Z0-9._-]{1,128}$/.test(n))throw new e(`INVALID_ARGS`,`Invalid human-control hold id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.`);return n}function M(e){return{...e,scope:{...e.scope}}}function N(t){return new e(`DEVICE_IN_USE`,`A human is interacting with this simulator or device; agent interactions are temporarily disabled.`,{reason:`human_control_active`,blockedBy:`human_control`,holdId:t.id,deviceKey:t.scope.deviceKey,pausedAt:new Date(t.createdAt).toISOString(),...t.expiresAt===void 0?{}:{expiresAt:new Date(t.expiresAt).toISOString()},...t.reason?{humanReason:t.reason}:{},hint:`Wait until the human-control hold is released before retrying.`})}export{r as _,O as a,T as c,C as d,w as f,c as g,s as h,j as i,a as l,b as m,M as n,S as o,g as p,N as r,y as s,D as t,E as u,n as v};
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";import{r as t}from"./request-cancel.js";import"./request.js";import{a as n}from"./human-control-contract.js";async function r(n){let{req:r,registry:s}=n,c=r.internal?.admittedLease;if(!c)throw new e(`UNAUTHORIZED`,`Human control requires an admitted remote lease.`);let l={kind:`lease`,leaseId:c.leaseId},u=r.positionals??[],[d,f=``,p=``]=u;switch(d){case`list`:return a(u,1),{ok:!0,data:{holds:s.listHumanControlHolds(l)}};case`put`:return a(u,3),{ok:!0,data:{hold:await s.putHumanControlHold(l,f,i(p),t(r.meta?.requestId)),state:`active`}};case`remove`:{a(u,2);let e=s.removeHumanControlHold(l,f);return{ok:!0,data:{released:!!e,...e?{hold:e}:{}}}}default:throw o()}}function i(t){let r;try{r=JSON.parse(t)}catch(t){throw new e(`INVALID_ARGS`,`Human-control payload must be valid JSON.`,void 0,t)}return n(r)}function a(e,t){if(e.length!==t)throw o()}function o(){return new e(`INVALID_ARGS`,`human_control requires list, put <id> <payload>, or remove <id>.`)}export{r as handleHumanControlCommand};
1
+ import{C as e}from"./sdk-contracts.js";import{a as t}from"./human-control-contract.js";import{r as n}from"./request-cancel.js";import"./request.js";async function r(t){let{req:r,registry:s}=t,c=r.internal?.admittedLease;if(!c)throw new e(`UNAUTHORIZED`,`Human control requires an admitted remote lease.`);let l={kind:`lease`,leaseId:c.leaseId},u=r.positionals??[],[d,f=``,p=``]=u;switch(d){case`list`:return a(u,1),{ok:!0,data:{holds:s.listHumanControlHolds(l)}};case`put`:return a(u,3),{ok:!0,data:{hold:await s.putHumanControlHold(l,f,i(p),n(r.meta?.requestId)),state:`active`}};case`remove`:{a(u,2);let e=s.removeHumanControlHold(l,f);return{ok:!0,data:{released:!!e,...e?{hold:e}:{}}}}default:throw o()}}function i(n){let r;try{r=JSON.parse(n)}catch(t){throw new e(`INVALID_ARGS`,`Human-control payload must be valid JSON.`,void 0,t)}return t(r)}function a(e,t){if(e.length!==t)throw o()}function o(){return new e(`INVALID_ARGS`,`human_control requires list, put <id> <payload>, or remove <id>.`)}export{r as handleHumanControlCommand};
@@ -1 +1 @@
1
- import{i as e,p as t,s as n}from"./session-snapshot.js";import{p as r}from"./quality-warnings.js";import{t as i}from"./backend-snapshot-options.js";import{a,i as o,n as s,o as c,r as l}from"./interaction-ref-policy.js";async function u(e){let{session:t,flags:n,contextFromFlags:a,options:o}=e,s={...n??{},...i(o)},c=a(s,t.appBundleId,t.trace?.outPath),l=await e.capture({flags:s,options:o,context:c});return r(l.snapshotQuality)||e.publishSnapshot(l),l}const d=async(r,i,a,o,s)=>await u({session:r,flags:i,contextFromFlags:o,options:s,capture:async({flags:e,options:i,context:a})=>{let{snapshot:o}=await n({device:r.device,session:r,flags:e,outPath:e.out,logPath:a.logPath??``,includeRects:i.includeRects,androidFreshnessMode:i.androidFreshnessMode,signal:i.signal,...i.boundCapture?{captureData:async()=>await i.boundCapture(t({flags:e,session:r,snapshotScope:e.snapshotScope,includeRects:i.includeRects,signal:i.signal,context:a}))}:{}});return o},publishSnapshot:t=>{e(r,t),a.set(r.name,r)}});function f(e){return a({...e,captureSnapshotForSession:e.captureSnapshotForSession??d})}async function p(e){return(await import(`./find.js`)).handleFindCommands(e)}async function m(e){return await(await import(`./interaction2.js`)).handleInteractionCommands({...e,captureSnapshotForSession:e.captureSnapshotForSession??d})}export{d as captureSnapshotForSession,f as createInteractionRuntime,c as finalizeTouchInteraction,p as handleFindCommands,m as handleInteractionCommands,l as readSettleRequest,s as refMutationAdmissionResponse,o as settleFlagGuardResponse};
1
+ import{i as e,p as t,s as n}from"./session-snapshot.js";import{p as r}from"./quality-warnings.js";import{t as i}from"./backend-snapshot-options.js";import{a,i as o,n as s,o as c,r as l}from"./interaction-ref-policy.js";async function u(e){let{session:t,flags:n,contextFromFlags:a,options:o}=e,s={...n??{},...i(o)},c=a(s,t.appBundleId,t.trace?.outPath),l=await e.capture({flags:s,options:o,context:c});return r(l.snapshotQuality)||e.publishSnapshot(l),l}const d=async(r,i,a,o,s)=>await u({session:r,flags:i,contextFromFlags:o,options:s,capture:async({flags:e,options:i,context:a})=>{let{snapshot:o}=await n({device:r.device,session:r,flags:e,outPath:e.out,logPath:a.logPath??``,includeRects:i.includeRects,androidFreshnessMode:i.androidFreshnessMode,signal:i.signal,...i.boundCapture?{captureData:async()=>await i.boundCapture(t({flags:e,session:r,snapshotScope:e.snapshotScope,includeRects:i.includeRects,signal:i.signal,context:a}))}:{}});return o},publishSnapshot:t=>{e(r,t),a.set(a.resolveStoredSessionName(r),r)}});function f(e){return a({...e,captureSnapshotForSession:e.captureSnapshotForSession??d})}async function p(e){return(await import(`./find.js`)).handleFindCommands(e)}async function m(e){return await(await import(`./interaction2.js`)).handleInteractionCommands({...e,captureSnapshotForSession:e.captureSnapshotForSession??d})}export{d as captureSnapshotForSession,f as createInteractionRuntime,c as finalizeTouchInteraction,p as handleFindCommands,m as handleInteractionCommands,l as readSettleRequest,s as refMutationAdmissionResponse,o as settleFlagGuardResponse};
@@ -1,4 +1,4 @@
1
- import{C as e}from"./sdk-contracts.js";import{h as t,l as n,u as r}from"./sdk-device.js";import{r as i}from"./snapshot-scope.js";import{d as a,i as o,l as s}from"./scroll-gesture.js";import{a as c,n as l}from"./alert-contract.js";import{a as u,c as d,n as ee,s as f}from"./location-coordinates.js";import{n as te,s as ne,t as re}from"./scroll-command.js";import"./device.js";import{t as ie}from"./device-rotation.js";import{c as ae,r as p}from"./diagnostics.js";import{_ as oe}from"./owner-identity.js";import{a as m}from"./exec.js";import{t as h}from"./timeouts.js";import{a as se}from"./tv-remote.js";import"./diagnostics2.js";import"./command.js";import{i as ce,n as g}from"./retry.js";import"./process.js";import{a as le}from"./gesture-plan.js";import{n as ue}from"./scoped-provider.js";import{n as de,r as fe}from"./ios-snapshot-planning.js";import{r as pe}from"./device-isolation.js";import{h as me,i as he,n as ge,p as _e}from"./quality-warnings.js";import{a as ve,t as ye}from"./ios-system-surface.js";import{r as be}from"./ios-snapshot-acquisition.js";import{i as xe,n as Se}from"./screenshot-density.js";import{n as Ce}from"./interactor-types.js";import{a as _,o as v,t as we}from"./runner-presentation.js";import{C as Te,g as Ee,r as y}from"./host-file.js";import{a as b,c as De,d as Oe,l as ke,u as Ae}from"./config2.js";import{o as je}from"./tool-provider.js";import{n as x,r as S,t as C}from"./physical-device-control.js";import{n as w}from"./simctl.js";import{n as T,r as Me}from"./apps-simctl.js";import{n as E,r as D,s as Ne}from"./runner.js";import{t as Pe}from"./runner-cache-metadata.js";import"./runner-disposal.js";import{m as O,p as Fe}from"./runner-client.js";import{n as Ie,r as Le,t as k}from"./app-launch.js";import{r as A,t as j}from"./simulator.js";import{a as Re,d as ze,f as Be,g as Ve,h as M,m as He,p as Ue}from"./app-resolution.js";import{a as We,i as Ge,o as Ke}from"./helper.js";import{n as qe}from"./multitouch-support.js";import{t as Je}from"./surface-snapshot.js";import N from"node:path";async function Ye(e){return r(e)?await ze():(A(e,`clipboard`),await j(e),m(await T(e,[`pbpaste`,e.id],{allowFailure:!0}),`Failed to read iOS simulator clipboard`).stdout.replaceAll(`\r
1
+ import{C as e}from"./sdk-contracts.js";import{h as t,l as n,u as r}from"./sdk-device.js";import{r as i}from"./snapshot-scope.js";import{d as a,i as o,l as s}from"./scroll-gesture.js";import{a as c,n as l}from"./alert-contract.js";import{a as u,c as d,n as ee,s as f}from"./location-coordinates.js";import{n as te,s as ne,t as re}from"./scroll-command.js";import"./device.js";import{t as ie}from"./device-rotation.js";import{c as ae,r as p}from"./diagnostics.js";import{_ as oe}from"./owner-identity.js";import{a as m}from"./exec.js";import{t as h}from"./timeouts.js";import{a as se}from"./tv-remote.js";import"./diagnostics2.js";import"./command.js";import{i as ce,n as g}from"./retry.js";import"./process.js";import{a as le}from"./gesture-plan.js";import{n as ue}from"./scoped-provider.js";import{n as de,r as fe}from"./ios-snapshot-planning.js";import{r as pe}from"./device-isolation.js";import{h as me,i as he,n as ge,p as _e}from"./quality-warnings.js";import{a as ve,t as ye}from"./ios-system-surface.js";import{r as be}from"./ios-snapshot-acquisition.js";import{i as xe,n as Se}from"./screenshot-density.js";import{n as Ce}from"./interactor-types.js";import{a as _,o as v,t as we}from"./runner-presentation.js";import{C as Te,g as Ee,r as y}from"./host-file.js";import{a as b,c as De,d as Oe,l as ke,u as Ae}from"./config.js";import{o as je}from"./tool-provider.js";import{n as x,r as S,t as C}from"./physical-device-control.js";import{n as w}from"./simctl.js";import{n as T,r as Me}from"./apps-simctl.js";import{n as E,r as D,s as Ne}from"./runner.js";import{t as Pe}from"./runner-cache-metadata.js";import"./runner-disposal.js";import{m as O,p as Fe}from"./runner-client.js";import{n as Ie,r as Le,t as k}from"./app-launch.js";import{r as A,t as j}from"./simulator.js";import{a as Re,d as ze,f as Be,g as Ve,h as M,m as He,p as Ue}from"./app-resolution.js";import{a as We,i as Ge,o as Ke}from"./helper.js";import{n as qe}from"./multitouch-support.js";import{t as Je}from"./surface-snapshot.js";import N from"node:path";async function Ye(e){return r(e)?await ze():(A(e,`clipboard`),await j(e),m(await T(e,[`pbpaste`,e.id],{allowFailure:!0}),`Failed to read iOS simulator clipboard`).stdout.replaceAll(`\r
2
2
  `,`
3
3
  `).replace(/\n$/,``))}async function Xe(e,t){if(r(e)){await Ue(t);return}A(e,`clipboard`),await j(e),m(await T(e,[`pbcopy`,e.id],{allowFailure:!0,stdin:t}),`Failed to write iOS simulator clipboard`)}const Ze=[`--time`,`9:41`,`--dataNetwork`,`wifi`,`--wifiMode`,`active`,`--wifiBars`,`3`,`--batteryState`,`charged`,`--batteryLevel`,`100`],Qe={0:`hide`,1:`wifi`,6:`3g`,7:`4g`,8:`lte`,9:`lte-a`,10:`lte+`,11:`5g`,12:`5g+`,13:`5g-uwb`,14:`5g-uc`},$e={1:`searching`,2:`failed`,3:`active`},et={0:`notSupported`,1:`searching`,2:`failed`,3:`active`};function P(e,t,n){return w(e,t,n)}const F=new Set;async function tt(e){let t=null,n=!1;if(rt(e))n=!0;else try{t=await it(e),n=!0}catch(t){ut(e,`snapshot_failed`,t)}try{(!n||t)&&await at(e),await ot(e,Ze)}catch(t){ut(e,`prepare_failed`,t)}return async()=>{await nt(e,n?t:null)}}async function nt(e,t){if(await at(e),!t){L(e);return}await ot(e,ct(t)),I(e)}function I(e){F.delete(R(e))}function L(e){F.add(R(e))}function rt(e){return F.has(R(e))}function R(e){return`${e.platform}:${e.kind}:${e.id}`}async function it(e){return st(m(await P(e,[`status_bar`,e.id,`list`],{allowFailure:!0}),`Failed to read simulator status bar overrides`).stdout)}async function at(e){await P(e,[`status_bar`,e.id,`clear`])}async function ot(e,t){t.length!==0&&await P(e,[`status_bar`,e.id,`override`,...t])}function st(t){let n={},r=t.split(`
4
4
  `).map(e=>e.trim()).filter(e=>e.length>0&&e!==`Current Status Bar Overrides:`&&!/^=+$/.test(e));for(let t of r){let r=/^DataNetworkType:\s+(\d+)$/.exec(t);if(r){let t=Number(r[1]),i=Qe[t];if(!i)throw new e(`COMMAND_FAILED`,`Unsupported simulator data network type: ${t}`);n.dataNetwork=i;continue}let i=/^WiFi Mode:\s+(\d+),\s+WiFi Bars:\s+(\d+)$/.exec(t);if(i){let e=$e[Number(i[1])];e&&(n.wifiMode=e),n.wifiBars=i[2];continue}let a=/^Cell Mode:\s+(\d+),\s+Cell Bars:\s+(\d+)$/.exec(t);if(a){let t=Number(a[1]),r=et[t];if(!r)throw new e(`COMMAND_FAILED`,`Unsupported simulator cellular mode: ${t}`);n.cellularMode=r,n.cellularBars=a[2];continue}let o=/^Operator Name:\s*(.*)$/.exec(t);if(o){n.operatorName=o[1]??``;continue}}return Object.keys(n).length===0?null:n}function ct(e){let t=[];return e.dataNetwork&&t.push(`--dataNetwork`,e.dataNetwork),e.wifiMode&&t.push(`--wifiMode`,e.wifiMode),e.wifiBars!==void 0&&(e.dataNetwork===`wifi`||e.wifiMode)&&t.push(`--wifiBars`,e.wifiBars),e.cellularMode&&t.push(`--cellularMode`,e.cellularMode),e.cellularBars!==void 0&&(e.cellularMode||lt(e.dataNetwork)||e.operatorName!==void 0)&&t.push(`--cellularBars`,e.cellularBars),e.operatorName!==void 0&&t.push(`--operatorName`,e.operatorName),t}function lt(e){return!!(e&&e!==`hide`&&e!==`wifi`)}function ut(e,t,n){p({level:`warn`,phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...S(n)}})}let z=null,dt;async function ft(t,n,i,a,o){if(r(t)){let t=n.toLowerCase();if(t===`appearance`){await Be(i);return}if(t===`permission`){let t=f(i);if(t===`deny`)throw new e(`INVALID_ARGS`,u(`permission`));let n=mt(o?.permissionTarget);return await We(t,n)}throw new e(`INVALID_ARGS`,u(n))}A(t,`settings`),await j(t);let s=n.toLowerCase();switch(s){case`clear-app-state`:{if(i.toLowerCase()!==`clear`)throw new e(`INVALID_ARGS`,`settings clear-app-state only supports clear.`);if(!a)throw new e(`INVALID_ARGS`,`settings clear-app-state requires an app id or an active app session.`);let n=await pt(t,a);return{bundleId:n.bundleId,containerPath:n.containerPath,cleared:!0}}case`reset-keychain`:if(i.toLowerCase()!==`clear`)throw new e(`INVALID_ARGS`,`settings reset-keychain only supports clear.`);return await T(t,[`keychain`,t.id,`reset`]),{scope:`simulator`,cleared:!0,message:`Reset the whole iOS simulator keychain. This clears keychain-backed credentials for every installed app, not just the app under test.`};case`wifi`:{let e=M(i)?`active`:`failed`;await T(t,[`status_bar`,t.id,`override`,`--wifiMode`,e]),I(t);return}case`airplane`:M(i)?(await T(t,[`status_bar`,t.id,`override`,`--dataNetwork`,`hide`,`--wifiMode`,`failed`,`--wifiBars`,`0`,`--cellularMode`,`failed`,`--cellularBars`,`0`,`--operatorName`,``]),I(t)):(await T(t,[`status_bar`,t.id,`clear`]),L(t));return;case`location`:{if(i.toLowerCase()===`set`){let{latitude:e,longitude:n}=ee(o);return await T(t,[`location`,t.id,`set`,`${e},${n}`]),{latitude:e,longitude:n}}let n=M(i);if(!a)throw new e(`INVALID_ARGS`,`location setting requires an active app in session`);let r=n?`grant`:`revoke`;await T(t,[`privacy`,t.id,r,`location`,a]);return}case`faceid`:case`touchid`:{let e=s,n=_t[e];await Tt(t,wt(i,e),{settingName:e,label:n.label,modalityAliases:n.modalityAliases});return}case`appearance`:{let e=await ht(t,i);await T(t,[`ui`,t.id,`appearance`,e]);return}case`permission`:if(!a)throw new e(`INVALID_ARGS`,`permission setting requires an active app in session`);await yt(t,vt(f(i)),Ct(o?.permissionTarget,o?.permissionMode),a);return;default:throw new e(`INVALID_ARGS`,`Unsupported setting: ${n}`)}}async function pt(t,r){if(!n(t)||t.kind!==`simulator`)throw new e(`UNSUPPORTED_OPERATION`,`Clearing app state is currently supported only on iOS simulators.`);let i=await Re(t,r);await j(t),await k(t,i);let a=m(await T(t,[`get_app_container`,t.id,i,`data`],{allowFailure:!0}),`simctl get_app_container failed for ${i}`).stdout.trim();if(!a)throw new e(`COMMAND_FAILED`,`simctl get_app_container returned an empty data container path for ${i}`);let o=await Ee(a);return await Promise.all(o.map(e=>Te(N.join(a,e)))),{bundleId:i,containerPath:a}}function mt(t){let n=t?.trim().toLowerCase();if(n===`accessibility`||n===`screen-recording`||n===`input-monitoring`)return n;throw new e(`INVALID_ARGS`,`Unsupported macOS permission target. Use accessibility|screen-recording|input-monitoring.`)}async function ht(t,n){let r=He(n);if(r!==`toggle`)return r;let i=m(await T(t,[`ui`,t.id,`appearance`],{allowFailure:!0}),`Failed to read current iOS appearance`),a=gt(i.stdout,i.stderr);if(!a)throw new e(`COMMAND_FAILED`,`Unable to determine current iOS appearance for toggle`,{stdout:i.stdout,stderr:i.stderr});return a===`dark`?`light`:`dark`}function gt(e,t){let n=/\b(light|dark|unsupported|unknown)\b/i.exec(`${e}\n${t}`);if(!n)return null;let r=n[1]?.toLowerCase();return r===`dark`?`dark`:r===`light`?`light`:null}const _t={faceid:{label:`Face ID`,modalityAliases:[`face`]},touchid:{label:`Touch ID`,modalityAliases:[`finger`,`touch`]}};function vt(e){return e===`deny`?`revoke`:e}async function yt(t,n,r,i){let a=await xt(t);if(!a.has(r))throw new e(`UNSUPPORTED_OPERATION`,`iOS simctl privacy does not support service "${r}" on this runtime.`,{deviceId:t.id,appBundleId:i,hint:`Supported services: ${Array.from(a).sort().join(`, `)}`});let o=[`privacy`,t.id,n,r,i],s=r===`notifications`;if(!(n===`reset`&&s))try{await T(t,o);return}catch(n){throw s&&bt(n)?new e(`UNSUPPORTED_OPERATION`,`iOS simulator does not support setting notifications permission via simctl privacy on this runtime.`,{deviceId:t.id,appBundleId:i,hint:`Use reset notifications for reprompt behavior, or toggle notifications manually in Settings.`}):n}try{await T(t,o);return}catch(e){if(!bt(e))throw e}try{await T(t,[`privacy`,t.id,`reset`,`all`,i])}catch(n){throw new e(`COMMAND_FAILED`,`iOS simulator blocked direct notifications reset. Fallback reset-all also failed.`,{deviceId:t.id,appBundleId:i,hint:`Use reinstall to force a fresh notifications prompt, or reset simulator content and settings.`},n instanceof Error?n:void 0)}}function bt(t){if(!(t instanceof e)||t.code!==`COMMAND_FAILED`)return!1;let n=String(t.details?.stderr??``).toLowerCase();return(n.includes(`failed to grant access`)||n.includes(`failed to revoke access`)||n.includes(`failed to reset access`))&&n.includes(`operation not permitted`)}async function xt(t){let n=pe(t.simulatorSetPath),r=`${oe(`PATH`)??``}::${n??``}`;if(z&&dt===r)return z;let i=await T(t,[`privacy`,`help`],{allowFailure:!0}),a=St(`${i.stdout}\n${i.stderr}`);if(a.size===0)throw new e(`COMMAND_FAILED`,`Unable to determine supported simctl privacy services`,{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,hint:"Run `xcrun simctl privacy help` manually to verify available services for this runtime."});return z=a,dt=r,a}function St(e){let t=new Set,n=!1;for(let r of e.split(`
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";import{v as t}from"./sdk-device.js";import{n,r}from"./provider-device-runtime.js";import{n as i,t as a}from"./register-builtins.js";a();async function o(i,a){if(r(i)){let r=n(i,a);if(r)return r;throw new e(`UNSUPPORTED_OPERATION`,`Provider device runtime does not have an active interactor for this device.`,{deviceId:i.id,platform:t(i)})}return await s(i,a)}async function s(e,t){return await i(e.platform).createInteractor(e,t)}export{o as getInteractor,s as getLocalInteractor};
1
+ import{r as e}from"./rolldown-runtime.js";import{C as t}from"./sdk-contracts.js";import{v as n}from"./sdk-device.js";import{n as r,t as i}from"./register-builtins.js";import{AsyncLocalStorage as a}from"node:async_hooks";let o=[];const s=new a;async function c(e,t){return await s.run([...e],t)}function l(e,t){for(let n of d()){if(!n.ownsDevice(e))continue;let r=n.getInteractor(e,t);if(r)return r}}function u(e){return d().some(t=>t.ownsDevice(e))}function d(){return s.getStore()??o}function f(e,t={}){C(e);let n=e.map(e=>e.provider);return{providerRuntimes:Object.freeze([...e]),providerRuntimeIds:n,providerRuntimeRequiredIds:v([...n,...t.providerRuntimeRequiredIds??[]]),leaseLifecycleProvider:y(e),recoverableProviderIds:e.filter(e=>e.recoverExpiredLease!==void 0).map(e=>e.provider),recoverExpiredLease:_(e),cloudArtifactProvider:b(e),providerAppCatalog:x(e),deviceInventorySource:S(e),appleRunnerProvider:m(e),appleRunnerScreenRecordingTransport:p(e),providerDeviceRuntimeScope:async t=>await c(e,t)}}function p(e){if(e.some(g))return t=>{for(let n of e){if(!g(n)||!n.ownsDevice(t.device))continue;let e=n.getAppleRunnerScreenRecordingTransport(t.device);if(e)return e}}}function m(e){if(e.some(h))return t=>{for(let n of e){if(!h(n)||!n.ownsDevice(t.device))continue;let e=n.getAppleRunnerProvider(t.device);if(e)return e}}}function h(e){return`getAppleRunnerProvider`in e&&typeof e.getAppleRunnerProvider==`function`}function g(e){return`getAppleRunnerScreenRecordingTransport`in e&&typeof e.getAppleRunnerScreenRecordingTransport==`function`}function _(e){if(e.some(e=>e.recoverExpiredLease!==void 0))return async n=>{let r=e.find(e=>E(e,n.leaseProvider));if(!r?.recoverExpiredLease)throw new t(`UNSUPPORTED_OPERATION`,`Provider ${n.leaseProvider??`unknown`} cannot recover an expired lease.`,{provider:n.leaseProvider,leaseId:n.leaseId});await r.recoverExpiredLease(n)}}function v(e){return[...new Set(e)]}function y(e){if(e.length!==0)return{allocate:async(t,n)=>await T(e,`allocate`,t,n),heartbeat:async(t,n)=>await T(e,`heartbeat`,t,n),release:async(t,n)=>await T(e,`release`,t,n)}}function b(e){if(e.length!==0)return{listCloudArtifacts:async t=>await w(e,t)}}function x(e){let n=e.filter(e=>e.appCatalog!==void 0);if(n.length!==0)return{supports:e=>n.some(t=>E(t,e)),list:async(e,r)=>{let i=n.find(t=>E(t,e.provider));if(!i?.appCatalog)throw new t(`UNSUPPORTED_OPERATION`,`Provider ${e.provider} does not expose an app catalog.`,{provider:e.provider});return await i.appCatalog(e,r)}}}function S(e){if(e.length!==0)return{discover:async(t,n)=>{n.throwIfAborted();for(let r of e){if(!E(r,t.leaseProvider))continue;let e=await r.deviceInventoryProvider(t,n);if(n.throwIfAborted(),e!=null)return{kind:`inventory`,devices:e}}return{kind:`declined`}}}}function C(e){let t=new Set;for(let n of e){if(t.has(n.provider))throw TypeError(`Duplicate provider device runtime: ${n.provider}`);t.add(n.provider)}}async function w(e,t){for(let n of e){if(!E(n,t.provider))continue;let e=await n.cloudArtifacts?.listCloudArtifacts?.(t);if(e)return e}}async function T(e,t,n,r){for(let i of e){if(!E(i,n.leaseProvider))continue;let e=i.leaseLifecycle[t],a=e?await e(n,r):void 0;if(a)return a}}function E(e,t){return e.provider===t}var D=e({getInteractor:()=>O,getLocalInteractor:()=>k});i();async function O(e,r){if(u(e)){let i=l(e,r);if(i)return i;throw new t(`UNSUPPORTED_OPERATION`,`Provider device runtime does not have an active interactor for this device.`,{deviceId:e.id,platform:n(e)})}return await k(e,r)}async function k(e,t){return await r(e.platform).createInteractor(e,t)}export{u as i,D as n,f as r,O as t};
@@ -1 +1 @@
1
- async function e(e,n,r){try{await t(e,n,r)}catch(e){r.stderr(`${e instanceof Error?e.message:String(e)}\n`),await(await n.processExit()).exitAfterFlush(1)}}async function t(e,t,l){if(e.length===0)return await n(t,l);if(o(e))return await r(t,l);let u=c(e);if(u!==void 0)return await i(u,e,t,l);if(s(e))return await(await t.mcp()).runAgentDeviceMcpServer();await a(e,t)}async function n(e,t){t.stdout(`${(await e.help()).buildUsageText()}\n`),await(await e.processExit()).exitAfterFlush(1)}async function r(e,t){t.stdout(`${t.bundledVersion??(await e.version()).readVersion()}\n`)}async function i(e,t,n,r){let i=await n.help(),o=e===null?`${i.buildUsageText()}\n`:i.resolveHelpTargetUsageText(e);if(o===null)return await a(t,n);r.stdout(o)}async function a(e,t){await(await t.cli()).runCliProcess(e)}function o(e){return e.length===1&&(e[0]===`--version`||e[0]===`-V`)}function s(e){return e[0]===`mcp`&&!e.some(l)}function c(e){let[t,n]=e;if(e.length===1)return t===`help`||l(t)?null:void 0;if(e.length===2)return t===`help`?n:l(n)?t:void 0}function l(e){return e===`--help`||e===`-h`}e(process.argv.slice(2),{help:()=>import(`../cli-help.js`).then(e=>e.n),cli:()=>import(`../process-entry.js`),mcp:()=>import(`../server.js`),version:()=>import(`../version.js`).then(e=>e.t),processExit:()=>import(`../process-exit.js`)},{bundledVersion:`0.21.2`,stdout:e=>{process.stdout.write(e)},stderr:e=>{process.stderr.write(e)}}).catch(()=>process.exit(1));export{};
1
+ async function e(e,n,r){try{await t(e,n,r)}catch(e){r.stderr(`${e instanceof Error?e.message:String(e)}\n`),await(await n.processExit()).exitAfterFlush(1)}}async function t(e,t,l){if(e.length===0)return await n(t,l);if(o(e))return await r(t,l);let u=c(e);if(u!==void 0)return await i(u,e,t,l);if(s(e))return await(await t.mcp()).runAgentDeviceMcpServer();await a(e,t)}async function n(e,t){t.stdout(`${(await e.help()).buildUsageText()}\n`),await(await e.processExit()).exitAfterFlush(1)}async function r(e,t){t.stdout(`${t.bundledVersion??(await e.version()).readVersion()}\n`)}async function i(e,t,n,r){let i=await n.help(),o=e===null?`${i.buildUsageText()}\n`:i.resolveHelpTargetUsageText(e);if(o===null)return await a(t,n);r.stdout(o)}async function a(e,t){await(await t.cli()).runCliProcess(e)}function o(e){return e.length===1&&(e[0]===`--version`||e[0]===`-V`)}function s(e){return e[0]===`mcp`&&!e.some(l)}function c(e){let[t,n]=e;if(e.length===1)return t===`help`||l(t)?null:void 0;if(e.length===2)return t===`help`?n:l(n)?t:void 0}function l(e){return e===`--help`||e===`-h`}e(process.argv.slice(2),{help:()=>import(`../cli-help.js`).then(e=>e.n),cli:()=>import(`../process-entry.js`),mcp:()=>import(`../server.js`),version:()=>import(`../version.js`).then(e=>e.t),processExit:()=>import(`../process-exit.js`)},{bundledVersion:`0.21.3`,stdout:e=>{process.stdout.write(e)},stderr:e=>{process.stderr.write(e)}}).catch(()=>process.exit(1));export{};