agent-device 0.21.34 → 0.21.35
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.34.apk → agent-device-android-ime-helper-0.21.35.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.35.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.34.manifest.json → agent-device-android-ime-helper-0.21.35.manifest.json} +4 -4
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.34.apk → agent-device-android-snapshot-helper-0.21.35.apk} +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.35.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.34.manifest.json → agent-device-android-snapshot-helper-0.21.35.manifest.json} +7 -7
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +27 -18
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +26 -7
- package/dist/src/agent-browser-provider.js +1 -1
- package/dist/src/agent-device-client.js +1 -1
- package/dist/src/ai-sdk.d.ts +1 -1
- package/dist/src/alert.js +1 -1
- package/dist/src/android-adb.d.ts +1 -1
- package/dist/src/app-backend.js +1 -1
- package/dist/src/app-launch.js +1 -1
- package/dist/src/app-lifecycle.js +1 -1
- package/dist/src/app-log-reconnect.js +1 -1
- package/dist/src/app-log-runtime2.js +2 -2
- package/dist/src/app-log-session-resource.js +1 -1
- package/dist/src/app-resolution.js +2 -2
- package/dist/src/app-state-runtime.d.ts +1 -1
- package/dist/src/apple-runner-platform.js +1 -1
- package/dist/src/application-lifecycle-interaction.js +1 -1
- package/dist/src/artifact-download.js +1 -1
- package/dist/src/back-mode.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +3 -2
- package/dist/src/cli.js +2 -2
- package/dist/src/client-types.d.ts +17 -4
- package/dist/src/cloud-artifacts.d.ts +2 -2
- package/dist/src/command-metadata.js +41 -41
- package/dist/src/command-schema.js +3 -1
- package/dist/src/command-tools.js +1 -1
- package/dist/src/composed-inventory-gateways.js +1 -1
- package/dist/src/composite-resource-admission.js +1 -1
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/connection.js +5 -5
- package/dist/src/contract.d.ts +2 -1
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/daemon-client-lease-beat.js +1 -1
- package/dist/src/daemon-client.js +2 -2
- package/dist/src/daemon-command-registry.js +1 -1
- package/dist/src/daemon-composition.js +1 -1
- package/dist/src/daemon-policy-file.js +1 -1
- package/dist/src/debug-symbols-facade.js +1 -1
- package/dist/src/destination-tunnel-dialer.js +27 -0
- package/dist/src/device-claim-recovery.js +1 -1
- package/dist/src/device-claims.js +1 -1
- package/dist/src/device-input-state.d.ts +1 -1
- package/dist/src/device-readiness-runtime.js +1 -1
- package/dist/src/device-selection-resolver.js +1 -1
- package/dist/src/device.js +1 -1
- package/dist/src/discovery.js +1 -1
- package/dist/src/doctor-facade.js +1 -1
- package/dist/src/durable-resource.js +1 -1
- package/dist/src/explicit-session-resolution.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/gesture-admission.js +1 -1
- package/dist/src/gesture-plan-types.d.ts +1 -1
- package/dist/src/gesture-runtime.js +1 -1
- package/dist/src/human-control.js +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/instance-client.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/interactor4.js +1 -1
- package/dist/src/interactors.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/inventory2.js +1 -1
- package/dist/src/ios-client.js +4 -4
- package/dist/src/launch-confirmation.js +1 -1
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease-registry-scope.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/leased-recording-retention.js +1 -1
- package/dist/src/legacy.js +1 -1
- package/dist/src/limrun.d.ts +6 -1
- package/dist/src/local-interactor-operation-set.js +1 -1
- package/dist/src/log-stream.js +2 -28
- package/dist/src/mechanics.js +1 -1
- package/dist/src/metro.d.ts +1 -1
- package/dist/src/network-har.js +2 -0
- package/dist/src/open-target-resolution.js +1 -1
- package/dist/src/perf-facade.js +1 -1
- package/dist/src/perf-target.js +1 -1
- package/dist/src/platform-runtime-daemon-services.js +1 -1
- package/dist/src/platform-runtime-open-target.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +3 -3
- package/dist/src/platform-runtime-runtime-hints.js +1 -1
- package/dist/src/platform-runtime-unavailable.js +1 -1
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/platform-runtime2.js +1 -1
- package/dist/src/plugin-inventory.js +1 -1
- package/dist/src/provider-device-runtime.d.ts +1 -1
- package/dist/src/provider-plugin.d.ts +1 -1
- package/dist/src/proxy.js +2 -2
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime-response.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/registry.js +1 -1
- package/dist/src/replay-maestro-backend.js +3 -3
- package/dist/src/replay-script-selection.js +1 -1
- package/dist/src/replay.d.ts +1 -1
- package/dist/src/request-runtime-binding.js +1 -1
- package/dist/src/result-serialization.js +2 -1
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-dev-tools-security.js +1 -1
- package/dist/src/runner-device-readiness.js +1 -1
- package/dist/src/runner-retention.js +1 -1
- package/dist/src/runner-selector-query.js +1 -1
- package/dist/src/runner-startup-transport.js +1 -1
- package/dist/src/runner.js +1 -1
- package/dist/src/runtime-admission.js +1 -1
- package/dist/src/runtime-deployment.js +1 -1
- package/dist/src/runtime-session.js +1 -1
- package/dist/src/runtime.js +2 -2
- package/dist/src/runtime3.js +4 -4
- package/dist/src/runtime4.js +1 -1
- package/dist/src/runtime5.js +1 -1
- 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-resource-recovery.js +1 -1
- package/dist/src/screen-recording-session-resource.js +1 -1
- package/dist/src/screen-recording-transport.js +1 -1
- package/dist/src/screenshot-density.js +1 -1
- package/dist/src/screenshot-runtime.js +1 -1
- package/dist/src/sdk-batch-runner.js +2 -2
- package/dist/src/sdk-batch.js +2 -2
- package/dist/src/sdk-contracts.d.ts +4 -1
- package/dist/src/sdk-device.js +1 -1
- package/dist/src/sdk-finders.d.ts +1 -1
- package/dist/src/sdk-remote-config.d.ts +8 -1
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.d.ts +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/server-startup.js +1 -1
- package/dist/src/server.js +1 -1
- package/dist/src/session-artifact-paths.js +1 -1
- package/dist/src/session-device-resolution.js +1 -1
- package/dist/src/session-open.js +1 -1
- package/dist/src/session-runtime.js +1 -1
- package/dist/src/session-selector.js +1 -1
- package/dist/src/session-store.js +1 -1
- package/dist/src/session2.js +4 -4
- package/dist/src/settle-observation-capture.js +1 -1
- package/dist/src/simctl.js +1 -1
- package/dist/src/simulator-boot.js +1 -1
- package/dist/src/snapshot-diagnostics.js +1 -1
- package/dist/src/snapshot-runtime-binding.js +1 -1
- package/dist/src/snapshot-runtime-capture-input.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src3.js +4 -4
- package/dist/src/src4.js +1 -1
- package/dist/src/src9.js +1 -1
- package/dist/src/store.js +1 -1
- package/dist/src/telephony-runtime.js +1 -1
- package/dist/src/touch-runtime2.js +1 -1
- package/dist/src/transport.js +2 -2
- package/dist/src/tv-remote-runtime.js +1 -1
- package/dist/src/tv-remote.js +1 -1
- package/dist/src/type-text-runtime.js +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.34.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.34.apk.sha256 +0 -1
- package/dist/src/session-capture-binding.js +0 -1
- package/dist/src/session-teardown.js +0 -1
package/dist/src/session2.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{$ as e,A as t,C as n,N as r,Q as i,R as a,T as o,V as s,f as c,n as l,p as u,s as d,tt as f,w as p}from"./sdk-contracts.js";import{U as m,V as h,z as g}from"./tv-remote.js";import{j as _,n as v,t as y,v as b}from"./sdk-batch-runner.js";import{a as x,n as S,t as C}from"./snapshot-diagnostics.js";import{$ as w,A as ee,E as T,F as te,G as ne,I as re,M as E,N as ie,R as ae,T as oe,Y as se,at as ce,et as le,j as ue,k as de,m as fe,tt as pe}from"./back-mode.js";import{H as me,Q as he,St as ge,_t as D}from"./sdk-io.js";import"./diagnostics.js";import{C as O,E as _e,F as k,M as ve,N as ye,_ as be,w as A,y as j,z as xe}from"./sdk-device.js";import{$ as Se,B as Ce,D as we,Dr as Te,Er as Ee,F as De,Fn as Oe,H as ke,I as Ae,In as je,L as Me,Ln as Ne,M as Pe,Mt as Fe,N as Ie,Nt as Le,Q as Re,R as ze,St as Be,Tn as Ve,Tr as He,V as Ue,X as We,Xt as Ge,Y as Ke,ar as qe,cr as Je,et as Ye,ft as Xe,ht as Ze,jt as Qe,mr as $e,on as et,pt as tt,rt as nt,sr as rt,tt as it,v as at,xt as ot,z as st}from"./sdk-batch.js";import{c as ct,d as lt,f as ut,h as dt,l as ft,m as pt,o as M,p as mt,s as ht,u as gt}from"./session-store.js";import{a as _t,i as vt,n as yt,o as bt,t as xt}from"./target-evidence.js";import{a as St,i as Ct,n as wt,o as Tt,r as Et,s as Dt,t as Ot}from"./vars.js";import{F as kt,M as At,N as jt,_ as Mt,f as Nt,g as Pt,h as Ft,j as It,p as Lt,v as Rt,y as zt}from"./parameterized-recorded-fill.js";import{n as Bt,r as Vt,t as Ht}from"./target-evidence-tree.js";import{C as Ut,T as Wt,_ as Gt,g as Kt,k as qt,o as Jt,s as Yt}from"./src.js";import{g as Xt,i as Zt}from"./observability.js";import{i as N,n as Qt,r as P}from"./success-text.js";import{t as $t}from"./app-inventory.js";import{n as en,r as tn}from"./output-path.js";import"./command.js";import{t as F}from"./session-paths.js";import{c as nn}from"./session-artifact-paths.js";import{a as rn}from"./version.js";import"./retry.js";import{i as an,n as on}from"./replay-divergence.js";import{n as sn,t as cn}from"./deploy-result-target.js";import{c as ln,d as un,f as dn,h as fn,l as pn,m as mn,o as hn,p as gn,s as _n,u as vn}from"./screen-recording-session-resource.js";import{t as yn}from"./keyboard-actions.js";import{a as bn,c as xn,h as Sn,o as Cn,r as wn}from"./replay-script-selection.js";import{a as Tn,n as En}from"./artifact-tracking.js";import{n as Dn}from"./provider-device-admission.js";import{d as On,n as kn,o as I,r as An,u as jn}from"./snapshot-runtime-capture-input.js";import{a as Mn,d as Nn,i as Pn,m as Fn,p as In}from"./device-claims.js";import{a as Ln,c as Rn,d as zn,l as Bn,t as Vn,u as Hn}from"./request.js";import{i as Un,o as Wn}from"./lease-context.js";import{p as Gn}from"./daemon-command-registry.js";import{a as Kn,n as qn,o as Jn,r as Yn,s as Xn,t as Zn,u as Qn}from"./session-runtime.js";import{n as L}from"./device-isolation.js";import{a as $n,n as er,o as tr,r as nr}from"./device-inventory-context.js";import{l as rr}from"./selector-pipeline-policy.js";import{t as ir}from"./session-selector.js";import{a as ar,c as or,d as sr,f as cr,i as lr,n as ur,o as dr,r as fr,t as pr,u as mr}from"./session-teardown.js";import{i as hr,n as gr}from"./session-capture-binding.js";import{i as _r,n as R,t as vr}from"./runtime-admission.js";import{c as yr,f as br,r as xr}from"./runtime-session.js";import{n as Sr}from"./snapshot-node-lookup.js";import{a as Cr,i as z,n as B,r as V,t as wr}from"./session-runtime-admission.js";import{n as Tr}from"./gesture-runtime.js";import{a as Er,c as Dr,i as Or,l as kr,o as Ar,r as jr,s as Mr,t as Nr}from"./app-log-session-resource.js";import{a as Pr,i as Fr,n as H,r as U}from"./session-device-resolution.js";import{t as Ir}from"./record-runtime.js";import{handleSessionOpenCommands as Lr,n as Rr,r as zr,t as Br}from"./session-open.js";import{t as Vr}from"./audio-probe-result.js";import{a as Hr,c as Ur,d as Wr,g as Gr,h as Kr,l as qr,m as Jr,n as Yr,o as Xr,p as Zr,r as Qr,t as $r,u as ei}from"./session-replay-vars.js";import{n as ti}from"./replay.js";import{t as ni}from"./replay-backend-registry.js";import{t as ri}from"./session-test-source-discovery.js";import{n as ii}from"./status-markers.js";import{n as ai,r as oi}from"./doctor-lines.js";import{t as si}from"./project-runtime.js";import{createHash as ci}from"node:crypto";import W,{promises as li}from"node:fs";import G from"node:path";import{setTimeout as ui}from"node:timers/promises";function di(e){throw new a(`UNSUPPORTED_OPERATION`,`install_from_source ${String(e.kind)} sources require a compatible remote daemon`)}function fi(e){let t=e.meta?.installSource;if(!t)throw new a(`INVALID_ARGS`,`install_from_source requires a source payload`);switch(t.kind){case`url`:if(!t.url||t.url.trim().length===0)throw new a(`INVALID_ARGS`,`install_from_source url source requires a non-empty url`);return t;case`path`:if(!t.path||t.path.trim().length===0)throw new a(`INVALID_ARGS`,`install_from_source path source requires a non-empty path`);return t;case`github-actions-artifact`:throw new a(`UNSUPPORTED_OPERATION`,`install_from_source github-actions-artifact sources require a compatible remote daemon`);default:di(t)}}function pi(e){let t=fi(e),n=e.meta?.uploadedArtifactId;return!n||t.kind!==`path`?{source:t,cleanup:()=>{}}:{source:{kind:`path`,path:Tn(n,e.meta?.tenantId)},cleanup:()=>{En(n)}}}async function mi(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o,s,c;try{o=pi(t);let l=vi(t),u=await gi(a,t.flags,r.host.env,e.platformServices),d=await V(e.inspectFacts)(u),f=z(`install_from_source`,d.operations.ensureReady)??z(`install_from_source`,d.operations.materializeAppSource)??z(`install_from_source`,d.operations.deployMaterializedApp);if(f)return f;let p=await B(e.bindDevice)(u,Se);await p.operations.ensureReady({}),s=await p.operations.materializeAppSource({source:o.source}),c=await yi({artifact:s,retention:l,req:t,session:a,sessionName:n}),i&&I(r.requireCurrent(i));let m=await p.operations.deployMaterializedApp({artifact:s}),h=bi(u,s,m,c),g=N(h,`Installed: ${sn(h)}`);return M(r,i,t,`install_source`,g,{positionals:[]}),{ok:!0,data:g}}catch(e){return c&&await mr(c.materializationId,t.meta?.tenantId).catch(()=>{}),{ok:!1,error:f(e)}}finally{await s?.cleanup(),o?.cleanup()}}async function hi(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new a(`INVALID_ARGS`,`release_materialized_paths requires a materializationId`);return await mr(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:f(e)}}}async function gi(e,t,n,r){let i=_i(t?.platform);if(e&&i&&!ye(e.device,i))throw new a(`INVALID_ARGS`,`install_from_source requested platform ${i}, but session is bound to ${k(e.device)}`);if(!e&&!i)throw new a(`INVALID_ARGS`,`install_from_source requires platform "ios" or "android" when no session is provided`);return e?e.device:await U({session:e,flags:t,env:n,platformServices:r})}function _i(e){return e===`ios`||e===`android`?e:void 0}function vi(e){let t=e.meta?.retainMaterializedPaths===!0,n=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(n!==void 0&&n<=0)throw new a(`INVALID_ARGS`,`install_from_source retentionMs must be a positive integer`);return{enabled:!0,...n===void 0?{}:{ttlMs:n}}}async function yi(e){if(e.retention.enabled)return await cr({archivePath:e.artifact.archivePath,installablePath:e.artifact.installablePath,tenantId:e.req.meta?.tenantId,sessionName:e.session?e.sessionName:void 0,ttlMs:e.retention.ttlMs})}function bi(e,t,n,r){return O(e)?xi(t,n,r):Si(t,n,r)}function xi(e,t,n){let r=t.bundleId??e.bundleId;if(!r)throw new a(`COMMAND_FAILED`,`Installed iOS app identity could not be resolved from the artifact`);return{...wi(n),bundleId:r,...Ci(t,e),launchTarget:t.launchTarget??r}}function Si(e,t,n){let r=t.packageName??t.launchTarget??e.packageName;if(!r)throw new a(`COMMAND_FAILED`,`Installed Android app identity could not be resolved from the artifact or device state`);return{...wi(n),packageName:r,...Ci(t,e),launchTarget:t.launchTarget??r}}function Ci(e,t){let n=e.appName??t.appName;return n?{appName:n}:{}}function wi(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function Ti(e){let{req:t,session:n,inspectFacts:r,bindDevice:i,platformServices:a}=e,o=Ei(t);if(!o.ok)return o.response;let s=H(`runtime port-reverse`,n,t.flags);if(s)return s;let c=await U({session:n,flags:t.flags,env:e.env,platformServices:e.platformServices}),l=await R({device:c,inspectFacts:r,bindDevice:i,platformServices:a,command:`runtime port-reverse`,use:ke});if(l.type===`response`)return l.response;if(l.runtime.owner.kind!==`provider-runtime`||l.runtime.owner.provider!==o.options.provider)return d(`UNSUPPORTED_OPERATION`,`The selected device is not owned by the requested port-reverse provider.`,{provider:o.options.provider});let u=await l.runtime.operations.configureProviderPortReverse(o.options);return u?{ok:!0,data:{action:`port-reverse`,...u}}:d(`UNSUPPORTED_OPERATION`,`The selected provider device runtime does not support port reverse for this lease.`)}function Ei(e){let t=Di(e);if(!t.ok)return t;let n=Oi(e);return n.ok?{ok:!0,options:{leaseId:t.leaseId,provider:t.provider,devicePort:n.devicePort,hostPort:n.hostPort,name:e.flags?.portReverseName?.trim()||`runtime`}}:n}function Di(e){let t=e.flags?.leaseId,n=e.flags?.leaseProvider;return t?n?{ok:!0,leaseId:t,provider:n}:{ok:!1,response:d(`INVALID_ARGS`,`runtime port-reverse requires a lease provider.`)}:{ok:!1,response:d(`INVALID_ARGS`,`runtime port-reverse requires a resolved remote lease.`)}}function Oi(e){let t=ki(e.flags?.devicePort),n=ki(e.flags?.hostPort??e.flags?.devicePort);return!t||!n?{ok:!1,response:d(`INVALID_ARGS`,`runtime port-reverse requires numeric devicePort and hostPort values from 1 to 65535.`)}:{ok:!0,devicePort:t,hostPort:n}}function ki(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<1||e>65535))return e}async function Ai(e){return await R({...e,command:`runtime clear`,use:st})}async function ji(e){let{req:t,sessionName:n,sessionStore:r}=e,i=(t.positionals?.[0]??`show`).toLowerCase();if(i===`port-reverse`)return await Ti({req:t,session:r.get(n),env:r.host.env,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(i===`gesture-viewport`)return await Mi({...e,session:r.get(n)});if(!Ni(i))return d(`INVALID_ARGS`,`runtime requires set, show, clear, port-reverse, or gesture-viewport`);let a=r.lookup(n),o=a?.session,s=r.getRuntimeHints(n);return i===`clear`?await Pi({sessionName:n,sessionStore:r,ref:a,current:s,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice}):i===`show`?Fi(n,s):Li({req:t,sessionName:n,sessionStore:r,session:o,current:s})}async function Mi(e){if(!e.session)return d(`SESSION_NOT_FOUND`,`No active session. Run open first.`);let t=await Tr({device:e.session.device,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(!t.ok)return t.response;let n=An(e.logPath,e.req.flags,e.session.appBundleId,e.session.trace?.outPath,e.req.meta?.requestId,e.req.meta);return{ok:!0,data:{viewport:await t.read(n)}}}function Ni(e){return e===`set`||e===`show`||e===`clear`}async function Pi(e){let{sessionName:t,sessionStore:n,ref:r,current:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,c=r?n.requireCurrent(r):void 0;if(Yn(i)&&c?.appBundleId){let e=await Ai({device:c.device,inspectFacts:a,bindDevice:o,platformServices:s});if(e.type===`response`)return e.response;let t=n.requireCurrent(r);I(t),await e.runtime.operations.clearRuntimeHints({appId:t.appBundleId,values:Xn(i)})}let l=r?n.clearRuntimeHints(r):!!i;return r||n.setRuntimeHints(t,void 0),{ok:!0,data:{session:t,cleared:l}}}function Fi(e,t){return{ok:!0,data:{session:e,configured:!!t,runtime:t}}}function Ii(e){return e?k(e.device):void 0}function Li(e){let{req:t,sessionName:n,sessionStore:r,session:i,current:a}=e,o=Ii(i),s=Qn(t.flags?.platform??a?.platform??o);if(!s)return d(`INVALID_ARGS`,`runtime set only supports iOS, Android, and HarmonyOS sessions. Pass --platform ios|android|harmonyos or open a supported session first.`);if(o!==void 0&&o!==s)return d(`INVALID_ARGS`,`runtime set targets ${s}, but session "${n}" is already bound to ${o}.`);let c=Kn(a,Zn(t.flags,s));return qn(c)===0?d(`INVALID_ARGS`,`runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url.`):(r.setRuntimeHints(n,c),{ok:!0,data:{session:n,configured:!0,runtime:c}})}const Ri=/^[A-Za-z0-9_.:-]{1,64}$/,zi=8192,Bi=4096;function Vi(e){let t=e[0]?.trim(),n=e[1]?.trim();if(!t)throw new a(`INVALID_ARGS`,`trigger-app-event requires <event> [payloadJson]`);if(!Ri.test(t))throw new a(`INVALID_ARGS`,`Invalid trigger-app-event event name: ${t}`,{hint:`Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash.`});if(e.length>2)throw new a(`INVALID_ARGS`,`trigger-app-event accepts at most two arguments: <event> [payloadJson]`);return{eventName:t,payload:Ui(n,t)}}function Hi(e,t,n,r){let i=k(e),o=Wi(e,r);if(!o)throw new a(`UNSUPPORTED_OPERATION`,`No app event URL template configured for ${i}.`,{hint:`Set AGENT_DEVICE_${i.toUpperCase()}_APP_EVENT_URL_TEMPLATE or AGENT_DEVICE_APP_EVENT_URL_TEMPLATE, for example "myapp://agent-device/event?name={event}&payload={payload}".`});let s=n?JSON.stringify(n):``,c=o.replaceAll(`{event}`,encodeURIComponent(t)).replaceAll(`{payload}`,encodeURIComponent(s)).replaceAll(`{platform}`,encodeURIComponent(i));if(c.length>Bi)throw new a(`INVALID_ARGS`,`trigger-app-event URL exceeds maximum supported length`,{hint:`Reduce payload size or shorten AGENT_DEVICE_*_APP_EVENT_URL_TEMPLATE.`,length:c.length,maxLength:Bi});return c}function Ui(e,t){if(e)try{let n=JSON.parse(e);if(!n||typeof n!=`object`||Array.isArray(n))throw new a(`INVALID_ARGS`,`trigger-app-event payload for "${t}" must be a JSON object`);let r=JSON.stringify(n);if(Buffer.byteLength(r,`utf8`)>zi)throw new a(`INVALID_ARGS`,`trigger-app-event payload for "${t}" exceeds ${zi} bytes`);return n}catch(t){throw t instanceof a?t:new a(`INVALID_ARGS`,`Invalid trigger-app-event payload JSON: ${e}`)}}function Wi(e,t){return((O(e)?t.AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE:A(e)?t.AGENT_DEVICE_MACOS_APP_EVENT_URL_TEMPLATE:t.AGENT_DEVICE_ANDROID_APP_EVENT_URL_TEMPLATE)??t.AGENT_DEVICE_APP_EVENT_URL_TEMPLATE)?.trim()||void 0}async function Gi(e,t,n,r,i){let{eventName:a,payload:o}=Vi([...r]),s=Hi(t,a,o,i),c={eventUrl:s,...n.appBundleId===void 0?{}:{options:{appBundleId:n.appBundleId}},execution:kn(n)};return await e.operations.triggerAppEvent(c),{event:a,eventUrl:s,transport:`deep-link`,...P(`Triggered app event: ${a}`)}}async function Ki(e){let{host:t,device:n,positionals:r,inspectFacts:i,bindDevice:a,platformServices:o,readiness:s}=e,c=await R({command:`trigger-app-event`,device:n,use:Xe,inspectFacts:i,bindDevice:a,platformServices:o,readiness:s});if(c.type===`response`)return{ok:!1,response:c.response};let l=c.runtime;return{ok:!0,execute:e=>Gi(l,n,e,r,t.env)}}function qi(e){let t=(e[0]??`status`).toLowerCase();if(!yn(t))throw new a(`INVALID_ARGS`,`keyboard requires a subcommand: status, get, dismiss, enter, or return`);if(e.length>1)throw new a(`INVALID_ARGS`,`keyboard accepts at most one subcommand argument`);return Ji(t)}function Ji(e){return e===`get`?`status`:e===`return`?`enter`:e}const Yi={"ime-probe":`android`},Xi={"ime-probe":`android`,mechanism:`ios`,acknowledged:`harmonyos`},Zi={"visibility-echo":`ios`,"android-acknowledged":`android`,"harmonyos-acknowledged":`harmonyos`};function Qi(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:kn(e)}}async function $i(e,t){let n=await R(e);if(n.type===`response`)return{ok:!1,response:n.response};let r=n.runtime;return{ok:!0,execute:e=>t(r,e)}}function ea(e,t){return e.operations.keyboardStatus(Qi(t)).then(e=>({platform:Yi[e.kind],action:`status`,visible:e.visible,inputType:e.inputType,type:e.type,inputMethodPackage:e.inputMethodPackage,focusedPackage:e.focusedPackage,focusedResourceId:e.focusedResourceId,inputOwner:e.inputOwner}))}async function ta(e,t){let n=await e.operations.keyboardDismiss(Qi(t)),r=Xi[n.kind];return n.kind===`mechanism`?{platform:r,action:`dismiss`,wasVisible:n.wasVisible,dismissed:n.dismissed,visible:n.visible,mechanism:n.mechanism,...P(ia(n.dismissed===!0,n.mechanism))}:n.kind===`acknowledged`?{platform:r,action:`dismiss`,...P(`Keyboard dismissed`)}:{platform:r,action:`dismiss`,attempts:n.attempts,wasVisible:n.wasVisible,dismissed:n.dismissed,visible:n.visible,inputType:n.inputType,type:n.type,inputMethodPackage:n.inputMethodPackage,focusedPackage:n.focusedPackage,focusedResourceId:n.focusedResourceId,inputOwner:n.inputOwner}}async function na(e,t){let n=await e.operations.keyboardEnter(Qi(t)),r=Zi[n.kind];return n.kind===`visibility-echo`?{platform:r,action:`enter`,visible:n.visible,wasVisible:n.wasVisible,...P(`Keyboard enter pressed`)}:{platform:r,action:`enter`,...P(`Keyboard enter pressed`)}}async function ra(e){let t=qi(e.positionals),{device:n,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o}=e;return t===`status`?await $i({command:`keyboard status`,device:n,use:Le,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o},(e,t)=>ea(e,t)):t===`dismiss`?await $i({command:`keyboard dismiss`,device:n,use:Qe,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o},(e,t)=>ta(e,t)):await $i({command:`keyboard enter`,device:n,use:Fe,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o},(e,t)=>na(e,t))}function ia(e,t){return e?t===`dismissKey`?`Keyboard dismissed via its dismiss key`:`Keyboard dismissed`:`Keyboard already hidden`}async function aa(e){let{req:t,sessionName:n,sessionStore:r,command:i,positionals:a,recordPositionals:o,updateSession:s,prepare:c}=e,l=r.lookup(n),u=l?.session,d=t.flags??{},f=H(i,u,d);if(f)return f;let p=await U({session:u,flags:d,env:r.host.env,platformServices:e.platformServices});l&&r.requireCurrent(l);let m=await c(p,l);if(!m.ok)return m.response;let h=l?r.requireCurrent(l):void 0;h&&Gn(t)===`may-invalidate`&&I(h);let g=await m.execute();return l&&(s&&await s(l,g),M(r,l,t,i,g??{},{positionals:o??a})),{ok:!0,data:g??{}}}function oa(e,t,n){if(!(e||t!==`dismiss`&&t!==`enter`&&t!==`return`||n?.platform!==`ios`))return d(`SESSION_NOT_FOUND`,`iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.`)}async function sa(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,c=t.positionals??[];return await aa({req:t,sessionName:n,sessionStore:i,command:e.command,positionals:c,platformServices:s,...e.updateSession?{updateSession:e.updateSession}:{},prepare:async(n,l)=>{let u=await e.resolveRuntime({host:e.host,device:n,positionals:c,readiness:!0,inspectFacts:a,bindDevice:o,platformServices:s});if(!u.ok)return{ok:!1,response:u.response};let d=l?i.requireCurrent(l):void 0,f={...An(r,t.flags,d?.appBundleId,d?.trace?.outPath),surface:d?.surface};return{ok:!0,execute:()=>u.execute(f)}}})}async function ca(e){return oa(e.sessionStore.get(e.sessionName),e.req.positionals?.[0]?.trim().toLowerCase(),e.req.flags??{})||await sa({...e,command:T.keyboard,resolveRuntime:e=>ra(e)})}async function la(e){return await sa({...e,command:T.triggerAppEvent,resolveRuntime:e=>Ki(e),updateSession:async(t,n)=>{let r=typeof n?.eventUrl==`string`?n.eventUrl:void 0;if(!r)return;let i=e.sessionStore.requireCurrent(t),a=await e.platformServices.resolveSessionAppBundleIdForTarget(i.device,r,i.appBundleId);a!==void 0&&e.sessionStore.update(t,{appBundleId:a})}})}function ua(e){let t=e.trim();return t.startsWith(`{`)&&t.endsWith(`}`)||t.startsWith(`[`)&&t.endsWith(`]`)}function da(e,t){let n=t?.subject??`Payload`,r=e.trim();if(!r)throw new a(`INVALID_ARGS`,`${n} cannot be empty`);let i=t?.expandPath?t.expandPath(r,t.cwd):r;try{if(!W.statSync(i).isFile())throw new a(`INVALID_ARGS`,`${n} path is not a file: ${i}`);return{kind:`file`,path:i}}catch(e){if(e instanceof a)throw e;let t=e.code;if(t===`EACCES`||t===`EPERM`)throw new a(`INVALID_ARGS`,`${n} file is not readable: ${i}`);if(t&&t!==`ENOENT`)throw new a(`COMMAND_FAILED`,`Unable to read ${n} file: ${i}`,{cause:String(e)})}if(ua(r))return{kind:`inline`,text:r};throw new a(`INVALID_ARGS`,`${n} file not found: ${i}`)}async function fa(e){let t=da(e,{subject:`Push payload`}),n=t.kind===`inline`?t.text:await pa(t.path);try{let e=JSON.parse(n);if(!e||typeof e!=`object`||Array.isArray(e))throw new a(`INVALID_ARGS`,`push payload must be a JSON object`);return e}catch(t){throw t instanceof a?t:new a(`INVALID_ARGS`,`Invalid push payload JSON: ${e}`)}}async function pa(e){try{return await li.readFile(e,`utf8`)}catch(t){let n=t.code;throw n===`ENOENT`?new a(`INVALID_ARGS`,`Push payload file not found: ${e}`):n===`EISDIR`?new a(`INVALID_ARGS`,`Push payload path is not a file: ${e}`):n===`EACCES`||n===`EPERM`?new a(`INVALID_ARGS`,`Push payload file is not readable: ${e}`):new a(`COMMAND_FAILED`,`Unable to read push payload file: ${e}`,{cause:String(t)})}}async function ma(e){let{req:t,command:n,sessionName:r,sessionStore:i}=e,a=i.lookup(r),o=a?.session,s=t.flags??{},c=H(n,o,s);if(c)return c;let l=xa(n,t.positionals??[]);if(!l.ok)return l.response;let u=t.meta?.uploadedArtifactId;try{let r=u?Tn(u,t.meta?.tenantId):F(l.appPathInput,e.host.cwd);if(!W.existsSync(r))return d(`INVALID_ARGS`,`App binary not found: ${r}`);let c=await U({session:o,flags:s,env:i.host.env,platformServices:e.platformServices}),f=await V(e.inspectFacts)(c),p=z(n,f.operations.deployApp);if(p)return p;let m=await B(e.bindDevice)(c,Re);a&&I(i.requireCurrent(a));let h=await m.operations.deployApp({app:l.app,appPath:r,replaceExisting:n===`reinstall`}),g=_a(c,l.app,r,h),_=N(g,`Installed: ${g.appName??cn(g)}`);return ba(i,a,g),M(i,a,t,n,_),{ok:!0,data:_}}finally{u&&En(u)}}async function ha(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o=t.flags??{},s=H(`push`,a,o);if(s)return s;let c=t.positionals?.[0]?.trim(),l=t.positionals?.[1]?.trim();if(!c||!l)return d(`INVALID_ARGS`,`push requires <bundle|package> <payload.json|inline-json>`);let u=await fa(Sa(l,t.meta?.cwd??e.host.cwd)),f=await U({session:a,flags:o,env:r.host.env,platformServices:e.platformServices}),p=await V(e.inspectFacts)(f),m=z(`push`,p.operations.ensureReady)??z(`push`,p.operations.sendPushNotification);if(m)return m;let h=await B(e.bindDevice)(f,Ye);await h.operations.ensureReady({}),i&&I(r.requireCurrent(i));let g=await h.operations.sendPushNotification({appId:c,payload:u}),_=O(f)?N({platform:`ios`,bundleId:c},`Pushed notification to ${c}`):N({platform:k(f),package:c,action:g.action,extrasCount:g.extrasCount},`Pushed notification to ${c}`);return M(r,i,t,`push`,_,{positionals:[c,l]}),{ok:!0,data:_}}async function ga(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o=t.flags??{},s=H(`uninstall`,a,o);if(s)return s;let c=t.positionals?.[0]?.trim();if(!c)return d(`INVALID_ARGS`,`uninstall requires <app>`);let l=await U({session:a,flags:o,env:r.host.env,platformServices:e.platformServices}),u=await V(e.inspectFacts)(l),f=z(`uninstall`,u.operations.uninstallApp);if(f)return f;let p=await B(e.bindDevice)(l,it);i&&I(r.requireCurrent(i));let m=await p.operations.uninstallApp({app:c}),h=O(l)?`ios`:`android`,g=m.wasInstalled?`bundleId`in m?m.bundleId:m.packageName:void 0,_=g?N({platform:h,app:c,wasInstalled:!0,appId:g},`Uninstalled: ${g}`):N({platform:h,app:c,wasInstalled:!1},`Not installed: ${c}`);return M(r,i,t,`uninstall`,_),{ok:!0,data:_}}function _a(e,t,n,r){return O(e)?va(t,n,r):ya(e,t,n,r)}function va(e,t,n){let r=n.bundleId;return{app:e||r||n.launchTarget||t,appPath:t,platform:`ios`,...r?{appId:r,bundleId:r}:{},appName:n.appName,launchTarget:n.launchTarget}}function ya(e,t,n,r){let i=r.packageName,a=e.platform===`harmonyos`?`harmonyos`:`android`;return{app:t||i||r.launchTarget||n,appPath:n,platform:a,...i?{appId:i,package:i,packageName:i}:{},appName:r.appName,launchTarget:r.launchTarget}}function ba(e,t,n){!t||n.platform!==`harmonyos`||!n.appId||e.update(t,{appBundleId:n.appId,appName:n.appName??n.app})}function xa(e,t){let n=t[0]?.trim(),r=t[1]?.trim();if(e===`install`){let e=r??n;return e?{ok:!0,app:r?n??``:``,appPathInput:e}:{ok:!1,response:d(`INVALID_ARGS`,`install requires: install <path-to-app-binary>`)}}return!n||!r?{ok:!1,response:d(`INVALID_ARGS`,`reinstall requires: reinstall <app> <path-to-app-binary>`)}:{ok:!0,app:n,appPathInput:r}}function Sa(e,t){let n=da(e,{subject:`Push payload`,cwd:t,expandPath:(e,n)=>F(e,n??t)});return n.kind===`file`?n.path:n.text}async function K(e){let{host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}=e;return n.command===`install`||n.command===`reinstall`?await ma({host:t,req:n,command:n.command,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`install_source`?await mi({req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`uninstall`?await ga({host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`push`?await ha({host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):null}async function Ca(e,t,n){return await v(e,t,async(e,t)=>{let r=e;return await n({...r,internal:{...r.internal,executionPlan:{remainingSteps:t.remainingSteps}}})})}function wa(e,t,n){let r=e.requireCurrent(t);e.recordAction(t,{command:`close`,positionals:n.positionals??[],flags:n.flags??{},result:{session:r.name,...P(`Closed: ${r.name}`)}})}function Ta(e,t,n){let r=e.requireCurrent(t);if(!gt(r))return{kind:`not-armed`};let i=r.actions.length;wa(e,t,n);let a=Ft(r),o=e.writeSessionLog(t,{force:Nt(r,n.flags?.force)});return o.written?{kind:`committed`,path:o.path}:o.error?(r.actions.length=i,{kind:`failed`,error:o.error}):a?{kind:`committed`}:(ht(r),{kind:`aborted`})}function Ea(e,t){let n=f(t),r=At(e.scriptPublication??zt);return{ok:!1,error:{...n,details:{...n.details,session:e.name,...r?{savedScript:r}:{}},retriable:!0}}}function Da(e){let{req:t,ref:n,sessionStore:r,platformCloseError:i}=e,a=r.requireCurrent(n);i||wa(r,n,t);try{let e=r.writeSessionLog(n,{force:Nt(a,t.flags?.force)});e.written&&Mt(a,e.path);return}catch(e){return Oa(e)}}function Oa(e){let t={hint:`Remove the existing target (or pass --force/--overwrite), then re-record with open --save-script.`,retriable:!1};return e instanceof a?new a(`COMMAND_FAILED`,`The session was closed, but its script was not saved: ${e.message}`,{...e.details,...t},e.cause):new a(`COMMAND_FAILED`,`The session was closed, but its script was not saved: ${f(e).message}`,t)}async function ka(e){let t=e.clearRuntimeHints?Ue:Ce,n=await vr({...e,command:`close`,required:t.required});if(n.type===`response`)return n;if(!e.clearRuntimeHints)return{type:`runtime`,runtime:await n.bind(e.device,Ce)};let r=await n.bind(e.device,Ue);return{type:`runtime`,runtime:r,clearRuntimeHints:r.operations.clearRuntimeHints}}async function Aa(e){let{req:t,ref:n,logPath:r,sessionStore:i,lifecycle:a,clearRuntimeHints:o,cleanupFailures:s,repairArmed:c,dispatchTargetedPlatformClose:l,finalizeOrdinaryCloseScript:u}=e,{address:d}=n,f=i.requireCurrent(n),p=async(e,t)=>{try{return await t()}catch(t){s.push({step:e,error:t});return}},m=e.platformResourceCleanup.retainExecutionHostAfterClose({device:f.device,shutdownRequested:t.flags?.shutdown===!0,hasScreenRecording:!!f.screenRecording,hasLease:!!f.lease}),h=i.getRuntimeHints(d);await ja(n,i,p,e.platformResourceCleanup),f=i.requireCurrent(n);let g=c?void 0:await l({req:t,session:f,logPath:r,lifecycle:a});o&&f.appBundleId&&Yn(h)&&await p(`runtime_hints`,async()=>{await o({appId:f.appBundleId,values:Xn(h)})});let _=await p(`application_lifecycle`,async()=>await a.operations.finalizeApplicationClose({appBundleId:f.appBundleId,surface:f.surface??`app`,retainRunner:m,stateDir:i.resolveDaemonStateDir(),shutdownTarget:t.flags?.shutdown===!0})??{}),v=c?void 0:u({req:t,ref:n,sessionStore:i,platformCloseError:g});return await p(`materialized_paths`,()=>sr(d)),{platformCloseError:g,saveScriptError:v,shutdownResult:_?.shutdown}}async function ja(e,t,n,r){let i=t.resolveCurrent(e)??e.session;await n(`recording`,()=>ur({ref:e,sessionStore:t})),await n(`app_log`,()=>lr({ref:e,sessionStore:t})),await n(`audio_probe`,()=>pr({ref:e,sessionStore:t})),await n(`perf_capture`,()=>ar({ref:e,sessionStore:t})),await n(`platform_snapshot_helper`,()=>dr(i,r))}function Ma(e,t){return fr({sessionName:e,phase:`session_close_cleanup_failed`,failures:t})}function Na(e){if(e instanceof a)return e;let t=e instanceof Error?e.message:String(e);return new a(`COMMAND_FAILED`,`The platform close failed: ${t}`,{hint:`The repair transaction was not committed because the platform close failed; fix the underlying issue and retry close --save-script.`})}const Pa=(e,t)=>(e.positionals?.length??0)>0||or(t);async function Fa(e){let{req:t,ref:n,logPath:r,sessionStore:i,lifecycle:a}=e,o=i.requireCurrent(n),s=gt(o),c=JSON.stringify(t.positionals??[]);if(s&&!ft(o,c)){let e=await La({req:t,session:o,logPath:r,lifecycle:a});if(e)return{response:Ea(o,Na(e))};mt(i.requireCurrent(n),c)}let l=Ta(i,n,t);return l.kind===`failed`?{response:Ea(o,l.error)}:{repairArmed:s,...l.kind===`committed`&&l.path?{healedScriptPath:l.path}:{},...l.kind===`aborted`?{aborted:!0}:{}}}async function Ia(e){try{let{endedLeaseId:t,providerData:n}=await Wt(e);return t&&Yt(e.req,t),{providerData:n}}catch(t){let n=f(t);return{response:{ok:!1,error:{...n,hint:`The provider device could not be released. Retry close after the provider is reachable.`,details:{...n.details,session:e.session.name},retriable:!0}}}}}async function La(e){let{req:t,session:n,logPath:r,lifecycle:i}=e;if(Pa(t,n))try{await i.operations.closeApplication({positionals:t.positionals??[],outPath:t.flags?.out,appBundleId:n.appBundleId,surface:n.surface??`app`,...t.internal?.killApp===!0?{mode:`kill`}:{},execution:Rr(t,r,n.trace?.outPath)});return}catch(e){return e}}function Ra(e,t){if(!e.flags?.saveScript||Lt(t))return;let n=t.scriptPublication;if(n?.kind!==`repair`)throw n===void 0||n.kind===`none`?new a(`INVALID_ARGS`,`close --save-script cannot publish this session: recording was not armed before this journey began, so there is no recording-time target evidence to publish.`,{hint:`Retry with plain close (it tears down without writing). To capture a publishable recording, start a fresh session with open <app> --save-script[=<path>].`}):new a(`INVALID_ARGS`,`close --save-script cannot ${n.status===`published`?`re-publish`:`publish`} this terminal recording. Retry with plain close; it will tear down the session without writing.`)}async function za(e){let{session:t,app:n}=e;if(!t.device.hostApp||!n)return;let r=await R({command:`close`,device:t.device,use:We,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice,platformServices:e.platformServices});if(r.type===`response`)return r.response;await r.runtime.operations.resolveOpenTarget({target:n,surface:`app`,foreground:!1})}async function Ba(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:o,leaseLifecycleProvider:s}=e,c=i.lookup(n);if(!c)return await Wa({req:t,sessionName:n,logPath:r,env:e.host.env,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});let l=i.requireCurrent(c);Ra(t,l);let u=t.positionals?.[0],f=await za({session:l,app:u,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice,platformServices:e.platformServices});if(f)return f;if(t.internal?.closeAppOnly===!0&&!u)return d(`INVALID_ARGS`,`App-only close requires an app target`);if(!e.platformResourceCleanup)throw new a(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let p=e.platformResourceCleanup,m=await ka({device:l.device,clearRuntimeHints:t.internal?.closeAppOnly!==!0&&!!l.appBundleId&&Yn(i.getRuntimeHints(n)),inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(m.type===`response`)return m.response;if(l=i.requireCurrent(c),I(l),t.internal?.closeAppOnly===!0&&u)return await Ua({req:t,session:l,logPath:r,lifecycle:m.runtime,app:u});let h=await Fa({req:t,ref:c,logPath:r,sessionStore:i,lifecycle:m.runtime});if(`response`in h)return h.response;let g=await Va({env:e.host.env,req:t,ref:c,logPath:r,sessionStore:i,leaseRegistry:o,leaseLifecycleProvider:s,lifecycle:m.runtime,clearRuntimeHints:m.clearRuntimeHints,repairArmed:h.repairArmed,platformResourceCleanup:p});return g.kind===`response`?g.response:Ha({session:l,repair:h,requestedSaveScript:!!t.flags?.saveScript,shutdownResult:g.shutdownResult,providerData:g.providerData})}async function Va(e){let{req:t,ref:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o,lifecycle:s,clearRuntimeHints:c}=e,{address:l}=n,u=[],{platformCloseError:d,saveScriptError:f,shutdownResult:p}=await Aa({req:t,ref:n,logPath:r,sessionStore:i,lifecycle:s,clearRuntimeHints:c,cleanupFailures:u,repairArmed:e.repairArmed,dispatchTargetedPlatformClose:La,finalizeOrdinaryCloseScript:Da,platformResourceCleanup:e.platformResourceCleanup}),m=i.requireCurrent(n),h=await Ia({req:t,session:m,leaseRegistry:a,leaseLifecycleProvider:o});if(h.response)return{kind:`response`,response:h.response};m=i.resolveCurrent(n)??m;let g=Ma(l,u),_=d??g;if(_?m.deviceClaim&&D({level:`warn`,phase:`device_claim_close_effects_unconfirmed`,data:{deviceKey:m.deviceClaim.deviceKey,session:l}}):await Pn(m.deviceClaim,e.env),i.retire(n),_)throw _;if(f)throw f;return{kind:`closed`,providerData:h.providerData,shutdownResult:p}}function Ha(e){let{session:t,repair:n,requestedSaveScript:r,shutdownResult:i,providerData:a}=e;if(n.aborted&&r)return{ok:!1,error:{code:`COMMAND_FAILED`,message:`The repair was aborted and no script was written.`,hint:`Recovery: replay --from <n> --plan-digest <digest> before closing.`,details:{session:t.name}}};let o=n.healedScriptPath?{savedScript:n.healedScriptPath}:{},s=a?{provider:a}:{},c=`Closed: ${t.name}`;return i?{ok:!0,data:N({session:t.name,shutdown:i,...o,...s},c)}:{ok:!0,data:{session:t.name,...P(c),...o,...s}}}async function Ua(e){let{req:t,session:n,logPath:r,lifecycle:i,app:a}=e,o=await La({req:t,session:n,logPath:r,lifecycle:i});if(o)throw o;return{ok:!0,data:{app:a,...P(`Closed: ${a}`)}}}async function Wa(e){let{req:t,sessionName:n,logPath:r,env:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,{requireNamedSessionHoldsDevice:c}=await import(`./explicit-session-resolution.js`);if(c({req:t,sessionAddress:n,session:void 0}),!t.positionals||t.positionals.length===0)return d(`SESSION_NOT_FOUND`,`No active session`);let l=await ka({device:await U({session:void 0,flags:t.flags,env:i,platformServices:s}),clearRuntimeHints:!1,inspectFacts:a,bindDevice:o,platformServices:s});return l.type===`response`?l.response:(await l.runtime.operations.closeApplication({positionals:t.positionals,outPath:t.flags?.out,surface:`app`,ensureReady:!0,...t.internal?.killApp===!0?{mode:`kill`}:{},execution:Rr(t,r)}),{ok:!0,data:{app:t.positionals[0],...P(`Closed: ${t.positionals[0]}`)}})}function Ga(e,t){return e.operations.ensureReady(t)}function Ka(e,t,n){return e.operations.listApps({device:t,filter:n})}async function qa(e){let{req:t,sessionName:n,sessionStore:r}=e;switch(t.command){case`session_list`:return Ja(t,r);case`devices`:return await Xa(t,e.host.env);case`capabilities`:return await io({req:t,sessionName:n,sessionStore:r,inspectFacts:e.inspectFacts,platformServices:e.platformServices});case`apps`:return await co({env:e.host.env,req:t,sessionName:n,sessionStore:r,bindDevice:e.bindDevice,platformServices:e.platformServices,inspectFacts:e.inspectFacts,providerAppCatalog:e.providerAppCatalog});default:return null}}function Ja(e,t){let n=Kt(e);return{ok:!0,data:{sessions:t.listRefs().filter(e=>Gt(e.session,n)).map(e=>Ya(e,t))}}}function Ya({address:e,session:t},n){let r=n.resolveSessionDir(e);return{name:t.name,address:e,sessionStateDir:r,runnerLogPath:nn(r),platform:k(t.device),...j(t.device.platform)&&t.device.appleOs?{appleOs:t.device.appleOs}:{},target:t.device.target??`mobile`,surface:t.surface??`app`,device:t.device.name,id:t.device.id,device_id:t.device.id,createdAt:t.createdAt,...j(t.device.platform)&&!A(t.device)&&{device_udid:t.device.id,ios_simulator_device_set:t.device.simulatorSetPath??null}}}async function Xa(e,t){try{let n=Za(t);return{ok:!0,data:{devices:(await $a(e,t)).map(e=>({...go(e),...Qa(e,n)}))}}}catch(e){let t=s(e);return{ok:!1,error:{code:t.code,message:t.message,...t.details?{details:t.details}:{}}}}}function Za(e){let t=new Map;for(let n of In({},e)){let e=n.claim;!e||Nn(n.classification)||t.set(e.deviceKey,{session:e.session,workspace:e.workspace})}return t}function Qa(e,t){let n=Mn(e),r=Fn({...n,id:be(e.id)}),i=t.get(Fn(n))??[...t].find(([e])=>e.startsWith(r))?.[1];return i?{claimedBy:i}:{}}async function $a(e,t){let n=e.flags?.platform;return ro(await er(eo(e,n,t)),e.flags?.platform,e.flags?.target)}function eo(e,t,n){let r=e.flags;return{platform:t,target:r?.target,deviceName:r?.device,udid:r?.udid,serial:r?.serial,iosSimulatorSetPath:to(r?.iosSimulatorDeviceSet,t,r?.target,n),androidSerialAllowlist:no(r?.androidDeviceAllowlist,n)}}function to(e,t,n,r){return xe({requestedSetPath:e,platform:t,target:n,env:r})}function no(e,t){let n=L(e,t);return n?Array.from(n).sort():void 0}function ro(e,t,n){let r=t?e.filter(e=>_o(e,t)):e;return n?r.filter(e=>(e.target??`mobile`)===n):r}async function io(e){let t=await ho({...e,androidAvdSelection:`include-stopped`});if(`response`in t)return t.response;let{device:n}=t,r=ao(n,e.sessionStore.get(e.sessionName),e.req.flags),i=await fo(n,e.inspectFacts);return{ok:!0,data:{device:go(n),...n.platform===`android`&&zr(`press`,i)?{targetReadiness:{press:`bounded-geometry`}}:{},availableCommands:at().filter(e=>e===`appstate`&&r?!0:zr(e,i))}}}function ao(e,t,n){return!t||!O(e)&&!A(e)||!Pr(n,t)?!1:oo(t)||so(e,t)}function oo(e){return!!(e.appName||e.appBundleId)}function so(e,t){return!!(A(e)&&t.surface!==void 0&&t.surface!==`app`&&t.surface!==`frontmost-app`)}async function co(e){let{req:t,sessionName:n,sessionStore:r,bindDevice:i,inspectFacts:a,platformServices:o}=e,s=await lo(t,e.providerAppCatalog);if(s)return s;let c=await ho({req:t,sessionName:n,sessionStore:r,androidAvdSelection:`include-stopped`,platformServices:o});if(`response`in c)return c.response;let{device:l}=c,u=$t(t.flags?.appsFilter),d=L(t.flags?.androidDeviceAllowlist,e.env),f=await po({device:l,inspectFacts:a,bindDevice:i,platformServices:o});if(`response`in f)return f.response;let p=f.runtime;return mo(await Ka(p,await Ga(p,{serial:t.flags?.serial,androidSerialAllowlist:d?[...d].sort():void 0}),u))}async function lo(e,t){let n=uo(e);if(!(!t||!n||!t.supports(n.provider)))return{ok:!0,data:{apps:[...await t.list(n,Rn(e.meta?.requestId))]}}}function uo(e){let t=Un(e);if(t.leaseId)return;let n=t.leaseProvider;if(!n)return;let r=e.flags?.platform;if(r===`android`||r===`ios`)return{provider:n,platform:r,...e.internal?.publicNetworkOnly?{publicNetworkOnly:!0}:{}}}async function fo(e,t){if(t)try{return await t(e)}catch{return}}async function po(e){let t=await V(e.inspectFacts)(e.device),n=[t.operations.ensureReady,t.operations.listApps].find(e=>!e.available);return n&&!n.available?{response:_r(`apps`,n)}:{runtime:await B(e.bindDevice)(e.device,Ze)}}function mo(e){return{ok:!0,data:{apps:e.map(e=>e.name&&e.name!==e.id?`${e.name} (${e.id})`:e.id)}}}async function ho(e){let{req:t,sessionName:n,sessionStore:r,androidAvdSelection:i,platformServices:a}=e,o=r.get(n),s=t.flags??{},c=H(t.command,o,s);return c?{response:c}:{device:await U({session:o,flags:s,env:r.host.env,platformServices:a,androidAvdSelection:i})}}function go({simulatorSetPath:e,iosPhysicalDeviceBackend:t,appleOs:n,...r}){return{...r,platform:k({platform:r.platform,appleOs:n}),...j(r.platform)&&n?{appleOs:n}:{}}}function _o(e,t){return ye(e,t)}function vo(e,t){return{ok:!0,data:{platform:k(e),target:e.target??`mobile`,device:e.name,id:e.id,kind:e.kind,...t,...j(e.platform)&&e.appleOs?{appleOs:e.appleOs}:{}}}}function yo(e){return t=>d(e?`INVALID_ARGS`:`UNSUPPORTED_OPERATION`,e?`boot --headless is supported only for Android emulators.`:`boot is not supported on this device`,void 0,t.hint?{hint:t.hint}:void 0)}function bo(e,t){return!!(e?.trim()||t?.platform===`android`&&t.kind===`emulator`)}async function xo(e,t){let{sessionName:n,sessionStore:r,req:i,platformServices:a}=e,o=r.get(n),c=i.flags??{};try{let e=await Fr({session:o,flags:c,env:r.host.env,platformServices:a});return c.target&&(e.target??`mobile`)!==c.target?{refusal:d(`DEVICE_NOT_FOUND`,`No ${e.platform} device found matching --target ${c.target}.`)}:e}catch(e){if(t&&!bo(c.device,o?.device)&&s(e).code===`DEVICE_NOT_FOUND`)return{refusal:d(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`)};throw e}}async function So(e){let t=e.req.flags??{},n=H(e.req.command,e.sessionStore.get(e.sessionName),t);if(n)return n;let r=L(t.androidDeviceAllowlist,e.host.env),i=r?[...r].sort():void 0,a=Ge({headless:t.headless===!0}),o=await xo(e,a.kind===`boot-target-headless`);if(`refusal`in o)return o.refusal;let s=await vr({command:`boot`,device:o,required:a.use.required,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,unavailableResponse:yo(a.kind===`boot-target-headless`)});if(s.type===`response`)return s.response;let c={serial:t.serial,androidSerialAllowlist:i,deadlineAtMs:Br(t.timeoutMs)};return vo(a.kind===`boot-target-headless`?await(await s.bind(o,a.use)).operations.bootTargetHeadless(c):await(await s.bind(o,a.use)).operations.bootTarget(c),{booted:!0})}function Co(e){return e.available?null:d(`UNSUPPORTED_OPERATION`,`shutdown is supported only for Apple simulators and Android emulators.`,void 0,e.hint?{hint:e.hint}:void 0)}function wo(e){let t=e.error?.message??e.stderr.trim();return t.length>0?t:`Shutdown failed`}async function To(e){let t=e.sessionStore.get(e.sessionName),n=e.req.flags??{},r=H(e.req.command,t,n);if(r)return r;let i=await Fr({flags:n,session:t,env:e.sessionStore.host.env,platformServices:e.platformServices}),a=Co((await V(e.inspectFacts)(i)).operations.shutdownTarget);if(a)return a;if(t&&t.device.platform===i.platform&&t.device.id===i.id)return d(`DEVICE_IN_USE`,`Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.`,{hint:`Run agent-device close --shutdown --session ${e.sessionName}`,session:e.sessionName,platform:k(i),target:i.target??`mobile`,device:i.name,id:i.id,kind:i.kind});let o=await(await B(e.bindDevice)(i,et)).operations.shutdownTarget();return o.success?vo(i,{shutdown:o}):d(o.error?.code??`COMMAND_FAILED`,wo(o),{platform:k(i),target:i.target??`mobile`,device:i.name,id:i.id,kind:i.kind,shutdown:o})}function Eo(t,n){return j(n)?d(`SESSION_NOT_FOUND`,`No active session "${t}". Run open with --session ${t} first.`,e(t)):d(`SESSION_NOT_FOUND`,`No active session "${t}". Run open with --session ${t} first, or omit --session to query by device selector.`,e(t))}function Do(e){return d(`SESSION_NOT_FOUND`,e===`macos`?`macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").`:`iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).`)}async function Oo(e,t){if(!t.appBundleId)return;let n=await R({command:`appstate`,device:t.device,use:tt,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(n.type!==`response`)try{return(await n.runtime.operations.appState({appBundleId:t.appBundleId})).applicationState}catch(e){if(i(e))throw e;D({level:`warn`,phase:`apple_appstate_runner_read_failed`,data:{code:s(e).code,message:s(e).message}});return}}function ko(e){if(!(!A(e.device)||!e.surface)&&e.surface!==`app`&&e.surface!==`frontmost-app`)return{ok:!0,data:{platform:k(e.device),appName:e.surface,appBundleId:e.appBundleId,source:`session`,surface:e.surface}}}async function Ao(e,t){if(!t.appName&&!t.appBundleId){let e=ko(t);if(e)return e;let n=A(t.device)?`macOS`:`iOS`;return d(`COMMAND_FAILED`,`No foreground app is tracked for this ${n} session. Open an app in the session, then retry appstate.`)}let n=await Oo(e,t),r=t.appName??t.appBundleId;return{ok:!0,data:{platform:k(t.device),appName:r??`unknown`,appBundleId:t.appBundleId,source:n?`runner`:`session`,...n?{state:n}:{},surface:t.surface??`app`,...O(t.device)?{device_udid:t.device.id,ios_simulator_device_set:t.device.simulatorSetPath??null}:{}}}}function jo(e,t){let n=L(e,t);return n?[...n].sort():void 0}async function Mo(e,t,n){if(O(t)||A(t))return n?Eo(e.sessionName,t.platform):Do(A(t)?`macos`:`ios`);let r=e.req.flags??{},i=await R({command:`appstate`,device:t,use:tt,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(i.type===`response`)return i.response;let a=i.runtime;await a.operations.ensureReady({serial:r.serial,androidSerialAllowlist:jo(r.androidDeviceAllowlist,e.host.env)});let o=await a.operations.appState();return{ok:!0,data:{platform:k(t),package:o.package,activity:o.activity}}}function No(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),a=t.flags??{},o=a.platform;if(!i&&c(t)&&(!Ut(a)||j(o)))return{refusal:Eo(n,o)};let s=H(`appstate`,i,a);if(s)return{refusal:s};let l=j(i?.device.platform)&&Pr(a,i);return o===`ios`&&!l?{refusal:Do(`ios`)}:o===`macos`&&!l?{refusal:Do(`macos`)}:l&&i?{answeredBy:`apple-session`,session:i}:{answeredBy:`device-runtime`,session:i,namedSessionMissing:!i&&c(t)}}async function Po(e){let t=No(e);return`refusal`in t?t.refusal:t.answeredBy===`apple-session`?await Ao(e,t.session):await Mo(e,await U({session:t.session,flags:e.req.flags??{},env:e.sessionStore.host.env,platformServices:e.platformServices}),t.namedSessionMissing)}function Fo(e){return mn.createNextFence({admissionLedger:e.ledger,resourcePath:e.resourcePath,device:e.device})}async function Io(e){try{return await Lo(e)}catch(e){return{ok:!1,error:f(e)}}}async function Lo(e){let t=Ro(e);if(!t.ok)return t;let n=t.ref,r=e.sessionStore.requireCurrent(n),i=De(e.req.positionals),a=await e.inspectFacts(r.device),o=a.operations.audioProbeStart,s=a.operations.audioProbeQuery,c=o.available?`capture`:s.available?`query`:void 0;if(c===void 0)return zo(o,s);let l=Ae({probeAction:i.probeAction,mode:c});switch(l.kind){case`query`:return{ok:!0,data:await(await e.bindDevice(r.device,l.use)).operations.audioProbeQuery({action:l.action,durationMs:i.durationMs,bucketMs:i.bucketMs})};case`capture-start`:return await Bo(e,n,i,l.use);case`capture-status`:return await Vo(e,n);case`capture-stop`:return await Ho(e,n)}}function Ro(e){let t=e.sessionStore.lookup(e.sessionName);return t?{ok:!0,ref:t}:d(`SESSION_NOT_FOUND`,`audio requires an active session`)}function zo(e,t){let n=(e.available?void 0:e.hint)??(t.available?void 0:t.hint),r=e.available?void 0:e.reason;return d(`UNSUPPORTED_OPERATION`,n??`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`,r?{reason:r}:void 0)}async function Bo(e,t,n,r){let i=e.sessionStore.requireCurrent(t),a=gr(e.sessionStore,t);i.audioProbe&&(await gn({intent:`disposal`,binding:a}),i=e.sessionStore.requireCurrent(t));let o=await e.bindDevice(i.device,r),s=dn.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),c=dn.createNextFence({admissionLedger:e.audioProbeAdmissionLedger,resourcePath:s,device:i.device}),l=G.join(e.sessionStore.ensureSessionDir(e.sessionName),`audio-probe.json`);a.assertAdoptable();let u=await o.operations.audioProbeStart({sessionId:e.sessionName,statusPath:l,durationMs:n.durationMs,bucketMs:n.bucketMs,fence:c});await un({admissionLedger:e.audioProbeAdmissionLedger,binding:a,device:i.device,owner:o.owner,fence:c,...u,throwIfCanceled:e.throwIfCanceled});let d=a.read();if(!d)throw TypeError(`Audio probe adoption did not publish a live handle`);return{ok:!0,data:await d.handle.status()}}async function Vo(e,t){let n=gr(e.sessionStore,t),r=n.read();if(!r)return{ok:!0,data:Uo()};let i=await r.handle.status();return i.state===`stopped`&&await gn({intent:`disposal`,binding:n}),{ok:!0,data:i}}async function Ho(e,t){let n=gr(e.sessionStore,t);return n.read()?{ok:!0,data:await gn({intent:`capture`,binding:n})}:{ok:!0,data:Uo()}}function Uo(){return Vr({state:`stopped`,source:`system-audio`,backend:`host-system-audio`,durationMs:0,bucketMs:0,sourceCount:0,reason:`not-started`,notes:[`No active host audio probe is running.`]})}async function Wo(e){let t=e.sessionStore.lookup(e.sessionName);if(!t)return d(`SESSION_NOT_FOUND`,`perf requires an active session. Run open first.`);let n=e.sessionStore.requireCurrent(t),r={...e,ref:t};try{if(Xt(e.req.positionals?.[0]))throw new a(`INVALID_ARGS`,Zt);us(e.req);let t=pn({positionals:e.req.positionals,kind:fs(e.req.flags?.kind),outPath:fs(e.req.flags?.out)}),i=vn(t);if(i.kind===`capture-stop`)return Go(r,await Yo(r,n,i.request));let o=await wr({device:n.device,plan:i,inspectFacts:e.inspectFacts});return o.admitted?Go(r,await Ko(r,n,o)):z(`perf`,o.fact)??d(`UNSUPPORTED_OPERATION`,`perf is not supported on this device`)}catch(e){return{ok:!1,error:f(e)}}}function Go(e,t){return t.ok&&M(e.sessionStore,e.ref,e.req,`perf`,b(t.data)?{...t.data}:{}),t}async function Ko(e,t,n){let{device:r,plan:i}=Cr(n),o=B(e.bindDevice);switch(i.kind){case`frames`:return{ok:!0,data:ts(t,await(await o(r,i.use)).operations.perfFrames({appId:t.appBundleId}))};case`memory-sample`:return{ok:!0,data:os(t,await(await o(r,i.use)).operations.perfMemorySample({appId:t.appBundleId}))};case`memory-snapshot`:return{ok:!0,data:ss(t,await(await o(r,i.use)).operations.perfMemorySnapshot({appId:t.appBundleId,kind:i.request.kind,outPath:i.request.outPath?F(i.request.outPath,e.req.meta?.cwd??e.host.cwd):void 0,artifactsDir:G.join(e.sessionStore.ensureSessionDir(e.sessionName),`artifacts`)}))};case`capture-start`:return await qo(e,t,await o(r,i.use),i.request);case`profile-report`:{let n=await o(r,i.use),s=t.lastPerfProfile,c=i.request.tracePath??s?.outPath;if(!c)throw new a(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace or tracePath option`);if(t.perfCapture)throw new a(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace; stop the active capture first.`);let l=ls(e,i.request.outPath,`cpu-report.json`);return{ok:!0,data:{perf:`reported`,...await n.operations.perfProfileReport({appId:t.appBundleId,kind:i.request.kind,tracePath:F(c,e.req.meta?.cwd??e.host.cwd),outPath:l,template:i.request.template??(s?.kind===`xctrace`?s.template:void 0),profile:s})}}}}}async function qo(e,t,n,r){if(t.perfCapture)return d(`INVALID_ARGS`,`native perf capture already in progress`);if(!t.appBundleId)return d(`COMMAND_FAILED`,`No app is associated with this session.`,{hint:`Run open <app> first so perf can resolve the app process identity.`});let i=r.kind===`xctrace`?`perf-${r.area===`cpu`?`cpu-profile`:`trace`}.trace`:r.kind===`perfetto`?`app.perfetto-trace`:`cpu.perf.data`,a=ls(e,r.outPath,i),o=ln.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),s=ln.createNextFence({admissionLedger:Jo(e),resourcePath:o,device:t.device}),c=hr(e.sessionStore,e.ref);c.assertAdoptable();let l=await n.operations.perfNativeCaptureStart({sessionId:e.sessionName,appId:t.appBundleId,mode:r.area===`cpu`?`cpu-profile`:`trace`,kind:r.kind,template:r.template,outPath:a,fence:s});return await hn({admissionLedger:Jo(e),binding:c,device:t.device,owner:n.owner,fence:s,pendingHandle:l.pendingHandle,envelope:l.envelope,throwIfCanceled:e.throwIfCanceled}),{ok:!0,data:l.response}}function Jo(e){if(e.perfCaptureAdmissionLedger)return e.perfCaptureAdmissionLedger;throw new a(`COMMAND_FAILED`,`Perf capture admission ledger is not configured`,{reason:`runtime-gateway-missing`})}async function Yo(e,t,n){let r=t.perfCapture;if(!r)return d(`INVALID_ARGS`,`no active native perf capture`);let i=es(r.handle.inspect(),n);if(i)return d(`INVALID_ARGS`,i);n.outPath&&r.handle.setOutputPath(F(n.outPath,e.req.meta?.cwd??e.host.cwd));let a=await _n({intent:`capture`,binding:hr(e.sessionStore,e.ref)});if(n.area===`cpu`){let t=Xo(a);e.sessionStore.update(e.ref,{lastPerfProfile:t})}return{ok:!0,data:a}}function Xo(e){if(Zo(e)||Qo(e))return e;throw new a(`COMMAND_FAILED`,`Stopped CPU profile metadata is malformed.`)}function Zo(e){return e.kind===`xctrace`&&e.mode===`cpu-profile`&&typeof e.outPath==`string`&&typeof e.template==`string`}function Qo(e){return e.kind===`simpleperf`&&e.mode===`cpu-profile`&&$o(e,[`outPath`,`packageName`,`appPid`,`profilerPid`,`remotePath`])}function $o(e,t){return t.every(t=>typeof e[t]==`string`)}function es(e,t){let n=t.area===`cpu`?`cpu-profile`:`trace`;if(e.kind!==t.kind||e.mode!==n)return`No ${t.kind} ${n} is active for this session.`}function ts(e,t){return{...cs(e),metrics:{fps:ns(t.metric,e)},sampling:{fps:t.sampling}}}function ns(e,t){if(!b(e)||e.available!==!0)return e;let n=rs(t.actions,e);return n.length===0?e:{...e,relatedActions:n}}function rs(e,t){let n=is(t.windowStartedAt),r=is(t.windowEndedAt)??is(t.measuredAt);return n===void 0||r===void 0?[]:e.filter(({ts:e})=>e>=n&&e<=r).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:as(e)})).slice(-12)}function is(e){if(typeof e!=`string`)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function as(e){for(let t of[`refLabel`,`ref`,`appName`,`appBundleId`]){let n=e.result?.[t];if(typeof n==`string`&&n.length>0)return n}}function os(e,t){return{...cs(e),metrics:{memory:t.metric},sampling:{memory:t.sampling}}}function ss(e,t){return{...cs(e),artifact:t.artifact,sampling:{snapshot:t.sampling},support:t.support}}function cs(e){return{session:e.name,platform:k(e.device),device:e.device.name,deviceId:e.device.id}}function ls(e,t,n){return t?F(t,e.req.meta?.cwd??e.host.cwd):G.join(e.sessionStore.ensureSessionDir(e.sessionName),`${ds()}-${n}`)}function us(e){let t=e.positionals?.[0]?.toLowerCase(),n=e.positionals?.[1]?.toLowerCase();if(e.flags?.out&&t!==`cpu`&&t!==`trace`&&(t!==`memory`||n!==`snapshot`))throw new a(`INVALID_ARGS`,`--out is only supported with perf memory snapshot, perf cpu profile, or perf trace`)}function ds(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}function fs(e){return typeof e==`string`&&e.length>0?e:void 0}const ps=[`dump`,`log`],ms=`network requires ${ps.join(` or `)}`,hs=`network include mode must be one of: ${l.join(`, `)}`,gs=2048;async function _s(e){let t=e.sessionStore.get(e.sessionName);if(!t)return d(`SESSION_NOT_FOUND`,`network requires an active session`);try{let n=vs(e.bindDevice),r=(await n(t.device,Pe)).facts.networkDump;if(!r.available)return _r(`network`,r);let i=ys(e.req);if(!i.ok)return i;let a=Ie({action:i.action,include:i.include}),o=await n(t.device,a.use),s=t.appLog?.handle.inspect();return Cs(await o.operations.networkDump({sessionId:e.sessionName,appBundleId:t.appBundleId,...s?{appLogSnapshot:{state:s.state,startedAt:s.startedAt}}:{},maxEntries:i.maxEntries,include:a.include,maxPayloadChars:gs,maxScanLines:4e3}),i,!!t.appLog,s?.state)}catch(e){return{ok:!1,error:f(e)}}}function vs(e){if(e)return e;throw new a(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`})}function ys(e){let t=bs(e);if(!t.ok)return t;let n=xs(e);if(!n.ok)return n;let r=Ss(e);return r.ok?{ok:!0,action:t.action,include:r.include,maxEntries:n.maxEntries}:r}function bs(e){let t=(e.positionals?.[0]??`dump`).toLowerCase();return ps.includes(t)?{ok:!0,action:t}:d(`INVALID_ARGS`,ms)}function xs(e){let t=e.positionals?.[1]?Number.parseInt(e.positionals[1],10):25;return!Number.isInteger(t)||t<1||t>200?d(`INVALID_ARGS`,`network dump limit must be an integer in range 1..200`):{ok:!0,maxEntries:t}}function Ss(e){let t=e.positionals?.[2]?.toLowerCase(),n=e.flags?.networkInclude;if(t&&n&&t!==n)return d(`INVALID_ARGS`,`network include mode was provided both positionally and via --include with different values`);let r=(n??t??`summary`).toLowerCase();return l.includes(r)?{ok:!0,include:r}:d(`INVALID_ARGS`,hs)}function Cs(e,t,n,r){return e.source===`app-log`?{ok:!0,data:{...e.dump,active:n,state:r??`inactive`,backend:e.backend,notes:e.notes}}:{ok:!0,data:{entries:e.entries,active:!0,state:`active`,backend:e.backend,include:t.include,matchedLines:e.entries.length,scannedLines:e.entries.length,limits:{maxEntries:t.maxEntries,maxPayloadChars:gs,maxScanLines:e.entries.length},notes:e.notes}}}function ws(e,t){let n=Ar(e);return{...n,backend:n.backend??t,notes:n.state===`failed`&&e.appLogFailure?[Ts(e.appLogFailure)]:Es(n.state)}}function Ts(e){return e.hint?`${e.message} ${e.hint}`:e.message}function Es(e){return e===`failed`?[`The app log stream process exited with an error. Run logs doctor for backend diagnostics.`]:e===`ended`?[`The app log stream process ended. Run logs clear --restart before the next capture window.`]:void 0}function Ds(e,t){return Te([...e,...t.notes??[]])}async function Os(e){let{req:t}=e;return t.command===`perf`?await Wo({...e,throwIfCanceled:e.throwIfCanceled??(()=>{})}):t.command===`logs`?As(e):t.command===`events`?await ks(e):t.command===`network`?await _s(e):t.command===`audio`?await Io(Hs(e)):null}async function ks(e){let{req:t,sessionName:n,sessionStore:r}=e;try{return await r.flushEvents(n),{ok:!0,data:r.readEvents(n,{limit:t.positionals?.[0],cursor:t.positionals?.[1]})}}catch(e){return{ok:!1,error:f(e)}}}async function As(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n);if(!i)return d(`SESSION_NOT_FOUND`,`logs requires an active session`);try{let n=r.requireCurrent(i),a=Us({...e,session:n,ref:i}),o=(await a.bindDevice(n.device,Me)).facts.appLogInspect;if(!o.available)return _r(`logs`,o);let s=Ns(ze({action:t.positionals?.[0],restart:!!t.flags?.restart,marker:t.positionals?.slice(1).join(` `)}),n);return`ok`in s?s:await js(a,s)}catch(e){return{ok:!1,error:f(e)}}}async function js(e,t){switch(t.kind){case`path`:return Ps(e,(await(await e.bindDevice(e.session.device,t.use)).operations.appLogInspect()).backend);case`doctor`:return Fs(e,await(await e.bindDevice(e.session.device,t.use)).operations.appLogDoctor({appBundleId:e.session.appBundleId}));case`start`:case`clear-restart`:return await Ms(e,t);case`stop`:return await e.bindDevice(e.session.device,t.use),await Bs(e);case`mark`:return await e.bindDevice(e.session.device,t.use),Is(t.marker,e.sessionName,e.sessionStore,e.host.env);case`clear`:return await e.bindDevice(e.session.device,t.use),Ls(e)}}async function Ms(e,t){let n=await e.bindDevice(e.session.device,t.use);return t.kind===`start`?await zs(e,t.appBundleId,n.owner,n.operations.appLogStart):await Rs(e,t.appBundleId,n.owner,n.operations.appLogStart)}function Ns(e,t){return e.requiresAppSession?t.appBundleId?Object.freeze({...e,appBundleId:t.appBundleId}):d(`INVALID_ARGS`,`logs ${e.kind===`start`?`start`:`clear --restart`} requires an app session; run open <app> first`):e}function Ps(e,t){let{session:n,sessionName:r,sessionStore:i}=e,a=i.resolveAppLogPath(r),o=kr(a),s=ws(n,t);return{ok:!0,data:{path:a,active:s.active,state:s.state,backend:s.backend,sizeBytes:o.sizeBytes,modifiedAt:o.modifiedAt,startedAt:s.startedAt?new Date(s.startedAt).toISOString():void 0,failureCode:s.failureCode,failureMessage:s.failureMessage,hint:s.hint??String.raw`Grep the file for token-efficient debugging, e.g. grep -n "Error\|Exception" <path>`,notes:s.notes}}}async function Fs(e,t){let{session:n,sessionName:r,sessionStore:i}=e,a=i.resolveAppLogPath(r),o=ws(n,t.backend);return{ok:!0,data:{path:a,active:o.active,state:o.state,backend:o.backend,checks:t.checks,failureCode:o.failureCode,failureMessage:o.failureMessage,hint:o.hint,notes:Ds(t.notes,o)}}}function Is(e,t,n,r){let i=n.resolveAppLogPath(t);return Dr(i,e,r),{ok:!0,data:{path:i,marked:!0}}}function Ls(e){return{ok:!0,data:Or(e)}}async function Rs(e,t,n,r){let{session:i,sessionStore:a}=e;i.appLog&&await Er({intent:`disposal`,ref:e.ref,sessionStore:a});let o=Or(e),s=await Vs(e,t,r,n);return s.ok?{ok:!0,data:{...o,restarted:!0}}:s}async function zs(e,t,n,r){let{session:i}=e;return i.appLog?d(`INVALID_ARGS`,`app log already streaming; run logs stop first`):await Vs(e,t,r,n)}async function Bs(e){let{session:t,sessionName:n,sessionStore:r}=e;if(!t.appLog)return d(`INVALID_ARGS`,`no app log stream active`);let i=r.resolveAppLogPath(n);return await Er({intent:`capture`,ref:e.ref,sessionStore:r}),{ok:!0,data:{path:i,stopped:!0}}}async function Vs(e,t,n,r){let{session:i,sessionName:a,sessionStore:o}=e,s=o.resolveAppLogPath(a),c=fn.resolvePath(o.resolveSessionDir(a));try{let l=Fo({ledger:e.appLogAdmissionLedger,resourcePath:c,device:i.device});jr(o,e.ref).assertAdoptable();let u=await n({sessionId:a,appBundleId:t,outputPath:s,pidPath:o.resolveAppLogPidPath(a),fence:l});return await Nr({admissionLedger:e.appLogAdmissionLedger,ref:e.ref,sessionStore:o,device:i.device,owner:r,fence:l,pendingHandle:u.pendingHandle,envelope:u.envelope,throwIfCanceled:e.throwIfCanceled??(()=>{})}),{ok:!0,data:{path:s,started:!0}}}catch(t){return{ok:!1,error:Mr({ref:e.ref,sessionStore:o,error:t})}}}function Hs(e){if(!e.bindDevice||!e.inspectFacts)throw new a(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`});if(!e.audioProbeAdmissionLedger)throw new a(`COMMAND_FAILED`,`Audio probe admission ledger is not configured`,{reason:`runtime-gateway-missing`});return{req:e.req,sessionName:e.sessionName,sessionStore:e.sessionStore,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,audioProbeAdmissionLedger:e.audioProbeAdmissionLedger,throwIfCanceled:e.throwIfCanceled??(()=>{})}}function Us(e){if(!e.bindDevice)throw new a(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`});if(!e.appLogAdmissionLedger)throw new a(`COMMAND_FAILED`,`App-log admission ledger is not configured`,{reason:`runtime-gateway-missing`});return{...e,bindDevice:e.bindDevice,platformServices:e.platformServices,appLogAdmissionLedger:e.appLogAdmissionLedger}}const Ws=new WeakMap;function Gs(e){return{store:t=>Ks(e,t),finalize:(t,n)=>qs({...e,evidence:t,projection:n})}}function Ks(e,t){let{sessionStore:n,ref:r}=e;if(!r)throw Error(`Internal observation session is no longer available.`);let i=n.requireCurrent(r);br(i,t);let a=i.snapshotGeneration;if(a===void 0)throw Error(`Internal observation did not establish a snapshot generation.`);let o={};return Ws.set(o,{ref:r,snapshot:t,snapshotGeneration:a,runtimeRevision:jn(i),refFrame:On(i)}),{evidence:o,refsGeneration:a}}function qs(e){let t=Ws.get(e.evidence);Ws.delete(e.evidence);let n=Ys(e.projection.refs);if(n.size===0)return{published:!1,reason:`empty`};if(e.signal?.aborted===!0)return{published:!1,reason:`cancelled`};let r=t&&Js(e,t);return!t||!r?{published:!1,reason:`stale-capture`}:e.projection.refsGeneration!==t.snapshotGeneration||!Xs(n,t.snapshot)?{published:!1,reason:`invalid-projection`}:(yr(r,n),{published:!0,refsGeneration:t.snapshotGeneration,refCount:n.size})}function Js(e,t){if(!e.ref||e.ref.lifetime!==t.ref.lifetime)return;let n=e.sessionStore.resolveCurrent(e.ref);return n&&n.snapshot===t.snapshot&&n.snapshotGeneration===t.snapshotGeneration&&jn(n)===t.runtimeRevision&&On(n)===t.refFrame?n:void 0}function Ys(e){let t=new Set;for(let n of e){let e=n.startsWith(`@`)?n.slice(1):n,r=e.indexOf(`~`),i=r===-1?e:e.slice(0,r);i.length>0&&t.add(i)}return t}function Xs(e,t){let n=new Set(t.nodes.flatMap(e=>typeof e.ref==`string`?[e.ref]:[]));return[...e].every(e=>n.has(e))}function Zs(e){let t=Qs(e),n=He(t);return ci(`sha256`).update(n,`utf8`).digest(`hex`)}function Qs(e){let{actions:t,actionLines:n,actionSourcePaths:r,metadata:i}=e;return{platform:i.platform??null,target:i.target??null,steps:t.map((e,t)=>$s(e,n[t]??null,r?.[t]??null))}}function $s(e,t,n){return{command:e.command,positionals:e.positionals??[],flags:e.flags??{},runtime:e.runtime??null,targetEvidence:e.targetEvidence??null,targetEvidences:e.targetEvidences??null,source:{path:n,line:t}}}function ec(e,t,n){let{from:r,digest:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e;if(r===void 0&&i===void 0)return{ok:!0,value:0};if(r===void 0||i===void 0)return{ok:!1,message:`replay --from requires --plan-digest (and --plan-digest requires --from).`};let s=tc({from:r,digest:i,planDigest:n,actionCount:t,pendingRecordAndHeal:a,sessionActionsLength:o});return s?{ok:!1,message:s}:{ok:!0,value:r-1}}function tc(e){let{from:t,digest:n,planDigest:r,actionCount:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e,s=[()=>nc({from:t,actionCount:i,pendingRecordAndHeal:a}),()=>rc({from:t,pendingRecordAndHeal:a,sessionActionsLength:o}),()=>ic(n,r)];for(let e of s){let t=e();if(t)return t}}function nc(e){let{from:t,actionCount:n,pendingRecordAndHeal:r}=e,i=t===n+1&&r!==void 0&&r.expectedFrom===t;return Number.isInteger(t)&&t>=1&&(t<=n||i)?void 0:`replay --from ${t} is out of range for a ${n}-step plan.`}function rc(e){let{from:t,pendingRecordAndHeal:n,sessionActionsLength:r}=e;if(n?.expectedFrom===t&&r===n.actionsCountAtDivergence)return`replay --from ${t} continues a record-and-heal-shaped repair, but no corrective action was recorded in this repair segment; press the correct control via a blessed @ref from the divergence's screen.refs (recorded, no --no-record) — or, if your corrective action was a read (get/is/find/snapshot), re-run it with --record so it lands in the heal — before resuming with --from ${t}.`}function ic(e,t){if(e!==t)return`replay --plan-digest does not match the current plan digest; the script, its includes, or its platform-conditioned expansion changed since the divergence report was generated. Run a fresh full replay to get a new digest.`}function ac(e,t){let n=e.trimStart()[0];if(n===`{`||n===`[`)throw new a(`INVALID_ARGS`,`replay accepts .ad script files. JSON replay payloads are no longer supported.`);let r=te(e),i=re(e),o=Zs({actions:r.actions,actionLines:r.actionLines,actionSourcePaths:r.actionSourcePaths,metadata:{platform:t?.platform??ae(r.actions)??i.platform,target:t?.target??i.target}}),s=r.actions.length;return{actions:r.actions,actionLines:r.actionLines,actionSourcePaths:r.actionSourcePaths,metadata:i,planDigest:o,resolveEntryIndex:e=>ec(e,s,o)}}function oc(e){let{recorded:t,isSelectorWait:n}=e;return n?t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`deferred-landmark`,landmark:t}:{kind:`skip`}}function sc(e){let{recorded:t,token:n}=e;return n===void 0||!n.startsWith(`@`)&&je(`positional`,[n]).kind!==`expression`?{kind:`skip`}:t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`verify`,token:n}}function cc(e,t){if(!(!e||!t)&&(e.documentOrder!==t.documentOrder||e.sibling!==t.sibling))return`position: recorded=doc${e.documentOrder}/sibling${e.sibling} observed=doc${t.documentOrder}/sibling${t.sibling}`}function lc(e,t,n){let{observed:r,expectedStructural:i,observedStructural:a}=t,o=cc(i,a);return{matchCount:n,observed:r,mismatches:[...r?Je(e,r):[],...o?[o]:[]],causeMessage:`Dispatch resolution (with occlusion/visibility guards) resolved a different element than pre-action verification isolated; the action was not sent.`}}function uc(e,t){let{matchCount:n,observed:r,observedAncestry:i}=t;return{matchCount:n,observed:r,mismatches:r?[...Je(e,r),...rt(e.ancestry,i)]:[],causeMessage:`Candidates matched the recorded wait selector during polling, but none carried the recorded landmark identity before the timeout; the wait did not report success.`}}async function dc(e,t,n,r,i,a){if(n.targetEvidences)return fc(e,t,n,r,i,a);let o=n.targetEvidence;if(!o)return q(e,n,r,i,a);let s=e.beginTargetVerification(n,r,i);if(s.kind===`inactive`)return q(e,n,r,i,a);if(s.kind===`post-resolution`){let c=oc({recorded:o,isSelectorWait:s.isSelectorWait});switch(c.kind){case`skip`:return q(e,n,r,i,a);case`recorded-unverifiable`:return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(n,i,a,t)};case`deferred-landmark`:return mc(e,t,n,r,i,a,{kind:`landmark`,landmark:c.landmark})}}let c=sc({recorded:o,token:s.token});if(c.kind===`skip`)return q(e,n,r,i,a);if(c.kind===`recorded-unverifiable`)return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(n,i,a,t)};let l=c.token,u=await e.observeTarget({action:n,index:i,token:l});if(u.state!==`classified`)return{status:`failed`,failure:await e.buildTargetBindingFailure(n,i,pc(u),a,t)};let{classification:d}=u;return d.verified?mc(e,t,n,r,i,a,{kind:`target`,guard:d.guard}):{status:`failed`,failure:await e.buildTargetBindingFailure(n,i,{kind:d.kind,matchCount:d.matchCount,observed:d.observed,candidateNodes:d.candidateNodes,mismatches:d.mismatches,causeCode:d.causeCode,causeMessage:d.causeMessage},a,t)}}async function fc(e,t,n,r,i,a){let o=n.targetEvidences,s={};for(let c of[`source`,`destination`]){let l={...n,targetEvidence:o[c]},u=e.beginTargetVerification(l,r,i,c);if(u.kind!==`pre-dispatch`)return q(e,n,r,i,a);let d=sc({recorded:o[c],token:u.token});if(d.kind===`skip`)return q(e,n,r,i,a);if(d.kind===`recorded-unverifiable`)return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(l,i,a,t)};let f=await e.observeTarget({action:l,index:i,token:d.token});if(f.state!==`classified`)return{status:`failed`,failure:await e.buildTargetBindingFailure(l,i,pc(f),a,t)};let{classification:p}=f;if(!p.verified)return{status:`failed`,failure:await e.buildTargetBindingFailure(l,i,{kind:p.kind,matchCount:p.matchCount,observed:p.observed,candidateNodes:p.candidateNodes,mismatches:p.mismatches,causeCode:p.causeCode,causeMessage:p.causeMessage},a,t)};s[c]=p.guard}return mc(e,t,n,r,i,a,{kind:`targets`,guards:{source:s.source,destination:s.destination}})}function pc(e){return{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Could not capture a fresh snapshot to verify the recorded target before acting (${e.reason}).`,...e.hint===void 0?{}:{causeHint:e.hint}}}async function q(e,t,n,r,i){let a=await e.dispatchStep(t,n,r,i,void 0);switch(a.status){case`ok`:return{status:`ok`,artifactPaths:a.artifactPaths};case`failed`:return{status:`failed`,failure:a.failure};case`guard-mismatch`:case`landmark-mismatch`:return{status:`failed`,failure:a.plainFailure}}}async function mc(e,t,n,r,i,a,o){let s=await e.dispatchStep(n,r,i,a,o);if(s.status===`ok`)return{status:`ok`,artifactPaths:s.artifactPaths};if(s.status===`failed`)return{status:`failed`,failure:s.failure};let c=hc(n,o,s);if(!c)return{status:`failed`,failure:s.plainFailure};let l=gc(c.recorded,c.matchCount,s);return{status:`failed`,failure:await e.buildPostDispatchTargetBindingFailure(c.reportAction,i,{kind:`identity-mismatch`,matchCount:l.matchCount,observed:l.observed,candidateNodes:[],mismatches:l.mismatches,causeCode:`IDENTITY_MISMATCH`,causeMessage:l.causeMessage},a,t)}}function hc(e,t,n){if(n.status!==`guard-mismatch`||t.kind!==`targets`)return e.targetEvidence?{recorded:e.targetEvidence,reportAction:e,matchCount:t.kind===`target`?t.guard.matchCount:0}:void 0;let r=n.evidence.targetRole??`source`,i=e.targetEvidences?.[r];return i?{recorded:i,reportAction:{...e,targetEvidence:i},matchCount:t.guards[r].matchCount}:void 0}function gc(e,t,n){return n.status===`guard-mismatch`?lc(e,n.evidence,t):uc(e,n.evidence)}async function _c(e,t){let{actions:n,entryIndex:r,keepSession:i}=e,a=Ot(e.varSources),o=[],s=[],c=xc(n),l=0;for(let u=r;u<n.length;u+=1){let r=n[u];if(!bc(r)||(t.armStep(),u===c&&(i||t.isRepairArmed())))continue;if(l+=1,t.onStep){let e=t.describeStepValue(r);t.onStep(Sc(u,n.length,r,e))}let d=Dt(r,a,yc(e,u)),f=wt(a),p=t.diagnosticsMarker(),m=await dc(t,f,r,d,u,o);if(s.push(...t.diagnosticsSince(p)),m.status===`ok`){o=m.artifactPaths;continue}let h=await t.handleActionFailure({action:r,index:u,artifactPaths:vc(o,m.failure.artifactPaths),snapshotDiagnosticSamples:s,scrubVars:f});return{status:`failed`,stepIndex:u,failure:h}}return{status:`completed`,replayed:l,artifactPaths:[...o],snapshotDiagnosticSamples:s}}function vc(e,t){return t.length===0?e:[...new Set([...e,...t])]}function yc(e,t){return{file:e.actionSourcePaths?.[t]??e.resolvedPath,line:e.actionLines[t]??1}}function bc(e){return!!(e&&e.command!==`replay`)}function xc(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(bc(n))return n.command===`close`?t:void 0}}function Sc(e,t,n,r){return{index:e+1,total:t,command:n.command,...r===void 0?{}:{value:r}}}async function Cc(e){return await wc({...e,snapshotDiagnostics:x(e.snapshotDiagnosticSamples)})}async function wc(e){let{response:t,action:n,index:r,replayPath:i,sourcePath:a,sourceLine:o,artifactPaths:s=[],snapshotDiagnostics:c,scrubVars:l,req:u,sessionStore:d,observationStore:f,resumeStamper:p,logPath:m,planActions:h,planDigest:g}=e;if(t.ok)return t;let _=Tc(t.error.details?.replaySource),v=Hr(t.error),y=await Ur({error:v,action:n,index:r,sourcePath:_?.path??a,sourceLine:_?.line??o,session:f.get(),sessionStore:d,observationStore:f,resumeStamper:p,logPath:m,responseLevel:u.meta?.responseLevel,scrubVars:l,planActions:h,planDigest:g,signal:Rn(u.meta?.requestId)});return Qr({error:v,action:n,step:r+1,replayPath:i,artifactPaths:s,snapshotDiagnostics:c,divergence:y,scrubVars:l})}function Tc(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=typeof t.path==`string`&&t.path.length>0?t.path:void 0,r=typeof t.line==`number`?t.line:void 0;if(n!==void 0||r!==void 0)return{path:n,line:r}}async function Ec(e){let{req:t,sessionName:n,action:r,resolved:i,filePath:o,line:s,step:c,sourcePath:l,tracePath:u,invoke:d,resolvedSessionScope:p,dependencies:m}=e,h=Date.now();Yr(u,{type:`replay_action_start`,ts:new Date(h).toISOString(),replayPath:o,...l?{sourcePath:l}:{},line:s,step:c,command:i.command,positionals:Sn(i)??[]});let g;try{g=await Oc({req:t,sessionName:n,resolved:i,sourceAction:r,invoke:d,resolvedSessionScope:p,dependencies:m})}catch(e){if(!(e instanceof a))throw e;g={ok:!1,error:f(e)}}let _=Date.now();return Yr(u,{type:`replay_action_stop`,ts:new Date(_).toISOString(),replayPath:o,...l?{sourcePath:l}:{},line:s,step:c,command:i.command,ok:g.ok,durationMs:_-h,resultTiming:g.ok?Ac(g.data):void 0,errorCode:g.ok?void 0:g.error.code}),Dc(g,l??o,s)}function Dc(e,t,n){return e.ok||e.error.details?.replaySource!==void 0?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},replaySource:{path:t,line:n}}}}}async function Oc(e){let{req:t,sessionName:n,resolved:r,sourceAction:i,invoke:o,resolvedSessionScope:s,dependencies:c}=e,l=w(r.command,r.positionals??[],r.flags??{},`after variable substitution`);if(l)throw new a(`INVALID_ARGS`,l);let u=y(t.flags,{...r.flags??{}}),d=i.command===`fill`?kt(jt(i)):void 0;return d&&(u.recordAs=d),await o(kc({token:t.token,session:n,flags:u,runtime:r.runtime,meta:t.meta,dispatch:{...t.dispatch,replayPlanStep:!0,...r.command===`open`?{resolvedSessionScope:s??c.resolveSessionScope(t)}:{}}},r))}function kc(e,t){let n=t.positionals??[];return t.command===`gesture`?{...e,command:t.command,positionals:[],input:pe(n,{pointerCount:e.flags?.pointerCount,holdMs:e.flags?.holdMs,count:e.flags?.count,pauseMs:e.flags?.pauseMs})}:t.command===`swipe`?{...e,command:t.command,positionals:[],input:ce(n,{count:e.flags?.count,pauseMs:e.flags?.pauseMs,pattern:e.flags?.pattern})}:{...e,command:t.command,positionals:n}}function Ac(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.timing;if(!(!t||typeof t!=`object`||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return t===`number`||t===`string`||t===`boolean`}))}function jc(e){return Rc(e.ok?Nc(e.data):Mc(e.error.details?.artifactPaths))}function Mc(e){return Array.isArray(e)?e.filter(Lc):[]}function Nc(e){return e?[Ic(e.path),Ic(e.outPath),...Pc(e.artifacts)].filter(Lc):[]}function Pc(e){return Array.isArray(e)?e.map(Fc).filter(Lc):[]}function Fc(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;return Ic(t.localPath)??Ic(t.path)}function Ic(e){return typeof e==`string`?e:void 0}function Lc(e){return typeof e==`string`}function Rc(e){return[...new Set(e.filter(zc))]}function zc(e){try{return W.statSync(e).isFile()}catch{return!1}}function Bc(e){let{recorded:t,token:n,nodes:i,platform:a,refLabel:o,requireRect:s,allowDisambiguation:c}=e,l=Vc({token:n,nodes:i,platform:a,refLabel:o,requireRect:s,allowDisambiguation:c}),u=Bt(i),d=qe(t),f=Vt(l.matchedNodes,u,d,t.ancestry),p=f.filter(e=>yt(i,e)===t.sibling),m=f.filter(e=>vt(e,u,t.scrollRegion)),h=_t(m)[t.viewportOrder]?.ref,g=bt({winnerRef:l.winnerRef,matchedRefs:r(l.matchedNodes),identitySetRefs:r(f),siblingMatchRefs:r(p),regionMemberRefs:r(m),viewportCandidateRef:h}),_=l.matchedNodes.find(e=>e.ref===l.winnerRef);return g.outcome===`verified`&&_?{verified:!0,winnerNode:_,matchCount:l.matchedNodes.length}:g.outcome===`verified`?{verified:!1,kind:`identity-unverifiable`,matchCount:l.matchedNodes.length,observedNode:void 0,candidateNodes:f.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Verification isolated a member that is not part of the matched-node domain (capture anomaly).`}:{verified:!1,...Wc({classification:g,matchCount:l.matchedNodes.length,winnerNode:_,identitySet:f,byIndex:u,recorded:t})}}function Vc(e){let{token:t,nodes:n,platform:r,refLabel:i,requireRect:a,allowDisambiguation:o}=e;return t.startsWith(`@`)?Hc(n,t,i,a):Uc(n,t,r,a,o)}function Hc(e,r,i,a){let s=e=>e!==null&&(!a||!!e.rect),c=t(r),l=c?n(e,c):null;if(s(l)&&l.ref!==void 0)return{matchedNodes:[l],winnerRef:l.ref};let u=i?Sr(e,i):null;return s(u)&&o(u)?{matchedNodes:[u],winnerRef:u.ref}:{matchedNodes:[],winnerRef:``}}function Uc(e,t,n,r,i){let a=Ne(t,e,{platform:n,requireRect:r,allowDisambiguation:i});if(a.kind===`resolved`&&a.winner.ref!==void 0)return{matchedNodes:[...a.matchedNodes],winnerRef:a.winner.ref};let o=rr(e,a.matchedNodes);return{matchedNodes:[...a.matchedNodes],winnerRef:o?.ref??``}}function Wc(e){let{classification:t,matchCount:n,winnerNode:r,identitySet:i,byIndex:a,recorded:o}=e;switch(t.reason){case`selector-miss`:return{kind:`selector-miss`,matchCount:0,observedNode:void 0,candidateNodes:[],mismatches:[],causeCode:`SELECTOR_MISS`,causeMessage:`The recorded target no longer matches any current element.`};case`identity-set-empty`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Gc(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`The recorded selector/ref still matches, but nothing in the current tree carries the recorded identity.`};case`unique-but-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Gc(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`Exactly one current element carries the recorded identity, but the resolved target is a different element.`};case`signal-isolated-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Gc(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`A disambiguation signal (sibling or viewport position) isolated a different element than the resolved target.`};case`no-signal-isolation`:return{kind:`identity-unverifiable`,matchCount:n,observedNode:r,candidateNodes:i.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`${i.length} current elements carry the recorded identity and neither disambiguation signal isolated one.`}}}function Gc(e,t,n){let r=xt(t),i=Ht(t,n,Math.max(e.ancestry.length,1)).chain;return[...Je(e,r),...rt(e.ancestry,i)].slice(0,5)}function Kc(e,t){let n=e.positionals??[];if(e.command===`gesture`){let e=le(n);return e?e[t??`source`]:void 0}if(e.command===`get`)return n[1];if(e.command===`is`){let e=je(`is`,n);return e.kind===`expression`?e.expression:void 0}if(!se(e.command)&&e.command!==`fill`)return;let r=n[0];if(r!==void 0&&!(Jc(r)&&Jc(n[1])))return r}function qc(e){let t=e.result?.refLabel;return typeof t==`string`&&t.length>0?t:void 0}function Jc(e){return e!==void 0&&e.trim().length>0&&!Number.isNaN(Number(e))}function Yc(e,t){let{recorded:n,action:r,step:i,sourcePath:a,sourceLine:o,replayPath:s,artifactPaths:c,sessionStore:l,resumeStamper:u,responseLevel:d,scrubVars:f,planActions:p,planDigest:m}=e,h=on(f),g={classification:t.kind,...t.matchCount===void 0?{}:{matchCount:t.matchCount},recorded:al(qe(n),h),...t.observed?{observed:al(t.observed,h)}:{},mismatches:t.mismatches.slice(0,5).map(e=>h(e)),candidates:t.candidateNodes.slice(0,5).map(e=>ol(e,h))},_=Jr({kind:t.kind,targetEvidence:n,capture:t.repairCapture}),v=Kr({failedIndex:i,actions:p,planDigest:m,repairHint:_,resumeStamper:u}),y={version:1,kind:t.kind,step:{index:i,source:{path:h(a),line:o}},action:h(ne(r)),cause:{code:t.causeCode,message:h(t.causeMessage),...t.causeHint?{hint:h(t.causeHint)}:{}},screen:t.screen,suggestions:[],suggestionCount:0,resume:v,repairHint:_,targetBinding:g},b=Zr({sessionStore:l,observationStore:e.observationStore,divergence:y,responseLevel:d,evidence:t.publicationEvidence,...e.signal?{signal:e.signal}:{}}),x={code:t.causeCode,message:t.causeMessage};return Qr({error:x,action:r,step:i,replayPath:s,artifactPaths:c,divergence:b,scrubVars:f})}function Xc(e,t,n){let r=on(e.scrubVars);return Yc(e,{kind:t.kind,matchCount:t.matchCount,observed:t.observed,candidateNodes:t.candidateNodes,mismatches:t.mismatches,causeCode:t.causeCode,causeMessage:t.causeMessage,...t.causeHint===void 0?{}:{causeHint:t.causeHint},screen:Xr(n,r),publicationEvidence:el(n),repairCapture:Wr(n)})}async function Zc(e){let{session:t,observationStore:n,logPath:r,action:i,unavailableHint:a,signal:o}=e;return t?await qr({session:t,observationStore:n,logPath:r,action:i,signal:o}):{state:`unavailable`,reason:`no-session`,hint:a}}async function Qc(e,t){return Xc(e,{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`The recorded target evidence could not verify itself when it was captured (a structural capture anomaly), so replay cannot trust it before acting.`},await Zc({...t,signal:e.signal,unavailableHint:`The session closed before a screen could be captured to verify the recorded target evidence.`}))}async function $c(e,t,n){return Xc(e,t,await Zc({...n,signal:e.signal,unavailableHint:`The session closed before a post-failure screen could be captured.`}))}function el(e){return e.state===`available`?e.evidence:void 0}function tl(e){let{action:t,resolvedAction:n,sessionStore:r,targetRole:i}=e,a=r.get();return a?we(t.command)===`post-resolution`?{kind:`post-resolution`,isSelectorWait:Ve(n.positionals??[])?.kind===`selector`}:{kind:`pre-dispatch`,token:Kc(n,i),platform:a.device.platform}:{kind:`inactive`}}function nl(e){let{recorded:t,token:n,action:r,nodes:i,platform:a}=e,o=ei(r),s=Bc({recorded:t,token:n,nodes:i,platform:a,refLabel:qc(r),requireRect:o.requiresRect,allowDisambiguation:o.allowDisambiguation});return s.verified?{verified:!0,guard:{expected:{identity:xt(s.winnerNode),structural:$e(s.winnerNode,i)},matchCount:s.matchCount}}:{verified:!1,kind:s.kind,matchCount:s.matchCount,observed:s.observedNode?xt(s.observedNode):void 0,candidateNodes:s.candidateNodes,mismatches:s.mismatches,causeCode:s.causeCode,causeMessage:s.causeMessage}}function rl(e){return!e.ok&&e.error.details?.reason===`replay_target_guard_mismatch`}function il(e){return!e.ok&&e.error.details?.reason===ti}function al(e,t){return{...e.id===void 0?{}:{id:t(e.id)},role:t(e.role),...e.label===void 0?{}:{label:t(e.label)}}}function ol(e,t){let n=p(e.type??`Element`),r=fe(e,n);return{...e.ref?{ref:e.ref}:{},role:t(n),...r?{label:t(r)}:{}}}function sl(e,t){let n=t?.kind===`target`?{replayTargetGuard:t.guard.expected}:t?.kind===`targets`?{replayTargetGuards:{source:t.guards.source.expected,destination:t.guards.destination.expected}}:t?.kind===`landmark`?{replayLandmarkGuard:t.landmark}:void 0;return n?{...e,dispatch:{...e.dispatch,...n}}:e}function cl(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.role==`string`)return{...typeof t.id==`string`?{id:t.id}:{},role:t.role,...typeof t.label==`string`?{label:t.label}:{}}}function ll(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`||Array.isArray(n))return[];let e=n;if(typeof e.role!=`string`)return[];t.push({role:e.role,...typeof e.label==`string`?{label:e.label}:{}})}return t}function ul(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.documentOrder==`number`&&typeof t.sibling==`number`)return{documentOrder:t.documentOrder,sibling:t.sibling}}function dl(e){return{...e?.targetRole===`source`||e?.targetRole===`destination`?{targetRole:e.targetRole}:{},observed:cl(e?.observed),expectedStructural:ul(e?.expectedStructural),observedStructural:ul(e?.observedStructural)}}function fl(e){return{matchCount:typeof e?.matchCount==`number`?e.matchCount:void 0,observed:cl(e?.observed),observedAncestry:ll(e?.observedAncestry)}}function pl(e,t){return{kind:e.error.code,message:e.error.message,artifactPaths:t}}function ml(e,t,n){let r=pl(e,n);return(t?.kind===`target`||t?.kind===`targets`)&&rl(e)?{status:`guard-mismatch`,evidence:dl(e.error.details),plainFailure:r,artifactPaths:n}:t?.kind===`landmark`&&il(e)?{status:`landmark-mismatch`,evidence:fl(e.error.details),plainFailure:r,artifactPaths:n}:{status:`failed`,failure:r}}function hl(e){let{ctx:t,req:n,artifactPaths:r,onStep:i,armSaveScript:a}=e,o,s,c=(e,n,r,i)=>({recorded:e.targetEvidence,action:e,step:n+1,sourcePath:t.actionSourcePaths?.[n]??t.resolved,sourceLine:t.actionLines[n]??1,replayPath:t.resolved,artifactPaths:[...r],sessionStore:t.sessionStore,observationStore:t.observationStore,resumeStamper:t.coordinator.resumeStamper,responseLevel:t.responseLevel,scrubVars:i,planActions:t.actions,planDigest:t.planDigest,signal:t.signal}),l=e=>(o=e,pl(gl(e),jc(e))),u=async e=>{let n=t.observationStore.get();return n?await qr({session:n,observationStore:t.observationStore,logPath:t.logPath,action:e,retryLaunchRace:!0,signal:t.signal}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a screen could be captured to verify the recorded target.`}};return{runtime:{beginTargetVerification(e,n,r,i){return tl({action:e,resolvedAction:n,sessionStore:t.sessionStore,targetRole:i})},async observeTarget({action:e,token:n}){let r=await u(e);if(s=r,r.state!==`available`)return{state:`unavailable`,reason:r.reason,hint:r.hint};let i=t.sessionStore.get();return{state:`classified`,classification:nl({recorded:e.targetEvidence,token:n,action:e,nodes:[...r.nodes],platform:i.device.platform})}},async dispatchStep(e,n,i,a,s){let c=t.actionLines[i]??1,l=await Ec({req:sl(t.replayReq,s),sessionName:t.sessionName,action:e,resolved:n,filePath:t.resolved,line:c,sourcePath:t.actionSourcePaths?.[i],step:i+1,tracePath:t.actionTracePath,invoke:t.invoke,resolvedSessionScope:t.resolvedSessionScope,dependencies:t.dependencies});o=l,jc(l).forEach(e=>r.add(e));let u=[...r];return l.ok?{status:`ok`,artifactPaths:u}:ml(l,s,u)},async buildRecordedUnverifiableFailure(e,n,r,i){let a=await Qc(c(e,n,r,i),{session:t.observationStore.get(),observationStore:t.observationStore,logPath:t.logPath,action:e});return l(a)},async buildTargetBindingFailure(e,t,n,r,i){let a=s??{state:`unavailable`,reason:`observation-missing`,hint:`No capture was recorded before this target-binding failure.`},o=Xc(c(e,t,r,i),n,a);return l(o)},async buildPostDispatchTargetBindingFailure(e,n,r,i,a){let o=await $c(c(e,n,i,a),r,{session:t.observationStore.get(),observationStore:t.observationStore,logPath:t.logPath,action:e});return l(o)},async handleActionFailure({action:e,index:r,artifactPaths:i,snapshotDiagnosticSamples:a,scrubVars:s}){let c=gl(o),u=await _l(t,n,e,r,c,[...i],[...a],s);return l(u)},armStep:()=>{s=void 0,a()},isRepairArmed:()=>t.coordinator.view()?.repairBoundary!==void 0,describeStepValue:e=>vl(e),onStep:i,diagnosticsMarker:()=>bl(t.sessionStore),diagnosticsSince:e=>xl(t.sessionStore,e)},readLastResponse:()=>o}}function gl(e){return e&&!e.ok?e:d(`COMMAND_FAILED`,`replay step reported failure with no recorded response`)}async function _l(e,t,n,r,i,a,o,s){let c=t=>e.coordinator.markSessionHeldIfArmed(t);return yl(i)?c(i):c(await Cc({response:i,action:n,index:r,replayPath:e.resolved,sourcePath:e.actionSourcePaths?.[r]??e.resolved,sourceLine:e.actionLines[r]??1,artifactPaths:a,snapshotDiagnosticSamples:o,scrubVars:s,req:t,sessionStore:e.sessionStore,observationStore:e.observationStore,resumeStamper:e.coordinator.resumeStamper,logPath:e.logPath,planActions:e.actions,planDigest:e.planDigest}))}function vl(e){let t=e.positionals??[],n=Oe(t[0]);if(n)return n;if(t.length!==0)return t.join(` `)}function yl(e){if(e.ok||e.error.code!==`REPLAY_DIVERGENCE`)return!1;let t=e.error.details?.divergence,n=t&&typeof t==`object`?t.kind:void 0;return typeof n==`string`&&n!==`action-failure`}function bl(e){return e.get()?.snapshotDiagnostics?.samples.length??0}function xl(e,t){return e.get()?.snapshotDiagnostics?.samples.slice(t)??[]}async function Sl(e){let{resolved:t,keepSession:n,coordinator:r,command:i}=e,{request:a}=i,o=E(t,a.flags?.replayBackend);if(o!==`ad`)return n?d(`INVALID_ARGS`,`--keep-session is supported only for native .ad replay; Maestro YAML owns its lifecycle.`):r.view()?.repairBoundary===void 0?await(await ni(o)).runReplay(i):d(`INVALID_ARGS`,`This session has an active .ad --save-script repair run; finish it with replay --from or close before running Maestro YAML.`)}function Cl(e){let{req:t,host:n,sessionName:r,sessionStore:i,tracePath:a,resolved:o,script:s,coordinator:c,dispatch:l}=e,u=wl(t);if(u)return{ok:!1,response:u};let{manifest:d,replayReq:f}=Tl(t,s,l),{metadata:p,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_}=d,v=i.get(),y=El({req:t,coordinator:c,manifest:d,preEntrySession:v});return y.ok?{ok:!0,value:{replayReq:f,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_,preEntrySession:v,entryIndex:y.value,varSources:Ol({req:t,host:n,replayReq:f,sessionName:r,resolved:o,metadata:p}),actionTracePath:a??v?.trace?.outPath}}:{ok:!1,response:y.response}}function wl(e){let t=e.flags?.replayBackend;if(t&&!ee(t))return d(`INVALID_ARGS`,ie(t))}function Tl(e,t,n){let r=ac(t,{platform:e.flags?.platform,target:e.flags?.target});return{manifest:r,replayReq:Dl({...e,flags:wn(e.flags,r.actions),...n?{dispatch:n}:{}},r.metadata)}}function El(e){let{req:t,coordinator:n,manifest:r,preEntrySession:i}=e,a=r.resolveEntryIndex({from:t.flags?.replayFrom,digest:t.flags?.replayPlanDigest,pendingRecordAndHeal:n.view()?.pendingRecordAndHeal,sessionActionsLength:i?.actions.length??0});return a.ok?{ok:!0,value:a.value}:{ok:!1,response:d(`INVALID_ARGS`,a.message)}}function Dl(e,t){return!t.platform&&!t.target?e:{...e,flags:kl(e.flags,t)}}function Ol(e){let{req:t,host:n,replayReq:r,sessionName:i,resolved:a,metadata:o}=e;return{builtins:$r({req:r,sessionName:i,metadata:o,resolvedPath:a,hostCwd:n.cwd}),fileEnv:o.env,shellEnv:Et(Tt(t.flags?.replayShellEnv,n.env)),cliEnv:Ct(St(t.flags?.replayEnv))}}function kl(e,t){return{...e??{},...t.platform!==void 0&&e?.platform===void 0?{platform:t.platform}:{},...t.target!==void 0&&e?.target===void 0?{target:t.target}:{}}}const Al={kind:`none`,status:void 0,targetPath:void 0,targetForce:!1};function jl(e){let{req:t,entryIndex:n,hostCwd:r,sessionStore:i,sourcePath:a,coordinator:o}=e,s=Ml({entryIndex:n,sessionStore:i,coordinator:o});return s?{ok:!1,response:s}:(Fl({req:t,coordinator:o}),Pl({req:t,hostCwd:r,sessionStore:i,sourcePath:a,coordinator:o}))}function Ml(e){let t=Il(e);if(t)return t;if(e.entryIndex>0&&!e.sessionStore.get())return u()}function Nl(e){let{saveScript:t,force:n,hostCwd:r,preRunState:i,sourcePath:a}=e;return t&&i.kind===`authoring`?d(`INVALID_ARGS`,`replay --save-script cannot re-arm an ordinary recording in terminal/active state ${i.status}. Close this session and use a fresh one for repair authoring.`):Ll({saveScript:t,liveForce:n,persistedForce:i.targetForce||void 0,hostCwd:r,sourcePath:a,existingSaveScriptPath:i.targetPath})}function Pl(e){let{req:t,hostCwd:n,sourcePath:r,coordinator:i}=e,{saveScript:a,force:o}=t.flags??{},s=Nl({saveScript:a,force:o,hostCwd:n,preRunState:i.view()?.scriptPublication??Al,sourcePath:r});return s?{ok:!1,response:s}:(i.demoteForRerunIfArmed(),{ok:!0,armSaveScript:Rl({saveScript:a,force:o,coordinator:i,sourcePath:r})})}function Fl(e){let{req:t,coordinator:n}=e;n.clearCorrectiveWatermarkIfExpected(t.flags?.replayFrom),t.flags?.saveScript&&n.clearTombstone()}function Il(e){let{entryIndex:t,coordinator:n}=e;if(!(t>0)&&n.view()?.repairBoundary!==void 0)return d(`INVALID_ARGS`,`This session has an active --save-script repair run; continue it with replay --from <n> --plan-digest <sha256>, or finish with close, before starting a fresh full replay.`)}function Ll(e){let{saveScript:t,liveForce:n,persistedForce:r,hostCwd:i,sourcePath:a,existingSaveScriptPath:o}=e;if(!t)return;let s=typeof t==`string`?F(t,i):o??Gr(a);if(!(n||r&&s===o)&&W.existsSync(s))return d(`COMMAND_FAILED`,`A file already exists at ${s}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`)}function Rl(e){let{saveScript:t,force:n,coordinator:r,sourcePath:i}=e;if(!t)return()=>{};let a=!0;return()=>{r.armStep({saveScript:t,force:n,sourcePath:i,firstArm:a}),a=!1}}async function zl(e){let{request:t,host:n,session:{name:r,logPath:i,store:a,observationStore:o,coordinator:s},tracePath:c,onStep:l,invoke:u}=e,p=t.flags?.replayScriptSource;if(!p)return d(`INVALID_ARGS`,bn);let m=Date.now(),h=t.flags?.replayKeepSession===!0,g=``,_=new Set;try{if(g=p.entry,de(g)&&t.flags?.replayBackend!==`maestro`)return d(`INVALID_ARGS`,ue(`replay`,g));let f=await Sl({resolved:g,keepSession:h,coordinator:s,command:e});if(f)return f;let v=Cl({req:t,host:n,sessionName:r,sessionStore:a,tracePath:c,resolved:g,script:Cn(p,g),coordinator:s,dispatch:e.dispatch});if(!v.ok)return v.response;let{replayReq:y,actions:b,actionLines:x,actionSourcePaths:S,planDigest:C,entryIndex:w,varSources:ee,actionTracePath:T}=v.value,te=jl({req:t,entryIndex:w,hostCwd:n.cwd,sessionStore:a,sourcePath:g,coordinator:s});if(!te.ok)return te.response;let{runtime:ne,readLastResponse:re}=hl({ctx:{replayReq:y,sessionName:r,sessionStore:a,observationStore:o,logPath:i,resolved:g,actions:b,actionLines:x,actionSourcePaths:S,planDigest:C,actionTracePath:T,responseLevel:t.meta?.responseLevel,invoke:u,signal:Rn(t.meta?.requestId),coordinator:s,resolvedSessionScope:e.resolvedSessionScope,dependencies:e.dependencies},req:t,artifactPaths:_,onStep:l,armSaveScript:te.armSaveScript}),E=await _c({actions:b,entryIndex:w,keepSession:h,actionLines:x,actionSourcePaths:S,resolvedPath:g,varSources:ee},ne);return E.status===`failed`?re()??d(`COMMAND_FAILED`,`replay step failed with no recorded response`):Bl({startedAt:m,sessionName:r,sessionStore:a,replayed:E.replayed,artifactPaths:E.artifactPaths,snapshotDiagnosticSamples:E.snapshotDiagnosticSamples,armSaveScript:te.armSaveScript,coordinator:s,keepSession:h})}catch(e){let t=f(e);return _.size===0?{ok:!1,error:t}:{ok:!1,error:{...t,details:{...t.details,artifactPaths:[..._]}}}}}function Bl(e){let{startedAt:t,sessionName:n,sessionStore:r,replayed:i,artifactPaths:a,snapshotDiagnosticSamples:o,armSaveScript:s,coordinator:c,keepSession:l}=e;s(),c.markCompleteIfArmed();let u=r.get(),d=Hl({keepSession:l,sessionName:n,completedSession:u,artifactPaths:a});if(d)return d;let f=x([...o]);return{ok:!0,data:{replayed:i,healed:0,session:n,sessionActive:u!==void 0,artifactPaths:[...a],...f?{snapshotDiagnostics:f}:{},message:Vl(i,Date.now()-t)}}}function Vl(e,t){let n=(t/1e3).toFixed(1);return`Replayed ${e} ${e===1?`step`:`steps`} in ${n}s`}function Hl(e){let{keepSession:t,sessionName:n,completedSession:r,artifactPaths:i}=e;if(!(!t||r))return d(`COMMAND_FAILED`,`Replay completed but --keep-session could not preserve session "${n}". Run the script again after checking which action closed the session.`,i.length>0?{artifactPaths:[...i]}:void 0)}function Ul(e){let{artifactsDir:t,cwd:n,suiteInvocationId:r}=e,i=G.resolve(n??`.`,t??`.agent-device/test-artifacts`);return G.join(i,r)}function Wl(e,t){let n=t?G.relative(t,e):G.basename(e),r=n.length===0||n.startsWith(`..`)?G.basename(e):n;return Ee(r.toLowerCase().replaceAll(/[\\/]+/g,`__`).replaceAll(/[^a-z0-9._-]+/g,`-`))||`test`}function Gl(e,t){W.mkdirSync(t,{recursive:!0}),Jl(e,t)}function Kl(e){let{outcome:t,filePath:n,sessionName:r,attempts:i,maxAttempts:a,attemptArtifactsDir:o}=e,s=t.status===`passed`,c=new Set(t.artifactPaths);t.status===`failed`&&typeof t.error.logPath==`string`&&c.add(t.error.logPath);let l=G.join(o,`result.txt`),u=G.join(o,`failure.txt`),d=ql([...c],o,[l,u]),f=[`file: ${n}`,`session: ${r}`,`attempt: ${i}/${a}`,`status: ${s?`passed`:`failed`}`];t.status===`passed`?f.push(`replayed: ${t.replayed}`,`healed: ${t.healed}`):(f.push(`code: ${t.error.code}`,`message: ${t.error.message}`),t.error.hint&&f.push(`hint: ${t.error.hint}`),t.error.diagnosticId&&f.push(`diagnosticId: ${t.error.diagnosticId}`),t.error.logPath&&f.push(`logPath: ${t.error.logPath}`),t.error.details?.reason===`timeout`&&f.push(`timeoutMode: cooperative`)),d.length>0&&f.push(`copiedArtifacts: ${d.map(e=>G.basename(e)).join(`, `)}`);let p=`${f.join(`
|
|
2
|
-
`)}\n`;W.writeFileSync(l,p),s||W.writeFileSync(u,p)}function ql(e,t,n){let r=[],i=new Set(n.map(e=>G.basename(e).toLowerCase()));for(let n of e){if(!Xl(n))continue;let e=G.basename(n);if(G.resolve(n)===G.resolve(t,e)&&!i.has(e.toLowerCase())){r.push(n);continue}let a=Yl(e,t,i),o=G.join(t,a);W.copyFileSync(n,o),r.push(o)}return r}function Jl(e,t){let n=G.join(t,`replay.ad`);if(W.copyFileSync(e,n),G.extname(e).toLowerCase()===`.ad`)return;let r=G.join(t,G.basename(e));G.resolve(r)!==G.resolve(n)&&W.copyFileSync(e,r)}function Yl(e,t,n){let r=G.extname(e),i=r?e.slice(0,-r.length):e,a=e,o=2;for(;n.has(a.toLowerCase())||W.existsSync(G.join(t,a));)a=`${i}-${o++}${r}`;return a}function Xl(e){try{return W.statSync(e).isFile()}catch{return!1}}function Zl(e){let{platformFilter:t,discoverSources:n}=e,r=n(),i=[],o={undeclared:0,declaredOther:0};for(let e of r){let{path:n,manifest:r}=e,a={kind:`run`,path:n,title:r.title,manifest:r};if(!t){i.push(a);continue}let s=r.device.platform;if(s.kind===`caller-bound`){i.push(a);continue}if(s.kind===`unspecified`){o.undeclared+=1,i.push({kind:`skip`,path:n,reason:`skipped-by-filter`,message:`missing platform metadata for --platform ${t}`});continue}if(!su(t,s.value)){o.declaredOther+=1;continue}i.push(a)}if(i.filter(e=>e.kind===`run`).length===0)throw new a(`INVALID_ARGS`,eu({platformFilter:t,...o}));return i}const Ql={web:!0};function $l(e){return!Object.hasOwn(Ql,e)}function eu(e){let{platformFilter:t,undeclared:n,declaredOther:r}=e,i=t?` for --platform ${t}`:``;return t===void 0||n===0&&r===0?`No replay tests matched${i}.`:`No replay tests matched${i}: ${[...n>0?[`${n} without a platform declaration`]:[],...r>0?[`${r} declaring another platform`]:[]].join(`, `)}. ${tu(t,n)}`}function tu(e,t){return $l(e)?t>0?`Add "context platform=${e}" to the first line of a script that has none, or drop --platform when the device is already selected.`:`Run a source that declares ${e}, or drop --platform.`:`No script can declare ${e} as its platform; run this suite without --platform.`}function nu(e,t,n,r,i=0){let a=G.basename(n,G.extname(n)),o=Ee(a.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`));return`${e}:test:${t}:${r+1}${o?`-${o}`:``}:attempt-${i+1}`}function ru(e){let t=e?.trim()||`${process.pid}-${Date.now().toString(36)}`;return Ee(t.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`))||`suite`}function iu(e){let{requestId:t,suiteInvocationId:n,filePath:r,caseIndex:i,attemptIndex:a,shardIndex:o}=e;return[t??n,...o===void 0?[]:[`shard`,o+1],`test`,i+1,G.basename(r),`attempt`,a+1].join(`:`)}function au(e,t){return typeof e==`number`?e:t}function ou(e,t){let n=typeof e==`number`?e:t;return typeof n==`number`?Math.max(0,Math.min(3,n)):0}function su(e,t){return e===`apple`?j(t):t===e}function J(e){return{status:`failed`,error:e.error,artifactPaths:e.artifactPaths??[],warnings:e.warnings??[],infrastructure:e.infrastructure??!1,...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}const cu=2e3;async function lu(e){let{filePath:t,sessionName:n,requestId:r,parentRequestId:i,timeoutMs:a,platform:o,target:s,artifactsDir:c,shard:l,onStep:u,runReplay:d,cleanupSession:p,finalizeAttempt:m,emitDiagnostic:h,bindAttemptCancellation:g}=e,_=g({attemptId:r,parentAttemptId:i}),v=new Set,y,b=!1,x,S=Date.now(),C=gu({artifactsDir:c,artifactPaths:v,filePath:t,sessionName:n,requestId:r,timeoutMs:a,platform:o,target:s}),w=d({filePath:t,sessionName:n,platform:o,target:s,requestId:r,artifactsDir:c,artifactPaths:v,tracePath:C,appendTimingEvent:e=>Y(C,e),shard:l,onStep:u}).catch(e=>J({error:f(e)})).finally(()=>{_.release()});try{x=typeof a==`number`?await Promise.race([w,new Promise(e=>{y=setTimeout(()=>{b=!0,_.cancel(),e(_u(a,[...v]))},a)})]):await w,Y(C,{type:`replay_test_attempt_stop`,ts:new Date().toISOString(),session:n,ok:x.status===`passed`,timedOut:b,durationMs:Date.now()-S,errorCode:x.status===`passed`?void 0:x.error.code})}finally{y&&clearTimeout(y),b&&(await du(w)||(x=mu(x),h({level:`warn`,phase:`test_timeout_cleanup_race`,data:{session:n,requestId:r,graceMs:cu}}),fu({replayPromise:w,cleanupSession:p,sessionName:n,requestId:r,emitDiagnostic:h})));let e=await pu({finalizeAttempt:m,sessionName:n,artifactPaths:v,artifactsDir:c,tracePath:C,emitDiagnostic:h});x?.status===`passed`&&e&&(x=hu(x,`Replay test finalization failed: ${e.error.message}`));let t=Date.now();try{Y(C,{type:`replay_test_cleanup_start`,ts:new Date().toISOString(),session:n}),await p(n),Y(C,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:n,ok:!0,durationMs:Date.now()-t})}catch(e){let r=f(e);Y(C,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:n,ok:!1,durationMs:Date.now()-t,errorCode:r.code}),h({level:`warn`,phase:`test_cleanup_failed`,data:{session:n,error:r.message}}),x=uu(x,r,v)}}return x??J({error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}})}function uu(e,t,n){return e?.status===`failed`?{...e,infrastructure:!0}:J({error:t,artifactPaths:[...n],infrastructure:!0})}async function du(e){return await Promise.race([e.then(()=>!0),ui(cu).then(()=>!1)])}async function fu(e){let{replayPromise:t,cleanupSession:n,sessionName:r,requestId:i,emitDiagnostic:a}=e;try{await t}finally{try{await n(r)}catch(e){a({level:`warn`,phase:`test_late_cleanup_failed`,data:{session:r,requestId:i,error:f(e).message}})}}}async function pu(e){let{finalizeAttempt:t,sessionName:n,artifactPaths:r,artifactsDir:i,tracePath:a,emitDiagnostic:o}=e;if(!t)return;let s=Date.now();Y(a,{type:`replay_test_finalize_start`,ts:new Date().toISOString(),session:n});try{let e=await t({sessionName:n,artifactPaths:r,artifactsDir:i,tracePath:a,appendTimingEvent:e=>Y(a,e)});return Y(a,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:n,ok:e===void 0,durationMs:Date.now()-s,errorCode:e?.error.code}),e}catch(e){let t=f(e);return Y(a,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:n,ok:!1,durationMs:Date.now()-s,errorCode:t.code}),o({level:`warn`,phase:`test_finalize_failed`,data:{session:n,error:t.message}}),J({error:t})}}function mu(e){return!e||e.status===`passed`?e:{...e,infrastructure:!0,error:{...e.error,details:{...e.error.details??{},reason:`timeout_cleanup_pending`,timeoutCleanupPending:!0}}}}function hu(e,t){return{...e,warnings:[...e.warnings,t]}}function gu(e){let{artifactsDir:t,artifactPaths:n,filePath:r,sessionName:i,requestId:a,timeoutMs:o,platform:s,target:c}=e;if(!t)return;let l=G.join(t,`replay-timing.ndjson`);return W.mkdirSync(G.dirname(l),{recursive:!0}),W.writeFileSync(l,``),n.add(l),Y(l,{type:`replay_test_attempt_start`,ts:new Date().toISOString(),replayPath:r,session:i,requestId:a,timeoutMs:o,platform:s,target:c}),l}function Y(e,t){e&&W.appendFileSync(e,`${JSON.stringify(t)}\n`)}function _u(e,t=[]){return J({artifactPaths:t,error:{code:`COMMAND_FAILED`,message:`TIMEOUT after ${e}ms`,hint:`Replay test timeouts are cooperative; the active command may take a short grace period to stop.`,details:{reason:`timeout`,timeoutMs:e,timeoutMode:`cooperative`,artifactPaths:t}}})}async function vu(e){let t=yu(e),n=await bu(e,t);return{result:Eu(e,t,n),infrastructure:n.finalOutcome?.status===`failed`&&n.finalOutcome.infrastructure}}function yu(e){let{entry:t,cwd:n,retries:r,suiteArtifactsDir:i,shard:a}=e;return{testStartedAt:Date.now(),testArtifactsDir:G.join(i,...a?[`shard-${a.shardIndex+1}`]:[],Wl(t.path,n)),maxAttempts:r+1}}async function bu(e,t){Su(e,t);let n={finalSessionName:``,attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let r=0;r<=e.retries&&!e.isCanceled();r+=1){let i=await xu(e,t,r);if(Cu(n,i),wu(e,i.outcome,r))break;Tu(e,t,i)}return n}async function xu(e,t,n){let{entry:r,sessionName:i,suiteInvocationId:a,caseIndex:o,suiteIndex:s,suiteTotal:c,requestId:l,timeoutMs:u,shard:d}=e,f=n+1,p=Date.now(),m=nu(i,a,r.path,o,n),h=G.join(t.testArtifactsDir,`attempt-${f}`);Gl(r.path,h);let g=iu({requestId:l,suiteInvocationId:a,filePath:r.path,caseIndex:o,attemptIndex:n,shardIndex:d?.shardIndex}),_={file:r.path,title:r.title,index:s,total:c,attempt:f,maxAttempts:t.maxAttempts,session:m,artifactsDir:t.testArtifactsDir,...X(d)},v=await lu({filePath:r.path,sessionName:m,requestId:g,parentRequestId:l,timeoutMs:u,platform:r.manifest.device.platform.kind===`declared`?r.manifest.device.platform.value:void 0,target:r.manifest.device.target,artifactsDir:h,shard:d,onStep:t=>{e.emitProgress({type:`replay-test`,..._,status:`progress`,stepIndex:t.index,stepTotal:t.total,...t.command===void 0?{}:{stepCommand:t.command},...t.value===void 0?{}:{stepValue:t.value}})},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt,emitDiagnostic:e.emitDiagnostic,bindAttemptCancellation:e.bindAttemptCancellation}),y=Date.now()-p;return Kl({outcome:v,filePath:r.path,sessionName:m,attempts:f,maxAttempts:t.maxAttempts,attemptArtifactsDir:h}),{outcome:v,sessionName:m,attempt:f,durationMs:y}}function Su(e,t){let{entry:n,sessionName:r,suiteInvocationId:i,caseIndex:a,suiteIndex:o,suiteTotal:s,shard:c}=e;e.emitProgress({type:`replay-test`,file:n.path,title:n.title,status:`start`,index:o,total:s,maxAttempts:t.maxAttempts,session:nu(r,i,n.path,a),artifactsDir:t.testArtifactsDir,...X(c)})}function Cu(e,t){e.finalOutcome=t.outcome,e.finalSessionName=t.sessionName,e.attempts=t.attempt,e.finalAttemptDurationMs=t.durationMs,t.outcome.status!==`passed`&&e.attemptFailures.push({attempt:t.attempt,message:t.outcome.error.message,durationMs:t.durationMs})}function wu(e,t,n){return t.status===`passed`||e.isCanceled()||t.infrastructure||t.status===`failed`&&t.stopRetries===!0||n>=e.retries}function Tu(e,t,n){n.outcome.status!==`passed`&&e.emitProgress({type:`replay-test`,file:e.entry.path,title:e.entry.title,status:`fail`,index:e.suiteIndex,total:e.suiteTotal,attempt:n.attempt,maxAttempts:t.maxAttempts,durationMs:n.durationMs,retrying:!0,message:n.outcome.error.message,hint:n.outcome.error.hint,session:n.sessionName,artifactsDir:t.testArtifactsDir,...X(e.shard)})}function Eu(e,t,n){let r=Date.now()-t.testStartedAt;return n.finalOutcome?.status===`passed`?Du(e,t,n,r):Ou(e,t,n,r)}function Du(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalOutcome;if(c?.status!==`passed`)throw Error(`Expected passing replay test outcome.`);return e.emitProgress({type:`replay-test`,file:i.path,title:i.title,status:`pass`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,...X(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`passed`,durationMs:r,finalAttemptDurationMs:n.finalAttemptDurationMs,attempts:n.attempts,artifactsDir:t.testArtifactsDir,replayed:c.replayed,healed:c.healed,...c.warnings.length>0?{warnings:[...c.warnings]}:{},...c.snapshotDiagnostics?{snapshotDiagnostics:c.snapshotDiagnostics}:{},...Au(s),...n.attemptFailures.length>0?{attemptFailures:n.attemptFailures}:{}}}function Ou(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalOutcome,l=c?.status===`failed`?c.error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`};return e.emitProgress({type:`replay-test`,file:i.path,title:i.title,status:`fail`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,message:l.message,hint:l.hint,...X(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`failed`,durationMs:r,attempts:n.attempts,artifactsDir:t.testArtifactsDir,error:l,...ku(c),...Au(s)}}function ku(e){let t=e?.status===`failed`?e:void 0;return{...t&&t.warnings.length>0?{warnings:[...t.warnings]}:{},...t?.infrastructure?{infrastructure:!0}:{},...e?.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}function Au(e){return X(e)}function X(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function ju(e,t,n,r){if(!e||t.length===0)return;let i=await r(e.count);return{mode:e.kind,shardCount:e.count,total:n+(e.kind===`all`?t.length*e.count:t.length),shards:i.map((n,r)=>({shardIndex:r,shardCount:e.count,device:n,entries:e.kind===`all`?t:t.filter((t,n)=>n%e.count===r)}))}}async function Mu(e){let{request:t,runReplay:n,cleanupSession:r,finalizeAttempt:i,emitProgress:a,isCanceled:o,emitDiagnostic:c,bindAttemptCancellation:l,discoverSources:u,resolveShardTargets:d}=e,f=t.sessionName;if(t.inputs.length===0)return{status:`failed`,error:{code:`INVALID_ARGS`,message:`test requires at least one path or glob`}};try{let e=Date.now(),s=await Nu(t,u,d);Lu(s,a);let p=s.shardPlan?Ru({entries:s.entries,total:s.total,emitProgress:a}):[];return s.shardPlan?p.push(...await zu({shards:s.shardPlan.shards,sessionName:f,suiteInvocationId:s.suiteInvocationId,cwd:t.cwd,requestId:t.requestId,request:t,suiteArtifactsDir:s.suiteArtifactsDir,suiteTotal:s.total,runReplay:n,cleanupSession:r,finalizeAttempt:i,emitProgress:a,isCanceled:o,emitDiagnostic:c,bindAttemptCancellation:l})):p.push(...await Uu({discoveryEntries:s.entries,sessionName:f,suiteInvocationId:s.suiteInvocationId,cwd:t.cwd,requestId:t.requestId,request:t,suiteArtifactsDir:s.suiteArtifactsDir,suiteTotal:s.total,runReplay:n,cleanupSession:r,finalizeAttempt:i,emitProgress:a,isCanceled:o,emitDiagnostic:c,bindAttemptCancellation:l})),{status:`completed`,data:Ku(s.total,p,Date.now()-e,s.suiteArtifactsDir)}}catch(e){let t=s(e);return{status:`failed`,error:{code:t.code,message:t.message}}}}async function Nu(e,t,n){let r=Pu(e,t),i=Fu(r),a=r.length-i.length,o=ru(e.requestId),s=await ju(e.shard?{kind:e.shard.mode,count:e.shard.count}:void 0,i,a,n);return{entries:r,runnable:i,shardPlan:s,suiteInvocationId:o,suiteArtifactsDir:Iu(e,o),total:s?.total??r.length}}function Pu(e,t){return Zl({platformFilter:e.platformFilter,discoverSources:t})}function Fu(e){return e.flatMap((e,t)=>e.kind===`run`?[{entry:e,suiteIndex:t+1}]:[])}function Iu(e,t){return Ul({artifactsDir:typeof e.artifactsDir==`string`?e.artifactsDir:void 0,cwd:e.cwd,suiteInvocationId:t})}function Lu(e,t){t({type:`replay-test-suite`,status:`start`,total:e.total,runnable:e.runnable.length,skipped:e.entries.length-e.runnable.length,artifactsDir:e.suiteArtifactsDir,shardMode:e.shardPlan?.mode,shardCount:e.shardPlan?.shardCount})}function Ru(e){let{entries:t,total:n}=e,r=[];for(let[i,a]of t.entries())a.kind===`skip`&&(e.emitProgress({type:`replay-test`,file:a.path,status:`skip`,index:i+1,total:n,message:a.message}),r.push({file:a.path,status:`skipped`,durationMs:0,reason:a.reason,message:a.message}));return r}async function zu(e){return(await Promise.allSettled(e.shards.map(async t=>await Vu({...e,shard:t})))).flatMap((t,n)=>{if(t.status===`fulfilled`)return t.value;let r=e.shards[n];return r?[Bu(r,e.sessionName,t.reason)]:[]})}function Bu(e,t,n){let r=f(n);return{file:e.entries[0]?.entry.path??`shard-${e.shardIndex+1}`,session:Hu(t,e),status:`failed`,durationMs:0,attempts:1,error:{code:r.code,message:r.message,hint:r.hint,diagnosticId:r.diagnosticId,logPath:r.logPath,details:r.details},shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}}async function Vu(e){let{shard:t,sessionName:n}=e;return await Wu({...e,entries:t.entries,sessionName:Hu(n,t),shard:t})}function Hu(e,t){return`${e}:shard-${t.shardIndex+1}`}async function Uu(e){let{discoveryEntries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,request:o,suiteArtifactsDir:s,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d,emitProgress:f,isCanceled:p,emitDiagnostic:m,bindAttemptCancellation:h}=e,g=[],_=0;for(let[e,v]of t.entries()){if(p())break;if(v.kind===`skip`){f({type:`replay-test`,file:v.path,status:`skip`,index:e+1,total:c,message:v.message}),g.push({file:v.path,status:`skipped`,durationMs:0,reason:v.reason,message:v.message});continue}_+=1;let t=await vu({entry:v,sessionName:n,suiteInvocationId:r,caseIndex:_-1,cwd:i,requestId:a,retries:ou(o.retries,v.manifest.attemptDefaults?.retries),timeoutMs:au(o.timeoutMs,v.manifest.attemptDefaults?.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d,emitProgress:f,isCanceled:p,emitDiagnostic:m,bindAttemptCancellation:h});if(g.push(t.result),Gu(t,o,p))break}return g}async function Wu(e){let{entries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,request:o,suiteArtifactsDir:s,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f,emitProgress:p,isCanceled:m,emitDiagnostic:h,bindAttemptCancellation:g}=e,_=[];for(let[e,v]of t.entries()){if(m())break;let{entry:t,suiteIndex:y}=v,b=await vu({entry:t,sessionName:n,suiteInvocationId:r,caseIndex:e,cwd:i,requestId:a,retries:ou(o.retries,t.manifest.attemptDefaults?.retries),timeoutMs:au(o.timeoutMs,t.manifest.attemptDefaults?.timeoutMs),suiteArtifactsDir:s,suiteIndex:y,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f,emitProgress:p,isCanceled:m,emitDiagnostic:h,bindAttemptCancellation:g});if(_.push(b.result),Gu(b,o,m))break}return _}function Gu(e,t,n){return n()||t.failFast===!0&&e.result.status===`failed`||e.infrastructure}function Ku(e,t,n,r){let i=t.filter(e=>e.status===`passed`).length,a=t.filter(e=>e.status===`failed`),o=a.length,s=t.filter(e=>e.status===`skipped`).length,c=i+o,l=C(t.map(e=>e.status===`skipped`?void 0:e.snapshotDiagnostics));return{total:e,executed:c,passed:i,failed:o,skipped:s,notRun:Math.max(0,e-c-s),durationMs:n,failures:a,tests:t,artifactsDir:r,...l?{snapshotDiagnostics:l}:{}}}function qu(e,t){return async n=>(await Xu(e,n,t)).map(Ju)}function Ju(e){if(e.platform===`web`||!_e(e))throw new a(`INVALID_ARGS`,`test sharding requires a mobile device; ${e.id} is ${e.platform}`);return{id:e.id,name:e.name,platform:e.platform,...e.target===void 0?{}:{target:e.target}}}function Yu(e,t){if(!t)return e;let n={...e??{},device:void 0,udid:void 0,serial:void 0,platform:t.device.platform,target:t.device.target,shardAll:void 0,shardSplit:void 0,shardCount:t.shardCount,shardIndex:t.shardIndex};return t.device.platform===`android`?{...n,serial:t.device.id}:{...n,udid:t.device.id}}async function Xu(e,t,n){let r=ed(e),i=Qu(await er(Zu(e,n)),r,e);if(i.length<t)throw new a(`DEVICE_NOT_FOUND`,`test sharding requires ${$u(t)}, but only ${i.length} matched`);return i.slice(0,t)}function Zu(e,t){let n=L(e?.androidDeviceAllowlist,t);return{platform:e?.platform,target:e?.target,iosSimulatorSetPath:xe({requestedSetPath:e?.iosSimulatorDeviceSet,platform:e?.platform,target:e?.target,env:t}),androidSerialAllowlist:n?Array.from(n).sort():void 0}}function Qu(e,t,n){return t.length>0?td(e,t,n):e.filter(e=>nd(e,n)).sort(ad)}function $u(e){return`${e} device${e===1?``:`s`}`}function ed(e){let t=e?.device;return typeof t!=`string`||t.trim().length===0?[]:t.split(`,`).map(e=>e.trim()).filter(Boolean)}function td(e,t,n){return t.map(t=>{let r=id(t),i=e.find(e=>rd(e,n)&&(e.id===t||id(e.name)===r));if(!i)throw new a(`DEVICE_NOT_FOUND`,`No shard device matched ${t}`);return i})}function nd(e,t){return!rd(e,t)||!_e(e)?!1:e.booted!==!1}function rd(e,t){return!(!ye(e,t?.platform)||t?.target&&(e.target??`mobile`)!==t.target)}function id(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}function ad(e,t){return e.id.localeCompare(t.id)}function od(e){let t=sd(e?.shardAll,`--shard-all`),n=sd(e?.shardSplit,`--shard-split`);if(t!==void 0&&n!==void 0)throw new a(`INVALID_ARGS`,`--shard-all and --shard-split are mutually exclusive`);if(t!==void 0)return{mode:`all`,count:t};if(n!==void 0)return{mode:`split`,count:n}}function sd(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isInteger(e)||e<1)throw new a(`INVALID_ARGS`,`${t} requires a positive integer`);return e}}const cd=new Set([`IOS_BOOT_TIMEOUT`,`IOS_RUNNER_CONNECT_TIMEOUT`,`IOS_RUNNER_OWNED_BY_OTHER_DAEMON`,`IOS_TOOL_MISSING`,`ANDROID_BOOT_TIMEOUT`,`ADB_TRANSPORT_UNAVAILABLE`,`CI_RESOURCE_STARVATION_SUSPECTED`]);function ld(e){return cd.has(e.toUpperCase())}const ud=[`failed to start daemon`,`runner did not accept connection`,`xcodebuild exited early`,`device is offline`,`device offline`,`device unauthorized`];function dd(e){if(!(`ok`in e)&&e.status===`failed`&&e.infrastructure===!0)return!0;let t=fd(e);return t?pd(t.details)||md(t.code,t.message):!1}function fd(e){return`ok`in e?e.ok?null:e.error:e.status===`failed`?e.error:null}function pd(e){if(e?.recovery===`runner_recycle_budget_exhausted`)return!0;let t=typeof e?.reason==`string`?e.reason:``;return t===`timeout_cleanup_pending`||m(t)?!0:t?ld(t):!1}function md(e,t){let n=`${e}\n${t}`.toLowerCase();return ud.some(e=>n.includes(e))}function hd(e){if(!e.ok)return{status:`failed`,error:e.error,artifactPaths:vd(e.error.details?.artifactPaths),warnings:Qt(e.error.details),infrastructure:dd(e),...e.error.details?.reason===`bounded_composite_resource_unsupported`?{stopRetries:!0}:{},...yd(e.error.details?.snapshotDiagnostics)};let t=e.data;return{status:`passed`,replayed:typeof t?.replayed==`number`?t.replayed:0,healed:typeof t?.healed==`number`?t.healed:0,warnings:Qt(t),artifactPaths:vd(t?.artifactPaths),...yd(t?.snapshotDiagnostics)}}function gd(e){if(!e||e.ok)return;let t=hd(e);return t.status===`failed`?t:void 0}function _d(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function vd(e){return[...new Set(_d(e))]}function yd(e){let t=S(e);return t?{snapshotDiagnostics:t}:{}}const bd=1e3,xd=3e3;function Sd(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await Cd(e)}}async function Cd(e){let{req:t,sessionName:n,sessionStore:r,artifactsDir:i,appendTimingEvent:a}=e;if(t.flags?.recordVideo!==!0)return;let o=r.get();if(!o||o.screenRecording)return;let s=tn(o.device.platform),c=i?G.join(i,`recording${s}`):en(o.device.platform);Z(a,{type:`video_recording_start`,session:n,videoPath:c}),D({phase:`replay_test_video_recording_start`,data:{session:n,videoPath:c}}),e.video.throwIfCanceled();let l=await e.video.record(Td({req:t,sessionName:n,phase:`start`,outputPath:c}));if(!l.ok)return Z(a,{type:`video_recording_start_failed`,session:n,videoPath:c,errorCode:l.error.code}),l;let u=Date.now();return await me(bd),Z(a,{type:`video_preroll_done`,session:n,durationMs:Date.now()-u,requestedDurationMs:bd}),D({phase:`replay_test_video_recording_preroll_done`,durationMs:Date.now()-u,data:{session:n,requestedDurationMs:bd}}),l}async function wd(e){let{req:t,sessionName:n,sessionStore:r,artifactPaths:i,appendTimingEvent:a}=e;if(t.flags?.recordVideo!==!0||!r.get()?.screenRecording)return;Z(a,{type:`video_tail_start`,session:n,requestedDurationMs:xd});let o=Date.now();await me(xd);let s=Date.now(),c=await e.video.record(Td({req:t,sessionName:n,phase:`stop`}));return jc(c).forEach(e=>i.add(e)),Z(a,{type:`video_recording_stop`,session:n,ok:c.ok,durationMs:Date.now()-s,tailDurationMs:s-o,errorCode:c.ok?void 0:c.error.code}),D({phase:`replay_test_video_recording_stop`,durationMs:Date.now()-s,data:{session:n,ok:c.ok,tailDurationMs:s-o}}),c}function Z(e,t){e({...t,ts:new Date().toISOString()})}function Td(e){let t={token:e.req.token,meta:e.req.meta};return e.phase===`start`?{request:t,sessionName:e.sessionName,phase:`start`,outputPath:e.outputPath}:{request:t,sessionName:e.sessionName,phase:`stop`}}const Ed=[{keys:[`replayKeepSession`],requested:e=>e.replayKeepSession===!0,message:`test does not support --keep-session; suite attempts own their cleanup. Run one native .ad script directly with replay --keep-session.`},{keys:[`replayFrom`,`replayPlanDigest`],requested:e=>e.replayFrom!==void 0||e.replayPlanDigest!==void 0,message:`test does not support --from/--plan-digest; resume is replay-only. Run the failing script directly with replay --from.`},{keys:[`saveScript`,`force`],requested:e=>!!e.saveScript||e.force===!0,message:`test does not support --save-script/--force; the agent-supervised repair loop is replay-only. Repair the failing script directly with replay --save-script.`}],Dd=({attemptId:e,parentAttemptId:t})=>{let n=Od(zn(e,t)?.controller,t);return{cancel:()=>Hn(e),release:()=>{n(),Ln(e)}}};function Od(e,t){if(!t||!e)return()=>{};let n=Rn(t);if(!n||n===e.signal)return()=>{};let r=()=>{e.abort(n.reason)};return n.aborted?(r(),()=>{}):(n.addEventListener(`abort`,r,{once:!0}),()=>{n.removeEventListener(`abort`,r)})}function kd(e){let{platform:t,target:n,artifactsDir:r,shard:i,sourceBundle:a}=e,o=Ad(e.parentFlags);return t===void 0&&n===void 0&&r===void 0&&i===void 0&&a===void 0?o:Yu({...o??{},...t===void 0?{}:{platform:t},...n===void 0?{}:{target:n},...r===void 0?{}:{artifactsDir:r},...a===void 0?{}:{replayScriptSource:a}},i)}function Ad(e){if(!e||e.recordVideo!==!0&&e.replayScriptSources===void 0)return e;let t={...e};return delete t.recordVideo,delete t.replayScriptSources,Object.keys(t).length>0?t:void 0}async function jd(e){let{request:t,session:{name:n,logPath:r},createSession:i,invoke:a,cleanupSession:o,video:c}=e;if(t.flags?.recordVideo===!0&&c===void 0)return d(`COMMAND_FAILED`,`Screen-recording runtime is not configured for replay video capture`);let l=t.flags??{};for(let e of Ed)if(e.requested(l))return d(`INVALID_ARGS`,e.message);let u,f;try{u=Fd(t,n,e.host.cwd),f=Pd(t)}catch(e){let t=s(e);return d(t.code,t.message)}let p=new Map(f.map(e=>[e.entry,e])),m=await Mu({request:u,emitProgress:Vn,isCanceled:()=>Bn(t.meta?.requestId),emitDiagnostic:D,bindAttemptCancellation:Dd,runReplay:async({filePath:n,sessionName:o,platform:s,target:l,requestId:u,artifactsDir:d,artifactPaths:f,tracePath:m,appendTimingEvent:h,shard:g,onStep:_})=>{let v=e=>(f&&jc(e).forEach(e=>f.add(e)),e),y=kd({parentFlags:t.flags,platform:s,target:l,artifactsDir:d,shard:g,sourceBundle:p.get(n)}),b=i(o,r),x=c?{req:t,sessionName:o,sessionStore:b.store,artifactsDir:d,appendTimingEvent:h,video:c}:void 0,S=x?Sd(x):void 0;return Md(hd(await zl({...Id(e,{request:{...t,command:`replay`,session:o,positionals:[n],flags:y,meta:{...t.meta??{},...u?{requestId:u}:{}}},openLifecycle:S}),session:b,tracePath:m,onStep:_,publicNetworkOnly:e.publicNetworkOnly,invoke:async e=>{let t=x?await Cd(x):void 0;return t&&!t.ok?t:v(await a(e))}})))},finalizeAttempt:async({sessionName:e,artifactPaths:n,artifactsDir:a,appendTimingEvent:o})=>{if(c)return gd(await wd({req:t,sessionName:e,sessionStore:i(e,r).store,artifactsDir:a,appendTimingEvent:o,artifactPaths:n,video:c}))},discoverSources:await ri(f,t.flags?.replayBackend),resolveShardTargets:qu(t.flags,e.host.env),cleanupSession:o});return m.status===`completed`?{ok:!0,data:Nd(m.data,t)}:d(m.error.code,m.error.message)}function Md(e){if(e.status!==`failed`||e.error.details?.reason!==`bounded_composite_resource_unsupported`)return e;let t=e.error.details,n=`Run the original test directly with its original paths and options in the live outer session, using the same --session value and private CLI context.`,r=t.divergence,i=r&&typeof r==`object`&&`cause`in r?r.cause:void 0,a=r&&typeof r==`object`&&`screen`in r?r.screen:void 0,o=r&&typeof r==`object`&&i&&typeof i==`object`?{...r,cause:{...i,hint:n},...a&&typeof a==`object`&&`state`in a&&a.state===`unavailable`?{screen:{...a,hint:n}}:{}}:r;return{...e,error:{...e.error,hint:n,details:{...t,divergence:o,standaloneCommandName:`test`}}}}function Nd(e,t){let n=t.meta?.clientArtifactPaths?.artifactsDir,r=e.artifactsDir;if(!n||!r)return e;let i=G.join(n,G.basename(r)),a=e=>e===r||e.startsWith(r+G.sep)?i+e.slice(r.length):e,o={...e,artifactsDir:i,tests:e.tests.map(e=>`artifactsDir`in e&&e.artifactsDir?{...e,artifactsDir:a(e.artifactsDir)}:e),failures:e.failures.map(e=>e.artifactsDir?{...e,artifactsDir:a(e.artifactsDir)}:e)};return W.existsSync(r)?{...o,artifacts:[{field:`artifactsDir`,artifactType:`test-artifacts`,path:r,localPath:n,fileName:G.basename(r)}]}:o}function Pd(e){let t=e.flags?.replayScriptSources;if(!t)throw new a(`INVALID_ARGS`,bn);return t}function Fd(e,t,n){let r=e.flags??{},i=e.meta?.cwd,a=Rd(r.artifactsDir);return{inputs:e.positionals??[],sessionName:t,cwd:i,requestId:e.meta?.requestId,platformFilter:r.platform,artifactsDir:a===void 0?void 0:F(a,i??n),failFast:r.failFast===!0,retries:Ld(r.retries),timeoutMs:Ld(r.timeoutMs),shard:od(r)}}function Id(e,t){let{host:n,publicNetworkOnly:r,resolvedSessionScope:i,dispatch:a,dependencies:o}=e,s=a||t.openLifecycle?{...a,...t.openLifecycle?{openLifecycle:t.openLifecycle}:{}}:void 0;return{request:t.request,host:n,...r?{publicNetworkOnly:r}:{},...i?{resolvedSessionScope:i}:{},...s?{dispatch:s}:{},dependencies:o}}function Ld(e){return typeof e==`number`?e:void 0}function Rd(e){return typeof e==`string`?e:void 0}function zd(e,t,n,r){return{name:e,logPath:t,store:{...n,assertSelectorMatches:r.assertSelectorMatches,resolveOpenRuntimeHints:r.resolveOpenRuntimeHints},observationStore:{get:n.get,bindAuthority:r.bindAuthority},coordinator:r.createCoordinator()}}function Bd(e){let{internal:t,...n}=e;return{request:n,...t?.publicNetworkOnly?{publicNetworkOnly:!0}:{},...t?.resolvedSessionScope?{resolvedSessionScope:t.resolvedSessionScope}:{}}}function Vd(e,t){let n=_({...e,...t});return Object.keys(n).length>0?n:void 0}function Hd(e,t){return async({dispatch:n,...r})=>{let i=Vd(t.internal,n);return await e(i?{...r,internal:i}:r)}}function Ud(e){let{sessionStore:t,mutationStore:n,hostCwd:r}=e,i=()=>t.get();return{view(){let e=i();if(e)return{repairBoundary:pt(e),pendingRecordAndHeal:e.pendingRecordAndHeal,scriptPublication:Wd(e.scriptPublication??zt)}},armStep(e){n.update(t=>{ct(t,{saveScript:e.saveScript,force:e.force,sourcePath:e.sourcePath,healedSiblingPath:Gr(e.sourcePath),firstArm:e.firstArm},r)})},demoteForRerunIfArmed(){pt(i())!==void 0&&n.update(dt)},markCompleteIfArmed(){pt(i())!==void 0&&n.update(ut)},markSessionHeldIfArmed(e){if(e.ok||!lt(i()))return e;let t=an(e.error.details?.divergence);return t&&(t.repairSessionHeld=!0),e},clearTombstone(){n.clearRepairTombstone()},clearCorrectiveWatermarkIfExpected(e){i()?.pendingRecordAndHeal?.expectedFrom===e&&n.update(t=>{t.pendingRecordAndHeal?.expectedFrom===e&&Kd(t)})},resumeStamper:{sessionExists:()=>i()!==void 0,stampCorrectiveWatermark(e){n.update(t=>{Gd({session:t,...e})})}}}}function Wd(e){return{kind:e.kind,status:e.kind===`none`?void 0:e.status,targetPath:At(e),targetForce:It(e)}}function Gd(e){let{session:t,resume:n,repairHint:r,failedIndex:i,actions:a}=e;t.pendingRecordAndHeal=qd({resume:n,repairHint:r,failedIndex:i,actions:a,actionsCountAtDivergence:t.actions.length})}function Kd(e){e.pendingRecordAndHeal=void 0}function qd(e){let{resume:t,repairHint:n,failedIndex:r,actions:i,actionsCountAtDivergence:a}=e;if(n===`record-and-heal`)return t.allowed?{expectedFrom:t.from,actionsCountAtDivergence:a}:void 0;if((n===`caution`||n===`manual`)&&r===i.length)return{expectedFrom:r+1,actionsCountAtDivergence:a}}function Jd(e){let{sessionStore:t,bindDevice:n,platformServices:r,bindExactDevice:i,screenRecordingAdmissionLedger:a,requestScope:o,retainDeviceExecutionLock:s,throwIfCanceled:c}=e;return!n||!i||!a||!o||!s||!c?void 0:{throwIfCanceled:c,record:async e=>await Ir({req:Yd(e),sessionName:e.sessionName,sessionStore:t,bindDevice:n,platformServices:r,bindExactDevice:i,admissionLedger:a,requestScope:o,retainDeviceExecutionLock:s,throwIfCanceled:c})}}function Yd(e){return{token:e.request.token,session:e.sessionName,command:`record`,positionals:e.phase===`start`?[`start`,e.outputPath]:[`stop`],flags:{},meta:e.request.meta}}const Xd={resolveSessionScope:Kt},Zd=async({req:e,host:t,sessionName:n,logPath:r,sessionStore:i,invoke:a,invokeReplayAction:o})=>await zl({...Bd(e),host:t,session:$d(n,r,i),invoke:Hd(o??a,e),dependencies:Xd}),Qd=async({host:e,req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:o,invoke:s,invokeReplayAction:c,bindDevice:l,platformServices:u,inspectFacts:d,bindExactDevice:f,screenRecordingAdmissionLedger:p,requestScope:m,retainDeviceExecutionLock:h,throwIfCanceled:g,platformResourceCleanup:_})=>{if(!_)throw new a(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let v=Jd({sessionStore:i,bindDevice:l,platformServices:u,bindExactDevice:f,screenRecordingAdmissionLedger:p,requestScope:m,retainDeviceExecutionLock:h,throwIfCanceled:g});return await jd({...Bd(t),host:e,session:$d(n,r,i),createSession:(e,t)=>$d(e,t,i),invoke:Hd(c??s,t),dependencies:Xd,cleanupSession:async n=>await ef({host:e,req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:o,inspectFacts:d,bindDevice:l,platformServices:u,platformResourceCleanup:_}),...v?{video:v}:{}})};function $d(e,t,n){let r=t=>{let r=n.get(e);return r?(t(r),!0):!1},i={get:()=>n.get(e),lookup:()=>n.lookup(e),getRuntimeHints:()=>n.getRuntimeHints(e),ensureSessionDir:()=>n.ensureSessionDir(e)};return zd(e,t,i,{createCoordinator:()=>Ud({sessionStore:i,mutationStore:{update:r,clearRepairTombstone:()=>n.clearRepairTombstone(e)},hostCwd:n.host.cwd}),assertSelectorMatches:t=>{let r=n.lookup(e);r&&ir(r,t)},resolveOpenRuntimeHints:({request:t,device:r,platform:i})=>Jn({req:t,sessionStore:{getRuntimeHints:t=>t===e?n.getRuntimeHints(e):void 0},sessionName:e,device:r,platform:i}),bindAuthority:t=>{let r=n.lookup(e);return{...Gs({sessionStore:n,ref:r,signal:t}),capture:async({flags:i,logPath:o})=>{let s=r?n.requireCurrent(r):void 0;if(!s)throw new a(`NO_ACTIVE_SESSION`,`Session "${e}" is no longer active.`);return await xr({device:s.device,session:s,flags:i,logPath:o,signal:t})}}}})}async function ef(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e;if(!i.get(n))return;let o=await Ba({host:e.host,req:Jt({token:t.token,session:n,command:`close`,positionals:[],flags:{},meta:t.meta,internal:{cleanupIntent:`suite-owned-test-session`}},t),sessionName:n,logPath:r,sessionStore:i,leaseRegistry:e.leaseRegistry,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,platformResourceCleanup:e.platformResourceCleanup});if(!o.ok)throw new a(o.error.code,o.error.message,{...o.error.details??{},...o.error.hint?{hint:o.error.hint}:{}})}function tf(e){let{req:t,sessionName:n,sessionStore:r}=e;if(t.command!==oe.sessionSaveScript)return null;if((t.positionals?.length??0)>1)return Q(new a(`INVALID_ARGS`,`session save-script accepts at most one output path.`));let i=r.lookup(n);if(!i)return Q(new a(`SESSION_NOT_FOUND`,`No active session "${n}".`,{hint:`Start a fresh journey with open <app> --save-script[=<path>], then retry.`}));let o=r.requireCurrent(i),s=af(o);if(s)return Q(s);let c=t.positionals?.[0]?.trim();if(t.positionals?.[0]!==void 0&&!c)return Q(new a(`INVALID_ARGS`,`session save-script path cannot be empty.`));Rt(o,{explicitPath:c,liveForce:t.flags?.force},r.host.cwd);let l=r.writeSessionLog(i,{force:Nt(o,t.flags?.force),publication:`active`});return l.written?(Pt(o,l.path),{ok:!0,data:{session:o.name,savedScript:l.path,actionCount:l.actionCount,...P(`Published script: ${l.path}`)}}):Q(l.error??new a(`COMMAND_FAILED`,`The active session script was not published.`,{retriable:!0,hint:`The session remains armed; retry session save-script.`}))}function nf(e){if(gt(e))return`repair`;let t=e.scriptPublication;return t?.kind===`authoring`&&t.status!==`armed`?t.status:Lt(e)?void 0:`not-armed`}const rf={repair:()=>new a(`COMMAND_FAILED`,`This session has an active .ad repair transaction and cannot use ordinary active-session publication.`,{hint:`Finish or abort the repair through replay --from and its existing close/teardown protocol.`}),aborted:()=>new a(`COMMAND_FAILED`,`This script recording was aborted by a second successful open and cannot be published.`,{hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`}),published:()=>new a(`COMMAND_FAILED`,`This script recording has already been published.`,{hint:`Continue using the live session, or close it and start a fresh authoring session.`}),"not-armed":()=>new a(`COMMAND_FAILED`,`Script recording was not armed before this journey began; session history cannot be published without recording-time target evidence.`,{hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`})};function af(e){let t=nf(e);return t?rf[t]():void 0}function Q(e){return{ok:!1,error:f(e)}}function of(e){let t=(e[0]??``).toLowerCase();return t===`read`||t===`write`?t:void 0}function sf(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:kn(e)}}async function cf(e,t,n){if(n.length!==1)throw new a(`INVALID_ARGS`,`clipboard read does not accept additional arguments`);return{action:`read`,text:await e.operations.readClipboard(sf(t))}}async function lf(e,t,n){if(n.length<2)throw new a(`INVALID_ARGS`,`clipboard write requires text (use "" to clear clipboard)`);let r=n.slice(1).join(` `),i={...sf(t),text:r};return await e.operations.writeClipboard(i),{action:`write`,textLength:Array.from(r).length,...P(`Clipboard updated`)}}async function uf(e){let{device:t,action:n,positionals:r,inspectFacts:i,bindDevice:a,platformServices:o}=e;if(n===`read`){let e=await R({command:`clipboard`,device:t,use:ot,inspectFacts:i,bindDevice:a,platformServices:o,readiness:!0});if(e.type===`response`)return{ok:!1,response:e.response};let n=e.runtime;return{ok:!0,execute:e=>cf(n,e,r)}}let s=await R({command:`clipboard`,device:t,use:Be,inspectFacts:i,bindDevice:a,platformServices:o,readiness:!0});if(s.type===`response`)return{ok:!1,response:s.response};let c=s.runtime;return{ok:!0,execute:e=>lf(c,e,r)}}async function df(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,c=i.lookup(n),l=c?.session,u=t.flags??{},f=H(T.clipboard,l,u);if(f)return f;let p=t.positionals??[],m=of(p);if(!m)return d(`INVALID_ARGS`,`clipboard requires a subcommand: read or write`);let h=await U({session:l,flags:u,env:i.host.env,platformServices:s});c&&i.requireCurrent(c);let g=await uf({device:h,action:m,positionals:p,inspectFacts:a,bindDevice:o,platformServices:s});if(!g.ok)return g.response;let _=c?i.requireCurrent(c):void 0,v=await g.execute(An(r,t.flags,_?.appBundleId,_?.trace?.outPath));return M(i,c,t,t.command,v),{ok:!0,data:{platform:k(h),...v}}}function ff(e){return e.some(e=>e.status===`fail`)?`fail`:e.some(e=>e.status===`warn`)?`warn`:`pass`}function pf(e){return e===`fail`?`Blockers found before the run.`:e===`warn`?`No hard blockers found, but warnings need attention.`:`No blockers found.`}function mf(e){let t={fail:0,warn:1,pass:2,info:3};return[...e].sort((e,n)=>t[e.status]-t[n.status])}function hf(e,t,...n){for(let r of n)$(e,r,t)}function $(e,t,n){e.push(t),Vn({type:`command`,status:`progress`,message:gf(t,n)})}function gf(e,t){return[oi(e,{useColor:t}),...ai(e)].join(`
|
|
3
|
-
`)}async function _f(e,t){let{device:n,targetApp:r,session:i,listInstalledApps:a,useColor:o}=t;if(r)try{let t=a?vf(r,await a(`all`))?.id:void 0;if(!t){$(e,{id:`target-app`,status:`info`,summary:`Target app installation checks are not supported for ${
|
|
1
|
+
import{$ as e,A as t,C as n,N as r,Q as i,R as a,T as o,V as s,f as c,n as l,p as u,s as d,tt as f,w as p}from"./sdk-contracts.js";import{U as m,V as h,z as g}from"./tv-remote.js";import{M as _,n as v,t as y,y as b}from"./sdk-batch-runner.js";import{a as x,n as S,t as C}from"./snapshot-diagnostics.js";import{$ as w,A as ee,E as T,F as te,G as ne,I as re,M as E,N as ie,R as ae,T as oe,Y as se,at as ce,et as le,j as ue,k as de,m as fe,tt as pe}from"./back-mode.js";import{H as me,Q as he,St as ge,_t as D}from"./sdk-io.js";import"./diagnostics.js";import{D as _e,L as O,N as ve,P as ye,T as k,V as be,b as A,v as xe,w as j}from"./sdk-device.js";import{B as Se,Ct as Ce,D as we,Dr as Te,Er as Ee,F as De,Fn as Oe,Ft as ke,H as Ae,In as je,L as Me,Ln as Ne,M as Pe,Nt as Fe,P as Ie,Pt as Le,Q as Re,Qt as ze,R as Be,Tr as Ve,U as He,V as Ue,W as We,Z as Ge,_t as Ke,ar as qe,at as Je,cn as Ye,cr as Xe,et as Ze,ht as Qe,mr as $e,mt as et,nt as tt,rt as nt,sr as rt,tt as it,v as at,wt as ot,z as st}from"./sdk-batch.js";import{c as ct,d as lt,f as ut,h as dt,l as ft,m as pt,o as M,p as mt,s as ht,u as gt}from"./session-store.js";import{a as _t,i as vt,n as yt,o as bt,t as xt}from"./target-evidence.js";import{a as St,i as Ct,n as wt,o as Tt,r as Et,s as Dt,t as Ot}from"./vars.js";import{F as kt,M as At,N as jt,_ as Mt,f as Nt,g as Pt,h as Ft,j as It,p as Lt,v as Rt,y as zt}from"./parameterized-recorded-fill.js";import{n as Bt,r as Vt,t as Ht}from"./target-evidence-tree.js";import{C as Ut,H as Wt,I as Gt,O as Kt,R as qt,S as Jt,_ as Yt,h as Xt,k as Zt,m as Qt,o as $t,p as en,s as tn,w as nn,x as rn,y as an}from"./src.js";import{g as on,i as sn}from"./observability.js";import{i as N,n as cn,r as P}from"./success-text.js";import{t as ln}from"./app-inventory.js";import{o as un,s as dn}from"./transport.js";import{n as fn,r as pn}from"./output-path.js";import"./command.js";import{t as F}from"./session-paths.js";import{c as mn,l as hn}from"./session-artifact-paths.js";import{a as gn}from"./version.js";import"./retry.js";import{i as _n,n as vn}from"./replay-divergence.js";import{n as yn,t as bn}from"./deploy-result-target.js";import{c as xn,d as Sn,f as Cn,l as wn,o as Tn,p as En,s as Dn,u as On}from"./screen-recording-session-resource.js";import{t as kn}from"./keyboard-actions.js";import{a as An,c as jn,h as Mn,o as Nn,r as Pn}from"./replay-script-selection.js";import{a as Fn,n as In}from"./artifact-tracking.js";import{n as Ln}from"./provider-device-admission.js";import{d as Rn,n as zn,o as I,r as Bn,u as Vn}from"./snapshot-runtime-capture-input.js";import{a as Hn,d as Un,i as Wn,m as Gn,p as Kn}from"./device-claims.js";import{a as qn,c as Jn,d as Yn,l as Xn,t as Zn,u as Qn}from"./request.js";import{i as $n,o as er}from"./lease-context.js";import{p as tr}from"./daemon-command-registry.js";import{a as nr,n as rr,o as ir,r as ar,s as or,t as sr,u as cr}from"./session-runtime.js";import{n as L}from"./device-isolation.js";import{a as lr,n as ur,o as dr,r as fr}from"./device-inventory-context.js";import{l as pr}from"./selector-pipeline-policy.js";import{t as mr}from"./session-selector.js";import{i as hr,n as R,t as gr}from"./runtime-admission.js";import{c as _r,f as vr,r as yr}from"./runtime-session.js";import{n as br}from"./snapshot-node-lookup.js";import{a as xr,i as z,n as B,r as V,t as Sr}from"./session-runtime-admission.js";import{n as Cr}from"./gesture-runtime.js";import{a as wr,c as Tr,i as Er,l as Dr,o as Or,r as kr,s as Ar,t as jr}from"./app-log-session-resource.js";import{n as Mr}from"./device-selection-resolver.js";import{a as Nr,i as H,n as U,o as Pr,r as Fr}from"./session-device-resolution.js";import{t as Ir}from"./record-runtime.js";import{handleSessionOpenCommands as Lr,n as Rr,r as zr,t as Br}from"./session-open.js";import{t as Vr}from"./audio-probe-result.js";import{a as Hr,c as Ur,d as Wr,g as Gr,h as Kr,l as qr,m as Jr,n as Yr,o as Xr,p as Zr,r as Qr,t as $r,u as ei}from"./session-replay-vars.js";import{n as ti}from"./replay.js";import{t as ni}from"./replay-backend-registry.js";import{t as ri}from"./session-test-source-discovery.js";import{n as ii}from"./status-markers.js";import{n as ai,r as oi}from"./doctor-lines.js";import{t as si}from"./project-runtime.js";import{createHash as ci,randomUUID as li}from"node:crypto";import W,{promises as ui}from"node:fs";import G from"node:path";import{setTimeout as di}from"node:timers/promises";function fi(e){throw new a(`UNSUPPORTED_OPERATION`,`install_from_source ${String(e.kind)} sources require a compatible remote daemon`)}function pi(e){let t=e.meta?.installSource;if(!t)throw new a(`INVALID_ARGS`,`install_from_source requires a source payload`);switch(t.kind){case`url`:if(!t.url||t.url.trim().length===0)throw new a(`INVALID_ARGS`,`install_from_source url source requires a non-empty url`);return t;case`path`:if(!t.path||t.path.trim().length===0)throw new a(`INVALID_ARGS`,`install_from_source path source requires a non-empty path`);return t;case`github-actions-artifact`:throw new a(`UNSUPPORTED_OPERATION`,`install_from_source github-actions-artifact sources require a compatible remote daemon`);default:fi(t)}}function mi(e){let t=pi(e),n=e.meta?.uploadedArtifactId;return!n||t.kind!==`path`?{source:t,cleanup:()=>{}}:{source:{kind:`path`,path:Fn(n,e.meta?.tenantId)},cleanup:()=>{In(n)}}}async function hi(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o,s,c;try{o=mi(t);let l=yi(t),u=await _i(a,t.flags,r.host.env,e.platformServices),d=await V(e.inspectFacts)(u),f=z(`install_from_source`,d.operations.ensureReady)??z(`install_from_source`,d.operations.materializeAppSource)??z(`install_from_source`,d.operations.deployMaterializedApp);if(f)return f;let p=await B(e.bindDevice)(u,it);await p.operations.ensureReady({}),s=await p.operations.materializeAppSource({source:o.source}),c=await bi({artifact:s,retention:l,req:t,session:a,sessionName:n}),i&&I(r.requireCurrent(i));let m=await p.operations.deployMaterializedApp({artifact:s}),h=xi(u,s,m,c),g=N(h,`Installed: ${yn(h)}`);return M(r,i,t,`install_source`,g,{positionals:[]}),{ok:!0,data:g}}catch(e){return c&&await rn(c.materializationId,t.meta?.tenantId).catch(()=>{}),{ok:!1,error:f(e)}}finally{await s?.cleanup(),o?.cleanup()}}async function gi(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new a(`INVALID_ARGS`,`release_materialized_paths requires a materializationId`);return await rn(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:f(e)}}}async function _i(e,t,n,r){let i=vi(t?.platform);if(e&&i&&!ye(e.device,i))throw new a(`INVALID_ARGS`,`install_from_source requested platform ${i}, but session is bound to ${O(e.device)}`);if(!e&&!i)throw new a(`INVALID_ARGS`,`install_from_source requires platform "ios" or "android" when no session is provided`);return e?e.device:await H({session:e,flags:t,env:n,platformServices:r})}function vi(e){return e===`ios`||e===`android`?e:void 0}function yi(e){let t=e.meta?.retainMaterializedPaths===!0,n=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(n!==void 0&&n<=0)throw new a(`INVALID_ARGS`,`install_from_source retentionMs must be a positive integer`);return{enabled:!0,...n===void 0?{}:{ttlMs:n}}}async function bi(e){if(e.retention.enabled)return await Ut({archivePath:e.artifact.archivePath,installablePath:e.artifact.installablePath,tenantId:e.req.meta?.tenantId,sessionName:e.session?e.sessionName:void 0,ttlMs:e.retention.ttlMs})}function xi(e,t,n,r){return j(e)?Si(t,n,r):Ci(t,n,r)}function Si(e,t,n){let r=t.bundleId??e.bundleId;if(!r)throw new a(`COMMAND_FAILED`,`Installed iOS app identity could not be resolved from the artifact`);return{...Ti(n),bundleId:r,...wi(t,e),launchTarget:t.launchTarget??r}}function Ci(e,t,n){let r=t.packageName??t.launchTarget??e.packageName;if(!r)throw new a(`COMMAND_FAILED`,`Installed Android app identity could not be resolved from the artifact or device state`);return{...Ti(n),packageName:r,...wi(t,e),launchTarget:t.launchTarget??r}}function wi(e,t){let n=e.appName??t.appName;return n?{appName:n}:{}}function Ti(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function Ei(e){let{req:t,session:n,inspectFacts:r,bindDevice:i,platformServices:a}=e,o=Di(t);if(!o.ok)return o.response;let s=U(`runtime port-reverse`,n,t.flags);if(s)return s;let c=await H({session:n,flags:t.flags,env:e.env,platformServices:e.platformServices}),l=await R({device:c,inspectFacts:r,bindDevice:i,platformServices:a,command:`runtime port-reverse`,use:We});if(l.type===`response`)return l.response;if(l.runtime.owner.kind!==`provider-runtime`||l.runtime.owner.provider!==o.options.provider)return d(`UNSUPPORTED_OPERATION`,`The selected device is not owned by the requested port-reverse provider.`,{provider:o.options.provider});let u=await l.runtime.operations.configureProviderPortReverse(o.options);return u?{ok:!0,data:{action:`port-reverse`,...u}}:d(`UNSUPPORTED_OPERATION`,`The selected provider device runtime does not support port reverse for this lease.`)}function Di(e){let t=Oi(e);if(!t.ok)return t;let n=ki(e);return n.ok?{ok:!0,options:{leaseId:t.leaseId,provider:t.provider,devicePort:n.devicePort,hostPort:n.hostPort,name:e.flags?.portReverseName?.trim()||`runtime`}}:n}function Oi(e){let t=e.flags?.leaseId,n=e.flags?.leaseProvider;return t?n?{ok:!0,leaseId:t,provider:n}:{ok:!1,response:d(`INVALID_ARGS`,`runtime port-reverse requires a lease provider.`)}:{ok:!1,response:d(`INVALID_ARGS`,`runtime port-reverse requires a resolved remote lease.`)}}function ki(e){let t=Ai(e.flags?.devicePort),n=Ai(e.flags?.hostPort??e.flags?.devicePort);return!t||!n?{ok:!1,response:d(`INVALID_ARGS`,`runtime port-reverse requires numeric devicePort and hostPort values from 1 to 65535.`)}:{ok:!0,devicePort:t,hostPort:n}}function Ai(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<1||e>65535))return e}async function ji(e){return await R({...e,command:`runtime clear`,use:Ue})}async function Mi(e){let{req:t,sessionName:n,sessionStore:r}=e,i=(t.positionals?.[0]??`show`).toLowerCase();if(i===`port-reverse`)return await Ei({req:t,session:r.get(n),env:r.host.env,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(i===`gesture-viewport`)return await Ni({...e,session:r.get(n)});if(!Pi(i))return d(`INVALID_ARGS`,`runtime requires set, show, clear, port-reverse, or gesture-viewport`);let a=r.lookup(n),o=a?.session,s=r.getRuntimeHints(n);return i===`clear`?await Fi({sessionName:n,sessionStore:r,ref:a,current:s,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice}):i===`show`?Ii(n,s):Ri({req:t,sessionName:n,sessionStore:r,session:o,current:s})}async function Ni(e){if(!e.session)return d(`SESSION_NOT_FOUND`,`No active session. Run open first.`);let t=await Cr({device:e.session.device,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(!t.ok)return t.response;let n=Bn(e.logPath,e.req.flags,e.session.appBundleId,e.session.trace?.outPath,e.req.meta?.requestId,e.req.meta);return{ok:!0,data:{viewport:await t.read(n)}}}function Pi(e){return e===`set`||e===`show`||e===`clear`}async function Fi(e){let{sessionName:t,sessionStore:n,ref:r,current:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,c=r?n.requireCurrent(r):void 0;if(ar(i)&&c?.appBundleId){let e=await ji({device:c.device,inspectFacts:a,bindDevice:o,platformServices:s});if(e.type===`response`)return e.response;let t=n.requireCurrent(r);I(t),await e.runtime.operations.clearRuntimeHints({appId:t.appBundleId,values:or(i)})}let l=r?n.clearRuntimeHints(r):!!i;return r||n.setRuntimeHints(t,void 0),{ok:!0,data:{session:t,cleared:l}}}function Ii(e,t){return{ok:!0,data:{session:e,configured:!!t,runtime:t}}}function Li(e){return e?O(e.device):void 0}function Ri(e){let{req:t,sessionName:n,sessionStore:r,session:i,current:a}=e,o=Li(i),s=cr(t.flags?.platform??a?.platform??o);if(!s)return d(`INVALID_ARGS`,`runtime set only supports iOS, Android, and HarmonyOS sessions. Pass --platform ios|android|harmonyos or open a supported session first.`);if(o!==void 0&&o!==s)return d(`INVALID_ARGS`,`runtime set targets ${s}, but session "${n}" is already bound to ${o}.`);let c=nr(a,sr(t.flags,s));return rr(c)===0?d(`INVALID_ARGS`,`runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url.`):(r.setRuntimeHints(n,c),{ok:!0,data:{session:n,configured:!0,runtime:c}})}const zi=/^[A-Za-z0-9_.:-]{1,64}$/,Bi=8192,Vi=4096;function Hi(e){let t=e[0]?.trim(),n=e[1]?.trim();if(!t)throw new a(`INVALID_ARGS`,`trigger-app-event requires <event> [payloadJson]`);if(!zi.test(t))throw new a(`INVALID_ARGS`,`Invalid trigger-app-event event name: ${t}`,{hint:`Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash.`});if(e.length>2)throw new a(`INVALID_ARGS`,`trigger-app-event accepts at most two arguments: <event> [payloadJson]`);return{eventName:t,payload:Wi(n,t)}}function Ui(e,t,n,r){let i=O(e),o=Gi(e,r);if(!o)throw new a(`UNSUPPORTED_OPERATION`,`No app event URL template configured for ${i}.`,{hint:`Set AGENT_DEVICE_${i.toUpperCase()}_APP_EVENT_URL_TEMPLATE or AGENT_DEVICE_APP_EVENT_URL_TEMPLATE, for example "myapp://agent-device/event?name={event}&payload={payload}".`});let s=n?JSON.stringify(n):``,c=o.replaceAll(`{event}`,encodeURIComponent(t)).replaceAll(`{payload}`,encodeURIComponent(s)).replaceAll(`{platform}`,encodeURIComponent(i));if(c.length>Vi)throw new a(`INVALID_ARGS`,`trigger-app-event URL exceeds maximum supported length`,{hint:`Reduce payload size or shorten AGENT_DEVICE_*_APP_EVENT_URL_TEMPLATE.`,length:c.length,maxLength:Vi});return c}function Wi(e,t){if(e)try{let n=JSON.parse(e);if(!n||typeof n!=`object`||Array.isArray(n))throw new a(`INVALID_ARGS`,`trigger-app-event payload for "${t}" must be a JSON object`);let r=JSON.stringify(n);if(Buffer.byteLength(r,`utf8`)>Bi)throw new a(`INVALID_ARGS`,`trigger-app-event payload for "${t}" exceeds ${Bi} bytes`);return n}catch(t){throw t instanceof a?t:new a(`INVALID_ARGS`,`Invalid trigger-app-event payload JSON: ${e}`)}}function Gi(e,t){return((j(e)?t.AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE:k(e)?t.AGENT_DEVICE_MACOS_APP_EVENT_URL_TEMPLATE:t.AGENT_DEVICE_ANDROID_APP_EVENT_URL_TEMPLATE)??t.AGENT_DEVICE_APP_EVENT_URL_TEMPLATE)?.trim()||void 0}async function Ki(e,t,n,r,i){let{eventName:a,payload:o}=Hi([...r]),s=Ui(t,a,o,i),c={eventUrl:s,...n.appBundleId===void 0?{}:{options:{appBundleId:n.appBundleId}},execution:zn(n)};return await e.operations.triggerAppEvent(c),{event:a,eventUrl:s,transport:`deep-link`,...P(`Triggered app event: ${a}`)}}async function qi(e){let{host:t,device:n,positionals:r,inspectFacts:i,bindDevice:a,platformServices:o,readiness:s}=e,c=await R({command:`trigger-app-event`,device:n,use:et,inspectFacts:i,bindDevice:a,platformServices:o,readiness:s});if(c.type===`response`)return{ok:!1,response:c.response};let l=c.runtime;return{ok:!0,execute:e=>Ki(l,n,e,r,t.env)}}function Ji(e){let t=(e[0]??`status`).toLowerCase();if(!kn(t))throw new a(`INVALID_ARGS`,`keyboard requires a subcommand: status, get, dismiss, enter, or return`);if(e.length>1)throw new a(`INVALID_ARGS`,`keyboard accepts at most one subcommand argument`);return Yi(t)}function Yi(e){return e===`get`?`status`:e===`return`?`enter`:e}const Xi={"ime-probe":`android`},Zi={"ime-probe":`android`,mechanism:`ios`,acknowledged:`harmonyos`},Qi={"visibility-echo":`ios`,"android-acknowledged":`android`,"harmonyos-acknowledged":`harmonyos`};function $i(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:zn(e)}}async function ea(e,t){let n=await R(e);if(n.type===`response`)return{ok:!1,response:n.response};let r=n.runtime;return{ok:!0,execute:e=>t(r,e)}}function ta(e,t){return e.operations.keyboardStatus($i(t)).then(e=>({platform:Xi[e.kind],action:`status`,visible:e.visible,inputType:e.inputType,type:e.type,inputMethodPackage:e.inputMethodPackage,focusedPackage:e.focusedPackage,focusedResourceId:e.focusedResourceId,inputOwner:e.inputOwner}))}async function na(e,t){let n=await e.operations.keyboardDismiss($i(t)),r=Zi[n.kind];return n.kind===`mechanism`?{platform:r,action:`dismiss`,wasVisible:n.wasVisible,dismissed:n.dismissed,visible:n.visible,mechanism:n.mechanism,...P(aa(n.dismissed===!0,n.mechanism))}:n.kind===`acknowledged`?{platform:r,action:`dismiss`,...P(`Keyboard dismissed`)}:{platform:r,action:`dismiss`,attempts:n.attempts,wasVisible:n.wasVisible,dismissed:n.dismissed,visible:n.visible,inputType:n.inputType,type:n.type,inputMethodPackage:n.inputMethodPackage,focusedPackage:n.focusedPackage,focusedResourceId:n.focusedResourceId,inputOwner:n.inputOwner}}async function ra(e,t){let n=await e.operations.keyboardEnter($i(t)),r=Qi[n.kind];return n.kind===`visibility-echo`?{platform:r,action:`enter`,visible:n.visible,wasVisible:n.wasVisible,...P(`Keyboard enter pressed`)}:{platform:r,action:`enter`,...P(`Keyboard enter pressed`)}}async function ia(e){let t=Ji(e.positionals),{device:n,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o}=e;return t===`status`?await ea({command:`keyboard status`,device:n,use:ke,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o},(e,t)=>ta(e,t)):t===`dismiss`?await ea({command:`keyboard dismiss`,device:n,use:Fe,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o},(e,t)=>na(e,t)):await ea({command:`keyboard enter`,device:n,use:Le,inspectFacts:r,bindDevice:i,platformServices:a,readiness:o},(e,t)=>ra(e,t))}function aa(e,t){return e?t===`dismissKey`?`Keyboard dismissed via its dismiss key`:`Keyboard dismissed`:`Keyboard already hidden`}async function oa(e){let{req:t,sessionName:n,sessionStore:r,command:i,positionals:a,recordPositionals:o,updateSession:s,prepare:c}=e,l=r.lookup(n),u=l?.session,d=t.flags??{},f=U(i,u,d);if(f)return f;let p=await H({session:u,flags:d,env:r.host.env,platformServices:e.platformServices});l&&r.requireCurrent(l);let m=await c(p,l);if(!m.ok)return m.response;let h=l?r.requireCurrent(l):void 0;h&&tr(t)===`may-invalidate`&&I(h);let g=await m.execute();return l&&(s&&await s(l,g),M(r,l,t,i,g??{},{positionals:o??a})),{ok:!0,data:g??{}}}function sa(e,t,n){if(!(e||t!==`dismiss`&&t!==`enter`&&t!==`return`||n?.platform!==`ios`))return d(`SESSION_NOT_FOUND`,`iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.`)}async function ca(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,c=t.positionals??[];return await oa({req:t,sessionName:n,sessionStore:i,command:e.command,positionals:c,platformServices:s,...e.updateSession?{updateSession:e.updateSession}:{},prepare:async(n,l)=>{let u=await e.resolveRuntime({host:e.host,device:n,positionals:c,readiness:!0,inspectFacts:a,bindDevice:o,platformServices:s});if(!u.ok)return{ok:!1,response:u.response};let d=l?i.requireCurrent(l):void 0,f={...Bn(r,t.flags,d?.appBundleId,d?.trace?.outPath),surface:d?.surface};return{ok:!0,execute:()=>u.execute(f)}}})}async function la(e){return sa(e.sessionStore.get(e.sessionName),e.req.positionals?.[0]?.trim().toLowerCase(),e.req.flags??{})||await ca({...e,command:T.keyboard,resolveRuntime:e=>ia(e)})}async function ua(e){return await ca({...e,command:T.triggerAppEvent,resolveRuntime:e=>qi(e),updateSession:async(t,n)=>{let r=typeof n?.eventUrl==`string`?n.eventUrl:void 0;if(!r)return;let i=e.sessionStore.requireCurrent(t),a=await e.platformServices.resolveSessionAppBundleIdForTarget(i.device,r,i.appBundleId);a!==void 0&&e.sessionStore.update(t,{appBundleId:a})}})}function da(e){let t=e.trim();return t.startsWith(`{`)&&t.endsWith(`}`)||t.startsWith(`[`)&&t.endsWith(`]`)}function fa(e,t){let n=t?.subject??`Payload`,r=e.trim();if(!r)throw new a(`INVALID_ARGS`,`${n} cannot be empty`);let i=t?.expandPath?t.expandPath(r,t.cwd):r;try{if(!W.statSync(i).isFile())throw new a(`INVALID_ARGS`,`${n} path is not a file: ${i}`);return{kind:`file`,path:i}}catch(e){if(e instanceof a)throw e;let t=e.code;if(t===`EACCES`||t===`EPERM`)throw new a(`INVALID_ARGS`,`${n} file is not readable: ${i}`);if(t&&t!==`ENOENT`)throw new a(`COMMAND_FAILED`,`Unable to read ${n} file: ${i}`,{cause:String(e)})}if(da(r))return{kind:`inline`,text:r};throw new a(`INVALID_ARGS`,`${n} file not found: ${i}`)}async function pa(e){let t=fa(e,{subject:`Push payload`}),n=t.kind===`inline`?t.text:await ma(t.path);try{let e=JSON.parse(n);if(!e||typeof e!=`object`||Array.isArray(e))throw new a(`INVALID_ARGS`,`push payload must be a JSON object`);return e}catch(t){throw t instanceof a?t:new a(`INVALID_ARGS`,`Invalid push payload JSON: ${e}`)}}async function ma(e){try{return await ui.readFile(e,`utf8`)}catch(t){let n=t.code;throw n===`ENOENT`?new a(`INVALID_ARGS`,`Push payload file not found: ${e}`):n===`EISDIR`?new a(`INVALID_ARGS`,`Push payload path is not a file: ${e}`):n===`EACCES`||n===`EPERM`?new a(`INVALID_ARGS`,`Push payload file is not readable: ${e}`):new a(`COMMAND_FAILED`,`Unable to read push payload file: ${e}`,{cause:String(t)})}}async function ha(e){let{req:t,command:n,sessionName:r,sessionStore:i}=e,a=i.lookup(r),o=a?.session,s=t.flags??{},c=U(n,o,s);if(c)return c;let l=Sa(n,t.positionals??[]);if(!l.ok)return l.response;let u=t.meta?.uploadedArtifactId;try{let r=u?Fn(u,t.meta?.tenantId):F(l.appPathInput,e.host.cwd);if(!W.existsSync(r))return d(`INVALID_ARGS`,`App binary not found: ${r}`);let c=await H({session:o,flags:s,env:i.host.env,platformServices:e.platformServices}),f=await V(e.inspectFacts)(c),p=z(n,f.operations.deployApp);if(p)return p;let m=await B(e.bindDevice)(c,Ze);a&&I(i.requireCurrent(a));let h=await m.operations.deployApp({app:l.app,appPath:r,replaceExisting:n===`reinstall`}),g=va(c,l.app,r,h),_=N(g,`Installed: ${g.appName??bn(g)}`);return xa(i,a,g),M(i,a,t,n,_),{ok:!0,data:_}}finally{u&&In(u)}}async function ga(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o=t.flags??{},s=U(`push`,a,o);if(s)return s;let c=t.positionals?.[0]?.trim(),l=t.positionals?.[1]?.trim();if(!c||!l)return d(`INVALID_ARGS`,`push requires <bundle|package> <payload.json|inline-json>`);let u=await pa(Ca(l,t.meta?.cwd??e.host.cwd)),f=await H({session:a,flags:o,env:r.host.env,platformServices:e.platformServices}),p=await V(e.inspectFacts)(f),m=z(`push`,p.operations.ensureReady)??z(`push`,p.operations.sendPushNotification);if(m)return m;let h=await B(e.bindDevice)(f,tt);await h.operations.ensureReady({}),i&&I(r.requireCurrent(i));let g=await h.operations.sendPushNotification({appId:c,payload:u}),_=j(f)?N({platform:`ios`,bundleId:c},`Pushed notification to ${c}`):N({platform:O(f),package:c,action:g.action,extrasCount:g.extrasCount},`Pushed notification to ${c}`);return M(r,i,t,`push`,_,{positionals:[c,l]}),{ok:!0,data:_}}async function _a(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o=t.flags??{},s=U(`uninstall`,a,o);if(s)return s;let c=t.positionals?.[0]?.trim();if(!c)return d(`INVALID_ARGS`,`uninstall requires <app>`);let l=await H({session:a,flags:o,env:r.host.env,platformServices:e.platformServices}),u=await V(e.inspectFacts)(l),f=z(`uninstall`,u.operations.uninstallApp);if(f)return f;let p=await B(e.bindDevice)(l,nt);i&&I(r.requireCurrent(i));let m=await p.operations.uninstallApp({app:c}),h=j(l)?`ios`:`android`,g=m.wasInstalled?`bundleId`in m?m.bundleId:m.packageName:void 0,_=g?N({platform:h,app:c,wasInstalled:!0,appId:g},`Uninstalled: ${g}`):N({platform:h,app:c,wasInstalled:!1},`Not installed: ${c}`);return M(r,i,t,`uninstall`,_),{ok:!0,data:_}}function va(e,t,n,r){return j(e)?ya(t,n,r):ba(e,t,n,r)}function ya(e,t,n){let r=n.bundleId;return{app:e||r||n.launchTarget||t,appPath:t,platform:`ios`,...r?{appId:r,bundleId:r}:{},appName:n.appName,launchTarget:n.launchTarget}}function ba(e,t,n,r){let i=r.packageName,a=e.platform===`harmonyos`?`harmonyos`:`android`;return{app:t||i||r.launchTarget||n,appPath:n,platform:a,...i?{appId:i,package:i,packageName:i}:{},appName:r.appName,launchTarget:r.launchTarget}}function xa(e,t,n){!t||n.platform!==`harmonyos`||!n.appId||e.update(t,{appBundleId:n.appId,appName:n.appName??n.app})}function Sa(e,t){let n=t[0]?.trim(),r=t[1]?.trim();if(e===`install`){let e=r??n;return e?{ok:!0,app:r?n??``:``,appPathInput:e}:{ok:!1,response:d(`INVALID_ARGS`,`install requires: install <path-to-app-binary>`)}}return!n||!r?{ok:!1,response:d(`INVALID_ARGS`,`reinstall requires: reinstall <app> <path-to-app-binary>`)}:{ok:!0,app:n,appPathInput:r}}function Ca(e,t){let n=fa(e,{subject:`Push payload`,cwd:t,expandPath:(e,n)=>F(e,n??t)});return n.kind===`file`?n.path:n.text}async function K(e){let{host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}=e;return n.command===`install`||n.command===`reinstall`?await ha({host:t,req:n,command:n.command,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`install_source`?await hi({req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`uninstall`?await _a({host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`push`?await ga({host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):null}async function wa(e,t,n){return await v(e,t,async(t,r)=>{let i=t;return await n({...i,internal:{...i.internal,...e.internal?.publicNetworkOnly?{publicNetworkOnly:!0}:{},executionPlan:{remainingSteps:r.remainingSteps}}})})}function Ta(e,t,n){let r=e.requireCurrent(t);e.recordAction(t,{command:`close`,positionals:n.positionals??[],flags:n.flags??{},result:{session:r.name,...P(`Closed: ${r.name}`)}})}function Ea(e,t,n){let r=e.requireCurrent(t);if(!gt(r))return{kind:`not-armed`};let i=r.actions.length;Ta(e,t,n);let a=Ft(r),o=e.writeSessionLog(t,{force:Nt(r,n.flags?.force)});return o.written?{kind:`committed`,path:o.path}:o.error?(r.actions.length=i,{kind:`failed`,error:o.error}):a?{kind:`committed`}:(ht(r),{kind:`aborted`})}function Da(e,t){let n=f(t),r=At(e.scriptPublication??zt);return{ok:!1,error:{...n,details:{...n.details,session:e.name,...r?{savedScript:r}:{}},retriable:!0}}}function Oa(e){let{req:t,ref:n,sessionStore:r,platformCloseError:i}=e,a=r.requireCurrent(n);i||Ta(r,n,t);try{let e=r.writeSessionLog(n,{force:Nt(a,t.flags?.force)});e.written&&Mt(a,e.path);return}catch(e){return ka(e)}}function ka(e){let t={hint:`Remove the existing target (or pass --force/--overwrite), then re-record with open --save-script.`,retriable:!1};return e instanceof a?new a(`COMMAND_FAILED`,`The session was closed, but its script was not saved: ${e.message}`,{...e.details,...t},e.cause):new a(`COMMAND_FAILED`,`The session was closed, but its script was not saved: ${f(e).message}`,t)}async function Aa(e){let t=e.clearRuntimeHints?He:Ae,n=await gr({...e,command:`close`,required:t.required});if(n.type===`response`)return n;if(!e.clearRuntimeHints)return{type:`runtime`,runtime:await n.bind(e.device,Ae)};let r=await n.bind(e.device,He);return{type:`runtime`,runtime:r,clearRuntimeHints:r.operations.clearRuntimeHints}}async function ja(e){let{req:t,ref:n,logPath:r,sessionStore:i,lifecycle:a,clearRuntimeHints:o,cleanupFailures:s,repairArmed:c,dispatchTargetedPlatformClose:l,finalizeOrdinaryCloseScript:u}=e,{address:d}=n,f=i.requireCurrent(n),p=async(e,t)=>{try{return await t()}catch(t){s.push({step:e,error:t});return}},m=e.platformResourceCleanup.retainExecutionHostAfterClose({device:f.device,shutdownRequested:t.flags?.shutdown===!0,hasScreenRecording:!!f.screenRecording,hasLease:!!f.lease}),h=i.getRuntimeHints(d),g=Qt({ref:n,sessionStore:i,platformCleanup:e.platformResourceCleanup,appLog:`run`});for(let{step:e,run:t}of g)await p(e,t);f=i.requireCurrent(n);let _=c?void 0:await l({req:t,session:f,logPath:r,lifecycle:a});o&&f.appBundleId&&ar(h)&&await p(`runtime_hints`,async()=>{await o({appId:f.appBundleId,values:or(h)})});let v=await p(`application_lifecycle`,async()=>await a.operations.finalizeApplicationClose({appBundleId:f.appBundleId,surface:f.surface??`app`,retainRunner:m,stateDir:i.resolveDaemonStateDir(),shutdownTarget:t.flags?.shutdown===!0})??{}),y=c?void 0:u({req:t,ref:n,sessionStore:i,platformCloseError:_});return await p(`materialized_paths`,()=>Jt(d)),{platformCloseError:_,saveScriptError:y,shutdownResult:v?.shutdown}}function Ma(e,t){return en({sessionName:e,phase:`session_close_cleanup_failed`,failures:t})}function Na(e){if(e instanceof a)return e;let t=e instanceof Error?e.message:String(e);return new a(`COMMAND_FAILED`,`The platform close failed: ${t}`,{hint:`The repair transaction was not committed because the platform close failed; fix the underlying issue and retry close --save-script.`})}const Pa=(e,t)=>(e.positionals?.length??0)>0||Xt(t);async function Fa(e){let{req:t,ref:n,logPath:r,sessionStore:i,lifecycle:a}=e,o=i.requireCurrent(n),s=gt(o),c=JSON.stringify(t.positionals??[]);if(s&&!ft(o,c)){let e=await La({req:t,session:o,logPath:r,lifecycle:a});if(e)return{response:Da(o,Na(e))};mt(i.requireCurrent(n),c)}let l=Ea(i,n,t);return l.kind===`failed`?{response:Da(o,l.error)}:{repairArmed:s,...l.kind===`committed`&&l.path?{healedScriptPath:l.path}:{},...l.kind===`aborted`?{aborted:!0}:{}}}async function Ia(e){try{let{endedLeaseId:t,providerData:n}=await qt(e);return t&&tn(e.req,t),{providerData:n}}catch(t){let n=f(t);return{response:{ok:!1,error:{...n,hint:`The provider device could not be released. Retry close after the provider is reachable.`,details:{...n.details,session:e.session.name},retriable:!0}}}}}async function La(e){let{req:t,session:n,logPath:r,lifecycle:i}=e;if(Pa(t,n))try{await i.operations.closeApplication({positionals:t.positionals??[],outPath:t.flags?.out,appBundleId:n.appBundleId,surface:n.surface??`app`,...t.internal?.killApp===!0?{mode:`kill`}:{},execution:Rr(t,r,n.trace?.outPath)});return}catch(e){return e}}function Ra(e,t){if(!e.flags?.saveScript||Lt(t))return;let n=t.scriptPublication;if(n?.kind!==`repair`)throw n===void 0||n.kind===`none`?new a(`INVALID_ARGS`,`close --save-script cannot publish this session: recording was not armed before this journey began, so there is no recording-time target evidence to publish.`,{hint:`Retry with plain close (it tears down without writing). To capture a publishable recording, start a fresh session with open <app> --save-script[=<path>].`}):new a(`INVALID_ARGS`,`close --save-script cannot ${n.status===`published`?`re-publish`:`publish`} this terminal recording. Retry with plain close; it will tear down the session without writing.`)}async function za(e){let{session:t,app:n}=e;if(!t.device.hostApp||!n)return;let r=await R({command:`close`,device:t.device,use:Re,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice,platformServices:e.platformServices});if(r.type===`response`)return r.response;await r.runtime.operations.resolveOpenTarget({target:n,surface:`app`,foreground:!1})}async function Ba(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:o,leaseLifecycleProvider:s}=e,c=i.lookup(n);if(!c)return await Wa({req:t,sessionName:n,logPath:r,env:e.host.env,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});let l=i.requireCurrent(c);Ra(t,l);let u=t.positionals?.[0],f=await za({session:l,app:u,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice,platformServices:e.platformServices});if(f)return f;if(t.internal?.closeAppOnly===!0&&!u)return d(`INVALID_ARGS`,`App-only close requires an app target`);if(!e.platformResourceCleanup)throw new a(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let p=e.platformResourceCleanup,m=await Aa({device:l.device,clearRuntimeHints:t.internal?.closeAppOnly!==!0&&!!l.appBundleId&&ar(i.getRuntimeHints(n)),inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(m.type===`response`)return m.response;if(l=i.requireCurrent(c),I(l),t.internal?.closeAppOnly===!0&&u)return await Ua({req:t,session:l,logPath:r,lifecycle:m.runtime,app:u});let h=await Fa({req:t,ref:c,logPath:r,sessionStore:i,lifecycle:m.runtime});if(`response`in h)return h.response;let g=await Va({env:e.host.env,req:t,ref:c,logPath:r,sessionStore:i,leaseRegistry:o,leaseLifecycleProvider:s,lifecycle:m.runtime,clearRuntimeHints:m.clearRuntimeHints,repairArmed:h.repairArmed,platformResourceCleanup:p});return g.kind===`response`?g.response:Ha({session:l,repair:h,requestedSaveScript:!!t.flags?.saveScript,shutdownResult:g.shutdownResult,providerData:g.providerData})}async function Va(e){let{req:t,ref:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o,lifecycle:s,clearRuntimeHints:c}=e,{address:l}=n,u=[],{platformCloseError:d,saveScriptError:f,shutdownResult:p}=await ja({req:t,ref:n,logPath:r,sessionStore:i,lifecycle:s,clearRuntimeHints:c,cleanupFailures:u,repairArmed:e.repairArmed,dispatchTargetedPlatformClose:La,finalizeOrdinaryCloseScript:Oa,platformResourceCleanup:e.platformResourceCleanup}),m=i.requireCurrent(n),h=await Ia({req:t,session:m,leaseRegistry:a,leaseLifecycleProvider:o});if(h.response)return{kind:`response`,response:h.response};m=i.resolveCurrent(n)??m;let g=Ma(l,u),_=d??g;if(_?m.deviceClaim&&D({level:`warn`,phase:`device_claim_close_effects_unconfirmed`,data:{deviceKey:m.deviceClaim.deviceKey,session:l}}):await Wn(m.deviceClaim,e.env),i.retire(n),_)throw _;if(f)throw f;return{kind:`closed`,providerData:h.providerData,shutdownResult:p}}function Ha(e){let{session:t,repair:n,requestedSaveScript:r,shutdownResult:i,providerData:a}=e;if(n.aborted&&r)return{ok:!1,error:{code:`COMMAND_FAILED`,message:`The repair was aborted and no script was written.`,hint:`Recovery: replay --from <n> --plan-digest <digest> before closing.`,details:{session:t.name}}};let o=n.healedScriptPath?{savedScript:n.healedScriptPath}:{},s=a?{provider:a}:{},c=`Closed: ${t.name}`;return i?{ok:!0,data:N({session:t.name,shutdown:i,...o,...s},c)}:{ok:!0,data:{session:t.name,...P(c),...o,...s}}}async function Ua(e){let{req:t,session:n,logPath:r,lifecycle:i,app:a}=e,o=await La({req:t,session:n,logPath:r,lifecycle:i});if(o)throw o;return{ok:!0,data:{app:a,...P(`Closed: ${a}`)}}}async function Wa(e){let{req:t,sessionName:n,logPath:r,env:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,{requireNamedSessionHoldsDevice:c}=await import(`./explicit-session-resolution.js`);if(c({req:t,sessionAddress:n,session:void 0}),!t.positionals||t.positionals.length===0)return d(`SESSION_NOT_FOUND`,`No active session`);let l=await Aa({device:await H({session:void 0,flags:t.flags,env:i,platformServices:s}),clearRuntimeHints:!1,inspectFacts:a,bindDevice:o,platformServices:s});return l.type===`response`?l.response:(await l.runtime.operations.closeApplication({positionals:t.positionals,outPath:t.flags?.out,surface:`app`,ensureReady:!0,...t.internal?.killApp===!0?{mode:`kill`}:{},execution:Rr(t,r)}),{ok:!0,data:{app:t.positionals[0],...P(`Closed: ${t.positionals[0]}`)}})}function Ga(e,t){return e.operations.ensureReady(t)}function Ka(e,t,n){return e.operations.listApps({device:t,filter:n})}async function qa(e){let{req:t,sessionName:n,sessionStore:r}=e;switch(t.command){case`session_list`:return Ja(t,r);case`devices`:return await Xa(t,e.host.env);case`capabilities`:return await io({req:t,sessionName:n,sessionStore:r,inspectFacts:e.inspectFacts,platformServices:e.platformServices});case`apps`:return await co({env:e.host.env,req:t,sessionName:n,sessionStore:r,bindDevice:e.bindDevice,platformServices:e.platformServices,inspectFacts:e.inspectFacts,providerAppCatalog:e.providerAppCatalog});default:return null}}function Ja(e,t){let n=Kt(e);return{ok:!0,data:{sessions:t.listRefs().filter(e=>Zt(e.session,n)).map(e=>Ya(e,t))}}}function Ya({address:e,session:t},n){let r=n.resolveSessionDir(e);return{name:t.name,address:e,sessionStateDir:r,runnerLogPath:mn(r),platform:O(t.device),...A(t.device.platform)&&t.device.appleOs?{appleOs:t.device.appleOs}:{},target:t.device.target??`mobile`,surface:t.surface??`app`,device:t.device.name,id:t.device.id,device_id:t.device.id,createdAt:t.createdAt,...A(t.device.platform)&&!k(t.device)&&{device_udid:t.device.id,ios_simulator_device_set:t.device.simulatorSetPath??null}}}async function Xa(e,t){try{let n=Za(t);return{ok:!0,data:{devices:(await $a(e,t)).map(e=>({...go(e),...Qa(e,n)}))}}}catch(e){let t=s(e);return{ok:!1,error:{code:t.code,message:t.message,...t.details?{details:t.details}:{}}}}}function Za(e){let t=new Map;for(let n of Kn({},e)){let e=n.claim;!e||Un(n.classification)||t.set(e.deviceKey,{session:e.session,workspace:e.workspace})}return t}function Qa(e,t){let n=Hn(e),r=Gn({...n,id:xe(e.id)}),i=t.get(Gn(n))??[...t].find(([e])=>e.startsWith(r))?.[1];return i?{claimedBy:i}:{}}async function $a(e,t){let n=e.flags?.platform;return ro(await ur(eo(e,n,t)),e.flags?.platform,e.flags?.target)}function eo(e,t,n){let r=e.flags;return{platform:t,target:r?.target,deviceName:r?.device,udid:r?.udid,serial:r?.serial,iosSimulatorSetPath:to(r?.iosSimulatorDeviceSet,t,r?.target,n),androidSerialAllowlist:no(r?.androidDeviceAllowlist,n)}}function to(e,t,n,r){return be({requestedSetPath:e,platform:t,target:n,env:r})}function no(e,t){let n=L(e,t);return n?Array.from(n).sort():void 0}function ro(e,t,n){let r=t?e.filter(e=>_o(e,t)):e;return n?r.filter(e=>(e.target??`mobile`)===n):r}async function io(e){let t=await ho({...e,androidAvdSelection:`include-stopped`});if(`response`in t)return t.response;let{device:n}=t,r=ao(n,e.sessionStore.get(e.sessionName),e.req.flags),i=await fo(n,e.inspectFacts);return{ok:!0,data:{device:go(n),...n.platform===`android`&&zr(`press`,i)?{targetReadiness:{press:`bounded-geometry`}}:{},availableCommands:at().filter(e=>e===`appstate`&&r?!0:zr(e,i))}}}function ao(e,t,n){return!t||!j(e)&&!k(e)||!Pr(n,t)?!1:oo(t)||so(e,t)}function oo(e){return!!(e.appName||e.appBundleId)}function so(e,t){return!!(k(e)&&t.surface!==void 0&&t.surface!==`app`&&t.surface!==`frontmost-app`)}async function co(e){let{req:t,sessionName:n,sessionStore:r,bindDevice:i,inspectFacts:a,platformServices:o}=e,s=await lo(t,e.providerAppCatalog);if(s)return s;let c=await ho({req:t,sessionName:n,sessionStore:r,androidAvdSelection:`include-stopped`,platformServices:o});if(`response`in c)return c.response;let{device:l}=c,u=ln(t.flags?.appsFilter),d=L(t.flags?.androidDeviceAllowlist,e.env),f=await po({device:l,inspectFacts:a,bindDevice:i,platformServices:o});if(`response`in f)return f.response;let p=f.runtime;return mo(await Ka(p,await Ga(p,{serial:t.flags?.serial,androidSerialAllowlist:d?[...d].sort():void 0}),u))}async function lo(e,t){let n=uo(e);if(!(!t||!n||!t.supports(n.provider)))return{ok:!0,data:{apps:[...await t.list(n,Jn(e.meta?.requestId))]}}}function uo(e){let t=$n(e);if(t.leaseId)return;let n=t.leaseProvider;if(!n)return;let r=e.flags?.platform;if(r===`android`||r===`ios`)return{provider:n,platform:r,...e.internal?.publicNetworkOnly?{publicNetworkOnly:!0}:{}}}async function fo(e,t){if(t)try{return await t(e)}catch{return}}async function po(e){let t=await V(e.inspectFacts)(e.device),n=[t.operations.ensureReady,t.operations.listApps].find(e=>!e.available);return n&&!n.available?{response:hr(`apps`,n)}:{runtime:await B(e.bindDevice)(e.device,Ke)}}function mo(e){return{ok:!0,data:{apps:e.map(e=>e.name&&e.name!==e.id?`${e.name} (${e.id})`:e.id)}}}async function ho(e){let{req:t,sessionName:n,sessionStore:r,androidAvdSelection:i,platformServices:a}=e,o=r.get(n),s=t.flags??{},c=U(t.command,o,s);return c?{response:c}:{device:await H({session:o,flags:s,env:r.host.env,platformServices:a,androidAvdSelection:i})}}function go({simulatorSetPath:e,iosPhysicalDeviceBackend:t,appleOs:n,...r}){return{...r,platform:O({platform:r.platform,appleOs:n}),...A(r.platform)&&n?{appleOs:n}:{}}}function _o(e,t){return ye(e,t)}function vo(e,t){return{ok:!0,data:{platform:O(e),target:e.target??`mobile`,device:e.name,id:e.id,kind:e.kind,...t,...A(e.platform)&&e.appleOs?{appleOs:e.appleOs}:{}}}}function yo(e){return t=>d(e?`INVALID_ARGS`:`UNSUPPORTED_OPERATION`,e?`boot --headless is supported only for Android emulators.`:`boot is not supported on this device`,void 0,t.hint?{hint:t.hint}:void 0)}function bo(e,t){return!!(e?.trim()||t?.platform===`android`&&t.kind===`emulator`)}async function xo(e,t){let{sessionName:n,sessionStore:r,req:i,platformServices:a}=e,o=r.get(n),c=i.flags??{};try{let e=await Fr({session:o,flags:c,env:r.host.env,platformServices:a}),{device:t}=e;return c.target&&(t.target??`mobile`)!==c.target?{refusal:d(`DEVICE_NOT_FOUND`,`No ${t.platform} device found matching --target ${c.target}.`)}:e}catch(e){if(t&&!bo(c.device,o?.device)&&s(e).code===`DEVICE_NOT_FOUND`)return{refusal:d(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`)};throw e}}async function So(e){let t=e.req.flags??{},n=U(e.req.command,e.sessionStore.get(e.sessionName),t);if(n)return n;let r=L(t.androidDeviceAllowlist,e.host.env),i=r?[...r].sort():void 0,a=ze({headless:t.headless===!0}),o=await xo(e,a.kind===`boot-target-headless`);if(`refusal`in o)return o.refusal;let s=o.device,c=await gr({command:`boot`,device:s,required:a.use.required,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,unavailableResponse:yo(a.kind===`boot-target-headless`)});if(c.type===`response`)return c.response;let l={serial:t.serial,androidSerialAllowlist:i,deadlineAtMs:Br(t.timeoutMs)},u=a.kind===`boot-target-headless`?await(await c.bind(s,a.use)).operations.bootTargetHeadless(l):await(await c.bind(s,a.use)).operations.bootTarget(l),{device:d,...f}=Mr(o);return vo(u,{booted:!0,selection:f})}function Co(e){return e.available?null:d(`UNSUPPORTED_OPERATION`,`shutdown is supported only for Apple simulators and Android emulators.`,void 0,e.hint?{hint:e.hint}:void 0)}function wo(e){let t=e.error?.message??e.stderr.trim();return t.length>0?t:`Shutdown failed`}async function To(e){let t=e.sessionStore.get(e.sessionName),n=e.req.flags??{},r=U(e.req.command,t,n);if(r)return r;let i=await Nr({flags:n,session:t,env:e.sessionStore.host.env,platformServices:e.platformServices}),a=Co((await V(e.inspectFacts)(i)).operations.shutdownTarget);if(a)return a;if(t&&t.device.platform===i.platform&&t.device.id===i.id)return d(`DEVICE_IN_USE`,`Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.`,{hint:`Run agent-device close --shutdown --session ${e.sessionName}`,session:e.sessionName,platform:O(i),target:i.target??`mobile`,device:i.name,id:i.id,kind:i.kind});let o=await(await B(e.bindDevice)(i,Ye)).operations.shutdownTarget();return o.success?vo(i,{shutdown:o}):d(o.error?.code??`COMMAND_FAILED`,wo(o),{platform:O(i),target:i.target??`mobile`,device:i.name,id:i.id,kind:i.kind,shutdown:o})}function Eo(t,n){return A(n)?d(`SESSION_NOT_FOUND`,`No active session "${t}". Run open with --session ${t} first.`,e(t)):d(`SESSION_NOT_FOUND`,`No active session "${t}". Run open with --session ${t} first, or omit --session to query by device selector.`,e(t))}function Do(e){return d(`SESSION_NOT_FOUND`,e===`macos`?`macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").`:`iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).`)}async function Oo(e,t){if(!t.appBundleId)return;let n=await R({command:`appstate`,device:t.device,use:Qe,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(n.type!==`response`)try{return(await n.runtime.operations.appState({appBundleId:t.appBundleId})).applicationState}catch(e){if(i(e))throw e;D({level:`warn`,phase:`apple_appstate_runner_read_failed`,data:{code:s(e).code,message:s(e).message}});return}}function ko(e){if(!(!k(e.device)||!e.surface)&&e.surface!==`app`&&e.surface!==`frontmost-app`)return{ok:!0,data:{platform:O(e.device),appName:e.surface,appBundleId:e.appBundleId,source:`session`,surface:e.surface}}}async function Ao(e,t){if(!t.appName&&!t.appBundleId){let e=ko(t);if(e)return e;let n=k(t.device)?`macOS`:`iOS`;return d(`COMMAND_FAILED`,`No foreground app is tracked for this ${n} session. Open an app in the session, then retry appstate.`)}let n=await Oo(e,t),r=t.appName??t.appBundleId;return{ok:!0,data:{platform:O(t.device),appName:r??`unknown`,appBundleId:t.appBundleId,source:n?`runner`:`session`,...n?{state:n}:{},surface:t.surface??`app`,...j(t.device)?{device_udid:t.device.id,ios_simulator_device_set:t.device.simulatorSetPath??null}:{}}}}function jo(e,t){let n=L(e,t);return n?[...n].sort():void 0}async function Mo(e,t,n){if(j(t)||k(t))return n?Eo(e.sessionName,t.platform):Do(k(t)?`macos`:`ios`);let r=e.req.flags??{},i=await R({command:`appstate`,device:t,use:Qe,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(i.type===`response`)return i.response;let a=i.runtime;await a.operations.ensureReady({serial:r.serial,androidSerialAllowlist:jo(r.androidDeviceAllowlist,e.host.env)});let o=await a.operations.appState();return{ok:!0,data:{platform:O(t),package:o.package,activity:o.activity}}}function No(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),a=t.flags??{},o=a.platform;if(!i&&c(t)&&(!Gt(a)||A(o)))return{refusal:Eo(n,o)};let s=U(`appstate`,i,a);if(s)return{refusal:s};let l=A(i?.device.platform)&&Pr(a,i);return o===`ios`&&!l?{refusal:Do(`ios`)}:o===`macos`&&!l?{refusal:Do(`macos`)}:l&&i?{answeredBy:`apple-session`,session:i}:{answeredBy:`device-runtime`,session:i,namedSessionMissing:!i&&c(t)}}async function Po(e){let t=No(e);return`refusal`in t?t.refusal:t.answeredBy===`apple-session`?await Ao(e,t.session):await Mo(e,await H({session:t.session,flags:e.req.flags??{},env:e.sessionStore.host.env,platformServices:e.platformServices}),t.namedSessionMissing)}function Fo(e){return Cn.createNextFence({admissionLedger:e.ledger,resourcePath:e.resourcePath,device:e.device})}async function Io(e){try{return await Lo(e)}catch(e){return{ok:!1,error:f(e)}}}async function Lo(e){let t=Ro(e);if(!t.ok)return t;let n=t.ref,r=e.sessionStore.requireCurrent(n),i=Me(e.req.positionals),a=await e.inspectFacts(r.device),o=a.operations.audioProbeStart,s=a.operations.audioProbeQuery,c=o.available?`capture`:s.available?`query`:void 0;if(c===void 0)return zo(o,s);let l=Be({probeAction:i.probeAction,mode:c});switch(l.kind){case`query`:return{ok:!0,data:await(await e.bindDevice(r.device,l.use)).operations.audioProbeQuery({action:l.action,durationMs:i.durationMs,bucketMs:i.bucketMs})};case`capture-start`:return await Bo(e,n,i,l.use);case`capture-status`:return await Vo(e,n);case`capture-stop`:return await Ho(e,n)}}function Ro(e){let t=e.sessionStore.lookup(e.sessionName);return t?{ok:!0,ref:t}:d(`SESSION_NOT_FOUND`,`audio requires an active session`)}function zo(e,t){let n=(e.available?void 0:e.hint)??(t.available?void 0:t.hint),r=e.available?void 0:e.reason;return d(`UNSUPPORTED_OPERATION`,n??`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`,r?{reason:r}:void 0)}async function Bo(e,t,n,r){let i=e.sessionStore.requireCurrent(t),a=Yt(e.sessionStore,t);i.audioProbe&&(await Sn({intent:`disposal`,binding:a}),i=e.sessionStore.requireCurrent(t));let o=await e.bindDevice(i.device,r),s=On.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),c=On.createNextFence({admissionLedger:e.audioProbeAdmissionLedger,resourcePath:s,device:i.device}),l=G.join(e.sessionStore.ensureSessionDir(e.sessionName),`audio-probe.json`);a.assertAdoptable();let u=await o.operations.audioProbeStart({sessionId:e.sessionName,statusPath:l,durationMs:n.durationMs,bucketMs:n.bucketMs,fence:c});await wn({admissionLedger:e.audioProbeAdmissionLedger,binding:a,device:i.device,owner:o.owner,fence:c,...u,throwIfCanceled:e.throwIfCanceled});let d=a.read();if(!d)throw TypeError(`Audio probe adoption did not publish a live handle`);return{ok:!0,data:await d.handle.status()}}async function Vo(e,t){let n=Yt(e.sessionStore,t),r=n.read();if(!r)return{ok:!0,data:Uo()};let i=await r.handle.status();return i.state===`stopped`&&await Sn({intent:`disposal`,binding:n}),{ok:!0,data:i}}async function Ho(e,t){let n=Yt(e.sessionStore,t);return n.read()?{ok:!0,data:await Sn({intent:`capture`,binding:n})}:{ok:!0,data:Uo()}}function Uo(){return Vr({state:`stopped`,source:`system-audio`,backend:`host-system-audio`,durationMs:0,bucketMs:0,sourceCount:0,reason:`not-started`,notes:[`No active host audio probe is running.`]})}async function Wo(e){let t=e.sessionStore.lookup(e.sessionName);if(!t)return d(`SESSION_NOT_FOUND`,`perf requires an active session. Run open first.`);let n=e.sessionStore.requireCurrent(t),r={...e,ref:t};try{if(on(e.req.positionals?.[0]))throw new a(`INVALID_ARGS`,sn);us(e.req);let t=un({positionals:e.req.positionals,kind:fs(e.req.flags?.kind),outPath:fs(e.req.flags?.out)}),i=dn(t);if(i.kind===`capture-stop`)return Go(r,await Yo(r,n,i.request));let o=await Sr({device:n.device,plan:i,inspectFacts:e.inspectFacts});return o.admitted?Go(r,await Ko(r,n,o)):z(`perf`,o.fact)??d(`UNSUPPORTED_OPERATION`,`perf is not supported on this device`)}catch(e){return{ok:!1,error:f(e)}}}function Go(e,t){return t.ok&&M(e.sessionStore,e.ref,e.req,`perf`,b(t.data)?{...t.data}:{}),t}async function Ko(e,t,n){let{device:r,plan:i}=xr(n),o=B(e.bindDevice);switch(i.kind){case`frames`:return{ok:!0,data:ts(t,await(await o(r,i.use)).operations.perfFrames({appId:t.appBundleId}))};case`memory-sample`:return{ok:!0,data:os(t,await(await o(r,i.use)).operations.perfMemorySample({appId:t.appBundleId}))};case`memory-snapshot`:{let n=await(await o(r,i.use)).operations.perfMemorySnapshot({appId:t.appBundleId,kind:i.request.kind,outPath:i.request.outPath?F(i.request.outPath,e.req.meta?.cwd??e.host.cwd):void 0,artifactsDir:G.join(e.sessionStore.ensureSessionDir(e.sessionName),`artifacts`)});return{ok:!0,data:nn(ss(t,n),e.req.internal?.publicNetworkOnly?`daemon`:`caller`,t.lease?.tenantId??e.req.meta?.tenantId)}}case`capture-start`:return await qo(e,t,await o(r,i.use),i.request);case`profile-report`:{let n=await o(r,i.use),s=t.lastPerfProfile,c=i.request.tracePath??s?.outPath;if(!c)throw new a(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace or tracePath option`);if(t.perfCapture)throw new a(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace; stop the active capture first.`);let l=ls(e,i.request.outPath,`cpu-report.json`),u=await n.operations.perfProfileReport({appId:t.appBundleId,kind:i.request.kind,tracePath:F(c,e.req.meta?.cwd??e.host.cwd),outPath:l,template:i.request.template??(s?.kind===`xctrace`?s.template:void 0),profile:s});return{ok:!0,data:nn({perf:`reported`,...u},e.req.internal?.publicNetworkOnly?`daemon`:`caller`,t.lease?.tenantId??e.req.meta?.tenantId)}}}}async function qo(e,t,n,r){if(t.perfCapture)return d(`INVALID_ARGS`,`native perf capture already in progress`);if(!t.appBundleId)return d(`COMMAND_FAILED`,`No app is associated with this session.`,{hint:`Run open <app> first so perf can resolve the app process identity.`});let i=r.kind===`xctrace`?`perf-${r.area===`cpu`?`cpu-profile`:`trace`}.trace`:r.kind===`perfetto`?`app.perfetto-trace`:`cpu.perf.data`,a=ls(e,r.outPath,i),o=xn.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),s=xn.createNextFence({admissionLedger:Jo(e),resourcePath:o,device:t.device}),c=an(e.sessionStore,e.ref,e.req.meta?.clientArtifactPaths?.outPath);c.assertAdoptable();let l=await n.operations.perfNativeCaptureStart({sessionId:e.sessionName,appId:t.appBundleId,mode:r.area===`cpu`?`cpu-profile`:`trace`,kind:r.kind,template:r.template,outPath:a,fence:s}),u=t.lease?.tenantId??e.req.meta?.tenantId;return await Tn({admissionLedger:Jo(e),binding:c,device:t.device,owner:n.owner,fence:s,pendingHandle:l.pendingHandle,envelope:e.req.internal?.publicNetworkOnly?{...l.envelope,metadata:{...l.envelope.metadata,remoteCaptureOutputPath:a,...u?{remoteCaptureTenantId:u}:{}}}:l.envelope,throwIfCanceled:e.throwIfCanceled}),{ok:!0,data:l.response}}function Jo(e){if(e.perfCaptureAdmissionLedger)return e.perfCaptureAdmissionLedger;throw new a(`COMMAND_FAILED`,`Perf capture admission ledger is not configured`,{reason:`runtime-gateway-missing`})}async function Yo(e,t,n){let r=t.perfCapture;if(!r)return d(`INVALID_ARGS`,`no active native perf capture`);let i=es(r.handle.inspect(),n);if(i)return d(`INVALID_ARGS`,i);n.outPath&&r.handle.setOutputPath(F(n.outPath,e.req.meta?.cwd??e.host.cwd));let a=await Dn({intent:`capture`,binding:an(e.sessionStore,e.ref)});if(n.area===`cpu`){let t=Xo(a);e.sessionStore.update(e.ref,{lastPerfProfile:t})}let o=e.req.meta?.clientArtifactPaths?.outPath??r.clientOutPath,s=typeof r.envelope.metadata?.remoteCaptureTenantId==`string`?r.envelope.metadata.remoteCaptureTenantId:t.lease?.tenantId;return{ok:!0,data:nn({...a,...o?{clientOutPath:o}:{}},r.envelope.metadata?.remoteCaptureOutputPath===a.outPath?`daemon`:`caller`,s)}}function Xo(e){if(Zo(e)||Qo(e))return e;throw new a(`COMMAND_FAILED`,`Stopped CPU profile metadata is malformed.`)}function Zo(e){return e.kind===`xctrace`&&e.mode===`cpu-profile`&&typeof e.outPath==`string`&&typeof e.template==`string`}function Qo(e){return e.kind===`simpleperf`&&e.mode===`cpu-profile`&&$o(e,[`outPath`,`packageName`,`appPid`,`profilerPid`,`remotePath`])}function $o(e,t){return t.every(t=>typeof e[t]==`string`)}function es(e,t){let n=t.area===`cpu`?`cpu-profile`:`trace`;if(e.kind!==t.kind||e.mode!==n)return`No ${t.kind} ${n} is active for this session.`}function ts(e,t){return{...cs(e),metrics:{fps:ns(t.metric,e)},sampling:{fps:t.sampling}}}function ns(e,t){if(!b(e)||e.available!==!0)return e;let n=rs(t.actions,e);return n.length===0?e:{...e,relatedActions:n}}function rs(e,t){let n=is(t.windowStartedAt),r=is(t.windowEndedAt)??is(t.measuredAt);return n===void 0||r===void 0?[]:e.filter(({ts:e})=>e>=n&&e<=r).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:as(e)})).slice(-12)}function is(e){if(typeof e!=`string`)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function as(e){for(let t of[`refLabel`,`ref`,`appName`,`appBundleId`]){let n=e.result?.[t];if(typeof n==`string`&&n.length>0)return n}}function os(e,t){return{...cs(e),metrics:{memory:t.metric},sampling:{memory:t.sampling}}}function ss(e,t){return{...cs(e),artifact:t.artifact,sampling:{snapshot:t.sampling},support:t.support}}function cs(e){return{session:e.name,platform:O(e.device),device:e.device.name,deviceId:e.device.id}}function ls(e,t,n){return t?F(t,e.req.meta?.cwd??e.host.cwd):G.join(e.sessionStore.ensureSessionDir(e.sessionName),`${ds()}-${n}`)}function us(e){let t=e.positionals?.[0]?.toLowerCase(),n=e.positionals?.[1]?.toLowerCase();if(e.flags?.out&&t!==`cpu`&&t!==`trace`&&(t!==`memory`||n!==`snapshot`))throw new a(`INVALID_ARGS`,`--out is only supported with perf memory snapshot, perf cpu profile, or perf trace`)}function ds(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}function fs(e){return typeof e==`string`&&e.length>0?e:void 0}const ps=[`dump`,`log`],ms=`network requires ${ps.join(` or `)}`,hs=`network include mode must be one of: ${l.join(`, `)}`,gs=2048;async function _s(e){let t=e.sessionStore.get(e.sessionName);if(!t)return d(`SESSION_NOT_FOUND`,`network requires an active session`);try{let n=vs(e.bindDevice),r=(await n(t.device,Ie)).facts.networkDump;if(!r.available)return hr(`network`,r);let i=ys(e.req);if(!i.ok)return i;let a=De({action:i.action,include:i.include}),o=await n(t.device,a.use),s=t.appLog?.handle.inspect();return Cs(await o.operations.networkDump({sessionId:e.sessionName,appBundleId:t.appBundleId,...s?{appLogSnapshot:{state:s.state,startedAt:s.startedAt}}:{},maxEntries:i.maxEntries,include:a.include,maxPayloadChars:gs,maxScanLines:4e3}),i,!!t.appLog,s?.state)}catch(e){return{ok:!1,error:f(e)}}}function vs(e){if(e)return e;throw new a(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`})}function ys(e){let t=bs(e);if(!t.ok)return t;let n=xs(e);if(!n.ok)return n;let r=Ss(e);return r.ok?{ok:!0,action:t.action,include:r.include,maxEntries:n.maxEntries}:r}function bs(e){let t=(e.positionals?.[0]??`dump`).toLowerCase();return ps.includes(t)?{ok:!0,action:t}:d(`INVALID_ARGS`,ms)}function xs(e){let t=e.positionals?.[1]?Number.parseInt(e.positionals[1],10):25;return!Number.isInteger(t)||t<1||t>200?d(`INVALID_ARGS`,`network dump limit must be an integer in range 1..200`):{ok:!0,maxEntries:t}}function Ss(e){let t=e.positionals?.[2]?.toLowerCase(),n=e.flags?.networkInclude;if(t&&n&&t!==n)return d(`INVALID_ARGS`,`network include mode was provided both positionally and via --include with different values`);let r=(n??t??`summary`).toLowerCase();return l.includes(r)?{ok:!0,include:r}:d(`INVALID_ARGS`,hs)}function Cs(e,t,n,r){return e.source===`app-log`?{ok:!0,data:{...e.dump,active:n,state:r??`inactive`,backend:e.backend,notes:e.notes}}:{ok:!0,data:{entries:e.entries,active:!0,state:`active`,backend:e.backend,include:t.include,matchedLines:e.entries.length,scannedLines:e.entries.length,limits:{maxEntries:t.maxEntries,maxPayloadChars:gs,maxScanLines:e.entries.length},notes:e.notes}}}function ws(e,t){let n=Or(e);return{...n,backend:n.backend??t,notes:n.state===`failed`&&e.appLogFailure?[Ts(e.appLogFailure)]:Es(n.state)}}function Ts(e){return e.hint?`${e.message} ${e.hint}`:e.message}function Es(e){return e===`failed`?[`The app log stream process exited with an error. Run logs doctor for backend diagnostics.`]:e===`ended`?[`The app log stream process ended. Run logs clear --restart before the next capture window.`]:void 0}function Ds(e,t){return Te([...e,...t.notes??[]])}async function Os(e){let{req:t}=e;return t.command===`perf`?await Wo({...e,throwIfCanceled:e.throwIfCanceled??(()=>{})}):t.command===`logs`?As(e):t.command===`events`?await ks(e):t.command===`network`?await _s(e):t.command===`audio`?await Io(Hs(e)):null}async function ks(e){let{req:t,sessionName:n,sessionStore:r}=e;try{return await r.flushEvents(n),{ok:!0,data:r.readEvents(n,{limit:t.positionals?.[0],cursor:t.positionals?.[1]})}}catch(e){return{ok:!1,error:f(e)}}}async function As(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n);if(!i)return d(`SESSION_NOT_FOUND`,`logs requires an active session`);try{let n=r.requireCurrent(i),a=Us({...e,session:n,ref:i}),o=(await a.bindDevice(n.device,st)).facts.appLogInspect;if(!o.available)return hr(`logs`,o);let s=Ns(Se({action:t.positionals?.[0],restart:!!t.flags?.restart,marker:t.positionals?.slice(1).join(` `)}),n);return`ok`in s?s:await js(a,s)}catch(e){return{ok:!1,error:f(e)}}}async function js(e,t){switch(t.kind){case`path`:return Ps(e,(await(await e.bindDevice(e.session.device,t.use)).operations.appLogInspect()).backend);case`doctor`:return Fs(e,await(await e.bindDevice(e.session.device,t.use)).operations.appLogDoctor({appBundleId:e.session.appBundleId}));case`start`:case`clear-restart`:return await Ms(e,t);case`stop`:return await e.bindDevice(e.session.device,t.use),await Bs(e);case`mark`:return await e.bindDevice(e.session.device,t.use),Is(t.marker,e.sessionName,e.sessionStore,e.host.env);case`clear`:return await e.bindDevice(e.session.device,t.use),Ls(e)}}async function Ms(e,t){let n=await e.bindDevice(e.session.device,t.use);return t.kind===`start`?await zs(e,t.appBundleId,n.owner,n.operations.appLogStart):await Rs(e,t.appBundleId,n.owner,n.operations.appLogStart)}function Ns(e,t){return e.requiresAppSession?t.appBundleId?Object.freeze({...e,appBundleId:t.appBundleId}):d(`INVALID_ARGS`,`logs ${e.kind===`start`?`start`:`clear --restart`} requires an app session; run open <app> first`):e}function Ps(e,t){let{session:n,sessionName:r,sessionStore:i}=e,a=i.resolveAppLogPath(r),o=Dr(a),s=ws(n,t);return{ok:!0,data:{path:a,active:s.active,state:s.state,backend:s.backend,sizeBytes:o.sizeBytes,modifiedAt:o.modifiedAt,startedAt:s.startedAt?new Date(s.startedAt).toISOString():void 0,failureCode:s.failureCode,failureMessage:s.failureMessage,hint:s.hint??String.raw`Grep the file for token-efficient debugging, e.g. grep -n "Error\|Exception" <path>`,notes:s.notes}}}async function Fs(e,t){let{session:n,sessionName:r,sessionStore:i}=e,a=i.resolveAppLogPath(r),o=ws(n,t.backend);return{ok:!0,data:{path:a,active:o.active,state:o.state,backend:o.backend,checks:t.checks,failureCode:o.failureCode,failureMessage:o.failureMessage,hint:o.hint,notes:Ds(t.notes,o)}}}function Is(e,t,n,r){let i=n.resolveAppLogPath(t);return Tr(i,e,r),{ok:!0,data:{path:i,marked:!0}}}function Ls(e){return{ok:!0,data:Er(e)}}async function Rs(e,t,n,r){let{session:i,sessionStore:a}=e;i.appLog&&await wr({intent:`disposal`,ref:e.ref,sessionStore:a});let o=Er(e),s=await Vs(e,t,r,n);return s.ok?{ok:!0,data:{...o,restarted:!0}}:s}async function zs(e,t,n,r){let{session:i}=e;return i.appLog?d(`INVALID_ARGS`,`app log already streaming; run logs stop first`):await Vs(e,t,r,n)}async function Bs(e){let{session:t,sessionName:n,sessionStore:r}=e;if(!t.appLog)return d(`INVALID_ARGS`,`no app log stream active`);let i=r.resolveAppLogPath(n);return await wr({intent:`capture`,ref:e.ref,sessionStore:r}),{ok:!0,data:{path:i,stopped:!0}}}async function Vs(e,t,n,r){let{session:i,sessionName:a,sessionStore:o}=e,s=o.resolveAppLogPath(a),c=En.resolvePath(o.resolveSessionDir(a));try{let l=Fo({ledger:e.appLogAdmissionLedger,resourcePath:c,device:i.device});kr(o,e.ref).assertAdoptable();let u=await n({sessionId:a,appBundleId:t,outputPath:s,pidPath:o.resolveAppLogPidPath(a),fence:l});return await jr({admissionLedger:e.appLogAdmissionLedger,ref:e.ref,sessionStore:o,device:i.device,owner:r,fence:l,pendingHandle:u.pendingHandle,envelope:u.envelope,throwIfCanceled:e.throwIfCanceled??(()=>{})}),{ok:!0,data:{path:s,started:!0}}}catch(t){return{ok:!1,error:Ar({ref:e.ref,sessionStore:o,error:t})}}}function Hs(e){if(!e.bindDevice||!e.inspectFacts)throw new a(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`});if(!e.audioProbeAdmissionLedger)throw new a(`COMMAND_FAILED`,`Audio probe admission ledger is not configured`,{reason:`runtime-gateway-missing`});return{req:e.req,sessionName:e.sessionName,sessionStore:e.sessionStore,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,audioProbeAdmissionLedger:e.audioProbeAdmissionLedger,throwIfCanceled:e.throwIfCanceled??(()=>{})}}function Us(e){if(!e.bindDevice)throw new a(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`});if(!e.appLogAdmissionLedger)throw new a(`COMMAND_FAILED`,`App-log admission ledger is not configured`,{reason:`runtime-gateway-missing`});return{...e,bindDevice:e.bindDevice,platformServices:e.platformServices,appLogAdmissionLedger:e.appLogAdmissionLedger}}const Ws=new WeakMap;function Gs(e){return{store:t=>Ks(e,t),finalize:(t,n)=>qs({...e,evidence:t,projection:n})}}function Ks(e,t){let{sessionStore:n,ref:r}=e;if(!r)throw Error(`Internal observation session is no longer available.`);let i=n.requireCurrent(r);vr(i,t);let a=i.snapshotGeneration;if(a===void 0)throw Error(`Internal observation did not establish a snapshot generation.`);let o={};return Ws.set(o,{ref:r,snapshot:t,snapshotGeneration:a,runtimeRevision:Vn(i),refFrame:Rn(i)}),{evidence:o,refsGeneration:a}}function qs(e){let t=Ws.get(e.evidence);Ws.delete(e.evidence);let n=Ys(e.projection.refs);if(n.size===0)return{published:!1,reason:`empty`};if(e.signal?.aborted===!0)return{published:!1,reason:`cancelled`};let r=t&&Js(e,t);return!t||!r?{published:!1,reason:`stale-capture`}:e.projection.refsGeneration!==t.snapshotGeneration||!Xs(n,t.snapshot)?{published:!1,reason:`invalid-projection`}:(_r(r,n),{published:!0,refsGeneration:t.snapshotGeneration,refCount:n.size})}function Js(e,t){if(!e.ref||e.ref.lifetime!==t.ref.lifetime)return;let n=e.sessionStore.resolveCurrent(e.ref);return n&&n.snapshot===t.snapshot&&n.snapshotGeneration===t.snapshotGeneration&&Vn(n)===t.runtimeRevision&&Rn(n)===t.refFrame?n:void 0}function Ys(e){let t=new Set;for(let n of e){let e=n.startsWith(`@`)?n.slice(1):n,r=e.indexOf(`~`),i=r===-1?e:e.slice(0,r);i.length>0&&t.add(i)}return t}function Xs(e,t){let n=new Set(t.nodes.flatMap(e=>typeof e.ref==`string`?[e.ref]:[]));return[...e].every(e=>n.has(e))}function Zs(e){let t=Qs(e),n=Ve(t);return ci(`sha256`).update(n,`utf8`).digest(`hex`)}function Qs(e){let{actions:t,actionLines:n,actionSourcePaths:r,metadata:i}=e;return{platform:i.platform??null,target:i.target??null,steps:t.map((e,t)=>$s(e,n[t]??null,r?.[t]??null))}}function $s(e,t,n){return{command:e.command,positionals:e.positionals??[],flags:e.flags??{},runtime:e.runtime??null,targetEvidence:e.targetEvidence??null,targetEvidences:e.targetEvidences??null,source:{path:n,line:t}}}function ec(e,t,n){let{from:r,digest:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e;if(r===void 0&&i===void 0)return{ok:!0,value:0};if(r===void 0||i===void 0)return{ok:!1,message:`replay --from requires --plan-digest (and --plan-digest requires --from).`};let s=tc({from:r,digest:i,planDigest:n,actionCount:t,pendingRecordAndHeal:a,sessionActionsLength:o});return s?{ok:!1,message:s}:{ok:!0,value:r-1}}function tc(e){let{from:t,digest:n,planDigest:r,actionCount:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e,s=[()=>nc({from:t,actionCount:i,pendingRecordAndHeal:a}),()=>rc({from:t,pendingRecordAndHeal:a,sessionActionsLength:o}),()=>ic(n,r)];for(let e of s){let t=e();if(t)return t}}function nc(e){let{from:t,actionCount:n,pendingRecordAndHeal:r}=e,i=t===n+1&&r!==void 0&&r.expectedFrom===t;return Number.isInteger(t)&&t>=1&&(t<=n||i)?void 0:`replay --from ${t} is out of range for a ${n}-step plan.`}function rc(e){let{from:t,pendingRecordAndHeal:n,sessionActionsLength:r}=e;if(n?.expectedFrom===t&&r===n.actionsCountAtDivergence)return`replay --from ${t} continues a record-and-heal-shaped repair, but no corrective action was recorded in this repair segment; press the correct control via a blessed @ref from the divergence's screen.refs (recorded, no --no-record) — or, if your corrective action was a read (get/is/find/snapshot), re-run it with --record so it lands in the heal — before resuming with --from ${t}.`}function ic(e,t){if(e!==t)return`replay --plan-digest does not match the current plan digest; the script, its includes, or its platform-conditioned expansion changed since the divergence report was generated. Run a fresh full replay to get a new digest.`}function ac(e,t){let n=e.trimStart()[0];if(n===`{`||n===`[`)throw new a(`INVALID_ARGS`,`replay accepts .ad script files. JSON replay payloads are no longer supported.`);let r=te(e),i=re(e),o=Zs({actions:r.actions,actionLines:r.actionLines,actionSourcePaths:r.actionSourcePaths,metadata:{platform:t?.platform??ae(r.actions)??i.platform,target:t?.target??i.target}}),s=r.actions.length;return{actions:r.actions,actionLines:r.actionLines,actionSourcePaths:r.actionSourcePaths,metadata:i,planDigest:o,resolveEntryIndex:e=>ec(e,s,o)}}function oc(e){let{recorded:t,isSelectorWait:n}=e;return n?t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`deferred-landmark`,landmark:t}:{kind:`skip`}}function sc(e){let{recorded:t,token:n}=e;return n===void 0||!n.startsWith(`@`)&&je(`positional`,[n]).kind!==`expression`?{kind:`skip`}:t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`verify`,token:n}}function cc(e,t){if(!(!e||!t)&&(e.documentOrder!==t.documentOrder||e.sibling!==t.sibling))return`position: recorded=doc${e.documentOrder}/sibling${e.sibling} observed=doc${t.documentOrder}/sibling${t.sibling}`}function lc(e,t,n){let{observed:r,expectedStructural:i,observedStructural:a}=t,o=cc(i,a);return{matchCount:n,observed:r,mismatches:[...r?Xe(e,r):[],...o?[o]:[]],causeMessage:`Dispatch resolution (with occlusion/visibility guards) resolved a different element than pre-action verification isolated; the action was not sent.`}}function uc(e,t){let{matchCount:n,observed:r,observedAncestry:i}=t;return{matchCount:n,observed:r,mismatches:r?[...Xe(e,r),...rt(e.ancestry,i)]:[],causeMessage:`Candidates matched the recorded wait selector during polling, but none carried the recorded landmark identity before the timeout; the wait did not report success.`}}async function dc(e,t,n,r,i,a){if(n.targetEvidences)return fc(e,t,n,r,i,a);let o=n.targetEvidence;if(!o)return q(e,n,r,i,a);let s=e.beginTargetVerification(n,r,i);if(s.kind===`inactive`)return q(e,n,r,i,a);if(s.kind===`post-resolution`){let c=oc({recorded:o,isSelectorWait:s.isSelectorWait});switch(c.kind){case`skip`:return q(e,n,r,i,a);case`recorded-unverifiable`:return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(n,i,a,t)};case`deferred-landmark`:return mc(e,t,n,r,i,a,{kind:`landmark`,landmark:c.landmark})}}let c=sc({recorded:o,token:s.token});if(c.kind===`skip`)return q(e,n,r,i,a);if(c.kind===`recorded-unverifiable`)return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(n,i,a,t)};let l=c.token,u=await e.observeTarget({action:n,index:i,token:l});if(u.state!==`classified`)return{status:`failed`,failure:await e.buildTargetBindingFailure(n,i,pc(u),a,t)};let{classification:d}=u;return d.verified?mc(e,t,n,r,i,a,{kind:`target`,guard:d.guard}):{status:`failed`,failure:await e.buildTargetBindingFailure(n,i,{kind:d.kind,matchCount:d.matchCount,observed:d.observed,candidateNodes:d.candidateNodes,mismatches:d.mismatches,causeCode:d.causeCode,causeMessage:d.causeMessage},a,t)}}async function fc(e,t,n,r,i,a){let o=n.targetEvidences,s={};for(let c of[`source`,`destination`]){let l={...n,targetEvidence:o[c]},u=e.beginTargetVerification(l,r,i,c);if(u.kind!==`pre-dispatch`)return q(e,n,r,i,a);let d=sc({recorded:o[c],token:u.token});if(d.kind===`skip`)return q(e,n,r,i,a);if(d.kind===`recorded-unverifiable`)return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(l,i,a,t)};let f=await e.observeTarget({action:l,index:i,token:d.token});if(f.state!==`classified`)return{status:`failed`,failure:await e.buildTargetBindingFailure(l,i,pc(f),a,t)};let{classification:p}=f;if(!p.verified)return{status:`failed`,failure:await e.buildTargetBindingFailure(l,i,{kind:p.kind,matchCount:p.matchCount,observed:p.observed,candidateNodes:p.candidateNodes,mismatches:p.mismatches,causeCode:p.causeCode,causeMessage:p.causeMessage},a,t)};s[c]=p.guard}return mc(e,t,n,r,i,a,{kind:`targets`,guards:{source:s.source,destination:s.destination}})}function pc(e){return{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Could not capture a fresh snapshot to verify the recorded target before acting (${e.reason}).`,...e.hint===void 0?{}:{causeHint:e.hint}}}async function q(e,t,n,r,i){let a=await e.dispatchStep(t,n,r,i,void 0);switch(a.status){case`ok`:return{status:`ok`,artifactPaths:a.artifactPaths};case`failed`:return{status:`failed`,failure:a.failure};case`guard-mismatch`:case`landmark-mismatch`:return{status:`failed`,failure:a.plainFailure}}}async function mc(e,t,n,r,i,a,o){let s=await e.dispatchStep(n,r,i,a,o);if(s.status===`ok`)return{status:`ok`,artifactPaths:s.artifactPaths};if(s.status===`failed`)return{status:`failed`,failure:s.failure};let c=hc(n,o,s);if(!c)return{status:`failed`,failure:s.plainFailure};let l=gc(c.recorded,c.matchCount,s);return{status:`failed`,failure:await e.buildPostDispatchTargetBindingFailure(c.reportAction,i,{kind:`identity-mismatch`,matchCount:l.matchCount,observed:l.observed,candidateNodes:[],mismatches:l.mismatches,causeCode:`IDENTITY_MISMATCH`,causeMessage:l.causeMessage},a,t)}}function hc(e,t,n){if(n.status!==`guard-mismatch`||t.kind!==`targets`)return e.targetEvidence?{recorded:e.targetEvidence,reportAction:e,matchCount:t.kind===`target`?t.guard.matchCount:0}:void 0;let r=n.evidence.targetRole??`source`,i=e.targetEvidences?.[r];return i?{recorded:i,reportAction:{...e,targetEvidence:i},matchCount:t.guards[r].matchCount}:void 0}function gc(e,t,n){return n.status===`guard-mismatch`?lc(e,n.evidence,t):uc(e,n.evidence)}async function _c(e,t){let{actions:n,entryIndex:r,keepSession:i}=e,a=Ot(e.varSources),o=[],s=[],c=xc(n),l=0;for(let u=r;u<n.length;u+=1){let r=n[u];if(!bc(r)||(t.armStep(),u===c&&(i||t.isRepairArmed())))continue;if(l+=1,t.onStep){let e=t.describeStepValue(r);t.onStep(Sc(u,n.length,r,e))}let d=Dt(r,a,yc(e,u)),f=wt(a),p=t.diagnosticsMarker(),m=await dc(t,f,r,d,u,o);if(s.push(...t.diagnosticsSince(p)),m.status===`ok`){o=m.artifactPaths;continue}let h=await t.handleActionFailure({action:r,index:u,artifactPaths:vc(o,m.failure.artifactPaths),snapshotDiagnosticSamples:s,scrubVars:f});return{status:`failed`,stepIndex:u,failure:h}}return{status:`completed`,replayed:l,artifactPaths:[...o],snapshotDiagnosticSamples:s}}function vc(e,t){return t.length===0?e:[...new Set([...e,...t])]}function yc(e,t){return{file:e.actionSourcePaths?.[t]??e.resolvedPath,line:e.actionLines[t]??1}}function bc(e){return!!(e&&e.command!==`replay`)}function xc(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(bc(n))return n.command===`close`?t:void 0}}function Sc(e,t,n,r){return{index:e+1,total:t,command:n.command,...r===void 0?{}:{value:r}}}async function Cc(e){return await wc({...e,snapshotDiagnostics:x(e.snapshotDiagnosticSamples)})}async function wc(e){let{response:t,action:n,index:r,replayPath:i,sourcePath:a,sourceLine:o,artifactPaths:s=[],snapshotDiagnostics:c,scrubVars:l,req:u,sessionStore:d,observationStore:f,resumeStamper:p,logPath:m,planActions:h,planDigest:g}=e;if(t.ok)return t;let _=Tc(t.error.details?.replaySource),v=Hr(t.error),y=await Ur({error:v,action:n,index:r,sourcePath:_?.path??a,sourceLine:_?.line??o,session:f.get(),sessionStore:d,observationStore:f,resumeStamper:p,logPath:m,responseLevel:u.meta?.responseLevel,scrubVars:l,planActions:h,planDigest:g,signal:Jn(u.meta?.requestId)});return Qr({error:v,action:n,step:r+1,replayPath:i,artifactPaths:s,snapshotDiagnostics:c,divergence:y,scrubVars:l})}function Tc(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=typeof t.path==`string`&&t.path.length>0?t.path:void 0,r=typeof t.line==`number`?t.line:void 0;if(n!==void 0||r!==void 0)return{path:n,line:r}}async function Ec(e){let{req:t,sessionName:n,action:r,resolved:i,filePath:o,line:s,step:c,sourcePath:l,tracePath:u,invoke:d,resolvedSessionScope:p,dependencies:m}=e,h=Date.now();Yr(u,{type:`replay_action_start`,ts:new Date(h).toISOString(),replayPath:o,...l?{sourcePath:l}:{},line:s,step:c,command:i.command,positionals:Mn(i)??[]});let g;try{g=await Oc({req:t,sessionName:n,resolved:i,sourceAction:r,invoke:d,resolvedSessionScope:p,dependencies:m})}catch(e){if(!(e instanceof a))throw e;g={ok:!1,error:f(e)}}let _=Date.now();return Yr(u,{type:`replay_action_stop`,ts:new Date(_).toISOString(),replayPath:o,...l?{sourcePath:l}:{},line:s,step:c,command:i.command,ok:g.ok,durationMs:_-h,resultTiming:g.ok?Ac(g.data):void 0,errorCode:g.ok?void 0:g.error.code}),Dc(g,l??o,s)}function Dc(e,t,n){return e.ok||e.error.details?.replaySource!==void 0?e:{ok:!1,error:{...e.error,details:{...e.error.details??{},replaySource:{path:t,line:n}}}}}async function Oc(e){let{req:t,sessionName:n,resolved:r,sourceAction:i,invoke:o,resolvedSessionScope:s,dependencies:c}=e,l=w(r.command,r.positionals??[],r.flags??{},`after variable substitution`);if(l)throw new a(`INVALID_ARGS`,l);let u=y(t.flags,{...r.flags??{}}),d=i.command===`fill`?kt(jt(i)):void 0;return d&&(u.recordAs=d),await o(kc({token:t.token,session:n,flags:u,runtime:r.runtime,meta:t.meta,dispatch:{...t.dispatch,replayPlanStep:!0,...r.command===`open`?{resolvedSessionScope:s??c.resolveSessionScope(t)}:{}}},r))}function kc(e,t){let n=t.positionals??[];return t.command===`gesture`?{...e,command:t.command,positionals:[],input:pe(n,{pointerCount:e.flags?.pointerCount,holdMs:e.flags?.holdMs,count:e.flags?.count,pauseMs:e.flags?.pauseMs})}:t.command===`swipe`?{...e,command:t.command,positionals:[],input:ce(n,{count:e.flags?.count,pauseMs:e.flags?.pauseMs,pattern:e.flags?.pattern})}:{...e,command:t.command,positionals:n}}function Ac(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.timing;if(!(!t||typeof t!=`object`||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,e])=>{let t=typeof e;return t===`number`||t===`string`||t===`boolean`}))}function jc(e){return Rc(e.ok?Nc(e.data):Mc(e.error.details?.artifactPaths))}function Mc(e){return Array.isArray(e)?e.filter(Lc):[]}function Nc(e){return e?[Ic(e.path),Ic(e.outPath),...Pc(e.artifacts)].filter(Lc):[]}function Pc(e){return Array.isArray(e)?e.map(Fc).filter(Lc):[]}function Fc(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;return Ic(t.localPath)??Ic(t.path)}function Ic(e){return typeof e==`string`?e:void 0}function Lc(e){return typeof e==`string`}function Rc(e){return[...new Set(e.filter(zc))]}function zc(e){try{return W.statSync(e).isFile()}catch{return!1}}function Bc(e){let{recorded:t,token:n,nodes:i,platform:a,refLabel:o,requireRect:s,allowDisambiguation:c}=e,l=Vc({token:n,nodes:i,platform:a,refLabel:o,requireRect:s,allowDisambiguation:c}),u=Bt(i),d=qe(t),f=Vt(l.matchedNodes,u,d,t.ancestry),p=f.filter(e=>yt(i,e)===t.sibling),m=f.filter(e=>vt(e,u,t.scrollRegion)),h=_t(m)[t.viewportOrder]?.ref,g=bt({winnerRef:l.winnerRef,matchedRefs:r(l.matchedNodes),identitySetRefs:r(f),siblingMatchRefs:r(p),regionMemberRefs:r(m),viewportCandidateRef:h}),_=l.matchedNodes.find(e=>e.ref===l.winnerRef);return g.outcome===`verified`&&_?{verified:!0,winnerNode:_,matchCount:l.matchedNodes.length}:g.outcome===`verified`?{verified:!1,kind:`identity-unverifiable`,matchCount:l.matchedNodes.length,observedNode:void 0,candidateNodes:f.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`Verification isolated a member that is not part of the matched-node domain (capture anomaly).`}:{verified:!1,...Wc({classification:g,matchCount:l.matchedNodes.length,winnerNode:_,identitySet:f,byIndex:u,recorded:t})}}function Vc(e){let{token:t,nodes:n,platform:r,refLabel:i,requireRect:a,allowDisambiguation:o}=e;return t.startsWith(`@`)?Hc(n,t,i,a):Uc(n,t,r,a,o)}function Hc(e,r,i,a){let s=e=>e!==null&&(!a||!!e.rect),c=t(r),l=c?n(e,c):null;if(s(l)&&l.ref!==void 0)return{matchedNodes:[l],winnerRef:l.ref};let u=i?br(e,i):null;return s(u)&&o(u)?{matchedNodes:[u],winnerRef:u.ref}:{matchedNodes:[],winnerRef:``}}function Uc(e,t,n,r,i){let a=Ne(t,e,{platform:n,requireRect:r,allowDisambiguation:i});if(a.kind===`resolved`&&a.winner.ref!==void 0)return{matchedNodes:[...a.matchedNodes],winnerRef:a.winner.ref};let o=pr(e,a.matchedNodes);return{matchedNodes:[...a.matchedNodes],winnerRef:o?.ref??``}}function Wc(e){let{classification:t,matchCount:n,winnerNode:r,identitySet:i,byIndex:a,recorded:o}=e;switch(t.reason){case`selector-miss`:return{kind:`selector-miss`,matchCount:0,observedNode:void 0,candidateNodes:[],mismatches:[],causeCode:`SELECTOR_MISS`,causeMessage:`The recorded target no longer matches any current element.`};case`identity-set-empty`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Gc(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`The recorded selector/ref still matches, but nothing in the current tree carries the recorded identity.`};case`unique-but-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Gc(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`Exactly one current element carries the recorded identity, but the resolved target is a different element.`};case`signal-isolated-wrong`:return{kind:`identity-mismatch`,matchCount:n,observedNode:r,candidateNodes:[],mismatches:r?Gc(o,r,a):[],causeCode:`IDENTITY_MISMATCH`,causeMessage:`A disambiguation signal (sibling or viewport position) isolated a different element than the resolved target.`};case`no-signal-isolation`:return{kind:`identity-unverifiable`,matchCount:n,observedNode:r,candidateNodes:i.slice(0,5),mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`${i.length} current elements carry the recorded identity and neither disambiguation signal isolated one.`}}}function Gc(e,t,n){let r=xt(t),i=Ht(t,n,Math.max(e.ancestry.length,1)).chain;return[...Xe(e,r),...rt(e.ancestry,i)].slice(0,5)}function Kc(e,t){let n=e.positionals??[];if(e.command===`gesture`){let e=le(n);return e?e[t??`source`]:void 0}if(e.command===`get`)return n[1];if(e.command===`is`){let e=je(`is`,n);return e.kind===`expression`?e.expression:void 0}if(!se(e.command)&&e.command!==`fill`)return;let r=n[0];if(r!==void 0&&!(Jc(r)&&Jc(n[1])))return r}function qc(e){let t=e.result?.refLabel;return typeof t==`string`&&t.length>0?t:void 0}function Jc(e){return e!==void 0&&e.trim().length>0&&!Number.isNaN(Number(e))}function Yc(e,t){let{recorded:n,action:r,step:i,sourcePath:a,sourceLine:o,replayPath:s,artifactPaths:c,sessionStore:l,resumeStamper:u,responseLevel:d,scrubVars:f,planActions:p,planDigest:m}=e,h=vn(f),g={classification:t.kind,...t.matchCount===void 0?{}:{matchCount:t.matchCount},recorded:al(qe(n),h),...t.observed?{observed:al(t.observed,h)}:{},mismatches:t.mismatches.slice(0,5).map(e=>h(e)),candidates:t.candidateNodes.slice(0,5).map(e=>ol(e,h))},_=Jr({kind:t.kind,targetEvidence:n,capture:t.repairCapture}),v=Kr({failedIndex:i,actions:p,planDigest:m,repairHint:_,resumeStamper:u}),y={version:1,kind:t.kind,step:{index:i,source:{path:h(a),line:o}},action:h(ne(r)),cause:{code:t.causeCode,message:h(t.causeMessage),...t.causeHint?{hint:h(t.causeHint)}:{}},screen:t.screen,suggestions:[],suggestionCount:0,resume:v,repairHint:_,targetBinding:g},b=Zr({sessionStore:l,observationStore:e.observationStore,divergence:y,responseLevel:d,evidence:t.publicationEvidence,...e.signal?{signal:e.signal}:{}}),x={code:t.causeCode,message:t.causeMessage};return Qr({error:x,action:r,step:i,replayPath:s,artifactPaths:c,divergence:b,scrubVars:f})}function Xc(e,t,n){let r=vn(e.scrubVars);return Yc(e,{kind:t.kind,matchCount:t.matchCount,observed:t.observed,candidateNodes:t.candidateNodes,mismatches:t.mismatches,causeCode:t.causeCode,causeMessage:t.causeMessage,...t.causeHint===void 0?{}:{causeHint:t.causeHint},screen:Xr(n,r),publicationEvidence:el(n),repairCapture:Wr(n)})}async function Zc(e){let{session:t,observationStore:n,logPath:r,action:i,unavailableHint:a,signal:o}=e;return t?await qr({session:t,observationStore:n,logPath:r,action:i,signal:o}):{state:`unavailable`,reason:`no-session`,hint:a}}async function Qc(e,t){return Xc(e,{kind:`identity-unverifiable`,matchCount:void 0,observed:void 0,candidateNodes:[],mismatches:[],causeCode:`IDENTITY_UNVERIFIABLE`,causeMessage:`The recorded target evidence could not verify itself when it was captured (a structural capture anomaly), so replay cannot trust it before acting.`},await Zc({...t,signal:e.signal,unavailableHint:`The session closed before a screen could be captured to verify the recorded target evidence.`}))}async function $c(e,t,n){return Xc(e,t,await Zc({...n,signal:e.signal,unavailableHint:`The session closed before a post-failure screen could be captured.`}))}function el(e){return e.state===`available`?e.evidence:void 0}function tl(e){let{action:t,resolvedAction:n,sessionStore:r,targetRole:i}=e,a=r.get();return a?we(t.command)===`post-resolution`?{kind:`post-resolution`,isSelectorWait:Pe(n.positionals??[])?.kind===`selector`}:{kind:`pre-dispatch`,token:Kc(n,i),platform:a.device.platform}:{kind:`inactive`}}function nl(e){let{recorded:t,token:n,action:r,nodes:i,platform:a}=e,o=ei(r),s=Bc({recorded:t,token:n,nodes:i,platform:a,refLabel:qc(r),requireRect:o.requiresRect,allowDisambiguation:o.allowDisambiguation});return s.verified?{verified:!0,guard:{expected:{identity:xt(s.winnerNode),structural:$e(s.winnerNode,i)},matchCount:s.matchCount}}:{verified:!1,kind:s.kind,matchCount:s.matchCount,observed:s.observedNode?xt(s.observedNode):void 0,candidateNodes:s.candidateNodes,mismatches:s.mismatches,causeCode:s.causeCode,causeMessage:s.causeMessage}}function rl(e){return!e.ok&&e.error.details?.reason===`replay_target_guard_mismatch`}function il(e){return!e.ok&&e.error.details?.reason===ti}function al(e,t){return{...e.id===void 0?{}:{id:t(e.id)},role:t(e.role),...e.label===void 0?{}:{label:t(e.label)}}}function ol(e,t){let n=p(e.type??`Element`),r=fe(e,n);return{...e.ref?{ref:e.ref}:{},role:t(n),...r?{label:t(r)}:{}}}function sl(e,t){let n=t?.kind===`target`?{replayTargetGuard:t.guard.expected}:t?.kind===`targets`?{replayTargetGuards:{source:t.guards.source.expected,destination:t.guards.destination.expected}}:t?.kind===`landmark`?{replayLandmarkGuard:t.landmark}:void 0;return n?{...e,dispatch:{...e.dispatch,...n}}:e}function cl(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.role==`string`)return{...typeof t.id==`string`?{id:t.id}:{},role:t.role,...typeof t.label==`string`?{label:t.label}:{}}}function ll(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`||Array.isArray(n))return[];let e=n;if(typeof e.role!=`string`)return[];t.push({role:e.role,...typeof e.label==`string`?{label:e.label}:{}})}return t}function ul(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;if(typeof t.documentOrder==`number`&&typeof t.sibling==`number`)return{documentOrder:t.documentOrder,sibling:t.sibling}}function dl(e){return{...e?.targetRole===`source`||e?.targetRole===`destination`?{targetRole:e.targetRole}:{},observed:cl(e?.observed),expectedStructural:ul(e?.expectedStructural),observedStructural:ul(e?.observedStructural)}}function fl(e){return{matchCount:typeof e?.matchCount==`number`?e.matchCount:void 0,observed:cl(e?.observed),observedAncestry:ll(e?.observedAncestry)}}function pl(e,t){return{kind:e.error.code,message:e.error.message,artifactPaths:t}}function ml(e,t,n){let r=pl(e,n);return(t?.kind===`target`||t?.kind===`targets`)&&rl(e)?{status:`guard-mismatch`,evidence:dl(e.error.details),plainFailure:r,artifactPaths:n}:t?.kind===`landmark`&&il(e)?{status:`landmark-mismatch`,evidence:fl(e.error.details),plainFailure:r,artifactPaths:n}:{status:`failed`,failure:r}}function hl(e){let{ctx:t,req:n,artifactPaths:r,onStep:i,armSaveScript:a}=e,o,s,c=(e,n,r,i)=>({recorded:e.targetEvidence,action:e,step:n+1,sourcePath:t.actionSourcePaths?.[n]??t.resolved,sourceLine:t.actionLines[n]??1,replayPath:t.resolved,artifactPaths:[...r],sessionStore:t.sessionStore,observationStore:t.observationStore,resumeStamper:t.coordinator.resumeStamper,responseLevel:t.responseLevel,scrubVars:i,planActions:t.actions,planDigest:t.planDigest,signal:t.signal}),l=e=>(o=e,pl(gl(e),jc(e))),u=async e=>{let n=t.observationStore.get();return n?await qr({session:n,observationStore:t.observationStore,logPath:t.logPath,action:e,retryLaunchRace:!0,signal:t.signal}):{state:`unavailable`,reason:`no-session`,hint:`The session closed before a screen could be captured to verify the recorded target.`}};return{runtime:{beginTargetVerification(e,n,r,i){return tl({action:e,resolvedAction:n,sessionStore:t.sessionStore,targetRole:i})},async observeTarget({action:e,token:n}){let r=await u(e);if(s=r,r.state!==`available`)return{state:`unavailable`,reason:r.reason,hint:r.hint};let i=t.sessionStore.get();return{state:`classified`,classification:nl({recorded:e.targetEvidence,token:n,action:e,nodes:[...r.nodes],platform:i.device.platform})}},async dispatchStep(e,n,i,a,s){let c=t.actionLines[i]??1,l=await Ec({req:sl(t.replayReq,s),sessionName:t.sessionName,action:e,resolved:n,filePath:t.resolved,line:c,sourcePath:t.actionSourcePaths?.[i],step:i+1,tracePath:t.actionTracePath,invoke:t.invoke,resolvedSessionScope:t.resolvedSessionScope,dependencies:t.dependencies});o=l,jc(l).forEach(e=>r.add(e));let u=[...r];return l.ok?{status:`ok`,artifactPaths:u}:ml(l,s,u)},async buildRecordedUnverifiableFailure(e,n,r,i){let a=await Qc(c(e,n,r,i),{session:t.observationStore.get(),observationStore:t.observationStore,logPath:t.logPath,action:e});return l(a)},async buildTargetBindingFailure(e,t,n,r,i){let a=s??{state:`unavailable`,reason:`observation-missing`,hint:`No capture was recorded before this target-binding failure.`},o=Xc(c(e,t,r,i),n,a);return l(o)},async buildPostDispatchTargetBindingFailure(e,n,r,i,a){let o=await $c(c(e,n,i,a),r,{session:t.observationStore.get(),observationStore:t.observationStore,logPath:t.logPath,action:e});return l(o)},async handleActionFailure({action:e,index:r,artifactPaths:i,snapshotDiagnosticSamples:a,scrubVars:s}){let c=gl(o),u=await _l(t,n,e,r,c,[...i],[...a],s);return l(u)},armStep:()=>{s=void 0,a()},isRepairArmed:()=>t.coordinator.view()?.repairBoundary!==void 0,describeStepValue:e=>vl(e),onStep:i,diagnosticsMarker:()=>bl(t.sessionStore),diagnosticsSince:e=>xl(t.sessionStore,e)},readLastResponse:()=>o}}function gl(e){return e&&!e.ok?e:d(`COMMAND_FAILED`,`replay step reported failure with no recorded response`)}async function _l(e,t,n,r,i,a,o,s){let c=t=>e.coordinator.markSessionHeldIfArmed(t);return yl(i)?c(i):c(await Cc({response:i,action:n,index:r,replayPath:e.resolved,sourcePath:e.actionSourcePaths?.[r]??e.resolved,sourceLine:e.actionLines[r]??1,artifactPaths:a,snapshotDiagnosticSamples:o,scrubVars:s,req:t,sessionStore:e.sessionStore,observationStore:e.observationStore,resumeStamper:e.coordinator.resumeStamper,logPath:e.logPath,planActions:e.actions,planDigest:e.planDigest}))}function vl(e){let t=e.positionals??[],n=Oe(t[0]);if(n)return n;if(t.length!==0)return t.join(` `)}function yl(e){if(e.ok||e.error.code!==`REPLAY_DIVERGENCE`)return!1;let t=e.error.details?.divergence,n=t&&typeof t==`object`?t.kind:void 0;return typeof n==`string`&&n!==`action-failure`}function bl(e){return e.get()?.snapshotDiagnostics?.samples.length??0}function xl(e,t){return e.get()?.snapshotDiagnostics?.samples.slice(t)??[]}async function Sl(e){let{resolved:t,keepSession:n,coordinator:r,command:i}=e,{request:a}=i,o=E(t,a.flags?.replayBackend);if(o!==`ad`)return n?d(`INVALID_ARGS`,`--keep-session is supported only for native .ad replay; Maestro YAML owns its lifecycle.`):r.view()?.repairBoundary===void 0?await(await ni(o)).runReplay(i):d(`INVALID_ARGS`,`This session has an active .ad --save-script repair run; finish it with replay --from or close before running Maestro YAML.`)}function Cl(e){let{req:t,host:n,sessionName:r,sessionStore:i,tracePath:a,resolved:o,script:s,coordinator:c,dispatch:l}=e,u=wl(t);if(u)return{ok:!1,response:u};let{manifest:d,replayReq:f}=Tl(t,s,l),{metadata:p,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_}=d,v=i.get(),y=El({req:t,coordinator:c,manifest:d,preEntrySession:v});return y.ok?{ok:!0,value:{replayReq:f,actions:m,actionLines:h,actionSourcePaths:g,planDigest:_,preEntrySession:v,entryIndex:y.value,varSources:Ol({req:t,host:n,replayReq:f,sessionName:r,resolved:o,metadata:p}),actionTracePath:a??v?.trace?.outPath}}:{ok:!1,response:y.response}}function wl(e){let t=e.flags?.replayBackend;if(t&&!ee(t))return d(`INVALID_ARGS`,ie(t))}function Tl(e,t,n){let r=ac(t,{platform:e.flags?.platform,target:e.flags?.target});return{manifest:r,replayReq:Dl({...e,flags:Pn(e.flags,r.actions),...n?{dispatch:n}:{}},r.metadata)}}function El(e){let{req:t,coordinator:n,manifest:r,preEntrySession:i}=e,a=r.resolveEntryIndex({from:t.flags?.replayFrom,digest:t.flags?.replayPlanDigest,pendingRecordAndHeal:n.view()?.pendingRecordAndHeal,sessionActionsLength:i?.actions.length??0});return a.ok?{ok:!0,value:a.value}:{ok:!1,response:d(`INVALID_ARGS`,a.message)}}function Dl(e,t){return!t.platform&&!t.target?e:{...e,flags:kl(e.flags,t)}}function Ol(e){let{req:t,host:n,replayReq:r,sessionName:i,resolved:a,metadata:o}=e;return{builtins:$r({req:r,sessionName:i,metadata:o,resolvedPath:a,hostCwd:n.cwd}),fileEnv:o.env,shellEnv:Et(Tt(t.flags?.replayShellEnv,n.env)),cliEnv:Ct(St(t.flags?.replayEnv))}}function kl(e,t){return{...e??{},...t.platform!==void 0&&e?.platform===void 0?{platform:t.platform}:{},...t.target!==void 0&&e?.target===void 0?{target:t.target}:{}}}const Al={kind:`none`,status:void 0,targetPath:void 0,targetForce:!1};function jl(e){let{req:t,entryIndex:n,hostCwd:r,sessionStore:i,sourcePath:a,coordinator:o}=e,s=Ml({entryIndex:n,sessionStore:i,coordinator:o});return s?{ok:!1,response:s}:(Fl({req:t,coordinator:o}),Pl({req:t,hostCwd:r,sessionStore:i,sourcePath:a,coordinator:o}))}function Ml(e){let t=Il(e);if(t)return t;if(e.entryIndex>0&&!e.sessionStore.get())return u()}function Nl(e){let{saveScript:t,force:n,hostCwd:r,preRunState:i,sourcePath:a}=e;return t&&i.kind===`authoring`?d(`INVALID_ARGS`,`replay --save-script cannot re-arm an ordinary recording in terminal/active state ${i.status}. Close this session and use a fresh one for repair authoring.`):Ll({saveScript:t,liveForce:n,persistedForce:i.targetForce||void 0,hostCwd:r,sourcePath:a,existingSaveScriptPath:i.targetPath})}function Pl(e){let{req:t,hostCwd:n,sourcePath:r,coordinator:i}=e,{saveScript:a,force:o}=t.flags??{},s=Nl({saveScript:a,force:o,hostCwd:n,preRunState:i.view()?.scriptPublication??Al,sourcePath:r});return s?{ok:!1,response:s}:(i.demoteForRerunIfArmed(),{ok:!0,armSaveScript:Rl({saveScript:a,force:o,coordinator:i,sourcePath:r})})}function Fl(e){let{req:t,coordinator:n}=e;n.clearCorrectiveWatermarkIfExpected(t.flags?.replayFrom),t.flags?.saveScript&&n.clearTombstone()}function Il(e){let{entryIndex:t,coordinator:n}=e;if(!(t>0)&&n.view()?.repairBoundary!==void 0)return d(`INVALID_ARGS`,`This session has an active --save-script repair run; continue it with replay --from <n> --plan-digest <sha256>, or finish with close, before starting a fresh full replay.`)}function Ll(e){let{saveScript:t,liveForce:n,persistedForce:r,hostCwd:i,sourcePath:a,existingSaveScriptPath:o}=e;if(!t)return;let s=typeof t==`string`?F(t,i):o??Gr(a);if(!(n||r&&s===o)&&W.existsSync(s))return d(`COMMAND_FAILED`,`A file already exists at ${s}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`)}function Rl(e){let{saveScript:t,force:n,coordinator:r,sourcePath:i}=e;if(!t)return()=>{};let a=!0;return()=>{r.armStep({saveScript:t,force:n,sourcePath:i,firstArm:a}),a=!1}}async function zl(e){let{request:t,host:n,session:{name:r,logPath:i,store:a,observationStore:o,coordinator:s},tracePath:c,onStep:l,invoke:u}=e,p=t.flags?.replayScriptSource;if(!p)return d(`INVALID_ARGS`,An);let m=Date.now(),h=t.flags?.replayKeepSession===!0,g=``,_=new Set;try{if(g=p.entry,de(g)&&t.flags?.replayBackend!==`maestro`)return d(`INVALID_ARGS`,ue(`replay`,g));let f=await Sl({resolved:g,keepSession:h,coordinator:s,command:e});if(f)return f;let v=Cl({req:t,host:n,sessionName:r,sessionStore:a,tracePath:c,resolved:g,script:Nn(p,g),coordinator:s,dispatch:e.dispatch});if(!v.ok)return v.response;let{replayReq:y,actions:b,actionLines:x,actionSourcePaths:S,planDigest:C,entryIndex:w,varSources:ee,actionTracePath:T}=v.value,te=jl({req:t,entryIndex:w,hostCwd:n.cwd,sessionStore:a,sourcePath:g,coordinator:s});if(!te.ok)return te.response;let{runtime:ne,readLastResponse:re}=hl({ctx:{replayReq:y,sessionName:r,sessionStore:a,observationStore:o,logPath:i,resolved:g,actions:b,actionLines:x,actionSourcePaths:S,planDigest:C,actionTracePath:T,responseLevel:t.meta?.responseLevel,invoke:u,signal:Jn(t.meta?.requestId),coordinator:s,resolvedSessionScope:e.resolvedSessionScope,dependencies:e.dependencies},req:t,artifactPaths:_,onStep:l,armSaveScript:te.armSaveScript}),E=await _c({actions:b,entryIndex:w,keepSession:h,actionLines:x,actionSourcePaths:S,resolvedPath:g,varSources:ee},ne);return E.status===`failed`?re()??d(`COMMAND_FAILED`,`replay step failed with no recorded response`):Bl({startedAt:m,sessionName:r,sessionStore:a,replayed:E.replayed,artifactPaths:E.artifactPaths,snapshotDiagnosticSamples:E.snapshotDiagnosticSamples,armSaveScript:te.armSaveScript,coordinator:s,keepSession:h})}catch(e){let t=f(e);return _.size===0?{ok:!1,error:t}:{ok:!1,error:{...t,details:{...t.details,artifactPaths:[..._]}}}}}function Bl(e){let{startedAt:t,sessionName:n,sessionStore:r,replayed:i,artifactPaths:a,snapshotDiagnosticSamples:o,armSaveScript:s,coordinator:c,keepSession:l}=e;s(),c.markCompleteIfArmed();let u=r.get(),d=Hl({keepSession:l,sessionName:n,completedSession:u,artifactPaths:a});if(d)return d;let f=x([...o]);return{ok:!0,data:{replayed:i,healed:0,session:n,sessionActive:u!==void 0,artifactPaths:[...a],...f?{snapshotDiagnostics:f}:{},message:Vl(i,Date.now()-t)}}}function Vl(e,t){let n=(t/1e3).toFixed(1);return`Replayed ${e} ${e===1?`step`:`steps`} in ${n}s`}function Hl(e){let{keepSession:t,sessionName:n,completedSession:r,artifactPaths:i}=e;if(!(!t||r))return d(`COMMAND_FAILED`,`Replay completed but --keep-session could not preserve session "${n}". Run the script again after checking which action closed the session.`,i.length>0?{artifactPaths:[...i]}:void 0)}function Ul(e){let{artifactsDir:t,cwd:n,suiteInvocationId:r}=e,i=G.resolve(n??`.`,t??`.agent-device/test-artifacts`);return G.join(i,r)}function Wl(e,t){let n=t?G.relative(t,e):G.basename(e),r=n.length===0||n.startsWith(`..`)?G.basename(e):n;return Ee(r.toLowerCase().replaceAll(/[\\/]+/g,`__`).replaceAll(/[^a-z0-9._-]+/g,`-`))||`test`}function Gl(e,t){W.mkdirSync(t,{recursive:!0}),Jl(e,t)}function Kl(e){let{outcome:t,filePath:n,sessionName:r,attempts:i,maxAttempts:a,attemptArtifactsDir:o}=e,s=t.status===`passed`,c=new Set(t.artifactPaths);t.status===`failed`&&typeof t.error.logPath==`string`&&c.add(t.error.logPath);let l=G.join(o,`result.txt`),u=G.join(o,`failure.txt`),d=ql([...c],o,[l,u]),f=[`file: ${n}`,`session: ${r}`,`attempt: ${i}/${a}`,`status: ${s?`passed`:`failed`}`];t.status===`passed`?f.push(`replayed: ${t.replayed}`,`healed: ${t.healed}`):(f.push(`code: ${t.error.code}`,`message: ${t.error.message}`),t.error.hint&&f.push(`hint: ${t.error.hint}`),t.error.diagnosticId&&f.push(`diagnosticId: ${t.error.diagnosticId}`),t.error.logPath&&f.push(`logPath: ${t.error.logPath}`),t.error.details?.reason===`timeout`&&f.push(`timeoutMode: cooperative`)),d.length>0&&f.push(`copiedArtifacts: ${d.map(e=>G.basename(e)).join(`, `)}`);let p=`${f.join(`
|
|
2
|
+
`)}\n`;W.writeFileSync(l,p),s||W.writeFileSync(u,p)}function ql(e,t,n){let r=[],i=new Set(n.map(e=>G.basename(e).toLowerCase()));for(let n of e){if(!Xl(n))continue;let e=G.basename(n);if(G.resolve(n)===G.resolve(t,e)&&!i.has(e.toLowerCase())){r.push(n);continue}let a=Yl(e,t,i),o=G.join(t,a);W.copyFileSync(n,o),r.push(o)}return r}function Jl(e,t){let n=G.join(t,`replay.ad`);if(W.copyFileSync(e,n),G.extname(e).toLowerCase()===`.ad`)return;let r=G.join(t,G.basename(e));G.resolve(r)!==G.resolve(n)&&W.copyFileSync(e,r)}function Yl(e,t,n){let r=G.extname(e),i=r?e.slice(0,-r.length):e,a=e,o=2;for(;n.has(a.toLowerCase())||W.existsSync(G.join(t,a));)a=`${i}-${o++}${r}`;return a}function Xl(e){try{return W.statSync(e).isFile()}catch{return!1}}function Zl(e){let{platformFilter:t,discoverSources:n}=e,r=n(),i=[],o={undeclared:0,declaredOther:0};for(let e of r){let{path:n,manifest:r}=e,a={kind:`run`,path:n,title:r.title,manifest:r};if(!t){i.push(a);continue}let s=r.device.platform;if(s.kind===`caller-bound`){i.push(a);continue}if(s.kind===`unspecified`){o.undeclared+=1,i.push({kind:`skip`,path:n,reason:`skipped-by-filter`,message:`missing platform metadata for --platform ${t}`});continue}if(!su(t,s.value)){o.declaredOther+=1;continue}i.push(a)}if(i.filter(e=>e.kind===`run`).length===0)throw new a(`INVALID_ARGS`,eu({platformFilter:t,...o}));return i}const Ql={web:!0};function $l(e){return!Object.hasOwn(Ql,e)}function eu(e){let{platformFilter:t,undeclared:n,declaredOther:r}=e,i=t?` for --platform ${t}`:``;return t===void 0||n===0&&r===0?`No replay tests matched${i}.`:`No replay tests matched${i}: ${[...n>0?[`${n} without a platform declaration`]:[],...r>0?[`${r} declaring another platform`]:[]].join(`, `)}. ${tu(t,n)}`}function tu(e,t){return $l(e)?t>0?`Add "context platform=${e}" to the first line of a script that has none, or drop --platform when the device is already selected.`:`Run a source that declares ${e}, or drop --platform.`:`No script can declare ${e} as its platform; run this suite without --platform.`}function nu(e,t,n,r,i=0){let a=G.basename(n,G.extname(n)),o=Ee(a.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`));return`${e}:test:${t}:${r+1}${o?`-${o}`:``}:attempt-${i+1}`}function ru(e){let t=e?.trim()||`${process.pid}-${Date.now().toString(36)}`;return Ee(t.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`))||`suite`}function iu(e){let{requestId:t,suiteInvocationId:n,filePath:r,caseIndex:i,attemptIndex:a,shardIndex:o}=e;return[t??n,...o===void 0?[]:[`shard`,o+1],`test`,i+1,G.basename(r),`attempt`,a+1].join(`:`)}function au(e,t){return typeof e==`number`?e:t}function ou(e,t){let n=typeof e==`number`?e:t;return typeof n==`number`?Math.max(0,Math.min(3,n)):0}function su(e,t){return e===`apple`?A(t):t===e}function J(e){return{status:`failed`,error:e.error,artifactPaths:e.artifactPaths??[],warnings:e.warnings??[],infrastructure:e.infrastructure??!1,...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}const cu=2e3;async function lu(e){let{filePath:t,sessionName:n,requestId:r,parentRequestId:i,timeoutMs:a,platform:o,target:s,artifactsDir:c,shard:l,onStep:u,runReplay:d,cleanupSession:p,finalizeAttempt:m,emitDiagnostic:h,bindAttemptCancellation:g}=e,_=g({attemptId:r,parentAttemptId:i}),v=new Set,y,b=!1,x,S=Date.now(),C=gu({artifactsDir:c,artifactPaths:v,filePath:t,sessionName:n,requestId:r,timeoutMs:a,platform:o,target:s}),w=d({filePath:t,sessionName:n,platform:o,target:s,requestId:r,artifactsDir:c,artifactPaths:v,tracePath:C,appendTimingEvent:e=>Y(C,e),shard:l,onStep:u}).catch(e=>J({error:f(e)})).finally(()=>{_.release()});try{x=typeof a==`number`?await Promise.race([w,new Promise(e=>{y=setTimeout(()=>{b=!0,_.cancel(),e(_u(a,[...v]))},a)})]):await w,Y(C,{type:`replay_test_attempt_stop`,ts:new Date().toISOString(),session:n,ok:x.status===`passed`,timedOut:b,durationMs:Date.now()-S,errorCode:x.status===`passed`?void 0:x.error.code})}finally{y&&clearTimeout(y),b&&(await du(w)||(x=mu(x),h({level:`warn`,phase:`test_timeout_cleanup_race`,data:{session:n,requestId:r,graceMs:cu}}),fu({replayPromise:w,cleanupSession:p,sessionName:n,requestId:r,emitDiagnostic:h})));let e=await pu({finalizeAttempt:m,sessionName:n,artifactPaths:v,artifactsDir:c,tracePath:C,emitDiagnostic:h});x?.status===`passed`&&e&&(x=hu(x,`Replay test finalization failed: ${e.error.message}`));let t=Date.now();try{Y(C,{type:`replay_test_cleanup_start`,ts:new Date().toISOString(),session:n}),await p(n),Y(C,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:n,ok:!0,durationMs:Date.now()-t})}catch(e){let r=f(e);Y(C,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:n,ok:!1,durationMs:Date.now()-t,errorCode:r.code}),h({level:`warn`,phase:`test_cleanup_failed`,data:{session:n,error:r.message}}),x=uu(x,r,v)}}return x??J({error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}})}function uu(e,t,n){return e?.status===`failed`?{...e,infrastructure:!0}:J({error:t,artifactPaths:[...n],infrastructure:!0})}async function du(e){return await Promise.race([e.then(()=>!0),di(cu).then(()=>!1)])}async function fu(e){let{replayPromise:t,cleanupSession:n,sessionName:r,requestId:i,emitDiagnostic:a}=e;try{await t}finally{try{await n(r)}catch(e){a({level:`warn`,phase:`test_late_cleanup_failed`,data:{session:r,requestId:i,error:f(e).message}})}}}async function pu(e){let{finalizeAttempt:t,sessionName:n,artifactPaths:r,artifactsDir:i,tracePath:a,emitDiagnostic:o}=e;if(!t)return;let s=Date.now();Y(a,{type:`replay_test_finalize_start`,ts:new Date().toISOString(),session:n});try{let e=await t({sessionName:n,artifactPaths:r,artifactsDir:i,tracePath:a,appendTimingEvent:e=>Y(a,e)});return Y(a,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:n,ok:e===void 0,durationMs:Date.now()-s,errorCode:e?.error.code}),e}catch(e){let t=f(e);return Y(a,{type:`replay_test_finalize_stop`,ts:new Date().toISOString(),session:n,ok:!1,durationMs:Date.now()-s,errorCode:t.code}),o({level:`warn`,phase:`test_finalize_failed`,data:{session:n,error:t.message}}),J({error:t})}}function mu(e){return!e||e.status===`passed`?e:{...e,infrastructure:!0,error:{...e.error,details:{...e.error.details??{},reason:`timeout_cleanup_pending`,timeoutCleanupPending:!0}}}}function hu(e,t){return{...e,warnings:[...e.warnings,t]}}function gu(e){let{artifactsDir:t,artifactPaths:n,filePath:r,sessionName:i,requestId:a,timeoutMs:o,platform:s,target:c}=e;if(!t)return;let l=G.join(t,`replay-timing.ndjson`);return W.mkdirSync(G.dirname(l),{recursive:!0}),W.writeFileSync(l,``),n.add(l),Y(l,{type:`replay_test_attempt_start`,ts:new Date().toISOString(),replayPath:r,session:i,requestId:a,timeoutMs:o,platform:s,target:c}),l}function Y(e,t){e&&W.appendFileSync(e,`${JSON.stringify(t)}\n`)}function _u(e,t=[]){return J({artifactPaths:t,error:{code:`COMMAND_FAILED`,message:`TIMEOUT after ${e}ms`,hint:`Replay test timeouts are cooperative; the active command may take a short grace period to stop.`,details:{reason:`timeout`,timeoutMs:e,timeoutMode:`cooperative`,artifactPaths:t}}})}async function vu(e){let t=yu(e),n=await bu(e,t);return{result:Eu(e,t,n),infrastructure:n.finalOutcome?.status===`failed`&&n.finalOutcome.infrastructure}}function yu(e){let{entry:t,cwd:n,retries:r,suiteArtifactsDir:i,shard:a}=e;return{testStartedAt:Date.now(),testArtifactsDir:G.join(i,...a?[`shard-${a.shardIndex+1}`]:[],Wl(t.path,n)),maxAttempts:r+1}}async function bu(e,t){Su(e,t);let n={finalSessionName:``,attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let r=0;r<=e.retries&&!e.isCanceled();r+=1){let i=await xu(e,t,r);if(Cu(n,i),wu(e,i.outcome,r))break;Tu(e,t,i)}return n}async function xu(e,t,n){let{entry:r,sessionName:i,suiteInvocationId:a,caseIndex:o,suiteIndex:s,suiteTotal:c,requestId:l,timeoutMs:u,shard:d}=e,f=n+1,p=Date.now(),m=nu(i,a,r.path,o,n),h=G.join(t.testArtifactsDir,`attempt-${f}`);Gl(r.path,h);let g=iu({requestId:l,suiteInvocationId:a,filePath:r.path,caseIndex:o,attemptIndex:n,shardIndex:d?.shardIndex}),_={file:r.path,title:r.title,index:s,total:c,attempt:f,maxAttempts:t.maxAttempts,session:m,artifactsDir:t.testArtifactsDir,...X(d)},v=await lu({filePath:r.path,sessionName:m,requestId:g,parentRequestId:l,timeoutMs:u,platform:r.manifest.device.platform.kind===`declared`?r.manifest.device.platform.value:void 0,target:r.manifest.device.target,artifactsDir:h,shard:d,onStep:t=>{e.emitProgress({type:`replay-test`,..._,status:`progress`,stepIndex:t.index,stepTotal:t.total,...t.command===void 0?{}:{stepCommand:t.command},...t.value===void 0?{}:{stepValue:t.value}})},runReplay:e.runReplay,cleanupSession:e.cleanupSession,finalizeAttempt:e.finalizeAttempt,emitDiagnostic:e.emitDiagnostic,bindAttemptCancellation:e.bindAttemptCancellation}),y=Date.now()-p;return Kl({outcome:v,filePath:r.path,sessionName:m,attempts:f,maxAttempts:t.maxAttempts,attemptArtifactsDir:h}),{outcome:v,sessionName:m,attempt:f,durationMs:y}}function Su(e,t){let{entry:n,sessionName:r,suiteInvocationId:i,caseIndex:a,suiteIndex:o,suiteTotal:s,shard:c}=e;e.emitProgress({type:`replay-test`,file:n.path,title:n.title,status:`start`,index:o,total:s,maxAttempts:t.maxAttempts,session:nu(r,i,n.path,a),artifactsDir:t.testArtifactsDir,...X(c)})}function Cu(e,t){e.finalOutcome=t.outcome,e.finalSessionName=t.sessionName,e.attempts=t.attempt,e.finalAttemptDurationMs=t.durationMs,t.outcome.status!==`passed`&&e.attemptFailures.push({attempt:t.attempt,message:t.outcome.error.message,durationMs:t.durationMs})}function wu(e,t,n){return t.status===`passed`||e.isCanceled()||t.infrastructure||t.status===`failed`&&t.stopRetries===!0||n>=e.retries}function Tu(e,t,n){n.outcome.status!==`passed`&&e.emitProgress({type:`replay-test`,file:e.entry.path,title:e.entry.title,status:`fail`,index:e.suiteIndex,total:e.suiteTotal,attempt:n.attempt,maxAttempts:t.maxAttempts,durationMs:n.durationMs,retrying:!0,message:n.outcome.error.message,hint:n.outcome.error.hint,session:n.sessionName,artifactsDir:t.testArtifactsDir,...X(e.shard)})}function Eu(e,t,n){let r=Date.now()-t.testStartedAt;return n.finalOutcome?.status===`passed`?Du(e,t,n,r):Ou(e,t,n,r)}function Du(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalOutcome;if(c?.status!==`passed`)throw Error(`Expected passing replay test outcome.`);return e.emitProgress({type:`replay-test`,file:i.path,title:i.title,status:`pass`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,...X(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`passed`,durationMs:r,finalAttemptDurationMs:n.finalAttemptDurationMs,attempts:n.attempts,artifactsDir:t.testArtifactsDir,replayed:c.replayed,healed:c.healed,...c.warnings.length>0?{warnings:[...c.warnings]}:{},...c.snapshotDiagnostics?{snapshotDiagnostics:c.snapshotDiagnostics}:{},...Au(s),...n.attemptFailures.length>0?{attemptFailures:n.attemptFailures}:{}}}function Ou(e,t,n,r){let{entry:i,suiteIndex:a,suiteTotal:o,shard:s}=e,c=n.finalOutcome,l=c?.status===`failed`?c.error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`};return e.emitProgress({type:`replay-test`,file:i.path,title:i.title,status:`fail`,index:a,total:o,attempt:n.attempts,maxAttempts:t.maxAttempts,durationMs:r,session:n.finalSessionName,artifactsDir:t.testArtifactsDir,message:l.message,hint:l.hint,...X(s)}),{file:i.path,title:i.title,session:n.finalSessionName,status:`failed`,durationMs:r,attempts:n.attempts,artifactsDir:t.testArtifactsDir,error:l,...ku(c),...Au(s)}}function ku(e){let t=e?.status===`failed`?e:void 0;return{...t&&t.warnings.length>0?{warnings:[...t.warnings]}:{},...t?.infrastructure?{infrastructure:!0}:{},...e?.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}function Au(e){return X(e)}function X(e){return e?{shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}:{}}async function ju(e,t,n,r){if(!e||t.length===0)return;let i=await r(e.count);return{mode:e.kind,shardCount:e.count,total:n+(e.kind===`all`?t.length*e.count:t.length),shards:i.map((n,r)=>({shardIndex:r,shardCount:e.count,device:n,entries:e.kind===`all`?t:t.filter((t,n)=>n%e.count===r)}))}}async function Mu(e){let{request:t,runReplay:n,cleanupSession:r,finalizeAttempt:i,emitProgress:a,isCanceled:o,emitDiagnostic:c,bindAttemptCancellation:l,discoverSources:u,resolveShardTargets:d}=e,f=t.sessionName;if(t.inputs.length===0)return{status:`failed`,error:{code:`INVALID_ARGS`,message:`test requires at least one path or glob`}};try{let e=Date.now(),s=await Nu(t,u,d);Lu(s,a);let p=s.shardPlan?Ru({entries:s.entries,total:s.total,emitProgress:a}):[];return s.shardPlan?p.push(...await zu({shards:s.shardPlan.shards,sessionName:f,suiteInvocationId:s.suiteInvocationId,cwd:t.cwd,requestId:t.requestId,request:t,suiteArtifactsDir:s.suiteArtifactsDir,suiteTotal:s.total,runReplay:n,cleanupSession:r,finalizeAttempt:i,emitProgress:a,isCanceled:o,emitDiagnostic:c,bindAttemptCancellation:l})):p.push(...await Uu({discoveryEntries:s.entries,sessionName:f,suiteInvocationId:s.suiteInvocationId,cwd:t.cwd,requestId:t.requestId,request:t,suiteArtifactsDir:s.suiteArtifactsDir,suiteTotal:s.total,runReplay:n,cleanupSession:r,finalizeAttempt:i,emitProgress:a,isCanceled:o,emitDiagnostic:c,bindAttemptCancellation:l})),{status:`completed`,data:Ku(s.total,p,Date.now()-e,s.suiteArtifactsDir)}}catch(e){let t=s(e);return{status:`failed`,error:{code:t.code,message:t.message}}}}async function Nu(e,t,n){let r=Pu(e,t),i=Fu(r),a=r.length-i.length,o=e.suiteInvocationId??ru(e.requestId),s=await ju(e.shard?{kind:e.shard.mode,count:e.shard.count}:void 0,i,a,n);return{entries:r,runnable:i,shardPlan:s,suiteInvocationId:o,suiteArtifactsDir:Iu(e,o),total:s?.total??r.length}}function Pu(e,t){return Zl({platformFilter:e.platformFilter,discoverSources:t})}function Fu(e){return e.flatMap((e,t)=>e.kind===`run`?[{entry:e,suiteIndex:t+1}]:[])}function Iu(e,t){return Ul({artifactsDir:typeof e.artifactsDir==`string`?e.artifactsDir:void 0,cwd:e.cwd,suiteInvocationId:t})}function Lu(e,t){t({type:`replay-test-suite`,status:`start`,total:e.total,runnable:e.runnable.length,skipped:e.entries.length-e.runnable.length,artifactsDir:e.suiteArtifactsDir,shardMode:e.shardPlan?.mode,shardCount:e.shardPlan?.shardCount})}function Ru(e){let{entries:t,total:n}=e,r=[];for(let[i,a]of t.entries())a.kind===`skip`&&(e.emitProgress({type:`replay-test`,file:a.path,status:`skip`,index:i+1,total:n,message:a.message}),r.push({file:a.path,status:`skipped`,durationMs:0,reason:a.reason,message:a.message}));return r}async function zu(e){return(await Promise.allSettled(e.shards.map(async t=>await Vu({...e,shard:t})))).flatMap((t,n)=>{if(t.status===`fulfilled`)return t.value;let r=e.shards[n];return r?[Bu(r,e.sessionName,t.reason)]:[]})}function Bu(e,t,n){let r=f(n);return{file:e.entries[0]?.entry.path??`shard-${e.shardIndex+1}`,session:Hu(t,e),status:`failed`,durationMs:0,attempts:1,error:{code:r.code,message:r.message,hint:r.hint,diagnosticId:r.diagnosticId,logPath:r.logPath,details:r.details},shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.device.id,deviceName:e.device.name}}async function Vu(e){let{shard:t,sessionName:n}=e;return await Wu({...e,entries:t.entries,sessionName:Hu(n,t),shard:t})}function Hu(e,t){return`${e}:shard-${t.shardIndex+1}`}async function Uu(e){let{discoveryEntries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,request:o,suiteArtifactsDir:s,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d,emitProgress:f,isCanceled:p,emitDiagnostic:m,bindAttemptCancellation:h}=e,g=[],_=0;for(let[e,v]of t.entries()){if(p())break;if(v.kind===`skip`){f({type:`replay-test`,file:v.path,status:`skip`,index:e+1,total:c,message:v.message}),g.push({file:v.path,status:`skipped`,durationMs:0,reason:v.reason,message:v.message});continue}_+=1;let t=await vu({entry:v,sessionName:n,suiteInvocationId:r,caseIndex:_-1,cwd:i,requestId:a,retries:ou(o.retries,v.manifest.attemptDefaults?.retries),timeoutMs:au(o.timeoutMs,v.manifest.attemptDefaults?.timeoutMs),suiteArtifactsDir:s,suiteIndex:e+1,suiteTotal:c,runReplay:l,cleanupSession:u,finalizeAttempt:d,emitProgress:f,isCanceled:p,emitDiagnostic:m,bindAttemptCancellation:h});if(g.push(t.result),Gu(t,o,p))break}return g}async function Wu(e){let{entries:t,sessionName:n,suiteInvocationId:r,cwd:i,requestId:a,request:o,suiteArtifactsDir:s,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f,emitProgress:p,isCanceled:m,emitDiagnostic:h,bindAttemptCancellation:g}=e,_=[];for(let[e,v]of t.entries()){if(m())break;let{entry:t,suiteIndex:y}=v,b=await vu({entry:t,sessionName:n,suiteInvocationId:r,caseIndex:e,cwd:i,requestId:a,retries:ou(o.retries,t.manifest.attemptDefaults?.retries),timeoutMs:au(o.timeoutMs,t.manifest.attemptDefaults?.timeoutMs),suiteArtifactsDir:s,suiteIndex:y,suiteTotal:c,shard:l,runReplay:u,cleanupSession:d,finalizeAttempt:f,emitProgress:p,isCanceled:m,emitDiagnostic:h,bindAttemptCancellation:g});if(_.push(b.result),Gu(b,o,m))break}return _}function Gu(e,t,n){return n()||t.failFast===!0&&e.result.status===`failed`||e.infrastructure}function Ku(e,t,n,r){let i=t.filter(e=>e.status===`passed`).length,a=t.filter(e=>e.status===`failed`),o=a.length,s=t.filter(e=>e.status===`skipped`).length,c=i+o,l=C(t.map(e=>e.status===`skipped`?void 0:e.snapshotDiagnostics));return{total:e,executed:c,passed:i,failed:o,skipped:s,notRun:Math.max(0,e-c-s),durationMs:n,failures:a,tests:t,artifactsDir:r,...l?{snapshotDiagnostics:l}:{}}}function qu(e,t){return async n=>(await Xu(e,n,t)).map(Ju)}function Ju(e){if(e.platform===`web`||!_e(e))throw new a(`INVALID_ARGS`,`test sharding requires a mobile device; ${e.id} is ${e.platform}`);return{id:e.id,name:e.name,platform:e.platform,...e.target===void 0?{}:{target:e.target}}}function Yu(e,t){if(!t)return e;let n={...e??{},device:void 0,udid:void 0,serial:void 0,platform:t.device.platform,target:t.device.target,shardAll:void 0,shardSplit:void 0,shardCount:t.shardCount,shardIndex:t.shardIndex};return t.device.platform===`android`?{...n,serial:t.device.id}:{...n,udid:t.device.id}}async function Xu(e,t,n){let r=ed(e),i=Qu(await ur(Zu(e,n)),r,e);if(i.length<t)throw new a(`DEVICE_NOT_FOUND`,`test sharding requires ${$u(t)}, but only ${i.length} matched`);return i.slice(0,t)}function Zu(e,t){let n=L(e?.androidDeviceAllowlist,t);return{platform:e?.platform,target:e?.target,iosSimulatorSetPath:be({requestedSetPath:e?.iosSimulatorDeviceSet,platform:e?.platform,target:e?.target,env:t}),androidSerialAllowlist:n?Array.from(n).sort():void 0}}function Qu(e,t,n){return t.length>0?td(e,t,n):e.filter(e=>nd(e,n)).sort(ad)}function $u(e){return`${e} device${e===1?``:`s`}`}function ed(e){let t=e?.device;return typeof t!=`string`||t.trim().length===0?[]:t.split(`,`).map(e=>e.trim()).filter(Boolean)}function td(e,t,n){return t.map(t=>{let r=id(t),i=e.find(e=>rd(e,n)&&(e.id===t||id(e.name)===r));if(!i)throw new a(`DEVICE_NOT_FOUND`,`No shard device matched ${t}`);return i})}function nd(e,t){return!rd(e,t)||!_e(e)?!1:e.booted!==!1}function rd(e,t){return!(!ye(e,t?.platform)||t?.target&&(e.target??`mobile`)!==t.target)}function id(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}function ad(e,t){return e.id.localeCompare(t.id)}function od(e){let t=sd(e?.shardAll,`--shard-all`),n=sd(e?.shardSplit,`--shard-split`);if(t!==void 0&&n!==void 0)throw new a(`INVALID_ARGS`,`--shard-all and --shard-split are mutually exclusive`);if(t!==void 0)return{mode:`all`,count:t};if(n!==void 0)return{mode:`split`,count:n}}function sd(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isInteger(e)||e<1)throw new a(`INVALID_ARGS`,`${t} requires a positive integer`);return e}}const cd=new Set([`IOS_BOOT_TIMEOUT`,`IOS_RUNNER_CONNECT_TIMEOUT`,`IOS_RUNNER_OWNED_BY_OTHER_DAEMON`,`IOS_TOOL_MISSING`,`ANDROID_BOOT_TIMEOUT`,`ADB_TRANSPORT_UNAVAILABLE`,`CI_RESOURCE_STARVATION_SUSPECTED`]);function ld(e){return cd.has(e.toUpperCase())}const ud=[`failed to start daemon`,`runner did not accept connection`,`xcodebuild exited early`,`device is offline`,`device offline`,`device unauthorized`];function dd(e){if(!(`ok`in e)&&e.status===`failed`&&e.infrastructure===!0)return!0;let t=fd(e);return t?pd(t.details)||md(t.code,t.message):!1}function fd(e){return`ok`in e?e.ok?null:e.error:e.status===`failed`?e.error:null}function pd(e){if(e?.recovery===`runner_recycle_budget_exhausted`)return!0;let t=typeof e?.reason==`string`?e.reason:``;return t===`timeout_cleanup_pending`||m(t)?!0:t?ld(t):!1}function md(e,t){let n=`${e}\n${t}`.toLowerCase();return ud.some(e=>n.includes(e))}function hd(e){if(!e.ok)return{status:`failed`,error:e.error,artifactPaths:vd(e.error.details?.artifactPaths),warnings:cn(e.error.details),infrastructure:dd(e),...e.error.details?.reason===`bounded_composite_resource_unsupported`?{stopRetries:!0}:{},...yd(e.error.details?.snapshotDiagnostics)};let t=e.data;return{status:`passed`,replayed:typeof t?.replayed==`number`?t.replayed:0,healed:typeof t?.healed==`number`?t.healed:0,warnings:cn(t),artifactPaths:vd(t?.artifactPaths),...yd(t?.snapshotDiagnostics)}}function gd(e){if(!e||e.ok)return;let t=hd(e);return t.status===`failed`?t:void 0}function _d(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function vd(e){return[...new Set(_d(e))]}function yd(e){let t=S(e);return t?{snapshotDiagnostics:t}:{}}const bd=1e3,xd=3e3;function Sd(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await Cd(e)}}async function Cd(e){let{req:t,sessionName:n,sessionStore:r,artifactsDir:i,appendTimingEvent:a}=e;if(t.flags?.recordVideo!==!0)return;let o=r.get();if(!o||o.screenRecording)return;let s=pn(o.device.platform),c=i?G.join(i,`recording${s}`):fn(o.device.platform);Z(a,{type:`video_recording_start`,session:n,videoPath:c}),D({phase:`replay_test_video_recording_start`,data:{session:n,videoPath:c}}),e.video.throwIfCanceled();let l=await e.video.record(Td({req:t,sessionName:n,phase:`start`,outputPath:c}));if(!l.ok)return Z(a,{type:`video_recording_start_failed`,session:n,videoPath:c,errorCode:l.error.code}),l;let u=Date.now();return await me(bd),Z(a,{type:`video_preroll_done`,session:n,durationMs:Date.now()-u,requestedDurationMs:bd}),D({phase:`replay_test_video_recording_preroll_done`,durationMs:Date.now()-u,data:{session:n,requestedDurationMs:bd}}),l}async function wd(e){let{req:t,sessionName:n,sessionStore:r,artifactPaths:i,appendTimingEvent:a}=e;if(t.flags?.recordVideo!==!0||!r.get()?.screenRecording)return;Z(a,{type:`video_tail_start`,session:n,requestedDurationMs:xd});let o=Date.now();await me(xd);let s=Date.now(),c=await e.video.record(Td({req:t,sessionName:n,phase:`stop`}));return jc(c).forEach(e=>i.add(e)),Z(a,{type:`video_recording_stop`,session:n,ok:c.ok,durationMs:Date.now()-s,tailDurationMs:s-o,errorCode:c.ok?void 0:c.error.code}),D({phase:`replay_test_video_recording_stop`,durationMs:Date.now()-s,data:{session:n,ok:c.ok,tailDurationMs:s-o}}),c}function Z(e,t){e({...t,ts:new Date().toISOString()})}function Td(e){let t={token:e.req.token,meta:e.req.meta};return e.phase===`start`?{request:t,sessionName:e.sessionName,phase:`start`,outputPath:e.outputPath}:{request:t,sessionName:e.sessionName,phase:`stop`}}const Ed=[{keys:[`replayKeepSession`],requested:e=>e.replayKeepSession===!0,message:`test does not support --keep-session; suite attempts own their cleanup. Run one native .ad script directly with replay --keep-session.`},{keys:[`replayFrom`,`replayPlanDigest`],requested:e=>e.replayFrom!==void 0||e.replayPlanDigest!==void 0,message:`test does not support --from/--plan-digest; resume is replay-only. Run the failing script directly with replay --from.`},{keys:[`saveScript`,`force`],requested:e=>!!e.saveScript||e.force===!0,message:`test does not support --save-script/--force; the agent-supervised repair loop is replay-only. Repair the failing script directly with replay --save-script.`}],Dd=({attemptId:e,parentAttemptId:t})=>{let n=Od(Yn(e,t)?.controller,t);return{cancel:()=>Qn(e),release:()=>{n(),qn(e)}}};function Od(e,t){if(!t||!e)return()=>{};let n=Jn(t);if(!n||n===e.signal)return()=>{};let r=()=>{e.abort(n.reason)};return n.aborted?(r(),()=>{}):(n.addEventListener(`abort`,r,{once:!0}),()=>{n.removeEventListener(`abort`,r)})}function kd(e){let{platform:t,target:n,artifactsDir:r,shard:i,sourceBundle:a}=e,o=Ad(e.parentFlags);return t===void 0&&n===void 0&&r===void 0&&i===void 0&&a===void 0?o:Yu({...o??{},...t===void 0?{}:{platform:t},...n===void 0?{}:{target:n},...r===void 0?{}:{artifactsDir:r},...a===void 0?{}:{replayScriptSource:a}},i)}function Ad(e){if(!e||e.recordVideo!==!0&&e.replayScriptSources===void 0)return e;let t={...e};return delete t.recordVideo,delete t.replayScriptSources,Object.keys(t).length>0?t:void 0}async function jd(e){let{request:t,session:{name:n,logPath:r},createSession:i,invoke:a,cleanupSession:o,video:c}=e;if(t.flags?.recordVideo===!0&&c===void 0)return d(`COMMAND_FAILED`,`Screen-recording runtime is not configured for replay video capture`);let l=t.flags??{};for(let e of Ed)if(e.requested(l))return d(`INVALID_ARGS`,e.message);let u,f;try{u={...Fd(t,n,e.host.cwd),...e.publicNetworkOnly?{suiteInvocationId:li()}:{}},f=Pd(t)}catch(e){let t=s(e);return d(t.code,t.message)}let p=new Map(f.map(e=>[e.entry,e])),m=await Mu({request:u,emitProgress:Zn,isCanceled:()=>Xn(t.meta?.requestId),emitDiagnostic:D,bindAttemptCancellation:Dd,runReplay:async({filePath:n,sessionName:o,platform:s,target:l,requestId:u,artifactsDir:d,artifactPaths:f,tracePath:m,appendTimingEvent:h,shard:g,onStep:_})=>{let v=e=>(f&&jc(e).forEach(e=>f.add(e)),e),y=kd({parentFlags:t.flags,platform:s,target:l,artifactsDir:d,shard:g,sourceBundle:p.get(n)}),b=i(o,r),x=c?{req:t,sessionName:o,sessionStore:b.store,artifactsDir:d,appendTimingEvent:h,video:c}:void 0,S=x?Sd(x):void 0;return Md(hd(await zl({...Id(e,{request:{...t,command:`replay`,session:o,positionals:[n],flags:y,meta:{...t.meta??{},...u?{requestId:u}:{}}},openLifecycle:S}),session:b,tracePath:m,onStep:_,publicNetworkOnly:e.publicNetworkOnly,invoke:async e=>{let t=x?await Cd(x):void 0;return t&&!t.ok?t:v(await a(e))}})))},finalizeAttempt:async({sessionName:e,artifactPaths:n,artifactsDir:a,appendTimingEvent:o})=>{if(c)return gd(await wd({req:t,sessionName:e,sessionStore:i(e,r).store,artifactsDir:a,appendTimingEvent:o,artifactPaths:n,video:c}))},discoverSources:await ri(f,t.flags?.replayBackend),resolveShardTargets:qu(t.flags,e.host.env),cleanupSession:o});return m.status===`completed`?{ok:!0,data:Nd(m.data,t)}:d(m.error.code,m.error.message)}function Md(e){if(e.status!==`failed`||e.error.details?.reason!==`bounded_composite_resource_unsupported`)return e;let t=e.error.details,n=`Run the original test directly with its original paths and options in the live outer session, using the same --session value and private CLI context.`,r=t.divergence,i=r&&typeof r==`object`&&`cause`in r?r.cause:void 0,a=r&&typeof r==`object`&&`screen`in r?r.screen:void 0,o=r&&typeof r==`object`&&i&&typeof i==`object`?{...r,cause:{...i,hint:n},...a&&typeof a==`object`&&`state`in a&&a.state===`unavailable`?{screen:{...a,hint:n}}:{}}:r;return{...e,error:{...e.error,hint:n,details:{...t,divergence:o,standaloneCommandName:`test`}}}}function Nd(e,t){let n=t.meta?.clientArtifactPaths?.artifactsDir,r=e.artifactsDir;if(!n||!r)return e;let i=G.join(n,G.basename(r)),a=e=>e===r||e.startsWith(r+G.sep)?i+e.slice(r.length):e,o={...e,artifactsDir:i,tests:e.tests.map(e=>`artifactsDir`in e&&e.artifactsDir?{...e,artifactsDir:a(e.artifactsDir)}:e),failures:e.failures.map(e=>e.artifactsDir?{...e,artifactsDir:a(e.artifactsDir)}:e)};return W.existsSync(r)?{...o,artifacts:[{field:`artifactsDir`,artifactType:`test-artifacts`,path:r,localPath:n,fileName:G.basename(r)}]}:o}function Pd(e){let t=e.flags?.replayScriptSources;if(!t)throw new a(`INVALID_ARGS`,An);return t}function Fd(e,t,n){let r=e.flags??{},i=e.meta?.cwd,a=Rd(r.artifactsDir);return{inputs:e.positionals??[],sessionName:t,cwd:i,requestId:e.meta?.requestId,platformFilter:r.platform,artifactsDir:a===void 0?void 0:F(a,i??n),failFast:r.failFast===!0,retries:Ld(r.retries),timeoutMs:Ld(r.timeoutMs),shard:od(r)}}function Id(e,t){let{host:n,publicNetworkOnly:r,resolvedSessionScope:i,dispatch:a,dependencies:o}=e,s=a||t.openLifecycle?{...a,...t.openLifecycle?{openLifecycle:t.openLifecycle}:{}}:void 0;return{request:t.request,host:n,...r?{publicNetworkOnly:r}:{},...i?{resolvedSessionScope:i}:{},...s?{dispatch:s}:{},dependencies:o}}function Ld(e){return typeof e==`number`?e:void 0}function Rd(e){return typeof e==`string`?e:void 0}function zd(e,t,n,r){return{name:e,logPath:t,store:{...n,assertSelectorMatches:r.assertSelectorMatches,resolveOpenRuntimeHints:r.resolveOpenRuntimeHints},observationStore:{get:n.get,bindAuthority:r.bindAuthority},coordinator:r.createCoordinator()}}function Bd(e){let{internal:t,...n}=e;return{request:n,...t?.publicNetworkOnly?{publicNetworkOnly:!0}:{},...t?.resolvedSessionScope?{resolvedSessionScope:t.resolvedSessionScope}:{}}}function Vd(e,t){let n=_({...e,...t});return Object.keys(n).length>0?n:void 0}function Hd(e,t){return async({dispatch:n,...r})=>{let i=Vd(t.internal,n);return await e(i?{...r,internal:i}:r)}}function Ud(e){let{sessionStore:t,mutationStore:n,hostCwd:r}=e,i=()=>t.get();return{view(){let e=i();if(e)return{repairBoundary:pt(e),pendingRecordAndHeal:e.pendingRecordAndHeal,scriptPublication:Wd(e.scriptPublication??zt)}},armStep(e){n.update(t=>{ct(t,{saveScript:e.saveScript,force:e.force,sourcePath:e.sourcePath,healedSiblingPath:Gr(e.sourcePath),firstArm:e.firstArm},r)})},demoteForRerunIfArmed(){pt(i())!==void 0&&n.update(dt)},markCompleteIfArmed(){pt(i())!==void 0&&n.update(ut)},markSessionHeldIfArmed(e){if(e.ok||!lt(i()))return e;let t=_n(e.error.details?.divergence);return t&&(t.repairSessionHeld=!0),e},clearTombstone(){n.clearRepairTombstone()},clearCorrectiveWatermarkIfExpected(e){i()?.pendingRecordAndHeal?.expectedFrom===e&&n.update(t=>{t.pendingRecordAndHeal?.expectedFrom===e&&Kd(t)})},resumeStamper:{sessionExists:()=>i()!==void 0,stampCorrectiveWatermark(e){n.update(t=>{Gd({session:t,...e})})}}}}function Wd(e){return{kind:e.kind,status:e.kind===`none`?void 0:e.status,targetPath:At(e),targetForce:It(e)}}function Gd(e){let{session:t,resume:n,repairHint:r,failedIndex:i,actions:a}=e;t.pendingRecordAndHeal=qd({resume:n,repairHint:r,failedIndex:i,actions:a,actionsCountAtDivergence:t.actions.length})}function Kd(e){e.pendingRecordAndHeal=void 0}function qd(e){let{resume:t,repairHint:n,failedIndex:r,actions:i,actionsCountAtDivergence:a}=e;if(n===`record-and-heal`)return t.allowed?{expectedFrom:t.from,actionsCountAtDivergence:a}:void 0;if((n===`caution`||n===`manual`)&&r===i.length)return{expectedFrom:r+1,actionsCountAtDivergence:a}}function Jd(e){let{sessionStore:t,bindDevice:n,platformServices:r,bindExactDevice:i,screenRecordingAdmissionLedger:a,requestScope:o,retainDeviceExecutionLock:s,throwIfCanceled:c}=e;return!n||!i||!a||!o||!s||!c?void 0:{throwIfCanceled:c,record:async e=>await Ir({req:Yd(e),sessionName:e.sessionName,sessionStore:t,bindDevice:n,platformServices:r,bindExactDevice:i,admissionLedger:a,requestScope:o,retainDeviceExecutionLock:s,throwIfCanceled:c})}}function Yd(e){return{token:e.request.token,session:e.sessionName,command:`record`,positionals:e.phase===`start`?[`start`,e.outputPath]:[`stop`],flags:{},meta:e.request.meta}}const Xd={resolveSessionScope:Kt},Zd=async({req:e,host:t,sessionName:n,logPath:r,sessionStore:i,invoke:a,invokeReplayAction:o})=>await zl({...Bd(e),host:t,session:$d(n,r,i),invoke:Hd(o??a,e),dependencies:Xd}),Qd=async({host:e,req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:o,invoke:s,invokeReplayAction:c,bindDevice:l,platformServices:u,inspectFacts:d,bindExactDevice:f,screenRecordingAdmissionLedger:p,requestScope:m,retainDeviceExecutionLock:h,throwIfCanceled:g,platformResourceCleanup:_})=>{if(!_)throw new a(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let v=Jd({sessionStore:i,bindDevice:l,platformServices:u,bindExactDevice:f,screenRecordingAdmissionLedger:p,requestScope:m,retainDeviceExecutionLock:h,throwIfCanceled:g});return await jd({...Bd(t.internal?.publicNetworkOnly?{...t,flags:{...t.flags,artifactsDir:hn(i.resolveSessionDir(n))}}:t),host:e,session:$d(n,r,i),createSession:(e,t)=>$d(e,t,i),invoke:Hd(c??s,t),dependencies:Xd,cleanupSession:async n=>await ef({host:e,req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:o,inspectFacts:d,bindDevice:l,platformServices:u,platformResourceCleanup:_}),...v?{video:v}:{}})};function $d(e,t,n){let r=t=>{let r=n.get(e);return r?(t(r),!0):!1},i={get:()=>n.get(e),lookup:()=>n.lookup(e),getRuntimeHints:()=>n.getRuntimeHints(e),ensureSessionDir:()=>n.ensureSessionDir(e)};return zd(e,t,i,{createCoordinator:()=>Ud({sessionStore:i,mutationStore:{update:r,clearRepairTombstone:()=>n.clearRepairTombstone(e)},hostCwd:n.host.cwd}),assertSelectorMatches:t=>{let r=n.lookup(e);r&&mr(r,t)},resolveOpenRuntimeHints:({request:t,device:r,platform:i})=>ir({req:t,sessionStore:{getRuntimeHints:t=>t===e?n.getRuntimeHints(e):void 0},sessionName:e,device:r,platform:i}),bindAuthority:t=>{let r=n.lookup(e);return{...Gs({sessionStore:n,ref:r,signal:t}),capture:async({flags:i,logPath:o})=>{let s=r?n.requireCurrent(r):void 0;if(!s)throw new a(`NO_ACTIVE_SESSION`,`Session "${e}" is no longer active.`);return await yr({device:s.device,session:s,flags:i,logPath:o,signal:t})}}}})}async function ef(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e;if(!i.get(n))return;let o=await Ba({host:e.host,req:$t({token:t.token,session:n,command:`close`,positionals:[],flags:{},meta:t.meta,internal:{cleanupIntent:`suite-owned-test-session`}},t),sessionName:n,logPath:r,sessionStore:i,leaseRegistry:e.leaseRegistry,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,platformResourceCleanup:e.platformResourceCleanup});if(!o.ok)throw new a(o.error.code,o.error.message,{...o.error.details??{},...o.error.hint?{hint:o.error.hint}:{}})}function tf(e){let{req:t,sessionName:n,sessionStore:r}=e;if(t.command!==oe.sessionSaveScript)return null;if((t.positionals?.length??0)>1)return Q(new a(`INVALID_ARGS`,`session save-script accepts at most one output path.`));let i=r.lookup(n);if(!i)return Q(new a(`SESSION_NOT_FOUND`,`No active session "${n}".`,{hint:`Start a fresh journey with open <app> --save-script[=<path>], then retry.`}));let o=r.requireCurrent(i),s=af(o);if(s)return Q(s);let c=t.positionals?.[0]?.trim();if(t.positionals?.[0]!==void 0&&!c)return Q(new a(`INVALID_ARGS`,`session save-script path cannot be empty.`));Rt(o,{explicitPath:c,liveForce:t.flags?.force},r.host.cwd);let l=r.writeSessionLog(i,{force:Nt(o,t.flags?.force),publication:`active`});return l.written?(Pt(o,l.path),{ok:!0,data:{session:o.name,savedScript:l.path,actionCount:l.actionCount,...P(`Published script: ${l.path}`)}}):Q(l.error??new a(`COMMAND_FAILED`,`The active session script was not published.`,{retriable:!0,hint:`The session remains armed; retry session save-script.`}))}function nf(e){if(gt(e))return`repair`;let t=e.scriptPublication;return t?.kind===`authoring`&&t.status!==`armed`?t.status:Lt(e)?void 0:`not-armed`}const rf={repair:()=>new a(`COMMAND_FAILED`,`This session has an active .ad repair transaction and cannot use ordinary active-session publication.`,{hint:`Finish or abort the repair through replay --from and its existing close/teardown protocol.`}),aborted:()=>new a(`COMMAND_FAILED`,`This script recording was aborted by a second successful open and cannot be published.`,{hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`}),published:()=>new a(`COMMAND_FAILED`,`This script recording has already been published.`,{hint:`Continue using the live session, or close it and start a fresh authoring session.`}),"not-armed":()=>new a(`COMMAND_FAILED`,`Script recording was not armed before this journey began; session history cannot be published without recording-time target evidence.`,{hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`})};function af(e){let t=nf(e);return t?rf[t]():void 0}function Q(e){return{ok:!1,error:f(e)}}function of(e){let t=(e[0]??``).toLowerCase();return t===`read`||t===`write`?t:void 0}function sf(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:zn(e)}}async function cf(e,t,n){if(n.length!==1)throw new a(`INVALID_ARGS`,`clipboard read does not accept additional arguments`);return{action:`read`,text:await e.operations.readClipboard(sf(t))}}async function lf(e,t,n){if(n.length<2)throw new a(`INVALID_ARGS`,`clipboard write requires text (use "" to clear clipboard)`);let r=n.slice(1).join(` `),i={...sf(t),text:r};return await e.operations.writeClipboard(i),{action:`write`,textLength:Array.from(r).length,...P(`Clipboard updated`)}}async function uf(e){let{device:t,action:n,positionals:r,inspectFacts:i,bindDevice:a,platformServices:o}=e;if(n===`read`){let e=await R({command:`clipboard`,device:t,use:Ce,inspectFacts:i,bindDevice:a,platformServices:o,readiness:!0});if(e.type===`response`)return{ok:!1,response:e.response};let n=e.runtime;return{ok:!0,execute:e=>cf(n,e,r)}}let s=await R({command:`clipboard`,device:t,use:ot,inspectFacts:i,bindDevice:a,platformServices:o,readiness:!0});if(s.type===`response`)return{ok:!1,response:s.response};let c=s.runtime;return{ok:!0,execute:e=>lf(c,e,r)}}async function df(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}=e,c=i.lookup(n),l=c?.session,u=t.flags??{},f=U(T.clipboard,l,u);if(f)return f;let p=t.positionals??[],m=of(p);if(!m)return d(`INVALID_ARGS`,`clipboard requires a subcommand: read or write`);let h=await H({session:l,flags:u,env:i.host.env,platformServices:s});c&&i.requireCurrent(c);let g=await uf({device:h,action:m,positionals:p,inspectFacts:a,bindDevice:o,platformServices:s});if(!g.ok)return g.response;let _=c?i.requireCurrent(c):void 0,v=await g.execute(Bn(r,t.flags,_?.appBundleId,_?.trace?.outPath));return M(i,c,t,t.command,v),{ok:!0,data:{platform:O(h),...v}}}function ff(e){return e.some(e=>e.status===`fail`)?`fail`:e.some(e=>e.status===`warn`)?`warn`:`pass`}function pf(e){return e===`fail`?`Blockers found before the run.`:e===`warn`?`No hard blockers found, but warnings need attention.`:`No blockers found.`}function mf(e){let t={fail:0,warn:1,pass:2,info:3};return[...e].sort((e,n)=>t[e.status]-t[n.status])}function hf(e,t,...n){for(let r of n)$(e,r,t)}function $(e,t,n){e.push(t),Zn({type:`command`,status:`progress`,message:gf(t,n)})}function gf(e,t){return[oi(e,{useColor:t}),...ai(e)].join(`
|
|
3
|
+
`)}async function _f(e,t){let{device:n,targetApp:r,session:i,listInstalledApps:a,useColor:o}=t;if(r)try{let t=a?vf(r,await a(`all`))?.id:void 0;if(!t){$(e,{id:`target-app`,status:`info`,summary:`Target app installation checks are not supported for ${O(n)}.`,evidence:{requested:r,platform:O(n)}},o);return}$(e,{id:`target-app`,status:`pass`,summary:`Target app is launchable: ${t}`,evidence:{requested:r,resolved:t,sessionApp:i?.appBundleId}},o)}catch(t){let r=f(t);$(e,{id:`target-app`,status:`fail`,summary:`Target app check failed: ${r.message}`,hint:r.hint??`Install the app or pass an exact package/bundle id or app name.`,command:`agent-device apps --platform ${O(n)} --all`,evidence:{code:r.code,message:r.message}},o)}}function vf(e,t){let n=e.trim().toLowerCase(),r=t.find(e=>e.id.toLowerCase()===n||e.name.toLowerCase()===n);if(r)return r;let i=t.filter(e=>e.id.toLowerCase().includes(n)||e.name.toLowerCase().includes(n));if(i.length===1)return i[0];throw i.length>1?new a(`AMBIGUOUS_MATCH`,`Multiple launchable apps matched "${e}"`,{matches:i.map(e=>e.id),hint:`Pass an exact package/bundle id from agent-device apps --all.`}):new a(`APP_NOT_INSTALLED`,`No launchable installed app matched "${e}"`)}async function yf(e,t,n,r,i){let a=xf(t,n,r);try{let t=await Cf(a),n=Sf(t.devices,a);return $(e,{id:`device`,status:n.length===0?`fail`:`pass`,summary:Of(n,a,t.failures),hint:n.length===0?jf(t.failures):void 0,command:n.length===0?If(a):void 0,evidence:Lf(n,t.failures)},i),n.length>0&&Tf(e,t.failures,i),{devices:n,hostDevices:n.filter(e=>t.hostDevices.includes(e)),platform:a.platform,target:a.target}}catch(t){let n=f(t);return $(e,{id:`device`,status:`fail`,summary:n.message,hint:n.hint,command:`agent-device devices`,evidence:{code:n.code,details:n.details}},i),{devices:[],hostDevices:[],platform:a.platform,target:a.target}}}function bf(e,t,n,r){if(!n||!t)return;let i=t.devices.filter(e=>e.booted===!0);if(i.length===1)return i[0];$(e,{id:`target-app-device`,status:`fail`,summary:i.length===0?`Target app check needs one booted device; none matched.`:`Target app check needs one booted device; ${i.length} matched.`,hint:i.length===0?`Boot a device, or adjust --platform/--target/--device/--udid/--serial.`:`Pass --platform/--target/--device/--udid/--serial so doctor checks the intended device.`,command:t.platform?`agent-device devices --platform ${t.platform}`:`agent-device devices`,evidence:{targetApp:n,booted:i.map(e=>({platform:O(e),id:e.id,name:e.name}))}},r)}function xf(e,t,n){let r=e.flags??{};return jn({platform:r.platform??t?.device.platform,target:r.target??t?.device.target,device:r.device,udid:r.udid,serial:r.serial,iosSimulatorDeviceSet:r.iosSimulatorDeviceSet,androidDeviceAllowlist:r.androidDeviceAllowlist},n)}function Sf(e,t){return e.filter(e=>ve(e,t,{includeExplicitSelectors:!0}))}async function Cf(e){if(e.platform)return{...wf([await lr(e)]),failures:[]};let t=[],n=[];for(let r of g)try{t.push(await lr({...e,platform:r}))}catch(e){n.push(Df(r,e))}return{...wf(t),failures:n}}function wf(e){return{devices:e.flatMap(e=>e.devices),hostDevices:e.flatMap(e=>e.source===`local`?e.devices:[])}}function Tf(e,t,n){for(let r of t)$(e,Ef(r),n)}function Ef(e){return{id:`device-${e.platform}`,status:`warn`,summary:`${Pf(e.platform)} device inventory could not be read: ${e.message}`,hint:e.hint??`Check the ${Pf(e.platform)} toolchain, or scope with --platform to skip it.`,evidence:{platform:e.platform,code:e.code}}}function Df(e,t){let n=f(t);return{platform:e,message:n.message,hint:n.hint,code:n.code}}function Of(e,t,n){if(e.length===0)return n.length>0?`No ${kf(t)} devices found; ${Af(n)}.`:`No ${kf(t)} devices found.`;let r=e.filter(e=>e.booted===!0).length,i=`${e.length} ${kf(t)} ${Ff(e.length,`device`)} available; ${r} booted`,a=Mf(e,t);return a?`${i} (${a}).`:`${i}.`}function kf(e){let t=e.platform?Pf(e.platform):`local`;return e.target?`${t} ${e.target}`:t}function Af(e){return e.slice(0,2).map(e=>`${Pf(e.platform)} inventory failed: ${e.message}`).join(`; `)}function jf(e){return e.find(e=>e.hint)?.hint??`Start or create a simulator/emulator, connect a device, or adjust --platform/--target/--device selectors.`}function Mf(e,t){if(t.platform||t.target)return;let n=h(e),r=Nf();return[`android`,`harmonyos`,`apple`,`vega`,`linux`,`web`].flatMap(e=>{let t=n[e];return t.available>0?[`${r[e]} ${t.available} available, ${t.booted} booted`]:[]}).join(`; `)}function Nf(){return{android:`Android`,harmonyos:`HarmonyOS`,apple:`Apple`,vega:`Vega`,linux:`Linux`,web:`web`}}function Pf(e){return e===`ios`?`iOS`:e===`macos`?`macOS`:e===`android`?`Android`:e===`harmonyos`?`HarmonyOS`:e===`vega`?`Vega`:e===`linux`?`Linux`:e===`web`?`web`:`Apple`}function Ff(e,t){return e===1?t:`${t}s`}function If(e){return e.platform?`agent-device devices --platform ${e.platform}`:`agent-device devices`}function Lf(e,t){let n=new Map;for(let t of e){let e=O(t),r=n.get(e)??{available:0,booted:0};r.available+=1,t.booted===!0&&(r.booted+=1),n.set(e,r)}return{available:e.length,booted:e.filter(e=>e.booted===!0).length,byPlatform:Object.fromEntries([...n.entries()].sort(([e],[t])=>e.localeCompare(t))),...t.length>0?{failures:t}:{}}}const Rf=1500;async function zf(e,t,n,r={}){let i=`http://${e}:${t}/status`;try{let a=await fetch(i,{signal:AbortSignal.timeout(1500)}),o=await a.text(),s=a.ok&&o.toLowerCase().includes(`packager-status:running`),c=s?await Bf(e,t,r):void 0;return{id:`metro`,status:s?`pass`:`warn`,summary:s?Vf(i,c):`React Native dev server responded at ${i}, but did not report packager-status:running.`,hint:s?void 0:`Verify this is the Metro/Re.Pack instance for the target app, or restart the dev server.`,evidence:{url:i,statusCode:a.status,body:o.slice(0,120),kind:n,...c?{process:c}:{}}}}catch(e){return{id:`metro`,status:n===`auto`?`warn`:`fail`,summary:`React Native dev server is not reachable at ${i}.`,hint:`Start Metro or Re.Pack for this project. For non-default endpoints, launch with open --metro-host/--metro-port, or run metro prepare with --public-base-url/--proxy-base-url before retrying doctor.`,command:`curl -fsS ${i}`,evidence:{url:i,error:e instanceof Error?e.message:String(e),kind:n}}}}async function Bf(e,t,n){try{return await(n.resolveProcessInfo??Hf)(e,t)}catch{return}}function Vf(e,t){return t?.cwd?`React Native dev server is reachable at ${e} (cwd: ${t.cwd}).`:`React Native dev server is reachable at ${e}.`}async function Hf(e,t){if(!Uf(e))return;let n=await Wf(t);if(n!==void 0)return{pid:n,cwd:await Gf(n)}}function Uf(e){return e===`127.0.0.1`||e===`localhost`||e===`::1`||e===`0.0.0.0`}async function Wf(e){let t=await he(`lsof`,[`-nP`,`-iTCP:${e}`,`-sTCP:LISTEN`,`-Fp`],{allowFailure:!0,timeoutMs:Rf});if(t.exitCode===0)return t.stdout.split(`
|
|
4
4
|
`).map(e=>e.startsWith(`p`)?Number.parseInt(e.slice(1),10):NaN).find(e=>Number.isInteger(e)&&e>0)}async function Gf(e){let t=await he(`lsof`,[`-nP`,`-a`,`-p`,String(e),`-d`,`cwd`,`-Fn`],{allowFailure:!0,timeoutMs:Rf});if(t.exitCode===0)return t.stdout.split(`
|
|
5
|
-
`).find(e=>e.startsWith(`n`)&&e.length>1)?.slice(1)}const Kf=[`daemonBaseUrl`,`tenant`,`runId`,`leaseId`,`leaseProvider`],qf=[`provider`,`providerSessionId`,`providerApp`,`providerOsVersion`,`providerDeviceType`,`providerProject`,`providerBuild`,`providerSessionName`,`providerDeviceOrientation`,`providerGeoLocation`,`providerTimezone`,`providerAppiumVersion`,`providerLanguage`,`providerLocale`,`providerNetworkProfile`,`providerCustomNetwork`,`providerNoResignApp`,`awsProjectArn`,`awsDeviceArn`,`awsAppArn`,`awsRegion`,`awsInteractionMode`];function Jf(e,t){let n=si(e.meta?.cwd);return{targetApp:$f(e.flags?.targetApp)??t?.appBundleId,metroHost:$f(e.runtime?.metroHost)??`127.0.0.1`,metroPort:ep(e.runtime?.metroPort)??8081,kind:n,remote:e.flags?.remote===!0,shouldProbeMetro:Zf(e,n)}}function Yf(e,t={}){let n=Qf(e);return n?[{id:`remote-connection`,status:t.required?`pass`:`info`,summary:`Remote daemon/session or provider scope is configured.`,evidence:n}]:t.required?[{id:`remote-connection`,status:`fail`,summary:`No remote daemon/session or provider scope is configured.`,hint:`Use connect, --remote-config <path>, or direct remote/provider flags for the command.`}]:[]}function Xf(e,t,n,r={}){let i=n?e.listRefs().filter(e=>e.address!==t&&e.session.device.platform===n.device.platform&&e.session.device.id===n.device.id).map(e=>e.address):[];return n?[{id:`session`,status:i.length>0?`warn`:`pass`,summary:i.length>0?`Other active sessions target the same device: ${i.join(`, `)}`:`Active session ${n.name} targets ${n.device.name}`,hint:i.length>0?`Close stale sessions before a QA run if they belong to old attempts.`:void 0,command:i.length>0?`agent-device close --session ${i[0]} --platform ${k(n.device)}`:void 0,evidence:{session:t,sameDeviceSessions:i,sessionStateDir:e.resolveSessionDir(t)}}]:[{id:`session`,status:`info`,summary:r.remote?`No active session named ${t}. Remote doctor will use configured remote scope.`:`No active session named ${t}. Doctor will use device inventory only.`,hint:`This is expected before a run. Use open when app foreground state matters.`}]}function Zf(e,t){return t!==`auto`||typeof e.runtime?.metroPort==`number`||typeof e.runtime?.metroHost==`string`}function Qf(e){let t={...Object.fromEntries([...Kf,...qf].flatMap(t=>typeof e.flags?.[t]==`string`?[[t,`<configured>`]]:[])),...e.flags?.sessionIsolation===`tenant`?{sessionIsolation:`tenant`}:{}};return Object.keys(t).length>0?t:void 0}function $f(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function ep(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:void 0}async function tp(e){let{req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,inspectFacts:a,bindDevice:o}=e;if(t.command!==T.doctor)return null;let s=np(e.hostDiagnostics),c=r.get(n),l=Jf(t,c),u=ap(r,n),d=ii(e.host.env,!!process.stderr.isTTY),f=[];if(hf(f,d,{id:`agent-device`,status:`pass`,summary:`agent-device ${rn()} using ${u}`,evidence:{version:rn(),stateDir:u}},...Yf(t,{required:l.remote}),...Xf(r,n,c,{remote:l.remote})),l.remote)return up(f,l);let p=rp(l,u,i),m=await yf(f,t,c,e.host.env,d),h=await s.toolchainCheck(c?.device.platform??m?.platform,p);h&&$(f,h,d);let g=await op({checks:f,context:p,hostDiagnostics:s,inventory:m,options:l,session:c,inspectFacts:a,bindDevice:o,req:t,env:e.host.env,useColor:d}),_=c?.device??ip(m,g);if(_){let e=await s.warmupCheck(_,p);e&&$(f,e,d)}return up(f,l,{device:g,includeMetro:!0,inventory:m})}function np(e){if(!e)throw new a(`COMMAND_FAILED`,`Host diagnostics gateway is not configured`,{reason:`runtime-gateway-missing`});return e}function rp(e,t,n){return Object.freeze({stateDir:t,metroPort:e.metroPort,shouldProbeMetro:e.shouldProbeMetro,isProviderDevice:e=>Dn(e),emitProgress:e=>Vn({type:`command`,status:`progress`,message:e}),listLocalDeviceInventory:async e=>await nr(e),shouldPropagateInventoryProbeError:tr,transportOverrides:Object.freeze({androidAdb:n})})}function ip(e,t){let n=e?.hostDevices??[];if(t)return n.includes(t)?t:void 0;let r=n.filter(e=>O(e)&&e.kind===`simulator`);return r.find(e=>e.booted===!0)??r[0]}function ap(e,t){let n=G.dirname(e.resolveSessionDir(t));return G.basename(n)===`sessions`?G.dirname(n):n}async function op(e){let{checks:t,context:n,hostDiagnostics:r,inventory:i,options:a,session:o,inspectFacts:s,bindDevice:c,req:l,env:u,useColor:d}=e,f=o?.device??bf(t,i,a.targetApp,d);return f&&await sp(t,{context:n,hostDiagnostics:r,device:f,options:a,session:o,inspectFacts:s,bindDevice:c,req:l,env:u,useColor:d}),a.shouldProbeMetro&&$(t,await zf(a.metroHost,a.metroPort,a.kind),d),hf(t,d,...await r.ambientChecks(n)),f}async function sp(e,t){let{context:n,hostDiagnostics:r,device:i,options:a,session:o,inspectFacts:s,bindDevice:c,req:l,env:u,useColor:d}=t,f;try{f=await cp({device:i,req:l,targetApp:a.targetApp,inspectFacts:s,bindDevice:c,env:u})}catch(e){f=async()=>{throw e}}await _f(e,{device:i,session:o,targetApp:a.targetApp,listInstalledApps:f,useColor:d}),hf(e,d,...await r.deviceChecks(i,n))}async function cp(e){if(e.device.platform!==`harmonyos`)return lp(e)}async function lp(e){let{device:t,req:n,targetApp:r,inspectFacts:i,bindDevice:a,env:o}=e;if(!r||!i||!a)return;let s=await i(t),c=s.operations.listApps,l=s.operations.ensureReady;if(!c.available||!l.available)return;let u=await a(t,Ze),d=L(n.flags?.androidDeviceAllowlist,o),f=await Ga(u,{serial:n.flags?.serial,androidSerialAllowlist:d?[...d].sort():void 0});return async e=>await Ka(u,f,e)}function up(e,t,n={}){let r=ff(e);return{ok:!0,data:{status:r,summary:pf(r),kind:t.kind,platform:n.device?k(n.device):n.inventory?.platform,target:n.device?.target??n.inventory?.target,targetApp:t.targetApp,metro:n.includeMetro&&t.shouldProbeMetro?{host:t.metroHost,port:t.metroPort}:void 0,checks:mf(e)}}}async function dp(e){return await R({...e,command:`prepare`,use:Ke})}async function fp(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=t.positionals?.[0]??``;if(a!==`ios-runner`)return d(`INVALID_ARGS`,`prepare requires a subcommand: ios-runner`);let o=i.get(n),s=t.flags??{},c=H(T.prepare,o,s);if(c)return c;let l=await ge(`prepare_resolve_device`,()=>U({session:o,flags:s,env:i.host.env,platformServices:e.platformServices}),void 0,`start`),u=await ge(`prepare_admit_runtime`,()=>dp({device:l,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice}),void 0,`start`);if(u.type===`response`)return u.response;let f=Date.now(),p=await u.runtime.operations.prepareAppleRunner({timeoutMs:pp(t),execution:{requestId:t.meta?.requestId,logPath:r,traceLogPath:o?.trace?.outPath,verbose:t.flags?.verbose,iosXctestrunFile:t.flags?.iosXctestrunFile,iosXctestDerivedDataPath:t.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:t.flags?.iosXctestEnvDir,runnerLeaseContext:Wn(t)}});return{ok:!0,data:mp(a,l,Math.max(0,Date.now()-f),p)}}function pp(e){let t=e.flags?.timeoutMs;return typeof t==`number`&&Number.isFinite(t)&&t>0?t:nt}function mp(e,t,n,r){return{action:e,platform:k(t),deviceId:t.id,deviceName:t.name,kind:t.kind,durationMs:n,...r,timing:hp(n,r),message:`Prepared Apple runner: ${t.name}`}}function hp(e,t){let n=gp(t.buildMs),r=_p(t.connectMs),i=_p(t.healthCheckMs);return{totalMs:e,additiveParts:{...n===void 0?{}:{buildMs:n},connectAfterBuildMs:Math.max(0,r-(n??0)),healthCheckMs:i},containment:n===void 0?{healthCheckMs:[]}:{connectMs:[`buildMs`],healthCheckMs:[]},note:`Top-level prepare timing fields are diagnostic and may overlap; use timing.additiveParts for additive wall-clock phases.`}}function gp(e){return e===void 0?void 0:_p(e)}function _p(e){return Number.isFinite(e)?Math.max(0,Math.round(e)):0}const vp=e=>qa(e),yp=e=>Lr({host:e.host,req:e.req,createCommandSurface:e.createCommandSurface,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim}),bp=e=>Ba({host:e.host,req:e.req,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,leaseRegistry:e.leaseRegistry,leaseLifecycleProvider:e.leaseLifecycleProvider,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,platformResourceCleanup:e.platformResourceCleanup}),xp=async({host:e,req:t,sessionName:n,sessionStore:r,bindDevice:i,platformServices:a,inspectFacts:o,appLogAdmissionLedger:s,audioProbeAdmissionLedger:c,perfCaptureAdmissionLedger:l,throwIfCanceled:u})=>await Os({host:e,req:t,sessionName:n,sessionStore:r,bindDevice:i,platformServices:a,inspectFacts:o,appLogAdmissionLedger:s,audioProbeAdmissionLedger:c,perfCaptureAdmissionLedger:l,throwIfCanceled:u}),Sp={session_list:vp,devices:vp,capabilities:vp,apps:vp,doctor:async({host:e,req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,hostDiagnostics:a,inspectFacts:o,bindDevice:s})=>await tp({host:e,req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,hostDiagnostics:a,inspectFacts:o,bindDevice:s}),boot:So,shutdown:To,appstate:Po,session_save_script:async({req:e,sessionName:t,sessionStore:n})=>tf({req:e,sessionName:t,sessionStore:n}),runtime:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await ji({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),clipboard:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await df({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),keyboard:ca,perf:xp,logs:xp,events:xp,network:xp,audio:xp,prepare:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await fp({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),install:K,reinstall:K,uninstall:K,install_source:K,release_materialized_paths:async({req:e})=>await hi({req:e}),push:K,"trigger-app-event":la,open:yp,replay:Zd,test:Qd,batch:async({req:e,sessionName:t,invoke:n})=>await Ca(e,t,n),close:bp};async function Cp(e){let{host:t,req:n,sessionName:r,logPath:i,sessionStore:a,leaseRegistry:o=new qt,leaseLifecycleProvider:s,providerAppCatalog:c,invoke:l,invokeReplayAction:u,androidAdbExecutor:d,inspectFacts:f,bindDevice:p,platformServices:m,bindExactDevice:h,appLogAdmissionLedger:g,audioProbeAdmissionLedger:_,perfCaptureAdmissionLedger:v,screenRecordingAdmissionLedger:y,hostDiagnostics:b,requestScope:x,retainDeviceExecutionLock:S,throwIfCanceled:C,reconcileOrphanedDeviceClaim:w,platformResourceCleanup:ee}=e,T=Sp[n.command];return T?await T({host:t,req:n,createCommandSurface:e.createCommandSurface,sessionName:r,logPath:i,sessionStore:a,leaseRegistry:o,leaseLifecycleProvider:s,providerAppCatalog:c,invoke:l,invokeReplayAction:u,androidAdbExecutor:d,inspectFacts:f,bindDevice:p,platformServices:m,bindExactDevice:h,appLogAdmissionLedger:g,audioProbeAdmissionLedger:_,perfCaptureAdmissionLedger:v,screenRecordingAdmissionLedger:y,hostDiagnostics:b,requestScope:x,retainDeviceExecutionLock:S,throwIfCanceled:C,reconcileOrphanedDeviceClaim:w,platformResourceCleanup:ee}):null}export{Cp as handleSessionCommands};
|
|
5
|
+
`).find(e=>e.startsWith(`n`)&&e.length>1)?.slice(1)}const Kf=[`daemonBaseUrl`,`tenant`,`runId`,`leaseId`,`leaseProvider`],qf=[`provider`,`providerSessionId`,`providerApp`,`providerOsVersion`,`providerDeviceType`,`providerProject`,`providerBuild`,`providerSessionName`,`providerDeviceOrientation`,`providerGeoLocation`,`providerTimezone`,`providerAppiumVersion`,`providerLanguage`,`providerLocale`,`providerNetworkProfile`,`providerCustomNetwork`,`providerNoResignApp`,`providerNetworkLogs`,`providerNetworkHosts`,`awsProjectArn`,`awsDeviceArn`,`awsAppArn`,`awsRegion`,`awsInteractionMode`];function Jf(e,t){let n=si(e.meta?.cwd);return{targetApp:$f(e.flags?.targetApp)??t?.appBundleId,metroHost:$f(e.runtime?.metroHost)??`127.0.0.1`,metroPort:ep(e.runtime?.metroPort)??8081,kind:n,remote:e.flags?.remote===!0,shouldProbeMetro:Zf(e,n)}}function Yf(e,t={}){let n=Qf(e);return n?[{id:`remote-connection`,status:t.required?`pass`:`info`,summary:`Remote daemon/session or provider scope is configured.`,evidence:n}]:t.required?[{id:`remote-connection`,status:`fail`,summary:`No remote daemon/session or provider scope is configured.`,hint:`Use connect, --remote-config <path>, or direct remote/provider flags for the command.`}]:[]}function Xf(e,t,n,r={}){let i=n?e.listRefs().filter(e=>e.address!==t&&e.session.device.platform===n.device.platform&&e.session.device.id===n.device.id).map(e=>e.address):[];return n?[{id:`session`,status:i.length>0?`warn`:`pass`,summary:i.length>0?`Other active sessions target the same device: ${i.join(`, `)}`:`Active session ${n.name} targets ${n.device.name}`,hint:i.length>0?`Close stale sessions before a QA run if they belong to old attempts.`:void 0,command:i.length>0?`agent-device close --session ${i[0]} --platform ${O(n.device)}`:void 0,evidence:{session:t,sameDeviceSessions:i,sessionStateDir:e.resolveSessionDir(t)}}]:[{id:`session`,status:`info`,summary:r.remote?`No active session named ${t}. Remote doctor will use configured remote scope.`:`No active session named ${t}. Doctor will use device inventory only.`,hint:`This is expected before a run. Use open when app foreground state matters.`}]}function Zf(e,t){return t!==`auto`||typeof e.runtime?.metroPort==`number`||typeof e.runtime?.metroHost==`string`}function Qf(e){let t={...Object.fromEntries([...Kf,...qf].flatMap(t=>typeof e.flags?.[t]==`string`||e.flags?.[t]===!0?[[t,`<configured>`]]:[])),...e.flags?.sessionIsolation===`tenant`?{sessionIsolation:`tenant`}:{}};return Object.keys(t).length>0?t:void 0}function $f(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function ep(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:void 0}async function tp(e){let{req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,inspectFacts:a,bindDevice:o}=e;if(t.command!==T.doctor)return null;let s=np(e.hostDiagnostics),c=r.get(n),l=Jf(t,c),u=ap(r,n),d=ii(e.host.env,!!process.stderr.isTTY),f=[];if(hf(f,d,{id:`agent-device`,status:`pass`,summary:`agent-device ${gn()} using ${u}`,evidence:{version:gn(),stateDir:u}},...Yf(t,{required:l.remote}),...Xf(r,n,c,{remote:l.remote})),l.remote)return up(f,l);let p=rp(l,u,i),m=await yf(f,t,c,e.host.env,d),h=await s.toolchainCheck(c?.device.platform??m?.platform,p);h&&$(f,h,d);let g=await op({checks:f,context:p,hostDiagnostics:s,inventory:m,options:l,session:c,inspectFacts:a,bindDevice:o,req:t,env:e.host.env,useColor:d}),_=c?.device??ip(m,g);if(_){let e=await s.warmupCheck(_,p);e&&$(f,e,d)}return up(f,l,{device:g,includeMetro:!0,inventory:m})}function np(e){if(!e)throw new a(`COMMAND_FAILED`,`Host diagnostics gateway is not configured`,{reason:`runtime-gateway-missing`});return e}function rp(e,t,n){return Object.freeze({stateDir:t,metroPort:e.metroPort,shouldProbeMetro:e.shouldProbeMetro,isProviderDevice:e=>Ln(e),emitProgress:e=>Zn({type:`command`,status:`progress`,message:e}),listLocalDeviceInventory:async e=>await fr(e),shouldPropagateInventoryProbeError:dr,transportOverrides:Object.freeze({androidAdb:n})})}function ip(e,t){let n=e?.hostDevices??[];if(t)return n.includes(t)?t:void 0;let r=n.filter(e=>j(e)&&e.kind===`simulator`);return r.find(e=>e.booted===!0)??r[0]}function ap(e,t){let n=G.dirname(e.resolveSessionDir(t));return G.basename(n)===`sessions`?G.dirname(n):n}async function op(e){let{checks:t,context:n,hostDiagnostics:r,inventory:i,options:a,session:o,inspectFacts:s,bindDevice:c,req:l,env:u,useColor:d}=e,f=o?.device??bf(t,i,a.targetApp,d);return f&&await sp(t,{context:n,hostDiagnostics:r,device:f,options:a,session:o,inspectFacts:s,bindDevice:c,req:l,env:u,useColor:d}),a.shouldProbeMetro&&$(t,await zf(a.metroHost,a.metroPort,a.kind),d),hf(t,d,...await r.ambientChecks(n)),f}async function sp(e,t){let{context:n,hostDiagnostics:r,device:i,options:a,session:o,inspectFacts:s,bindDevice:c,req:l,env:u,useColor:d}=t,f;try{f=await cp({device:i,req:l,targetApp:a.targetApp,inspectFacts:s,bindDevice:c,env:u})}catch(e){f=async()=>{throw e}}await _f(e,{device:i,session:o,targetApp:a.targetApp,listInstalledApps:f,useColor:d}),hf(e,d,...await r.deviceChecks(i,n))}async function cp(e){if(e.device.platform!==`harmonyos`)return lp(e)}async function lp(e){let{device:t,req:n,targetApp:r,inspectFacts:i,bindDevice:a,env:o}=e;if(!r||!i||!a)return;let s=await i(t),c=s.operations.listApps,l=s.operations.ensureReady;if(!c.available||!l.available)return;let u=await a(t,Ke),d=L(n.flags?.androidDeviceAllowlist,o),f=await Ga(u,{serial:n.flags?.serial,androidSerialAllowlist:d?[...d].sort():void 0});return async e=>await Ka(u,f,e)}function up(e,t,n={}){let r=ff(e);return{ok:!0,data:{status:r,summary:pf(r),kind:t.kind,platform:n.device?O(n.device):n.inventory?.platform,target:n.device?.target??n.inventory?.target,targetApp:t.targetApp,metro:n.includeMetro&&t.shouldProbeMetro?{host:t.metroHost,port:t.metroPort}:void 0,checks:mf(e)}}}async function dp(e){return await R({...e,command:`prepare`,use:Ge})}async function fp(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=t.positionals?.[0]??``;if(a!==`ios-runner`)return d(`INVALID_ARGS`,`prepare requires a subcommand: ios-runner`);let o=i.get(n),s=t.flags??{},c=U(T.prepare,o,s);if(c)return c;let l=await ge(`prepare_resolve_device`,()=>H({session:o,flags:s,env:i.host.env,platformServices:e.platformServices}),void 0,`start`),u=await ge(`prepare_admit_runtime`,()=>dp({device:l,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice}),void 0,`start`);if(u.type===`response`)return u.response;let f=Date.now(),p=await u.runtime.operations.prepareAppleRunner({timeoutMs:pp(t),execution:{requestId:t.meta?.requestId,logPath:r,traceLogPath:o?.trace?.outPath,verbose:t.flags?.verbose,iosXctestrunFile:t.flags?.iosXctestrunFile,iosXctestDerivedDataPath:t.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:t.flags?.iosXctestEnvDir,runnerLeaseContext:er(t)}});return{ok:!0,data:mp(a,l,Math.max(0,Date.now()-f),p)}}function pp(e){let t=e.flags?.timeoutMs;return typeof t==`number`&&Number.isFinite(t)&&t>0?t:Je}function mp(e,t,n,r){return{action:e,platform:O(t),deviceId:t.id,deviceName:t.name,kind:t.kind,durationMs:n,...r,timing:hp(n,r),message:`Prepared Apple runner: ${t.name}`}}function hp(e,t){let n=gp(t.buildMs),r=_p(t.connectMs),i=_p(t.healthCheckMs);return{totalMs:e,additiveParts:{...n===void 0?{}:{buildMs:n},connectAfterBuildMs:Math.max(0,r-(n??0)),healthCheckMs:i},containment:n===void 0?{healthCheckMs:[]}:{connectMs:[`buildMs`],healthCheckMs:[]},note:`Top-level prepare timing fields are diagnostic and may overlap; use timing.additiveParts for additive wall-clock phases.`}}function gp(e){return e===void 0?void 0:_p(e)}function _p(e){return Number.isFinite(e)?Math.max(0,Math.round(e)):0}const vp=e=>qa(e),yp=e=>Lr({host:e.host,req:e.req,createCommandSurface:e.createCommandSurface,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim}),bp=e=>Ba({host:e.host,req:e.req,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,leaseRegistry:e.leaseRegistry,leaseLifecycleProvider:e.leaseLifecycleProvider,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,platformResourceCleanup:e.platformResourceCleanup}),xp=async({host:e,req:t,sessionName:n,sessionStore:r,bindDevice:i,platformServices:a,inspectFacts:o,appLogAdmissionLedger:s,audioProbeAdmissionLedger:c,perfCaptureAdmissionLedger:l,throwIfCanceled:u})=>await Os({host:e,req:t,sessionName:n,sessionStore:r,bindDevice:i,platformServices:a,inspectFacts:o,appLogAdmissionLedger:s,audioProbeAdmissionLedger:c,perfCaptureAdmissionLedger:l,throwIfCanceled:u}),Sp={session_list:vp,devices:vp,capabilities:vp,apps:vp,doctor:async({host:e,req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,hostDiagnostics:a,inspectFacts:o,bindDevice:s})=>await tp({host:e,req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,hostDiagnostics:a,inspectFacts:o,bindDevice:s}),boot:So,shutdown:To,appstate:Po,session_save_script:async({req:e,sessionName:t,sessionStore:n})=>tf({req:e,sessionName:t,sessionStore:n}),runtime:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await Mi({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),clipboard:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await df({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),keyboard:la,perf:xp,logs:xp,events:xp,network:xp,audio:xp,prepare:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await fp({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),install:K,reinstall:K,uninstall:K,install_source:K,release_materialized_paths:async({req:e})=>await gi({req:e}),push:K,"trigger-app-event":ua,open:yp,replay:Zd,test:Qd,batch:async({req:e,sessionName:t,invoke:n})=>await wa(e,t,n),close:bp};async function Cp(e){let{host:t,req:n,sessionName:r,logPath:i,sessionStore:a,leaseRegistry:o=new Wt,leaseLifecycleProvider:s,providerAppCatalog:c,invoke:l,invokeReplayAction:u,androidAdbExecutor:d,inspectFacts:f,bindDevice:p,platformServices:m,bindExactDevice:h,appLogAdmissionLedger:g,audioProbeAdmissionLedger:_,perfCaptureAdmissionLedger:v,screenRecordingAdmissionLedger:y,hostDiagnostics:b,requestScope:x,retainDeviceExecutionLock:S,throwIfCanceled:C,reconcileOrphanedDeviceClaim:w,platformResourceCleanup:ee}=e,T=Sp[n.command];return T?await T({host:t,req:n,createCommandSurface:e.createCommandSurface,sessionName:r,logPath:i,sessionStore:a,leaseRegistry:o,leaseLifecycleProvider:s,providerAppCatalog:c,invoke:l,invokeReplayAction:u,androidAdbExecutor:d,inspectFacts:f,bindDevice:p,platformServices:m,bindExactDevice:h,appLogAdmissionLedger:g,audioProbeAdmissionLedger:_,perfCaptureAdmissionLedger:v,screenRecordingAdmissionLedger:y,hostDiagnostics:b,requestScope:x,retainDeviceExecutionLock:S,throwIfCanceled:C,reconcileOrphanedDeviceClaim:w,platformResourceCleanup:ee}):null}export{Cp as handleSessionCommands};
|