agent-device 0.21.1 → 0.21.2
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.
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.1.apk → agent-device-android-ime-helper-0.21.2.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.2.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.1.manifest.json → agent-device-android-ime-helper-0.21.2.manifest.json} +4 -4
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.1.manifest.json → agent-device-android-snapshot-helper-0.21.2.manifest.json} +6 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerScrollViewportPolicy.swift +413 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +34 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +56 -31
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +1 -13
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +4 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +9 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +1 -0
- package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/RecordingExportSupport.swift +0 -4
- package/dist/src/absence-observation-errors.js +1 -0
- package/dist/src/adapter.js +1 -1
- package/dist/src/agent-browser-lifecycle.js +1 -1
- package/dist/src/agent-browser-process-record.js +1 -1
- package/dist/src/agent-browser-tool.js +1 -1
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/ai-sdk.d.ts +1 -1
- package/dist/src/ai-sdk.js +1 -1
- package/dist/src/alert-runtime.js +1 -1
- package/dist/src/android-input-ownership.js +1 -1
- package/dist/src/app-helpers.js +1 -1
- package/dist/src/app-inventory-contract.js +1 -1
- package/dist/src/app-inventory.js +1 -1
- package/dist/src/app-log-runtime2.js +2 -2
- package/dist/src/auth-session.js +1 -1
- package/dist/src/back-mode.js +1 -0
- package/dist/src/browser-launch.js +1 -0
- package/dist/src/catalog.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +12 -12
- package/dist/src/cli-runner.js +1 -1
- package/dist/src/cli.js +3 -3
- package/dist/src/client-metro-companion.js +1 -1
- package/dist/src/client-metro.js +1 -1
- package/dist/src/client-types.d.ts +2 -1
- package/dist/src/code-signature-cache.js +1 -1
- package/dist/src/code-signature.js +1 -1
- package/dist/src/command-metadata.js +1 -1
- package/dist/src/command-schema.js +3 -3
- package/dist/src/command-tools.js +2 -2
- package/dist/src/config.js +1 -1
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/daemon-client-lifecycle.js +1 -1
- package/dist/src/daemon-process.js +1 -1
- package/dist/src/daemon-shutdown-report.js +1 -1
- package/dist/src/device-boot.js +1 -0
- package/dist/src/device-claim-inspection.js +1 -1
- package/dist/src/device-claim-rule.js +1 -1
- package/dist/src/device-input-state.d.ts +1 -1
- package/dist/src/device-session.js +1 -1
- package/dist/src/durable-resource.js +1 -1
- package/dist/src/engine-eval-script.js +1 -0
- package/dist/src/file.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/format.js +1 -0
- package/dist/src/generic-settle.js +1 -1
- package/dist/src/gesture-plan.js +1 -1
- package/dist/src/gesture-runtime.js +1 -1
- package/dist/src/helper.js +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/input-actions.js +1 -1
- package/dist/src/interaction-positionals.js +1 -1
- package/dist/src/interaction-ref-policy.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interaction2.js +1 -1
- package/dist/src/interactor.js +5 -5
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +2 -2
- package/dist/src/internal/png-worker.d.ts +3 -0
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/ios-snapshot-acquisition.js +1 -1
- package/dist/src/ios-snapshot-planning.js +1 -1
- package/dist/src/ios-snapshot-runtime.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun.d.ts +1 -1
- package/dist/src/local-interactor-operation-set.js +1 -1
- package/dist/src/mechanics.js +16 -16
- package/dist/src/mobile-snapshot-semantics.js +1 -1
- package/dist/src/mp4-atoms.js +1 -0
- package/dist/src/owner-identity.js +3 -3
- package/dist/src/parameterized-recorded-fill.js +1 -1
- package/dist/src/perf-facade.js +1 -1
- package/dist/src/perf-runtime-plan.js +1 -1
- package/dist/src/platform-request-scope.js +1 -1
- package/dist/src/platform-runtime-app-log-process.js +1 -1
- package/dist/src/platform-runtime-managed-owner.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-runner-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/platform-runtime2.js +1 -1
- package/dist/src/png-crop-bytes.js +1 -0
- package/dist/src/png-worker-contract.js +1 -1
- package/dist/src/png.js +1 -0
- package/dist/src/process.js +1 -1
- package/dist/src/provider-webdriver.js +1 -1
- package/dist/src/quality-warnings.js +1 -0
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/registry.js +36 -37
- package/dist/src/replay.js +1 -1
- package/dist/src/request-admission.js +1 -1
- package/dist/src/request-cancellation.js +1 -1
- package/dist/src/request-runtime-binding.js +1 -1
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-disposal.js +1 -1
- package/dist/src/runner-presentation.js +1 -1
- package/dist/src/runtime.js +3 -3
- package/dist/src/runtime10.js +1 -0
- package/dist/src/runtime2.js +4 -4
- package/dist/src/runtime4.js +3 -3
- package/dist/src/runtime6.js +1 -1
- package/dist/src/runtime7.js +1 -1
- package/dist/src/runtime8.js +1 -1
- package/dist/src/runtime9.js +1 -1
- package/dist/src/screen-recording-live-handle.js +1 -1
- package/dist/src/screen-recording-resource-recovery.js +1 -1
- package/dist/src/screenshot-runtime.js +1 -1
- package/dist/src/screenshot3.js +2 -2
- package/dist/src/script.js +1 -1
- package/dist/src/scroll-gesture.js +1 -1
- package/dist/src/sdk-batch.js +1 -1
- package/dist/src/sdk-contracts.d.ts +26 -26
- package/dist/src/sdk-finders.d.ts +1 -1
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-remote-config.d.ts +1 -1
- package/dist/src/sdk-selectors.d.ts +12 -4
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selection.js +0 -0
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/semantic-index.js +1 -1
- package/dist/src/server.js +1 -1
- package/dist/src/session-snapshot.js +1 -1
- package/dist/src/session-store.js +2 -2
- package/dist/src/session-target-evidence.js +1 -1
- package/dist/src/session2.js +5 -5
- package/dist/src/simulator-boot.js +3 -0
- package/dist/src/snapshot-runtime-binding.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot-state.js +1 -1
- package/dist/src/snapshot4.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src7.js +1 -1
- package/dist/src/src8.js +2 -2
- package/dist/src/telemetry.js +1 -1
- package/dist/src/touch-reference-frame.js +1 -1
- package/dist/src/tree.js +1 -1
- package/dist/src/type-text-runtime.js +1 -1
- package/dist/src/vars.js +2 -0
- package/dist/src/version.js +1 -1
- package/dist/src/video.js +2 -2
- package/dist/src/viewport.js +1 -0
- package/dist/src/webdriver-ios-snapshot.js +1 -1
- package/package.json +2 -1
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.1.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.1.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.1.apk.sha256 +0 -1
- package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-trim.swift +0 -93
- package/dist/src/snapshot-quality-verdict.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{N as o}from"./registry.js";import{_ as s,c,l,m as u,o as d,v as f}from"./sdk-device.js";import{d as p,l as m,n as h,r as ee}from"./lease-scope.js";import{Jt as g,Rr as _,Ut as te,Yt as ne,er as re,jr as ie,wr as ae,xr as oe}from"./sdk-batch.js";import{a as se,n as ce,r as le}from"./script.js";import"./session-store.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{r as De}from"./application-lifecycle-runtime.js";import{a as Oe,c as ke,n as Ae,o as je,r as Me,s as w,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 T}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{i as E}from"./request-runtime-binding.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{a 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{...ce(t),metadata:le(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{holdsByDevice=new Map;mutations=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=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)}releaseLease(e){let t=this.getLease(e);return t?(this.leases.delete(t.leaseId),this.unbindLease(t),{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)}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){let n=this.deviceBindings.get(e),r=n?this.leases.get(n):void 0;r&&this.refreshLease(r,r.expiresAt-r.heartbeatAt,Math.max(t,r.heartbeatAt))}consumeExpiredLeases(){this.expireHumanControlHolds();let e=this.now(),t=[];for(let n of this.leases.values()){if(n.expiresAt>e||this.hasHumanControl(n))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||n.expiresAt>this.now()||this.hasHumanControl(n))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 lt(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 ut(t,n,r,i={}){if(We(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??(ee(s)?3e5:void 0)};n.assertLeaseAdmission(m(s));let l=n.heartbeatLease(m(c));return Ue(t)&&n.assertHumanControlAdmission(l),l}function dt(e,t){let n=He(e);return n?.kind===`unconditional`||n?.kind===`provider-app-catalog`&&t?.supports(n.provider)===!0}function ft(e){We(e.command)||pt(e,ze(e))}function pt(t,n){if(t.command!==`open`)return;let r=h(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&&(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 ht(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 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:(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 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=p({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 xt=[`platform`,`target`],St=[`iosSimulatorDeviceSet`,`androidDeviceAllowlist`];function Ct(e){return d({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){return`${e.device.platform} device "${e.device.name.trim()}" (${e.device.id})`}function N(e,t){return e.session.screenRecording?Mt(e.address,t):Nt(e.address,t)}function jt(e,t){return E(`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 Mt(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 Nt(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 Pt(t,n){let{address:r,session:i}=t,a=Ft(i,n);if(a.length!==0)throw new e(`INVALID_ARGS`,`Session "${r}" is already bound to ${At(i)}, but this request selected ${a.map(P).join(`, `)}.`,{session:r,conflicts:a.map(P),hint:N(t,`selector-conflict`)})}function Ft(e,t){if(!t)return[];let n=[],r=e.device,i=t.platform;if(i&&!s(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&&(!l(r)||t.udid!==r.id)&&n.push({key:`udid`,value:t.udid}),t.serial&&(!u(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();(!l(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`${It(e.key)}=${e.value}`}function It(e){switch(e){case`iosSimulatorDeviceSet`:return`--ios-simulator-device-set`;case`androidDeviceAllowlist`:return`--android-device-allowlist`;default:return`--${e}`}}function Lt(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(re(t),`utf8`).digest(`hex`)}function Rt(e,t,n){return new qt(Bt(zt(t.resolve(e))),n).parse()}function zt(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1).trim():t}function Bt(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=Vt(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 Vt(e){return Ht(e)??Ut(e)??Wt(e)??Gt(e)??Kt(e)}function Ht(e){return e.startsWith(`maestro.platform`)?{value:{type:`platform`},length:16}:null}function Ut(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{value:{type:`operator`,value:t},length:t.length}:null}function Wt(e){let t=e[0];return t===`(`||t===`)`?{value:{type:`paren`,value:t},length:1}:null}function Gt(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{value:{type:`string`,value:t[2]??``},length:t[0].length}:null}function Kt(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{value:{type:`boolean`,value:t===`true`},length:t.length}:null}var qt=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 Jt(e){switch(e.kind){case`runFlow`:return!(`include`in e);case`repeat`:case`retry`:return!(`commands`in e);default:return!1}}function Yt(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 Xt(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 Zt(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 Qt(e,t){if(e.include.kind===`file`)return k.resolve(t?k.dirname(t):process.cwd(),e.include.path)}function $t(e){return e===void 0?void 0:k.resolve(e)}function en(t,n){let r=Qt(t,t.source.path);if(r&&n.has(r))throw new e(`INVALID_ARGS`,`Maestro runFlow cycle detected at ${r}.`);return r}function tn(t,n,r,i){let a=t.include.kind===`file`?$t(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 nn(e,t,n){return e.platform&&e.platform!==n.platform?!1:e.true===void 0?!0:typeof e.true==`boolean`?e.true:Rt(e.true,t,n.platform)}function rn(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 an(e,t){I(t.signal);let n=$t(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 on(e,[],void 0,e.source.path,r),staticallyExecutedControls:r.staticallyExecutedControls,staticallySkippedControls:r.staticallySkippedControls}}async function on(e,t,n,r,i){I(i.options.signal);let a=gn(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 cn(s,a,o,e.source.path??r,i));return n}finally{s()}}async function sn(e,t,n,r,i){let a=[];for(let o of e)a.push(...await cn(o,t,n,r,i));return a}async function cn(e,t,n,r,i){I(i.options.signal);let a=_n(e,r);switch(a.kind){case`runFlow`:{let e=un(a,i);if(e===`omit`)return i.staticallySkippedControls+=1,[];let o=await ln(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 sn(a.commands,t,n,r,i))];case`retry`:return[R(a,t,n,await sn(a.commands,t,n,r,i))];default:return[mn(a,t,n)]}}async function ln(e,t,n,r,i){let a=fn(e,i.context),o=en(a,i.activeIncludePaths),s=await Zt(a,i.options);I(i.options.signal);let c=tn(a,s,o,i.activeIncludePaths),l=gn(t,e.env),u=i.context.enter(e.env);try{return await on(s,l,n,s.source.path??e.source.path??r,i)}finally{u(),c.forEach(e=>i.activeIncludePaths.delete(e))}}function un(e,t){let n=e.when;return n?n.platform!==void 0&&n.platform!==t.options.platform?`omit`:dn(n.true,t)||(n.visible||n.notVisible?`opaque`:`flatten`):`flatten`}function dn(e,t){if(e===!1)return`omit`;if(typeof e==`string`)return pn(t.context.resolveDeferred(e))?`opaque`:Rt(e,t.context,t.options.platform)?void 0:`omit`}function fn(e,t){return e.include.kind===`file`?{...e,include:{...e.include,path:t.resolve(e.include.path)}}:e}function pn(e){return/\$\{[A-Za-z_][A-Za-z0-9_.]*\}/.test(e)}function mn(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:hn(e),source:e.source,scopes:t,body:r,appId:n})}function hn(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 gn(e,t){return t===void 0?e:[...e,t]}function _n(e,t){return e.source.path||!t?e:{...e,source:{...e.source,path:t}}}async function vn(e,t={}){let{steps:n,staticallyExecutedControls:r,staticallySkippedControls:i}=await an(e,t),a=yn(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=Lt(o);return bn({...o,digest:s})}function yn(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 bn(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;for(let t of Object.values(e))bn(t);return Object.freeze(e)}function xn(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`)return{allowed:!1,reason:`step ${t+1} (runScript) 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 Sn(t,n={}){let r=xn(t,n);if(!r.allowed)throw new e(`INVALID_ARGS`,r.reason);return r.startIndex}function Cn(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 wn=`maestro-test-failure`;function z(t,n={}){return new e(`COMMAND_FAILED`,t,{...n,reason:wn})}function Tn(t){return t instanceof e&&t.code===`COMMAND_FAILED`&&t.details?.reason===wn}const En=new Set([``,`false`,`0`,`null`,`undefined`]);function Dn(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0&&!Number.isNaN(e):!En.has(e)}async function On(e,t){I(t.options.signal);try{return await Bn(e,t.context,async()=>await kn(e,t))}catch(t){throw H(t,e)}}async function kn(e,t){if(e.kind===`command`)return await An(e.command,e.appId,t);await Fn(e,t)}async function An(e,t,n){let r=Yt(e,n.context);try{return await Nn(r,t,n)}catch(e){if(I(n.options.signal),Mn(r)&&Tn(e)){n.warnings.push(jn(r,e)),n.skipped+=1;return}throw Vn(e,r)}}function jn(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 Mn(e){return`optional`in e&&e.optional===!0}async function Nn(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(!Dn(e.condition))throw z(`Maestro assertTrue condition was falsy: ${JSON.stringify(e.condition)}`);n.executed+=1;return;case`extendedWaitUntil`:await V(zn(e),F(e.timeout,`extendedWaitUntil.timeout`)??n.timing.extendedWaitUntilTimeoutMs,n),n.executed+=1;return;default:return await Pn(e,t,n)}}async function Pn(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 Fn(e,t){let n=Yt(e.command,t.context);switch(n.kind){case`runFlow`:if(n.when&&!await Ln(n.when,t)){t.skipped+=1;return}t.executed+=1,await B(e.body,t);return;case`repeat`:{let r=Xt(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(Xt(n.maxRetries,1,t.context,`retry.maxRetries`),Qe.control.retryMaxRetries);t.executed+=1,await In(e.body,r,t);return}}}async function B(e,t){for(let n of e)await On(n,t)}async function In(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),!Tn(Un(e)))throw e;i=H(e,t[0])}}throw i||new e(`COMMAND_FAILED`,`Maestro retry commands failed.`)}async function Ln(e,t){if(!nn(e,t.context,t.options))return!1;for(let n of rn(e))if(I(t.options.signal),!(await Rn(n,t.timing.runFlowConditionTimeoutMs,t)).matched)return!1;return!0}async function V(e,t,n){if(!(await Rn(e,t,n)).matched)throw z(`Maestro ${e.kind} condition did not match.`)}async function Rn(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 zn(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 Bn(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(Hn(e))return e;let n=t?.source??{line:1};return{kind:`maestroPlanStepFailure`,error:Wn(e,t?.command),source:n,...t?{command:t.command}:{}}}function Vn(e,t){return{kind:`maestroPlanStepFailure`,error:Wn(e,t),source:t.source,command:t}}function Hn(e){return!!(e&&typeof e==`object`&&e.kind===`maestroPlanStepFailure`)}function Un(e){return Hn(e)?e.error:e}function Wn(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 Gn(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 Kn(t.steps[e],e,a)}catch(e){throw Un(e)}return{executed:a.executed,skipped:a.skipped,generation:a.context.generation,artifactPaths:[...a.artifacts],...a.warnings.length>0?{warnings:a.warnings}:{}}}async function Kn(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 On(e,n);I(n.options.signal),U(()=>n.options.observer?.commandCompleted?.({...s,durationMs:r()-i,...qn(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,...qn(a,n.port.readMetrics?.()),error:o.error,artifactPaths:[...n.artifacts]})),o}}function qn(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 Jn(e,t,n={}){let r=Yn(e,n);return await Gn(e,t,{...n,startIndex:r})}function Yn(e,t){return t.from!==void 0||t.planDigest!==void 0?Sn(e,{from:t.from,planDigest:t.planDigest}):Cn(e,t.startIndex??0)}function Xn(e){return Jt(e)?{command:e.kind,...e.kind===`runFlow`?G(e.label??e.includePath):{}}:{command:e.kind,...Zn(e)}}function Zn(e){return`label`in e&&e.label?G(e.label):Qn(e)?G(ar(e.target)):$n(e)?er(e):e.kind===`inputText`?G(`<text>`):tr(e)}function Qn(e){return e.kind===`tapOn`||e.kind===`doubleTapOn`||e.kind===`longPressOn`}function $n(e){return e.kind===`assertVisible`||e.kind===`assertNotVisible`||e.kind===`extendedWaitUntil`||e.kind===`scrollUntilVisible`}function er(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 tr(e){return nr(e)?rr(e):e.kind===`swipe`?ir(e):e.kind===`runFlow`?G(e.label??(e.include.kind===`file`?e.include.path:``)):e.kind===`assertTrue`?G(String(e.condition)):{}}function nr(e){return e.kind===`openLink`||e.kind===`takeScreenshot`||e.kind===`runScript`||e.kind===`pressKey`}function rr(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 ir(e){return G(e.gesture.kind===`coordinates`?`${or(e.gesture.start)} to ${or(e.gesture.end)}`:e.gesture.direction)}function ar(e){return e.space===`target`?W(e.selector):`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function W(e){return e?.id??e?.text}function or(e){return`${e.x},${e.y}${e.space===`percent`?`%`:``}`}function G(e){return e?{value:e}:{}}const sr=new Set(String.raw`^$\.*+?()[]{}|`);function cr(e,t){try{return RegExp(`^(?:${t})$`,`ims`).test(e)}catch{return e.toLocaleLowerCase()===t.toLocaleLowerCase()}}function lr(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(sr.has(r))return;t+=r;continue}let i=e[n+1];if(i===void 0||!sr.has(i))return;t+=i,n+=1}return t}function ur(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=>ae(e,n)?e:null);return r?_(r.rect)?t.isVisibleInEffectiveViewport(r):n!==`android`&&r.hittable===!0:!1}function dr(e,t,n){return!!n.findAncestor(e,e=>e.index===t.index?e:null)}function fr(e,t){let n=[t.id===void 0?void 0:mr(e.identifier,t.id),t.text===void 0?void 0:hr(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 pr(e){return e.matches.filter(t=>ur(t,e.visibility,e.platform))}function mr(e,t){let n=e??``;return O(n)===O(t)||cr(n,t)}function hr(e,t){return[e.label,Je(e),e.identifier].filter(e=>!!e).some(e=>mr(e,t))}function gr(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 _r(e){return e.text!==void 0||e.id!==void 0||e.enabled!==void 0||e.selected!==void 0}function vr(e,t,n){let r=[],i=0;for(let a of e)for(let e of n){let n=br(a.rect,e.rect);n===void 0||!yr(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 yr(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 br(e,t){if(!(!xr(e)||!xr(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 xr(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 Sr(t,n={},r={}){let i=oe(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=vr(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=Cr(t,i,l,u,m,p),n={matches:e,indexed:Dr(e,i.index,r.orderUnindexed)};return a.set(i,n),n}finally{o.delete(i)}};return{visibility:i,resolve:m,resolvePosition:f}}function Cr(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=_r(m)?e.nodes.filter(e=>fr(e,m)):[...e.nodes];if(s){let e=new Set(i(s).indexed.map(e=>e.index));h=h.filter(t=>Tr(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=>wr(i(e).indexed,r));h=h.filter(t=>e.every(e=>e.has(t.index)))}for(let[e,n]of Er(t)){let t=a(e,n);h=h.filter(e=>t.has(e.index))}return h}function wr(e,t){let n=new Set;for(let r of e)for(let e of t(r))n.add(e);return n}function Tr(e,t){for(let n of e)if(t.has(n))return!0;return!1}function Er(e){return[[`below`,e.below],[`above`,e.above],[`leftOf`,e.leftOf],[`rightOf`,e.rightOf]].filter(e=>e[1]!==void 0)}function Dr(e,t,n){if(t===void 0)return n?n(e):[...e];let r=kr(e)[Ar(t)];return r?[r]:[]}function Or(e,t){return t===void 0?e[0]:kr(e)[Ar(t)]}function kr(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 Ar(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 jr={android:{kind:`exact`,provider:`android-helper`},ios:{kind:`divergence`,provider:`apple-xctest`,reason:`maestro-clickable-not-exposed-by-provider`}};function Mr(e,t){let n=jr[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:Nr(t.clickableByNodeIndex.get(e.index))})).sort((e,t)=>t.rank-e.rank||e.order-t.order).map(({node:e})=>e):[...e]}function Nr(e){return e===!0?2:+(e===!1)}function Pr(e,t,n,r={}){let i=Mr(e,n),a=Ir(e,i,r),o=Fr(t,a),s=pr({visibility:a.visibility,matches:o.matches,platform:n});return{...o,visible:s,clickability:i,ranked:Lr(s,t,n,a.visibility,i)}}function Fr(e,t){return{matches:t.resolve(e).matches,parentMatched:e.childOf===void 0||t.resolve(e.childOf).indexed.length>0}}function Ir(e,t,n={}){return Sr(e,n,t?{orderUnindexed:e=>J(e,t)}:{})}function Lr(e,t,n,r,i){let a=n!==`ios`||!Vr(t)?e:e.filter(n=>{if(Wr(n))return!0;let i=e.filter(e=>e!==n&&Hr(n,e,t));return!i.some(e=>Wr(e)&&dr(n,e,r))&&!i.some(e=>dr(e,n,r))});return t.index===void 0&&i?J(a,i):a}function Rr(e,t){let n=t===void 0?e.find(Y):zr(e,t);return!n||!Y(n)?null:{node:n,rect:n.rect}}function zr(e,t){return Or(e,t)}function Br(e){return Y(e)?e.rect:void 0}function Y(e){return _(e.rect)}function Vr(e){return e.id!==void 0||e.text!==void 0}function Hr(e,t,n){if(n.id!==void 0&&X(e.identifier)!==X(t.identifier))return!1;if(n.text!==void 0){let n=Ur(e),r=new Set(Ur(t));if(!n.some(e=>r.has(e)))return!1}return!0}function Ur(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 Wr(e){let t=ie(e.type??``);return t===`button`||t===`link`||t===`switch`||t===`searchfield`||t===`textfield`||t===`securetextfield`||t===`textview`}const Gr=Symbol(`maestroFlowProgram`),Kr=Symbol(`maestroFailureCommand`),qr=Symbol(`maestroFailurePlan`);function Jr(e,t){let n=Ze(e,{sourcePath:t});return{sourcePath:t,name:n.config.name,appTarget:Qr(n),[Gr]:n}}async function Yr(e,t,n){let r;try{let i=Ye(k.dirname(e.sourcePath),n.readSource),a=await vn(e[Gr],{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,runtimeHints:n.runtimeHints,loadProgram:i,signal:n.signal}),o=Sn(a,{from:n.from,planDigest:n.planDigest}),s=await Jn(a,t,{defaults:n.defaults,env:n.env,platform:n.platform,target:n.target,loadProgram:i,signal:n.signal,startIndex:o,observer:Zr(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 Xr(e,t){let n=ei(e[Kr]),r=e[qr].platform;return!n||r!==`android`&&r!==`ios`?[]:Pr(t,n.selector,r).ranked.map(e=>({node:e,basis:ti(n.selector,e)}))}function Zr(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=xn(e,{from:r.stepIndex,planDigest:e.digest}),a={...Z(r),durationMs:r.durationMs,error:r.error,artifactPaths:r.artifactPaths,isControl:Jt(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},[Kr]:r.command,[qr]:e};n(a),t?.actionFailed?.(a)}}}function Z(e){let t=Xn(e.command);return{action:t.command,...t.value?{value:t.value}:{},source:e.source,generation:e.generation,stepIndex:e.stepIndex,stepTotal:e.stepTotal}}function Qr(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($r)}function $r(e){return!!(e?.trim()&&!e.includes(`$`)&&!i(e))}function ei(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 ti(e,t){return e.id!==void 0||e.text!==void 0&&fr({...t,label:void 0,value:void 0},{text:e.text})?`id`:e.text===void 0?`other`:`label`}const ni=`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 ri(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 ii(e){if(e.command!==`replay`||e.flags?.replayFrom!==void 0)return;let t=e.flags?.replayScriptSource;if(t)try{let n=t.entry,r=ri(t,n);if(o(n,e.flags?.replayBackend)===`maestro`){let t=Jr(r,n);return{flags:e.flags??{},options:ai(t.appTarget,e.flags?.platform)}}let i=it(r,e.flags),a=oi(i.actions);if(!a.appTarget)return;let s=si(e.flags,i.actions),c=s.platform??i.metadata.platform;return{flags:c&&s.platform===void 0?{...s,platform:c}:s,options:c===`ios`?li(a.appTarget):void 0}}catch{return}}function ai(e,t){return t===`ios`?li(e)??{}:{}}function oi(e){let t=se(e);for(let n of e){if(n.command!==`open`)continue;let e=n.positionals?.[0];return ci(e)?{appTarget:e,platform:t}:{appTarget:void 0,platform:t}}return{appTarget:void 0,platform:t}}function si(e,t){let n=oi(t);return e?.platform!==void 0||!n.platform?e??{}:{...e,platform:n.platform}}function ci(e){return!!(e&&e.trim()&&!e.includes(`$`)&&!i(e))}function li(e){let t=kt(e);return t?{appleSimulatorAppTarget:t}:void 0}const ui={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 di(e){let t=await A.mkdtemp(k.join(rt.tmpdir(),`agent-device-materialized-`));try{let n=await gi(e.installablePath,k.join(t,`installable`)),r=e.archivePath?await gi(e.archivePath,k.join(t,`archive`)):void 0,i=tt.randomUUID(),a=e.ttlMs??9e5,o=Date.now()+a,s=setTimeout(()=>{mi(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 fi(e,t){await hi(e,me(Q,e,t,ui))}async function pi(e){let t=Array.from(Q.entries()).filter(([,t])=>t.sessionName===e);await Promise.all(t.map(async([e,t])=>{await hi(e,t)}))}async function mi(e){let t=Q.get(e);if(t)try{await hi(e,t)}catch{}}async function hi(e,t){clearTimeout(t.timer),Q.delete(e),await A.rm(t.rootPath,{recursive:!0,force:!0})}async function gi(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 _i(e){return e.device.platform===`web`}function vi(e){return e.toArray().filter(e=>e.device.platform===`web`).map(e=>e.name)}async function yi(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 bi(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.perfCapture&&await Le({...e,session:t})}async function xi(e,t){await t.stopSnapshotHelper(e.device)}async function Si(e){let{session:t,sessionName:n,sessionStore:r,platformCleanup:i}=e;await i.closeManagedBrowser({device:t.device,sessionName:n,stateDir:r.resolveDaemonStateDir(),openSessionNames:()=>vi(r)})}async function Ci(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 wi(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 Ti(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:()=>Ei({session:n,sessionName:r,sessionStore:i})},...t.appLog===`run`?[{step:`app_log`,run:()=>yi({session:n,sessionName:r,sessionStore:i})}]:[],{step:`audio_probe`,run:()=>Di({session:n,sessionName:r,sessionStore:i})},{step:`perf_capture`,run:()=>bi({session:n,sessionName:r,sessionStore:i})},{step:`platform_snapshot_helper`,run:()=>xi(n,a)},{step:`web_browser`,run:()=>Si({session:n,sessionName:r,sessionStore:i,platformCleanup:a})}];o.push({step:`materialized_paths`,run:()=>pi(r)});let s=wi({sessionName:r,phase:`session_teardown_cleanup_failed`,failures:await Ci(o)});if(s)throw s}async function Ei(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.screenRecording&&await et({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}async function Di(e){let t=e.sessionStore.get(e.sessionName)??e.session;t.audioProbe&&await Fe({session:t,sessionName:e.sessionName,sessionStore:e.sessionStore})}function Oi(e){return l(e)&&e.kind===`simulator`}function ki(e){return e.platform===`android`&&e.kind===`emulator`}const Ai=[`platform`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`];function $(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>e!==void 0&&e!==``).length:0}function ji(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 Mi(e){return De(ji(e))}function Ni(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 Pi(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 Fi(t){if(t!==void 0){if(typeof t!=`number`)throw new e(`INVALID_ARGS`,`Invalid open runtime metroPort: expected integer.`);return Pi(t)}}function Ii(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 Li(e){if(n(e))return e}function Ri(e,t){return{platform:t,metroHost:b(e?.metroHost),metroPort:Pi(e?.metroPort),bundleUrl:b(e?.bundleUrl),launchUrl:b(e?.launchUrl)}}function zi(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 Bi(e){if(ki(e))return`10.0.2.2`;if(Oi(e))return`127.0.0.1`}function Vi(e,t){if(!e||b(e.metroHost)||b(e.bundleUrl)||e.metroPort===void 0)return e;let n=Bi(t);return n?{...e,metroHost:n}:e}function Hi(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=>!Ai.includes(e));if(o)throw new e(`INVALID_ARGS`,`Invalid open runtime field: ${o}. Supported fields are ${Ai.join(`, `)}.`);return{platform:Ii(a.platform,r,i),metroHost:Ni(a.metroHost,`metroHost`),metroPort:Fi(a.metroPort),bundleUrl:Ni(a.bundleUrl,`bundleUrl`),launchUrl:Ni(a.launchUrl,`launchUrl`)}}function Ui(e,t,n){if(n){if($(n)===0){e.clearRuntimeHints(t);return}return e.setRuntimeHints(t,n),n}}function Wi(t,n,r,i){let a=t.getRuntimeHints(n);if(!a)return;let o=r?f(r):void 0,s=Li(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 Gi(e){let{req:t,sessionStore:n,sessionName:r,device:i}=e,a=i?Li(f(i)):e.platform,o=n.getRuntimeHints(r),s=Hi({runtime:t.runtime,sessionName:r,platform:a});if(t.runtime===void 0){let e=Wi(n,r,i,a);return{runtime:i?Vi(e,i):e,previousRuntime:o,replacedStoredRuntime:!1}}let c=s&&$(s)>0?s:void 0;return{runtime:i?Vi(c,i):c,previousRuntime:o,replacedStoredRuntime:!0}}function Ki(e){return Gi(e).runtime}function qi(e){try{return{ok:!0,data:Gi(e)}}catch(e){let t=r(e);return E(t.code,t.message,t.details)}}async function Ji(e){let{previousRuntime:t,clearRuntimeHints:n}=e;if(!Yi(e))return;let r=e.session;r?.appBundleId&&await n({appId:r.appBundleId,values:ji(t)})}function Yi(e){return e.replacedStoredRuntime&&!!e.session?.appBundleId&&Mi(e.previousRuntime)&&!Mi(e.runtime)}function Xi(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=w(T(t)),s=Me(ke(o));if(!s)return{status:`missing`};let c=s.allocatorClaim;return!c||!Qi(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 Zi(e){let t=w(T(e));return Oe(ke(t))}function Qi(e,t){return k.resolve(e)===k.resolve(t)}const $i=new Set([`DEVICE_CLAIM_LIVE_OWNER`,`DEVICE_CLAIM_RECOVERY_PENDING`,`DEVICE_CLAIM_OWNER_UNCERTAIN`]);function ea(e){return $i.has(e)}function ta(e,t,n=`status`){let r=t.claim??t.allocatorClaim,i=f(r?{platform:r.device.family,appleOs:r.device.appleOs}:e),a=c(e.platform)?`--udid`:`--serial`;return[`agent-device device ${n}`,`--platform ${y(i)}`,`${a} ${y(e.id)}`,...n===`release`||Ae(t.classification)?[`--stale`]:[]].join(` `)}function na(t,n){if(n.classification===`allocator-held`)return ia(t,n);let r=n.claim,i=ta(t,n,Ne(n.classification)?`release`:`status`),a=f(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:da(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 ra(e,t){return ua(na(e,t))}function ia(t,n){let r=n.allocatorClaim,i=f({platform:r.device.family,appleOs:r.device.appleOs}),a=ta(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 aa(t,n){return new e(`COMMAND_FAILED`,`${f(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:w(T(t)),retriable:!1,hint:`A managed identity becomes executable only after its allocator activates it and this installation holds its allocator-held claim.`})}function oa(t,n,r){return new e(`COMMAND_FAILED`,`${f(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:w(T(t)),heldIncarnationId:r,retriable:!1,hint:`The managed identity was re-provisioned; obtain a new grant from the allocator.`})}function sa(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:w(T(t)),retriable:!1})}function ca(e,t,n){switch(n.status){case`binding-invalid`:return{admitted:!1,error:sa(e,t)};case`missing`:return{admitted:!1,error:aa(e,t)};case`covered`:return{admitted:!0};case`incarnation-stale`:return{admitted:!1,error:oa(e,t,n.heldIncarnationId)};case`conflict`:return{admitted:!1,error:na(e,n.conflict)}}}function la(e,t,n){let r=ca(e,t,n);return r.admitted?void 0:ua(r.error)}function ua(e){let{hint:t,retriable:n,...r}=e.details??{};return E(e.code,e.message,r,{hint:t,retriable:n})}function da(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 fa(e){switch(e.kind){case`local-family`:return`ordinary`;case`managed-local`:return`allocator-held`;case`provider-runtime`:return`none`}}export{lr as $,pi as A,Ir as B,yi as C,_i as D,Ti as E,ni as F,zr as G,Pr as H,ri as I,Mr as J,Br as K,Xr as L,ai as M,si as N,vi as O,ii as P,ur as Q,Yr as R,wi as S,xi as T,Lr as U,Fr as V,Rr as W,gr as X,Sr as Y,pr as Z,Yi as _,bt as _t,na as a,jt as at,Di as b,ct as bt,Xi as c,Ot as ct,Mi as d,Tt as dt,z as et,Ji as f,Et as ft,Ui as g,ht as gt,ji as h,_t as ht,ca as i,Ft as it,di as j,fi as k,Ri as l,wt as lt,Ki as m,gt as mt,la as n,Pt as nt,ea as o,N as ot,zi as p,vt as pt,J as q,ra as r,P as rt,Zi as s,At as st,fa as t,F as tt,$ as u,Ct as ut,Li as v,yt as vt,bi as w,Ei as x,ot as xt,qi as y,lt as yt,Jr 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{_ 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,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { O as Rect } from "./sdk-contracts.js";
|
|
2
2
|
import { D as PointerTrajectorySample, E as PointerTrajectory, O as SinglePointerGesturePlan, T as MultiTouchGesturePlan } from "./sdk-selectors.js";
|
|
3
3
|
import { Readable, Stream, Writable } from "node:stream";
|
|
4
4
|
//#region packages/platform-android/src/helper-artifacts.d.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e}from"./sdk-contracts.js";import{r as t}from"./sdk-batch-runner.js";import{
|
|
1
|
+
import{C as e}from"./sdk-contracts.js";import{r as t}from"./sdk-batch-runner.js";import{n}from"./app-inventory.js";import"./device.js";import{t as r}from"./request-cancellation.js";import{n as i,t as a}from"./ios-client.js";import{n as o,r as s}from"./snapshot.js";import c from"node:path";import l from"node:fs";import u from"node:os";import{setTimeout as d}from"node:timers/promises";function f(e){return e?.trim()||void 0}async function p(e,t){let n=await i({apiUrl:e.apiUrl,adbUrl:e.adbUrl,token:e.token,logLevel:`warn`}),r={platform:`android`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t},a={exec:async(e,t)=>await y(r,e,t),text:async e=>{await n.setText(e.target,e.text)}};return a.reverse=await t.android.createPortReverse(a.exec),Object.assign(r,{adbProvider:a})}function m(e){return e.dependencies.android.createInteractor(e.device,e.adbProvider)}async function h(e,t,n,i,a,o){a?.throwIfAborted();let s=f(i?.packageNameHint);i?.relaunch&&s&&await y(t,[`shell`,`am`,`force-stop`,s],{allowFailure:!0,signal:a});let c=await r(o,e.assets.getOrUpload({path:n,name:T(s,n)},{signal:a}),a);await r(o,t.client.sendAsset(c.signedDownloadUrl),a),a?.throwIfAborted();let l=s?await t.dependencies.android.inferAppName(s):void 0;return{...s?{packageName:s,launchTarget:s}:{},...l?{appName:l}:{}}}async function g(e,t){await e.adbProvider.reverse?.ensure({local:w(t.devicePort),remote:w(t.hostPort),ownerId:t.name})}async function _(e){await e.adbTunnelPromise?.catch(()=>{});let t=e.adbSerial;t&&(await v(e),await e.dependencies.host.runAdb([`disconnect`,t],{allowFailure:!0,timeoutMs:1e4}).catch(()=>{})),e.adbTunnel?.close(),e.adbTunnel=void 0,e.adbSerial=void 0,e.adbTunnelPromise=void 0}async function v(e){let t=e.adbProvider.reverse;if(!t?.list)return;let n=await t.list().catch(()=>[]),r=new Set,i=[];for(let e of n)e.ownerId?r.add(e.ownerId):i.push(e.local);await Promise.allSettled([...[...r].map(async e=>await t.removeAllOwned(e)),...i.map(async e=>await t.remove(e))])}async function y(e,t,n){let{adbArgs:r,result:i}=await b(e,t,n);return await x(r,i,n?.allowFailure,e.dependencies)}async function b(e,t,n){let r=[`-s`,await S(e),...t];return{adbArgs:r,result:await e.dependencies.host.runAdb(r,{allowFailure:n?.allowFailure,binaryStdout:n?.binaryStdout,stdin:n?.stdin,timeoutMs:n?.timeoutMs??3e4,signal:n?.signal})}}async function x(e,t,n,r){if(t.exitCode!==0&&n!==!0)throw await r.android.adbError(`Limrun Android ADB command failed`,t,{command:[`adb`,...e].join(` `)});return t}async function S(e){if(e.adbSerial)return e.adbSerial;let t=e.adbTunnelPromise??C(e);e.adbTunnelPromise=t;try{return await t}catch(n){throw e.adbTunnelPromise===t&&(e.adbTunnelPromise=void 0),n}}async function C(e){let t=await e.client.startAdbTunnel(),n=`${t.address.address}:${t.address.port}`;return e.adbTunnel=t,e.adbSerial=n,n}function w(t){if(!Number.isInteger(t)||t<1||t>65535)throw new e(`INVALID_ARGS`,`Invalid Android tcp reverse port: ${t}`);return`tcp:${t}`}function T(e,t){let n=c.extname(t)||`.apk`;return`${e?.replaceAll(/[^a-zA-Z0-9_.-]+/g,`-`)||`android-app`}${n}`}async function E(e,t){let n=await a({apiUrl:e.apiUrl,token:e.token,logLevel:`warn`});return{platform:`ios`,lease:e.lease,instanceId:e.instanceId,device:e.device,client:n,dependencies:t}}async function D(e,t,n,i,a,o){a?.throwIfAborted();let s=await j(n,t.dependencies);try{a?.throwIfAborted();let n=await r(o,e.assets.getOrUpload({path:s.uploadPath,name:s.assetName},{signal:a}),a),c=(await O(t,n.signedDownloadUrl,{md5:n.md5,relaunch:i?.relaunch,appIdentifierHint:i?.appIdentifierHint},a,o)).appId;return{...c?{bundleId:c,launchTarget:c}:{},...s.appName?{appName:s.appName}:{}}}finally{await s.cleanup()}}async function O(t,n,i,a,o){a?.throwIfAborted();let s=await r(o,t.client.listApps(),a).catch(e=>{if(a?.aborted)throw e}),c=f((await r(o,t.client.installApp(n,{md5:i?.md5,launchMode:i?.relaunch?`RelaunchIfRunning`:`ForegroundIfRunning`}),a)).bundleId),l=f(i?.appIdentifierHint),u=[];for(let e of N){e>0&&await d(e,void 0,{signal:a}),u=await r(o,t.client.listApps(),a);let n=P({resultBundleId:c,requestedBundleId:l,beforeInstallApps:s,afterInstallApps:u});if(n)return{appId:n}}throw new e(`COMMAND_FAILED`,`Limrun iOS app installation could not be verified.`,{resultBundleId:c,requestedBundleId:l,installedUserApps:u.filter(I).map(e=>e.bundleId).sort()})}function k(e){return new A(e)}var A=class{session;constructor(e){this.session=e}async open(e,n){if(n?.url){await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e)),await this.session.client.openUrl(n.url);return}if(t(e)){await this.session.client.openUrl(e);return}await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(e))}async openDevice(){}async close(e){e&&await this.session.client.terminateApp(await this.session.dependencies.ios.resolveAppAlias(e)).catch(()=>{})}async tap(e,t){await this.session.client.tap(e,t)}async tapElementSelector(e){await this.session.client.tapElement(o(e))}async doubleTap(e,t){await this.tap(e,t),await this.tap(e,t)}async longPress(){throw R(`longpress`,`Limrun iOS direct sessions do not expose long press yet.`)}async focus(e,t){await this.tap(e,t)}async type(e,t){if(t&&t>0){for(let n of Array.from(e))await this.session.client.typeText(n),await d(t);return}await this.session.client.typeText(e)}async fill(e,t,n){await this.tap(e,t),await this.session.client.typeText(n)}async scroll(e,t){await this.session.client.scroll(e,t?.pixels??300)}async screenshot(e){let t=await this.session.client.screenshot();await s(e,t.base64)}async snapshot(){let{captureLimrunIosSnapshot:e}=await import(`./ios-snapshot-adapter.js`);return await e(this.session)}async back(){await this.session.client.pressKey(`escape`)}async home(){throw R(`home`,`Limrun iOS direct sessions do not expose home yet.`)}async setOrientation(e){if(e===`portrait-upside-down`)throw R(`orientation`,`Limrun iOS direct sessions support portrait and landscape orientation, not portrait upside-down.`);await this.session.client.setOrientation(e===`portrait`?`Portrait`:`Landscape`)}async performGesture(){throw R(`gesture`,`Limrun iOS direct sessions do not expose portable gesture execution yet.`)}async appSwitcher(){throw R(`app-switcher`,`Limrun iOS direct sessions do not expose app switcher yet.`)}async tvRemote(){throw R(`tv-remote`,`Limrun iOS direct sessions do not expose tv remote control.`)}async readAlert(){throw R(`alert`,L)}async awaitAlert(){throw R(`alert`,L)}async acceptAlert(){throw R(`alert`,L)}async dismissAlert(){throw R(`alert`,L)}async readClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard read yet.`)}async writeClipboard(){throw R(`clipboard`,`Limrun iOS direct sessions do not expose clipboard write yet.`)}async setSetting(){throw R(`settings`,`Limrun iOS direct sessions do not expose settings changes yet.`)}};async function j(e,t){if(!(await l.promises.stat(e)).isDirectory())return{uploadPath:e,assetName:c.basename(e),appName:M(e),cleanup:async()=>{}};let n=await l.promises.mkdtemp(c.join(u.tmpdir(),`agent-device-limrun-ios-app-`)),r=c.join(n,`${c.basename(e)}.zip`);try{await t.host.archiveDirectory({sourceDirectory:c.dirname(e),entryName:c.basename(e),archivePath:r})}catch(e){throw await l.promises.rm(n,{recursive:!0,force:!0}),e}return{uploadPath:r,assetName:c.basename(r),appName:await t.ios.readBundleAppName(e)??M(e),cleanup:async()=>{await l.promises.rm(n,{recursive:!0,force:!0})}}}function M(e){return c.basename(e).replace(/\.(?:app|ipa|apk|aab|zip)$/i,``)||void 0}const N=[0,250];function P(e){let t=new Set(e.afterInstallApps.map(e=>e.bundleId));return(e.resultBundleId&&t.has(e.resultBundleId)?e.resultBundleId:void 0)??(e.requestedBundleId&&t.has(e.requestedBundleId)?e.requestedBundleId:void 0)??F(e.beforeInstallApps,e.afterInstallApps)}function F(e,t){if(!e)return;let n=new Set(e.map(e=>e.bundleId)),r=t.filter(e=>I(e)&&!n.has(e.bundleId));return r.length===1?r[0]?.bundleId:void 0}function I(e){return!e.bundleId.startsWith(`com.apple.`)&&!e.installType.toLowerCase().includes(`system`)}const L=`Limrun iOS direct sessions do not expose alert inspection yet.`;function R(t,n){throw new e(`UNSUPPORTED_OPERATION`,n,{command:t})}function z(e){return e.platform===`android`?B(e):V(e)}function B(e){let t=e.adbProvider.exec;return{platform:`android`,device:e.device,interactor:m(e),adb:e.adbProvider,listApps:async r=>await e.dependencies.android.listApps(t,n(r)),getForegroundApp:async n=>await e.dependencies.android.getForegroundApp(e.device,t,n),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},getKeyboardState:async()=>await e.dependencies.android.getKeyboardState(t),dismissKeyboard:async()=>await e.dependencies.android.dismissKeyboard(t),readLogs:async n=>await e.dependencies.android.readLogs(t,n),...H(e.client),installRemoteApp:async t=>{await e.client.sendAsset(t)}}}function V(e){return{platform:`ios`,device:e.device,interactor:k(e),viewport:{width:e.client.deviceInfo.screenWidth,height:e.client.deviceInfo.screenHeight},listApps:async t=>(await e.client.listApps()).filter(e=>n(t)===`all`||I(e)).map(e=>({id:e.bundleId,name:e.name,installType:e.installType})).sort((e,t)=>e.id.localeCompare(t.id)),pressKey:async(t,n)=>{await e.client.pressKey(t,n)},readLogs:async(t,n)=>await e.client.appLogTail(t,n),...H(e.client),installRemoteApp:async(t,n)=>await O(e,t,n),runSimctl:t=>e.client.simctl(t)}}function H(e){return{startRecording:async t=>{await e.startRecording(t)},stopRecording:async({outPath:t})=>await e.stopRecording({localPath:t})}}export{_ as a,p as c,D as i,h as l,k as n,g as o,E as r,m as s,z as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as e,s as t}from"./sdk-device.js";import{Gt as n,
|
|
1
|
+
import{f as e,s as t}from"./sdk-device.js";import{Gt as n,Jt as r,Kt as i}from"./sdk-batch.js";const a=4096;function o(e){return c(e,{seen:new WeakSet,nodes:0},0)}function s(e){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,p(t)])))}function c(e,t,n){if(!d(e)||n>32||t.seen.has(e))return!1;t.seen.add(e),t.nodes+=1;let r=t.nodes<=a&&Object.values(e).every(e=>l(e,t,n+1));return t.seen.delete(e),r}function l(e,t,n){return f(e)?!0:n>32?!1:Array.isArray(e)?u(e,t,n):c(e,t,n)}function u(e,t,n){if(t.seen.has(e))return!1;t.seen.add(e),t.nodes+=1;let r=t.nodes<=a&&e.every(e=>l(e,t,n+1));return t.seen.delete(e),r}function d(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function f(e){return e===null?!0:typeof e==`number`?Number.isFinite(e):typeof e==`string`||typeof e==`boolean`}function p(e){return Array.isArray(e)?Object.freeze(e.map(p)):typeof e==`object`&&e?s(e):e}function m(e){if(!P(e))return _(`Durable resource envelope must be an object`);let t=e.envelopeVersion;if(!N(t))return _(`Durable resource envelopeVersion must be a non-negative integer`);if(t!==1)return{status:`unreattachable`,reason:`descriptor-version-unsupported`,message:`Unsupported durable resource envelope version: ${t}`,version:t};if(!M(e.resourceKind))return _(`Durable resource resourceKind must be a non-empty string`);if(!M(e.sessionId))return _(`Durable resource sessionId must be a non-empty string`);let n=y(e.device);if(!n)return _(`Durable resource device identity is invalid`);let r=v(e.owner);if(!r)return _(`Durable resource owner reference is invalid`);if(r.kind===`local-family`&&r.family!==n.family)return _(`Durable resource local owner does not match the device family`);let i=D(e.fence);if(!i)return _(`Durable resource ownership fence is invalid`);if(!k(e.lifecycle))return _(`Durable resource lifecycle state is invalid`);let a=O(e.descriptor);return a?e.metadata!==void 0&&!o(e.metadata)?_(`Durable resource metadata must be a JSON object`):{status:`decoded`,envelope:Object.freeze({envelopeVersion:1,resourceKind:e.resourceKind,sessionId:e.sessionId,device:n,owner:r,fence:i,lifecycle:e.lifecycle,descriptor:a,...e.metadata===void 0?{}:{metadata:s(e.metadata)}})}:_(`Durable resource descriptor is invalid`)}function h(e,t){return Object.freeze({version:e.version,body:s(e.encode(t))})}function g(e){let t=m({envelopeVersion:1,...e});if(t.status!==`decoded`)throw TypeError(t.message);return t.envelope}function _(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function v(t){return P(t)?t.kind===`local-family`&&e(t.family)?n(t.family):t.kind===`managed-local`&&M(t.instance)?i(t.instance):t.kind===`provider-runtime`&&M(t.provider)&&M(t.instance)?r(t.provider,t.instance):null:null}function y(e){if(!P(e))return null;let t=x(e.id),n=S(e.family),r=C(e.kind),i=w(e.target);return!t||!n||!r||i===null||!T(e,n,r)?null:b(e,t,n,r,i)}function b(e,t,n,r,i){return Object.freeze({id:t,family:n,...e.appleOs===void 0?{}:{appleOs:e.appleOs},kind:r,...i===void 0?{}:{target:i},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend}})}function x(e){return M(e)?e:null}function S(t){return e(t)?t:null}function C(e){return A(e)?e:null}function w(e){if(e!==void 0)return j(e)?e:null}function T(e,n,r){if(n===`apple`){if(!t(e.appleOs))return!1}else if(e.appleOs!==void 0||e.iosPhysicalDeviceBackend!==void 0)return!1;return E(e.iosPhysicalDeviceBackend,r)}function E(e,t){return e===void 0?!0:t===`device`?e===`coredevice`||e===`xctest`:!1}function D(e){return!P(e)||!M(e.token)||!N(e.generation)?null:Object.freeze({token:e.token,generation:e.generation})}function O(e){return!P(e)||!N(e.version)||!o(e.body)?null:Object.freeze({version:e.version,body:s(e.body)})}function k(e){return e===`open`||e===`completed`}function A(e){return e===`simulator`||e===`emulator`||e===`device`}function j(e){return e===`mobile`||e===`tv`||e===`desktop`}function M(e){return typeof e==`string`&&e.trim().length>0}function N(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function F(e){return e.status===`cleaned`||e.status===`already-missing`}export{h as a,m as i,g as n,y as r,F as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{C as e,D as t}from"./sdk-contracts.js";const n=new Set([`__proto__`,`constructor`,`prototype`]);async function r(n,r){let o=a(r),c=i(n),{default:l}=await import(`node:vm`),u={...r,output:o};try{l.runInNewContext(c,u,{filename:`evalScript`,timeout:1e4})}catch(n){throw new e(`COMMAND_FAILED`,`Maestro evalScript failed: ${t(n)}`,void 0,n instanceof Error?n:void 0)}return s(u.output)}function i(e){let t=e.trim();return t.startsWith("${")&&t.endsWith(`}`)?t.slice(2,-1):t}function a(e){let t=Object.create(null);for(let[n,r]of Object.entries(e))!n.startsWith(`output.`)||n===`output`||o(t,n.slice(7),r);return t}function o(e,t,n){let r=t.split(`.`).filter(l);if(r.length===0)return;let i=e;for(let e of r.slice(0,-1)){let t=i[e];(typeof t!=`object`||!t)&&(i[e]=Object.create(null)),i=i[e]}i[r.at(-1)]=n}function s(e){let t={};return c(e,[],t,new Set),t}function c(e,t,n,r){if(e!==void 0){if(typeof e!=`object`||!e){n[`output${t.map(e=>`.${e}`).join(``)}`]=u(e);return}if(!r.has(e)){r.add(e);try{let i=Array.isArray(e)?[...e.keys(),`length`]:Object.keys(e).filter(l);for(let a of i){let i=String(a);c(Array.isArray(e)&&i===`length`?e.length:e[i],[...t,i],n,r)}}finally{r.delete(e)}}}}function l(e){return!n.has(e)}function u(e){return typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}export{r as evaluateMaestroEvalScript};
|
package/dist/src/file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{C as e}from"./sdk-contracts.js";import{O as t,t as n}from"./owner-identity.js";import{t as r}from"./timeouts.js";import i from"node:path";import a from"node:fs";async function o(t){let{lockDirPath:n,owner:o}=t,l=i.join(n,`owner.json`),d=Date.now()+(t.timeoutMs??3e4),f=t.pollMs??100,p=t.ownerGraceMs??5e3,m=t.description??`process lock`;for(a.mkdirSync(i.dirname(n),{recursive:!0});Date.now()<d;)try{a.mkdirSync(n),s(l,o);let e=!1;return async()=>{e||(e=!0,a.rmSync(n,{recursive:!0,force:!0}))}}catch(e){let t=e;if(t.code!==`EEXIST`)throw t;if(c(n,l,p))continue;await r(f)}throw new e(`COMMAND_FAILED`,`Timed out waiting for ${m}`,{lockDirPath:n,...u(n,l)})}function s(e,n){t({destination:e,contents:JSON.stringify(n)})}function c(e,t,n){let r=null;try{r=a.statSync(e)}catch{return!0}let i=l(t);return i?!d(i)&&(a.rmSync(e,{recursive:!0,force:!0}),!0):Date.now()-r.mtimeMs<n?!1:(a.rmSync(e,{recursive:!0,force:!0}),!0)}function l(e){try{return JSON.parse(a.readFileSync(e,`utf8`))}catch{return null}}function u(e,t){let r=Date.now(),i=l(t),o;try{o=Math.max(0,Math.round(r-a.statSync(e).mtimeMs))}catch{}return{...o===void 0?{}:{lockAgeMs:o},...i?{ownerPid:i.pid,ownerStartTime:i.startTime,ownerAgeMs:Math.max(0,Math.round(r-i.acquiredAtMs)),ownerLiveness:n({owner:i})}:{}}}function d(e){let t=n({owner:e});return t!==`owner-process-dead`&&t!==`owner-process-reused`}export{o as t};
|
package/dist/src/find.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{p as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{p as e}from"./sdk-contracts.js";import{An as t,Ft as n,Nn as r,On as i,ht as a,kn as o}from"./sdk-batch.js";import{c as s}from"./session-store.js";import{C as c,_ as l,g as u,h as d,p as f}from"./runtime.js";import{n as p,t as m}from"./success-text.js";import{f as h}from"./absence-observation-errors.js";import{a as g,i as _}from"./request-runtime-binding.js";import{C as v,E as y,S as b}from"./session-snapshot.js";import{p as x}from"./quality-warnings.js";import{t as S}from"./internal/daemon.js";import{t as C}from"./snapshot-runtime-binding.js";import{l as w,n as T,u as E}from"./selector-runtime.js";import{t as D}from"./type-text-runtime.js";function O(t,n){let r=n[0]?.rect;if(!r)return t;let i=t.filter(t=>{if(!t.rect)return!1;let n=e(t.rect);return n.x>=r.x&&n.x<=r.x+r.width&&n.y>=r.y&&n.y<=r.y+r.height}),a=i.length>0?i:t;return a.length<2?a:k(a,n,u(n))}function k(e,t,n){return e.map((e,r)=>({node:e,index:r,score:A(e,t,n)})).sort((e,t)=>t.score===e.score?M(e.node)-M(t.node)||e.index-t.index:t.score-e.score).map(e=>e.node)}function A(e,t,n){let r=n(e);if(r.reason===`covered`)return 0;let i=j(r,t[0]);return i>0?i:e.hittable&&e.rect&&!l(e,t[0])?3:+!!e.rect}function j(e,t){return e.node.rect?e.reason===`semantic-target`||e.reason===`same-rect-descendant`?4:e.reason===`hittable-ancestor`&&!l(e.node,t)?2:0:0}function M(e){return e.rect?e.rect.width*e.rect.height:1/0}function N(e,t,n){let r={matches:e.length,candidates:e.slice(0,5).map(e=>h(e,0,!1))};return _(`AMBIGUOUS_MATCH`,`find matched ${e.length} elements for ${t} "${n}". Use a more specific locator or selector.`,{locator:t,query:n,...r})}function P(e){if(e.ambiguity!==`reject-candidates`)throw Error(`find's resolution policy must reject candidates, got "${e.ambiguity}"`)}function F(e){let{nodes:t,locator:n,query:r,selectorExpression:i,flags:a,platform:s}=e,u=c.findAct,d=t.filter(e=>!l(e,t[0])),p=u.resolution,m;if(m=i?f(u,d,i,{platform:s}).list?.matchedNodes??[]:o(d,n,r,{requireRect:p.requireRect}).matches,m=O(m,t),m.length>1){P(p);let e=I(m,a);if(!e)return{ok:!1,response:N(m,n,r)};m=e}let h=m[0]??null;return h?{ok:!0,node:h}:{ok:!1,response:_(`COMMAND_FAILED`,`find did not match any element`)}}function I(e,t){return t?.findFirst?[e[0]]:t?.findLast?[e.at(-1)]:null}function L(e){let{device:t,session:n,req:r,logPath:i,locator:a,query:o,sessionStore:s,sessionName:c}=e,l=w({device:t,session:n,sessionStore:s,sessionName:c,req:r,logPath:i,capture:e.capture});return async()=>{let{snapshot:e}=await l.capture({flags:{...r.flags,snapshotInteractiveOnly:!0},recovery:{legacyIosSparse:{query:o,shouldScope:z(a)},sparseVerdictQueryScope:{query:o,shouldScope:z(a)}}});return{nodes:e.nodes,snapshotQuality:e.snapshotQuality,systemSurfaceOnly:e.systemSurfaceOnly,iosSystemSurfaceBundleId:e.iosSystemSurfaceBundleId}}}function R(e){return _(`COMMAND_FAILED`,`find could not read the current accessibility tree`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen.`})}function z(e){return e!==`role`}async function B(e){let{req:o,sessionName:s,logPath:l,sessionStore:u,invoke:f}=e,p=o.command;if(p!==`find`)return null;let m=o.positionals??[],h=i(m,o.flags);if(!h.ok)return _(h.code,h.message);let{locator:v,query:y,action:b,value:S}=h.parsed;if(o.flags?.record&&!t(b))return _(`INVALID_ARGS`,`find ${b} is a mutating action and is always recorded; --record only applies to a read-only find (exists, wait, list, get text, get attrs).`);let w=await T({req:o,sessionName:s,logPath:l,sessionStore:u,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(w)return w;let D=u.get(s);if(!D)return g();let O=D.device,k=await C({command:`find`,device:O,session:D,plan:n({hasActiveApp:D.appBundleId!==void 0,intent:a(b)}),inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(!k.ok)return k.response;let A=r(v,y),j=L({device:O,session:D,req:o,logPath:l,locator:v,query:y,sessionStore:u,sessionName:s,capture:k.capture}),M={req:o,sessionName:s,logPath:l,sessionStore:u,invoke:f,session:D,device:O,command:p,locator:v,query:y,publicFlags:X(o.flags),boundFocusPoint:k.focusPoint,boundTypeText:k.typeText},N=await j();if(x(N.snapshotQuality))return R(N.snapshotQuality);let{nodes:P}=N,I=F({nodes:P,locator:v,query:y,selectorExpression:A,flags:o.flags,platform:O.platform});if(!I.ok)return E(I.response,N);let z=I.node,B=await d(c.findAct,P,z),H=B.node,U=`@${H.ref}`,W={...o.flags??{},noRecord:!0},G=await V(M,{node:z,resolvedNode:H,ref:U,nodes:P,...N.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:N.iosSystemSurfaceBundleId}:{},actionFlags:W,...B.kind===`occluded`?{occludedNode:B.node}:{}},b,S);return G&&E(G,N)}async function V(e,t,n,r){let i={click:()=>U(e,t),fill:()=>W(e,t,r),focus:()=>G(e,t),type:()=>K(e,t,r)}[n];return i?await i():null}function H(e){return{ref:e.ref,node:e.resolvedNode,nodes:e.nodes,...e.iosSystemSurfaceBundleId?{iosSystemSurfaceBundleId:e.iosSystemSurfaceBundleId}:{}}}async function U(t,n){let{req:r,sessionName:i,sessionStore:a,session:o,invoke:c,command:l,locator:u,query:d,publicFlags:f}=t,h=await c({token:r.token,session:i,command:`click`,positionals:[n.ref],flags:n.actionFlags,internal:{findResolvedTarget:H(n)}});if(!h.ok)return h;let g=n.resolvedNode.rect?e(n.resolvedNode.rect):n.node.rect?e(n.node.rect):null,_={ref:n.ref,locator:u,query:d};g&&(_.x=g.x,_.y=g.y);let v=m(h.data)??`Tapped ${n.ref}${g?` (${g.x}, ${g.y})`:``}`;return Object.assign(_,p(v)),s(a,o,r,l,{ref:n.ref,action:`click`,locator:u,query:d},{flags:f}),{ok:!0,data:_}}async function W(e,t,n){let{req:r,sessionName:i,sessionStore:a,session:o,invoke:c,command:l,publicFlags:u}=e;if(n===void 0)return _(`INVALID_ARGS`,`find fill requires text (use "" to clear the field)`);let d=await c({token:r.token,session:i,command:`fill`,positionals:[t.ref,n],flags:t.actionFlags,internal:{findResolvedTarget:H(t)}});return d.ok&&s(a,o,r,l,{ref:t.ref,action:`fill`},{flags:u}),d}async function G(e,t){let n=await q(e,t);return n.ok&&Y(e,t,`focus`),n}async function K(e,t,n){let{req:r,logPath:i,session:a}=e;if(!n)return _(`INVALID_ARGS`,`find type requires text`);let o=await q(e,t);if(!o.ok)return o;y(a);let s=e.boundTypeText;if(!s)return _(`COMMAND_FAILED`,`find type was admitted without a text-entry operation`);let c=await D({operations:{typeText:s}},[n],v(i,r.flags,a.appBundleId,a.trace?.outPath));return Y(e,t,`type`),{ok:!0,data:c??{ref:t.ref}}}async function q(t,n){let{req:r,logPath:i,session:a}=t,o=J(n,`be focused`);if(o)return o;let s=n.resolvedNode.rect?e(n.resolvedNode.rect):null;if(!s)return _(`COMMAND_FAILED`,`matched element has no bounds`);y(a);let c=t.boundFocusPoint;return c?{ok:!0,data:await S({operations:{focusPoint:c}},s,v(i,r.flags,a.appBundleId,a.trace?.outPath))??{ref:n.ref}}:_(`COMMAND_FAILED`,`find focus was admitted without a focus operation`)}function J(e,t){let n=e.occludedNode;return n?_(`COMMAND_FAILED`,`Matched element ${e.ref} is covered by another visible element and cannot ${t} safely`,{ref:`@${n.ref}`,interactionBlocked:n.interactionBlocked,hint:`Use a different visible target, scroll it clear of the overlay, or inspect with snapshot/screenshot before retrying.`}):null}function Y(e,t,n){let{req:r,sessionStore:i,session:a,command:o,publicFlags:c}=e;s(i,a,r,o,{ref:t.ref,action:n},{flags:c})}function X(e){return{...b(e)??{}}}export{B as handleFindCommands};
|
package/dist/src/finders.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Mn as e}from"./sdk-batch.js";import{t}from"./sdk-finders.js";export{t as findBestMatchesByLocator,e as parseFindArgs};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"node:path";function t(t){let n=e.extname(t).toLowerCase();return n===`.yaml`||n===`.yml`}function n(e,t){return`Maestro YAML requires explicit --maestro routing: ${e} ${t} --maestro`}function r(e,n){return n===`maestro`&&t(e)?`maestro`:`ad`}export{n,r,t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{p as e}from"./sdk-batch.js";import{t}from"./session-snapshot.js";import{i as n,r}from"./interaction-ref-policy.js";import{captureSnapshotForSession as i,createInteractionRuntime as a}from"./interaction.js";function o(t){if(!e(t.command))return{};let i=n(t.command,t.flags);if(i)return{response:i};let a=r(t.flags);if(!a)return{};let o=t.session.snapshot,c={nodes:o?.nodes??[],...o?.iosSystemSurfaceBundleId?{surfaceBundleId:o.iosSystemSurfaceBundleId}:{}};return{observe:async()=>await s(t,a,c)}}async function s(e,n,r){let i=c(e);if(!i)return;let a=await i.interactions.settleObservation({...n,baseline:r,session:e.sessionName,requestId:e.req.meta?.requestId}),o=t(e.session,a);return o===void 0?a:{...a,refsGeneration:o}}function c(e){try{return a({req:e.req,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,contextFromFlags:e.contextFromFlags,captureSnapshotForSession:i})}catch{return}}export{o as planGenericSettleObservation};
|
package/dist/src/gesture-plan.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{C as e}from"./sdk-contracts.js";import{f as t,m as n}from"./scroll-gesture.js";import{t as r}from"./gesture-plan-types.js";const i={pinchAxisDegrees:-90,samplingProfile:`default`},a={ios:i,macos:i,android:{pinchAxisDegrees:0,samplingProfile:`android`},harmonyos:i,vega:i,linux:i,web:i};function o(e,t,n){let r=b(t),i=N(n);switch(e.intent){case`fling`:return u(e,r);case`pan`:return d(e,r,i);case`pinch`:return p({intent:`pinch`,origin:e.origin??k(r),delta:{x:0,y:0},scale:D(e.scale,`gesture pinch scale`),rotationDegrees:0,durationMs:300},r,i);case`rotate`:{let t=E(e.degrees,`gesture rotate degrees`);return p({intent:`rotate`,origin:e.origin??k(r),delta:{x:0,y:0},scale:1,rotationDegrees:t,durationMs:w(t)},r,i)}case`transform`:{let t=E(e.degrees,`gesture transform degrees`);return p({intent:`transform`,origin:e.origin,delta:e.delta,scale:D(e.scale,`gesture transform scale`),rotationDegrees:t,durationMs:x(e.durationMs,w(t),`gesture transform durationMs`)},r,i)}}}function s(e){let[{samples:t}]=e.pointers,n=t[0],r=t.at(-1);return{start:n.point,end:r.point}}function c(t,n){let i=b(n),a=S(t.sourceHoldMs,800,`gesture drag sourceHoldMs`),o=x(t.moveMs,500,`gesture drag moveMs`),s=C(t.destinationHoldMs,0,`gesture drag destinationHoldMs`);if(a+o+s>1e4)throw new e(`INVALID_ARGS`,`gesture drag total duration must be at most ${r}`);return l(f(`pan`,t.from,t.to,o,i,`timed-pan`),a,s)}function l(e,t,n){let r=e.pointers[0],[i,a]=r.samples,o=t+e.durationMs+n,s=[{offsetMs:0,point:i.point},{...i,offsetMs:i.offsetMs+t},{...a,offsetMs:a.offsetMs+t},...n>0?[{offsetMs:o,point:a.point}]:[]];return{...e,durationMs:o,pointers:[{...r,samples:s}]}}function u(e,t){if(`preset`in e){let{from:n,to:r}=M(e.preset,t);return f(`fling`,n,r,100,t,`endpoint-hold`)}if(`from`in e)return f(`fling`,e.from,e.to,100,t,`endpoint-hold`);let r=T(e.origin,`gesture fling origin`),i=O(e.distance??180,`gesture fling distance`);return f(`fling`,r,A(r,n(e.direction,i)),100,t,`endpoint-hold`)}function d(t,n,r){let i=x(t.durationMs,500,`gesture pan durationMs`);if((t.pointerCount??1)===1){let e=T(t.origin,`gesture pan origin`);return f(`pan`,e,A(e,T(t.delta,`gesture pan delta`)),i,n,t.executionProfile??`timed-pan`)}if(t.pointerCount!==2)throw new e(`INVALID_ARGS`,`gesture pan pointerCount must be 1 or 2`);return p({intent:`pan`,origin:t.origin,delta:t.delta,scale:1,rotationDegrees:0,durationMs:i},n,r)}function f(e,t,n,r,i,a){let o=T(t,`gesture ${e} start`),s=T(n,`gesture ${e} end`),c=[{offsetMs:0,point:o},{offsetMs:r,point:s}];return v(c,i,{intent:e,pointerId:0}),{topology:`single`,intent:e,executionProfile:a,durationMs:r,viewport:i,pointers:[{pointerId:0,samples:c}]}}function p(e,t,n){let r=T(e.origin,`gesture ${e.intent} origin`),i=A(r,T(e.delta,`gesture ${e.intent} delta`)),a=Math.min(t.width,t.height)*g(e.intent),o=e.scale>1?a/e.scale:a,s=o*e.scale;if(Math.min(o,s)<48)throw y({intent:e.intent,viewport:t,initialSpan:o,finalSpan:s,minimumReliableSpan:48});let c=o/2,l=_(e.durationMs,n.samplingProfile),u=(a,o)=>{let s=l.map(t=>({offsetMs:t,point:m({...e,start:r,end:i,initialRadius:c,offsetMs:t,side:o,profile:n})}));return v(s,t,{intent:e.intent,pointerId:a}),{pointerId:a,samples:s}};return{topology:`two`,intent:e.intent,durationMs:e.durationMs,viewport:t,pointers:[u(0,1),u(1,-1)]}}function m(e){let t=e.offsetMs/e.durationMs,n=j(e.start,e.end,t),r=e.initialRadius*(1+(e.scale-1)*t),i=P(h(e.intent,e.profile)+e.rotationDegrees*t);return{x:n.x+Math.cos(i)*r*e.side,y:n.y+Math.sin(i)*r*e.side}}function h(e,t){return e===`pinch`?t.pinchAxisDegrees:-90}function g(e){return e===`pinch`?.4:.25}function _(t,n){if(!Number.isFinite(t)||t<=0)throw new e(`INVALID_ARGS`,`gesture sample duration must be a positive finite number`);let r=t/16,i=Math.max(3,n===`android`?Math.round(r):Math.floor(r));return Array.from({length:i+1},(e,n)=>Math.round(t*n/i))}function v(t,n,r){let i=n.x+n.width-1,a=n.y+n.height-1;for(let o of t){let{x:t,y:s}=o.point;if(!Number.isFinite(t)||!Number.isFinite(s))throw new e(`INVALID_ARGS`,`Gesture motion produces non-finite pointer coordinates`,{...r,reason:`GESTURE_TRAJECTORY_NON_FINITE`,hint:`Reduce the requested rotation, translation, or scale.`});if(t<n.x+1||t>i||s<n.y+1||s>a)throw y({...r,viewport:n,sample:o})}}function y(t){return new e(`INVALID_ARGS`,`Gesture trajectory does not fit inside the viewport`,{...t,reason:`GESTURE_TRAJECTORY_OUT_OF_BOUNDS`,hint:`Move the gesture away from the edge or reduce its translation, scale, or rotation.`})}function b(t){let n={x:E(t.x,`gesture viewport x`),y:E(t.y,`gesture viewport y`),width:E(t.width,`gesture viewport width`),height:E(t.height,`gesture viewport height`)};if(n.width<=0||n.height<=0)throw new e(`INVALID_ARGS`,`gesture viewport width and height must be positive`);return n}function x(t,n,i){let a=t??n;if(!Number.isInteger(a)||a<16||a>1e4)throw new e(`INVALID_ARGS`,`${i} must be an integer between 16 and ${r}`);return a}function S(t,n,i){let a=t??n;if(!Number.isInteger(a)||a<1||a>1e4)throw new e(`INVALID_ARGS`,`${i} must be an integer between 1 and ${r}`);return a}function C(t,n,i){let a=t??n;if(!Number.isInteger(a)||a<0||a>1e4)throw new e(`INVALID_ARGS`,`${i} must be an integer between 0 and ${r}`);return a}function w(e){let t=Math.ceil(Math.abs(e)/3)*16;return Math.min(Math.max(300,t),2400)}function T(e,t){return{x:E(e.x,`${t} x`),y:E(e.y,`${t} y`)}}function E(t,n){if(!Number.isFinite(t))throw new e(`INVALID_ARGS`,`${n} must be a finite number`);return t}function D(t,n){let r=E(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be greater than 0`);return r}function O(t,n){let r=E(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be a positive number`);return r}function k(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function A(e,t){return{x:e.x+t.x,y:e.y+t.y}}function j(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function M(e,n){let r=t(e,{referenceWidth:n.width,referenceHeight:n.height});return{from:{x:n.x+r.x1,y:n.y+r.y1},to:{x:n.x+r.x2,y:n.y+r.y2}}}function N(e){return e===void 0?i:a[e]}function P(e){return e*Math.PI/180}export{s as a,_ as i,o as n,j as r,c as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e,M as t}from"./sdk-contracts.js";import{
|
|
1
|
+
import{C as e,M as t}from"./sdk-contracts.js";import{Mt as n,_t as r}from"./sdk-batch.js";import{g as i,h as a,m as o}from"./session-snapshot.js";import{a as s}from"./gesture-admission.js";async function c(e){let t=await i({command:`runtime gesture-viewport`,device:e.device,use:r,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});return t.type===`response`?{ok:!1,response:t.response}:{ok:!0,read:d(t.runtime).gestureViewport}}async function l(r){let i=n(r.input),o=await a({command:`gesture`,device:r.device,required:i.use.required,inspectFacts:r.inspectFacts,bindDevice:r.bindDevice,unavailableResponse:n=>({ok:!1,error:t(new e(`UNSUPPORTED_OPERATION`,s(r.device,i.tier,r.input.intent),{gesture:r.input.intent,...n.hint===void 0?{}:{hint:n.hint}}))})});return o.type===`response`?{ok:!1,response:o.response}:{ok:!0,gestures:await u(o.bind,r.device,i)}}async function u(e,t,n){switch(n.tier){case`plan`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performGesturePlan(f(e,t)),...d(r)}}case`directional-fling`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performDirectionalFlingPlan(f(e,t)),...d(r)}}case`multi-touch`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performMultiTouchGesturePlan(f(e,t)),...d(r)}}case`target-authored-drag`:{let r=await e(t,n.use);return{performPlan:async(e,t)=>await r.operations.performTargetAuthoredDrag(f(e,t)),...d(r)}}}}function d(e){let{gestureViewport:t}=e.operations,n=e.operations.captureSnapshot?{operations:{captureSnapshot:e.operations.captureSnapshot}}:void 0,r=t?{operations:{gestureViewport:t}}:void 0;return Object.freeze({...n?{captureSnapshot:async e=>await n.operations.captureSnapshot(e)}:{},...r?{gestureViewport:async e=>await r.operations.gestureViewport(p(e))}:{}})}function f(e,t){return{plan:e,...t.appBundleId===void 0?{}:{options:{appBundleId:t.appBundleId}},execution:o(t)}}function p(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:o(e)}}export{c as n,l as t};
|
package/dist/src/helper.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime.js";import{C as t}from"./sdk-contracts.js";import{
|
|
1
|
+
import{r as e}from"./rolldown-runtime.js";import{C as t}from"./sdk-contracts.js";import{E as n,_ as r,d as i}from"./owner-identity.js";import{l as a,o}from"./exec.js";import"./command.js";import"./process.js";import{D as s,c,f as l,g as u,h as d,n as f,o as p,r as m,t as h,w as g,y as _}from"./host-file.js";import{a as v,i as y,n as b}from"./tool-provider.js";import x from"node:path";import{createHash as S}from"node:crypto";import{fileURLToPath as C}from"node:url";var w=e({quitMacOsApp:()=>W,resolveFrontmostMacOsApp:()=>U,resolveMacOsHelperPackageRootFrom:()=>M,runMacOsAlertAction:()=>K,runMacOsPermissionAction:()=>G,runMacOsPressAction:()=>Y,runMacOsReadTextAction:()=>J,runMacOsScreenshotAction:()=>X,runMacOsSnapshotAction:()=>q,startMacOsAudioProbeProcess:()=>V});const T=`agent-device-macos-helper`,E=`AGENT_DEVICE_MACOS_HELPER_BIN`,D=x.join(l(),`.agent-device`,`macos-helper`,`current`),O=x.join(D,`manifest.json`),k=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/;function A(e){let n=e.trim();if(!k.test(n))throw new t(`INVALID_ARGS`,`macOS bundle id must use reverse-DNS form like com.example.App`,{bundleId:e});return n}function j(e,t){t.bundleId&&e.push(`--bundle-id`,A(t.bundleId)),t.surface&&e.push(`--surface`,t.surface)}function M(e){let n=x.dirname(e);for(;;){let e=x.join(n,`apple`,`macos-helper`);if(c(x.join(e,`Package.swift`)))return e;let t=x.dirname(n);if(t===n)break;n=t}throw new t(`COMMAND_FAILED`,`Unable to locate macOS helper package root`,{modulePath:e})}function N(){return M(C(import.meta.url))}function P(){return x.join(N(),`.build`,`release`,T)}function F(){return x.join(D,T)}async function I(e){let t=await u(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>{let n=x.join(e,t.name);return t.isDirectory()?t.name===`.build`?[]:await I(n):!t.isFile()||!t.name.endsWith(`.swift`)&&t.name!==`Package.swift`?[]:[n]}))).flat().sort()}async function L(e){let t=await I(e),n=S(`sha256`);for(let r of t)n.update(x.relative(e,r)),n.update(`\0`),n.update(await d(r)),n.update(`\0`);let r=await v(`swift`,[`--version`],{allowFailure:!0,cwd:e,timeoutMs:1e4});return n.update(`swift-version`),n.update(`\0`),n.update(r.stdout||r.stderr||`exit:${r.exitCode}`),n.update(`\0`),n.digest(`hex`)}async function R(){try{let e=JSON.parse(await _(O));return typeof e.fingerprint==`string`?e.fingerprint:null}catch{return null}}async function z(){let e=await o(r(E),E);if(e)return e;let t=N(),i=await L(t),a=F();try{if(await R()===i)return await h(a),a}catch{}let c=P();n(`agent-device: building macOS helper (first run or helper update)
|
|
2
2
|
`),await v(`swift`,[`build`,`-c`,`release`,`--package-path`,t],{cwd:t,timeoutMs:12e4}),await p(D);let l=`${a}.tmp`;return await m(c,l),await g(l,a),await f(a,493),await s(O,`${JSON.stringify({fingerprint:i},null,2)}\n`),a}async function B(){let e=r(E)?.trim();if(e){let t=await o(e,E);if(t)return t}if(b())return T;if(i()!==`darwin`)throw new t(`UNSUPPORTED_PLATFORM`,`macOS helper is only available on macOS`);return await z()}async function V(e){let t=await B();return a(t,[`audio-probe`,`--duration-ms`,String(e.durationMs),`--bucket-ms`,String(e.bucketMs),`--out`,e.statusPath],{allowFailure:!0,captureOutput:!0})}async function H(e,n={}){let r={allowFailure:!0,timeoutMs:3e4,signal:n.signal},i=y().macosHelper,a=i?T:await B(),o=i?await i.run(e,r):await v(a,e,r),s=o.stdout.trim(),c=null;if(s)try{c=JSON.parse(s)}catch{c=null}if(o.exitCode===0&&c?.ok)return c.data;let l=c&&!c.ok?c.error?.message??`macOS helper exited with code ${o.exitCode}`:s||o.stderr.trim()||`macOS helper exited with code ${o.exitCode}`;throw new t(`COMMAND_FAILED`,l,{helperPath:a,args:e,stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode,...c&&!c.ok?c.error?.details:{}})}async function U(){return await H([`app`,`frontmost`])}async function W(e){return await H([`app`,`quit`,`--bundle-id`,A(e)])}async function G(e,t){return await H([`permission`,e,t])}async function K(e,t={}){let n=[`alert`,e];return j(n,t),await H(n)}async function q(e,t={}){let n=[`snapshot`,`--surface`,e];return j(n,t),await H(n,{signal:t.signal})}async function J(e,t,n={}){let r=[`read`,`--x`,String(e),`--y`,String(t)];return j(r,n),await H(r)}async function Y(e,t,n={}){let r=[`press`,`--x`,String(e),`--y`,String(t)];return j(r,n),await H(r)}async function X(e,t={}){let n=[`screenshot`,`--out`,e];return j(n,t),t.fullscreen&&n.push(`--fullscreen`),await H(n)}export{G as a,K as i,W as n,X as o,U as r,V as s,w as t};
|
package/dist/src/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { R as centerOfRect, U as isAgentDeviceError, W as normalizeAgentDeviceError, z as AppError } from "./sdk-contracts.js";
|
|
2
2
|
import { n as AgentDeviceClientConfig, r as AgentDeviceDaemonTransport, t as AgentDeviceClient } from "./client-types.js";
|
|
3
3
|
import { p as createLocalArtifactAdapter } from "./sdk-io.js";
|
|
4
4
|
//#region src/agent-device-client.d.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{C as e}from"./sdk-contracts.js";import{d as t}from"./scroll-gesture.js";import{t as n}from"./timeouts.js";import"./retry.js";import{runHarmonyHdc as r}from"./hdc.js";import{invalidateHarmonyGestureViewport as i,readHarmonyGestureViewport as a}from"./snapshot2.js";async function o(e,t,n){await r(e,[`shell`,`uitest`,`uiInput`,`click`,String(t),String(n)])}async function s(e,t,n){await r(e,[`shell`,`uitest`,`uiInput`,`doubleClick`,String(t),String(n)])}async function c(e,t,n,i=800){await r(e,[`shell`,`uitest`,`uiInput`,`longClick`,String(t),String(n)])}async function l(e,t,i=0){await r(e,[`shell`,`uitest`,`uiInput`,`text`,t]),i>0&&await n(i)}async function u(e,t,i,a,o=0){await r(e,[`shell`,`uitest`,`uiInput`,`inputText`,String(t),String(i),a]),o>0&&await n(o)}async function d(e,n,i){let o=await a(e),s=t({direction:n,amount:i?.amount,pixels:i?.pixels,referenceWidth:o.width,referenceHeight:o.height});return await r(e,[`shell`,`uitest`,`uiInput`,`swipe`,String(s.x1),String(s.y1),String(s.x2),String(s.y2),String(i?.durationMs??300)]),s}async function f(t,n){if(n.topology!==`single`)throw new e(`UNSUPPORTED_OPERATION`,`HarmonyOS HDC does not support multi-touch gestures`);let i=n.pointers[0].samples,a=i[0],o=i.at(-1);if(!a||!o)throw new e(`COMMAND_FAILED`,`HarmonyOS gesture plan has no pointer endpoints`);let s=Math.hypot(o.point.x-a.point.x,o.point.y-a.point.y),c=Math.max(200,Math.min(4e4,Math.round(s/n.durationMs*1e3))),l=n.intent===`fling`?`fling`:`swipe`;return await r(t,[`shell`,`uitest`,`uiInput`,l,String(Math.round(a.point.x)),String(Math.round(a.point.y)),String(Math.round(o.point.x)),String(Math.round(o.point.y)),String(c)]),{backend:`harmonyos-hdc-uiinput`,command:l,velocity:c,viewport:n.viewport}}async function p(e){await r(e,[`shell`,`uitest`,`uiInput`,`keyEvent`,`Back`]),i(e)}async function m(e){await r(e,[`shell`,`uitest`,`uiInput`,`keyEvent`,`Home`]),i(e)}async function h(e){await r(e,[`shell`,`uitest`,`uiInput`,`keyEvent`,`Recent`]),i(e)}async function g(e,t){if(t===`Back`){await p(e);return}await r(e,[`shell`,`uitest`,`uiInput`,`keyEvent`,t])}async function _(t,n){throw new e(`UNSUPPORTED_OPERATION`,`HarmonyOS orientation control is not available through the public HDC API.`)}export{h as appSwitcherHarmony,p as backHarmony,s as doubleClickHarmony,u as fillHarmony,m as homeHarmony,c as longPressHarmony,f as performHarmonyGesture,o as pressHarmony,g as pressHarmonyKeyboardKey,d as scrollHarmony,_ as setHarmonyOrientation,l as typeHarmony};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{C as e}from"./sdk-contracts.js";import{gr as t,hr as n,mr as r,pr as i,vr as a}from"./sdk-batch.js";function o(e){return e?.startsWith(`@`)?e.slice(1):e}const s=/^e\d+$/;function c(t){if(t[0]?.startsWith(`@`)){let e=_(t.slice(1));return{ref:t[0],...e===void 0?{}:{label:e}}}if(s.test(t[0]??``))throw new e(`INVALID_ARGS`,`Did you mean "@${t[0]}"? Snapshot refs need the @ prefix.`);let n=a(t);if(n){if(n.rest.length>0)throw new e(`INVALID_ARGS`,m(t,n));return{selector:n.selectorExpression}}return u(t)}function l(t){let n=t[0];if(n?.startsWith(`@`)){let e=t.slice(1),r=e.length===0?void 0:e.join(` `);return{kind:`ref`,target:{ref:n},text:r}}if(s.test(n??``))throw new e(`INVALID_ARGS`,`Did you mean "@${n}"? Snapshot refs need the @ prefix.`);let r=a(t,{preferTrailingValue:!0});if(r)return{kind:`selector`,target:{selector:r.selectorExpression},text:r.rest.length===0?void 0:r.rest.join(` `)};let i=t.slice(2);return{kind:`point`,target:u(t.slice(0,2)),text:i.length===0?void 0:i.join(` `)}}function u(t){let n=t[0]??``,i=r(n);if(i){let r=d(n)?i.value:[i.value,...t.slice(1)].join(` `).trim();throw new e(`INVALID_ARGS`,f({key:i.key,value:r}))}let a=Number(t[0]),o=Number(t[1]);if(Number.isFinite(a)&&Number.isFinite(o))return{x:a,y:o};throw new e(`INVALID_ARGS`,p(t))}function d(e){let t=e.slice(e.indexOf(`=`)+1).trim();if(t.length<2)return!1;let n=t[0];return(n===`"`||n===`'`)&&t.endsWith(n)}function f(e){let{key:t,value:r}=e;return`Unknown selector key "${t}". Supported: ${i.join(`, `)}. ${n(t)?`Did you mean role=${t} label=${g(r)}?`:`Did you mean label=${g(r)}?`}`}function p(e){let n=e.filter(e=>e!==void 0).join(` `);if(!n.trim())return`Missing target. Pass an @ref from snapshot, a selector like text="Sign in", or "x y" coordinates.`;let r=`Target "${n}" is not a @ref, selector, or "x y" point.`;return e.some(e=>t(e??``))?`${r} Selector values with spaces need quotes, e.g. text="Sign in".`:`${r} To match by visible text, use text=${g(n)} (or label=/id=/role=), or pass an @ref from snapshot.`}function m(e,t){return`${`Selector ${t.selectorExpression} is followed by unexpected extra arguments: "${t.rest.join(` `)}".`} Selector values with spaces need quotes, e.g. ${h(e,t)??`text="Sign in"`}.`}function h(e,t){let n=e.length-t.rest.length,r=e[n-1];if(r===void 0)return;let i=r.indexOf(`=`);if(i<=0)return;let a=[r.slice(i+1),...t.rest].join(` `),o=`${r.slice(0,i+1)}${g(a)}`;return[...e.slice(0,n-1),o].join(` `)}function g(e){return`"${e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}"`}function _(e){return e.join(` `).trim()||void 0}export{c as n,o as r,l as t};
|