agent-device
Version:
Open source device layer for AI coding agents: a CLI, MCP server, and typed Node.js API to control mobile, web, TV, and desktop apps on devices and simulators, locally or in the cloud.
5 lines • 160 kB
JavaScript
import{B as e,Bt as t,F as n,H as r,Hn as i,Ir as a,L as o,Lr as s,N as c,O as l,Ot as u,P as d,Q as f,R as p,Rr as m,St as h,U as g,Un as _,V as v,Vn as y,Vt as b,W as x,Z as S,bt as C,et as ee,fr as w,hr as T,in as te,kt as ne,mn as re,mr as ie,nt as ae,rt as oe,st as se,tt as ce,ut as le,v as ue,xr as de,yt as fe,z as pe,zt as me}from"./sdk-batch.js";import{B as E,R as he,S as ge,ct as _e,f as ve,gt as ye,lt as be,n as xe,p as Se,pt as Ce,s as D,st as we,v as O}from"./sdk-contracts.js";import{A as Te,g as Ee,n as De,t as Oe}from"./sdk-batch-runner.js";import{a as ke,n as Ae,t as je}from"./snapshot-diagnostics.js";import"./capture.js";import{Ot as Me,St as k,q as Ne,rt as Pe}from"./sdk-io.js";import"./diagnostics.js";import{D as Fe,H as Ie,N as Le,P as Re,R as A,T as j,w as M,y as N}from"./sdk-device.js";import{i as P,n as ze,r as F}from"./success-text.js";import{b as Be,p as Ve}from"./lease-scope.js";import{c as He,f as Ue,n as We,o as Ge,r as Ke,s as qe}from"./script.js";import{m as Je,r as Ye,u as Xe}from"./open-script.js";import{c as Ze,d as Qe,f as $e,h as et,l as tt,m as nt,o as I,p as rt,s as it,u as at}from"./session-store.js";import{a as ot,i as st,n as ct,o as lt,t as ut}from"./target-evidence.js";import{a as dt,c as ft,n as pt,o as mt,r as ht,s as gt,t as _t}from"./vars.js";import{a as vt,i as yt,n as bt,r as xt,t as St}from"./format.js";import{C as Ct,H as wt,I as Tt,L as Et,V as Dt,W as Ot,_ as kt,b as At,f as jt,g as Mt,h as Nt,p as Pt,v as Ft,w as It,y as Lt}from"./parameterized-recorded-fill.js";import{n as Rt,r as zt,t as Bt}from"./target-evidence-tree.js";import{n as Vt,t as Ht}from"./catalog.js";import{g as Ut,i as Wt}from"./observability.js";import{t as Gt}from"./app-inventory.js";import{A as Kt,M as qt,O as Jt}from"./device.js";import{u as Yt}from"./file.js";import{n as Xt,r as Zt}from"./output-path.js";import{n as Qt,t as $t}from"./perf-runtime-plan.js";import{a as en}from"./version.js";import{t as L}from"./session-paths.js";import{c as tn,l as nn}from"./session-artifact-paths.js";import"./command.js";import{c as rn}from"./device-shell.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{n as ln,t as un}from"./app-log-durable-resource.js";import{a as dn,i as fn,n as pn,o as mn,r as hn,t as gn}from"./perf-capture-session-resource.js";import{o as _n,r as vn}from"./session-event-action.js";import{a as yn,n as bn}from"./artifact-tracking.js";import{n as xn}from"./provider-device-admission.js";import{p as Sn,u as Cn}from"./device-claim-rule.js";import{d as wn,n as Tn,o as R,t as En,u as Dn}from"./snapshot-runtime-capture-input.js";import{n as On,r as kn,s as An}from"./request-ended-leases.js";import{_ as jn,a as Mn,f as Nn,g as Pn,i as Fn,s as In}from"./device-claims.js";import{d as Ln,f as Rn,m as zn,n as Bn,o as Vn,p as Hn,s as Un}from"./request.js";import{a as Wn,i as Gn,n as Kn,o as qn,r as Jn}from"./lease-context.js";import{d as Yn,h as Xn}from"./daemon-command-registry.js";import{a as Zn,f as Qn,n as $n,o as er,r as tr,s as nr,t as rr,u as ir}from"./session-runtime.js";import{n as ar}from"./device-isolation.js";import{a as or,n as sr,o as cr,r as lr}from"./device-inventory-context.js";import{t as ur}from"./dispatch-resolve.js";import{r as dr}from"./device-selector-intent.js";import{n as fr}from"./snapshot-lines.js";import"./screen-recording-admission-ledger.js";import{n as z,t as pr}from"./context.js";import{t as mr}from"./session-selector.js";import{a as hr,o as gr}from"./session-routing.js";import{n as _r,t as vr}from"./script-source.js";import{r as yr}from"./replay-script-selection.js";import{a as br,c as xr,n as Sr,o as Cr,s as wr,t as Tr}from"./session-teardown.js";import{i as Er,n as Dr}from"./session-capture-binding.js";import{t as Or}from"./platform-request-scope.js";import{a as kr,n as B,r as Ar,t as jr}from"./runtime-admission.js";import{u as Mr}from"./selector-pipeline-policy.js";import{n as Nr}from"./snapshot-node-lookup.js";import{n as Pr}from"./replay.js";import{t as Fr}from"./request-script-delivery-ledger.js";import{c as Ir,f as Lr,r as Rr}from"./runtime-session.js";import{a as zr,i as V,n as H,r as U,t as Br}from"./session-runtime-admission.js";import{t as Vr}from"./observation-capture.js";import{n as Hr}from"./gesture-runtime.js";import{a as Ur,c as Wr,i as Gr,l as Kr,o as qr,r as Jr,s as Yr,t as Xr}from"./app-log-session-resource.js";import{r as Zr}from"./lease-release.js";import{n as Qr}from"./device-selection-resolver.js";import{a as $r,i as W,n as G,r as ei}from"./session-device-resolution.js";import{t as ti}from"./record-runtime.js";import{a as ni,handleSessionOpenCommands as ri,i as ii,n as ai,o as oi,r as si,t as ci}from"./session-open.js";import{t as li}from"./audio-probe-result.js";import{a as ui,c as di,d as fi,g as pi,h as mi,l as hi,m as gi,n as _i,o as vi,p as yi,r as bi,t as xi,u as Si}from"./session-replay-vars.js";import{t as Ci}from"./replay-backend-registry.js";import{t as wi}from"./session-test-source-discovery.js";import{n as Ti}from"./status-markers.js";import{n as Ei,r as Di}from"./doctor-lines.js";import{t as Oi}from"./project-runtime.js";import{createHash as ki,randomUUID as Ai}from"node:crypto";import K,{promises as ji}from"node:fs";import q from"node:path";import{setTimeout as Mi}from"node:timers/promises";function Ni(e){throw new O(`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 O(`INVALID_ARGS`,`install_from_source requires a source payload`);switch(t.kind){case`url`:if(!t.url||t.url.trim().length===0)throw new O(`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 O(`INVALID_ARGS`,`install_from_source path source requires a non-empty path`);return t;case`github-actions-artifact`:throw new O(`UNSUPPORTED_OPERATION`,`install_from_source github-actions-artifact sources require a compatible remote daemon`);default:Ni(t)}}function Fi(e){let t=Pi(e),n=e.meta?.uploadedArtifactId;return!n||t.kind!==`path`?{source:t,cleanup:()=>{}}:{source:{kind:`path`,path:yn(n,e.meta?.tenantId)},cleanup:()=>{bn(n)}}}async function Ii(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o,s,c;try{let l=Bi(t);o=Fi(t);let u=await Ri(a,t,r.host.env,e.platformServices),d=await U(e.inspectFacts)(u),f=V(`install_from_source`,d.operations.ensureReady)??V(`install_from_source`,d.operations.materializeAppSource)??V(`install_from_source`,d.operations.deployMaterializedApp);if(f)return f;let p=H(e.bindDevice);u=await(await p(u,ce)).operations.ensureReady({});let m=await p(u,ce),h=o.source.kind===`url`?Un(t.meta?.requestId):void 0;s=await m.operations.materializeAppSource({source:o.source,...h===void 0?{}:{materializationDeadlineMs:h-se}}),c=await Vi({artifact:s,retention:l,req:t,session:a,sessionName:n}),i&&R(r.requireCurrent(i));let g=await m.operations.deployMaterializedApp({artifact:s}),_=Hi(u,s,g,c),v=P(_,`Installed: ${sn(_)}`);return I(r,i,t,`install_source`,v,{positionals:[]}),{ok:!0,data:v}}catch(e){return c&&await br(c.materializationId,t.meta?.tenantId).catch(()=>{}),{ok:!1,error:E(e)}}finally{await s?.cleanup(),o?.cleanup()}}async function Li(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new O(`INVALID_ARGS`,`release_materialized_paths requires a materializationId`);return await br(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:E(e)}}}async function Ri(e,t,n,r){let i=t.flags,a=zi(i?.platform);if(e&&a&&!Re(e.device,a))throw new O(`INVALID_ARGS`,`install_from_source requested platform ${a}, but session is bound to ${A(e.device)}`);if(!e&&!a)throw new O(`INVALID_ARGS`,`install_from_source requires platform "ios" or "android" when no session is provided`);return e?e.device:await W({session:e,req:t,env:n,androidAvdSelection:Yn(t.command),platformServices:r})}function zi(e){return e===`ios`||e===`android`?e:void 0}function Bi(e){return e.meta?.retainMaterializedPaths===!0?{enabled:!0,ttlMs:wr(e.meta?.materializedPathRetentionMs)}:{enabled:!1}}async function Vi(e){if(e.retention.enabled)return await xr({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 Hi(e,t,n,r){return M(e)?Ui(t,n,r):Wi(t,n,r)}function Ui(e,t,n){let r=t.bundleId??e.bundleId;if(!r)throw new O(`COMMAND_FAILED`,`Installed iOS app identity could not be resolved from the artifact`);return{...Ki(n),bundleId:r,...Gi(t,e),launchTarget:t.launchTarget??r}}function Wi(e,t,n){let r=t.packageName??t.launchTarget??e.packageName;if(!r)throw new O(`COMMAND_FAILED`,`Installed Android app identity could not be resolved from the artifact or device state`);return{...Ki(n),packageName:r,...Gi(t,e),launchTarget:t.launchTarget??r}}function Gi(e,t){let n=e.appName??t.appName;return n?{appName:n}:{}}function Ki(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function qi(e){let{req:t,session:n,inspectFacts:r,bindDevice:i,platformServices:a}=e,o=Ji(t);if(!o.ok)return o.response;let s=G(`runtime port-reverse`,n,t.flags);if(s)return s;let c=await W({session:n,req:t,env:e.env,platformServices:e.platformServices}),l=await B({device:c,inspectFacts:r,bindDevice:i,platformServices:a,command:`runtime port-reverse`,use:x});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 Ji(e){let t=Yi(e);if(!t.ok)return t;let n=Xi(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 Yi(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 Xi(e){let t=Zi(e.flags?.devicePort),n=Zi(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 Zi(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<1||e>65535))return e}async function Qi(e){return await B({...e,command:`runtime clear`,use:v})}async function $i(e){let{req:t,sessionName:n,sessionStore:r}=e,i=(t.positionals?.[0]??`show`).toLowerCase();if(i===`port-reverse`)return await qi({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 ea({...e,session:r.get(n)});if(!ta(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 na({sessionName:n,sessionStore:r,ref:a,current:s,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice}):i===`show`?ra(n,s):aa({req:t,sessionName:n,sessionStore:r,session:o,current:s})}async function ea(e){if(!e.session)return D(`SESSION_NOT_FOUND`,`No active session. Run open first.`);let t=await Hr({device:e.session.device,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(!t.ok)return t.response;let n=pr(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 ta(e){return e===`set`||e===`show`||e===`clear`}async function na(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(tr(i)&&c?.appBundleId){let e=await Qi({device:c.device,inspectFacts:a,bindDevice:o,platformServices:s});if(e.type===`response`)return e.response;let t=n.requireCurrent(r);R(t),await e.runtime.operations.clearRuntimeHints({appId:t.appBundleId,values:nr(i)})}let l=r?n.clearRuntimeHints(r):!!i;return r||n.setRuntimeHints(t,void 0),{ok:!0,data:{session:t,cleared:l}}}function ra(e,t){return{ok:!0,data:{session:e,configured:!!t,runtime:t}}}function ia(e){return e?A(e.device):void 0}function aa(e){let{req:t,sessionName:n,sessionStore:r,session:i,current:a}=e,o=ia(i),s=ir(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=Zn(a,rr(t.flags,s));return $n(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 oa=`AGENT_DEVICE_APP_EVENT_URL_TEMPLATE`,sa={ios:`AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE`,macos:`AGENT_DEVICE_MACOS_APP_EVENT_URL_TEMPLATE`,android:`AGENT_DEVICE_ANDROID_APP_EVENT_URL_TEMPLATE`},ca=/^[A-Za-z0-9_.:-]{1,64}$/,la=8192,ua=4096;function da(e){let t=e[0]?.trim(),n=e[1]?.trim();if(!t)throw new O(`INVALID_ARGS`,`trigger-app-event requires <event> [payloadJson]`);if(!ca.test(t))throw new O(`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 O(`INVALID_ARGS`,`trigger-app-event accepts at most two arguments: <event> [payloadJson]`);return{eventName:t,payload:pa(n,t)}}function fa(e,t,n,r){let i=A(e),a=ma(i),o=ha(a,r);if(!o)throw new O(`UNSUPPORTED_OPERATION`,`No app event URL template configured for ${i}.`,{hint:`Set ${a.join(` or `)}, 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>ua)throw new O(`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:ua});return c}function pa(e,t){if(e)try{let n=JSON.parse(e);if(!n||typeof n!=`object`||Array.isArray(n))throw new O(`INVALID_ARGS`,`trigger-app-event payload for "${t}" must be a JSON object`);let r=JSON.stringify(n);if(Buffer.byteLength(r,`utf8`)>la)throw new O(`INVALID_ARGS`,`trigger-app-event payload for "${t}" exceeds ${la} bytes`);return n}catch(t){throw t instanceof O?t:new O(`INVALID_ARGS`,`Invalid trigger-app-event payload JSON: ${e}`)}}function ma(e){let t=sa[e];return t?[t,oa]:[oa]}function ha(e,t){return e.map(e=>t[e]).find(e=>e!==void 0)?.trim()||void 0}async function ga(e,t,n,r,i){let{eventName:a,payload:o}=da([...r]),s=fa(t,a,o,i),c={eventUrl:s,...n.appBundleId===void 0?{}:{options:{appBundleId:n.appBundleId}},execution:Tn(n)};return await e.operations.triggerAppEvent(c),{event:a,eventUrl:s,transport:`deep-link`,...F(`Triggered app event: ${a}`)}}async function _a(e){let{host:t,device:n,positionals:r,inspectFacts:i,bindDevice:a,platformServices:o,readinessScope:s}=e,c=await B({command:`trigger-app-event`,device:n,use:fe,inspectFacts:i,bindDevice:a,platformServices:o,readinessScope:s});if(c.type===`response`)return{ok:!1,response:c.response};let l=c.runtime;return{ok:!0,execute:e=>ga(l,n,e,r,t.env)}}function va(e){let t=(e[0]??`status`).toLowerCase();if(!_n(t))throw new O(`INVALID_ARGS`,`keyboard requires a subcommand: status, get, dismiss, enter, or return`);if(e.length>1)throw new O(`INVALID_ARGS`,`keyboard accepts at most one subcommand argument`);return ya(t)}function ya(e){return e===`get`?`status`:e===`return`?`enter`:e}const ba={"ime-probe":`android`,keyboard:`ios`},xa={"ime-probe":`android`,mechanism:`ios`,acknowledged:`harmonyos`},Sa={"visibility-echo":`ios`,"android-acknowledged":`android`,"harmonyos-acknowledged":`harmonyos`};function Ca(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:Tn(e)}}async function wa(e,t){let n=await B(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(Ca(t)).then(e=>{let t=e.returnKey??(e.visible===!0?`unknown`:void 0),n={platform:ba[e.kind],action:`status`,visible:e.visible,returnKey:t,...e.returnKeyLabel===void 0||t===void 0?{}:{returnKeyLabel:e.returnKeyLabel}};return e.kind===`keyboard`?n:{...n,inputType:e.inputType,type:e.type,inputMethodPackage:e.inputMethodPackage,focusedPackage:e.focusedPackage,focusedResourceId:e.focusedResourceId,inputOwner:e.inputOwner}})}async function Ea(e,t){let n=await e.operations.keyboardDismiss(Ca(t)),r=xa[n.kind];return n.kind===`mechanism`?{platform:r,action:`dismiss`,wasVisible:n.wasVisible,dismissed:n.dismissed,visible:n.visible,mechanism:n.mechanism,...F(ka(n.dismissed===!0,n.mechanism))}:n.kind===`acknowledged`?{platform:r,action:`dismiss`,...F(`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 Da(e,t){let n=await e.operations.keyboardEnter(Ca(t)),r=Sa[n.kind];return n.kind===`visibility-echo`?{platform:r,action:`enter`,visible:n.visible,wasVisible:n.wasVisible,...F(`Keyboard enter pressed`)}:{platform:r,action:`enter`,...F(`Keyboard enter pressed`)}}async function Oa(e){let n=va(e.positionals),{device:r,inspectFacts:i,bindDevice:a,platformServices:o,readinessScope:s}=e;return n===`status`?await wa({command:`keyboard status`,device:r,use:b,inspectFacts:i,bindDevice:a,platformServices:o,readinessScope:s},(e,t)=>Ta(e,t)):n===`dismiss`?await wa({command:`keyboard dismiss`,device:r,use:me,inspectFacts:i,bindDevice:a,platformServices:o,readinessScope:s},(e,t)=>Ea(e,t)):await wa({command:`keyboard enter`,device:r,use:t,inspectFacts:i,bindDevice:a,platformServices:o,readinessScope:s},(e,t)=>Da(e,t))}function ka(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=G(i,u,d);if(f)return f;let p=await W({session:u,req:t,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&&Xn(t)===`may-invalidate`&&R(h);let g=await m.execute();return l&&(s&&await s(l,g),I(r,l,t,i,g??{},{positionals:o??a})),{ok:!0,data:g??{}}}function ja(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 Ma(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,readinessScope:Or(t),inspectFacts:a,bindDevice:o,platformServices:s});if(!u.ok)return{ok:!1,response:u.response};let d=l?i.requireCurrent(l):void 0,f={...pr(r,t.flags,d?.appBundleId,d?.trace?.outPath),surface:d?.surface};return{ok:!0,execute:()=>u.execute(f)}}})}async function Na(e){return ja(e.sessionStore.get(e.sessionName),e.req.positionals?.[0]?.trim().toLowerCase(),e.req.flags??{})||await Ma({...e,command:Vt.keyboard,resolveRuntime:e=>Oa(e)})}async function Pa(e){return await Ma({...e,command:Vt.triggerAppEvent,resolveRuntime:e=>_a(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 Fa(e){let t=e.trim();return t.startsWith(`{`)&&t.endsWith(`}`)||t.startsWith(`[`)&&t.endsWith(`]`)}const Ia=new Set([`ENOENT`,`ENAMETOOLONG`,`ENOTDIR`]);function La(e,t){let n=t?.subject??`Payload`,r=e.trim();if(!r)throw new O(`INVALID_ARGS`,`${n} cannot be empty`);let i=t?.resolvePath?t.resolvePath(r):r;try{if(!K.statSync(i).isFile())throw new O(`INVALID_ARGS`,`${n} path is not a file: ${i}`);return{kind:`file`,path:i}}catch(e){if(e instanceof O)throw e;let t=e.code;if(t===`EACCES`||t===`EPERM`)throw new O(`INVALID_ARGS`,`${n} file is not readable: ${i}`);if(t&&!Ia.has(t))throw new O(`COMMAND_FAILED`,`Unable to read ${n} file: ${i}`,{cause:String(e)})}if(Fa(r))return{kind:`inline`,text:r};throw new O(`INVALID_ARGS`,`${n} file not found: ${i}`)}async function Ra(e,t){let n=La(e,{subject:`Push payload`,...t});return Ba(n.kind===`inline`?n.text:await Va(n.path),e)}function za(e){return Ba(e,e)}function Ba(e,t){try{let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))throw new O(`INVALID_ARGS`,`push payload must be a JSON object`);return t}catch(e){throw e instanceof O?e:new O(`INVALID_ARGS`,`Invalid push payload JSON: ${t}`)}}async function Va(e){try{return await ji.readFile(e,`utf8`)}catch(t){let n=t.code;throw n===`ENOENT`?new O(`INVALID_ARGS`,`Push payload file not found: ${e}`):n===`EISDIR`?new O(`INVALID_ARGS`,`Push payload path is not a file: ${e}`):n===`EACCES`||n===`EPERM`?new O(`INVALID_ARGS`,`Push payload file is not readable: ${e}`):new O(`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=G(n,o,s);if(c)return c;let l=Ya(n,t.positionals??[]);if(!l.ok)return l.response;let u=t.meta?.uploadedArtifactId,d=u?yn(u,t.meta?.tenantId):L(l.appPathInput,z(t,e.host));try{if(!K.existsSync(d))return D(`INVALID_ARGS`,`App binary not found: ${d}`);let r=await W({session:o,req:t,env:i.host.env,androidAvdSelection:Yn(n),platformServices:e.platformServices}),c=await U(e.inspectFacts)(r),u=V(n,c.operations.deployApp);if(u)return u;let f=H(e.bindDevice),p=await f(r,ee),m=await ii({device:r,owner:p.owner,bindDevice:f,flags:s,env:i.host.env,deadlineAtMs:void 0});m&&(r=m,p=await f(r,ee)),a&&R(i.requireCurrent(a));let h=await p.operations.deployApp({app:l.app,appPath:d,replaceExisting:n===`reinstall`}),g=Ga(r,l.app,d,h),_=P(g,`Installed: ${g.appName??cn(g)}`);return Ja(i,a,g),I(i,a,t,n,_),{ok:!0,data:_}}finally{u&&bn(u)}}async function Ua(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o=t.flags??{},s=G(`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=t.internal?.publicNetworkOnly?za(l):await Ra(l,{resolvePath:n=>L(n,z(t,e.host))}),d=await W({session:a,req:t,env:r.host.env,platformServices:e.platformServices}),f=await U(e.inspectFacts)(d),p=V(`push`,f.operations.ensureReady)??V(`push`,f.operations.sendPushNotification);if(p)return p;let m=await H(e.bindDevice)(d,ae);await m.operations.ensureReady({}),i&&R(r.requireCurrent(i));let h=await m.operations.sendPushNotification({appId:c,payload:u}),g=M(d)?P({platform:`ios`,bundleId:c},`Pushed notification to ${c}`):P({platform:A(d),package:c,action:h.action,extrasCount:h.extrasCount},`Pushed notification to ${c}`);return I(r,i,t,`push`,g,{positionals:[c,l]}),{ok:!0,data:g}}async function Wa(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.lookup(n),a=i?.session,o=t.flags??{},s=G(`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 W({session:a,req:t,env:r.host.env,platformServices:e.platformServices}),u=await U(e.inspectFacts)(l),d=V(`uninstall`,u.operations.uninstallApp);if(d)return d;let f=await H(e.bindDevice)(l,oe);i&&R(r.requireCurrent(i));let p=await f.operations.uninstallApp({app:c}),m=M(l)?`ios`:A(l),h=p.wasInstalled?`bundleId`in p?p.bundleId:p.packageName:void 0,g=h?P({platform:m,app:c,wasInstalled:!0,appId:h},`Uninstalled: ${h}`):P({platform:m,app:c,wasInstalled:!1},`Not installed: ${c}`);return I(r,i,t,`uninstall`,g),{ok:!0,data:g}}function Ga(e,t,n,r){return M(e)?Ka(t,n,r):qa(e,t,n,r)}function Ka(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 qa(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 Ja(e,t,n){!t||n.platform!==`harmonyos`||!n.appId||e.update(t,{appBundleId:n.appId,appName:n.appName??n.app})}function Ya(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}}async function Xa(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 Ii({req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`uninstall`?await Wa({host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):n.command===`push`?await Ua({host:t,req:n,sessionName:r,sessionStore:i,inspectFacts:a,bindDevice:o,platformServices:s}):null}async function Za(e,t,n){return await De(e,t,async(t,r)=>{let i=t,a=await n({...i,internal:{...i.internal,webSession:e.internal?.webSession,...e.internal?.publicNetworkOnly?{publicNetworkOnly:!0}:{},...e.internal?.scriptDelivery?{scriptDelivery:e.internal.scriptDelivery}:{},executionPlan:{remainingSteps:r.remainingSteps}}});return Fr(e,{number:r.stepNumber,command:i.command},a),a})}async function Qa(e){Kn(e.req)&&Jn(e.req,`provider-lease`);let t=Wn(e.req,e.session);if(e.owner.kind!==`provider-runtime`||t.leaseId!==e.leaseId||t.leaseProvider!==e.owner.provider||!e.leaseRegistry||!e.leaseLifecycleProvider?.release)throw new O(`UNAUTHORIZED`,`The selected target does not own this request lease.`,{reason:`TARGET_SHUTDOWN_LEASE_MISMATCH`});let n=Be(t),r=e.leaseRegistry.getLease(n);if(!r)throw new O(`UNAUTHORIZED`,`The target lease is no longer active.`,{reason:`LEASE_NOT_FOUND`,leaseId:e.leaseId});let i=await Zr(e.leaseRegistry,e.leaseLifecycleProvider,r,n);return kn(e.req,r.leaseId),{provider:i.provider,shutdown:{success:!0,exitCode:0,stdout:`Released provider instance lease.`,stderr:``}}}function $a(e,t,n){let r=e.requireCurrent(t);e.recordAction(t,{command:`close`,positionals:n.positionals??[],flags:n.flags??{},result:{session:r.name,...F(`Closed: ${r.name}`)}})}function eo(e,t,n){let r=e.requireCurrent(t);if(!at(r))return{kind:`not-armed`};let i=r.actions.length;$a(e,t,n);let a=Nt(r),o=e.writeSessionLog(t,{force:jt(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`}:(it(r),{kind:`aborted`})}function to(e,t){let n=E(t),r=Et(e.scriptPublication??It);return{ok:!1,error:{...n,details:{...n.details,session:e.name,...r?{savedScript:r}:{}},retriable:!0}}}function no(e){let{req:t,ref:n,sessionStore:r,platformCloseError:i}=e,a=r.requireCurrent(n);i||$a(r,n,t);let o=r.writeSessionLog(n,{force:jt(a,t.flags?.force)});o.written&&kt(a,o.path);let s=!o.written&&o.error?ro(o.error):void 0,c=Ft(a,s!==void 0);return c?{remote:c}:{error:s}}function ro(e){return new O(`COMMAND_FAILED`,`The session was closed, but its script was not saved: ${e.message}`,{...e.details,hint:io(e),retriable:!1},e.cause)}function io(e){switch(e.details?.reason){case`script_target_exists`:return`Remove the existing target (or pass --force/--overwrite), then re-record with open --save-script.`;case`script_write_failed`:return`Check the target path and its permissions, then re-record with open --save-script.`;default:return e.details?.hint}}async function ao(e){let t=e.clearRuntimeHints?g:r,n=await jr({...e,command:`close`,required:t.required});if(n.type===`response`)return n;if(!e.clearRuntimeHints)return{type:`runtime`,runtime:await n.bind(e.device,r)};let i=await n.bind(e.device,g);return{type:`runtime`,runtime:i,clearRuntimeHints:i.operations.clearRuntimeHints}}async function oo(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,leaseWillEnd:!!f.lease&&!await p(`lease_retention`,async()=>Cn({session:f,leaseRegistry:e.leaseRegistry}))}),h=i.getRuntimeHints(d),g=Sr({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&&tr(h)&&await p(`runtime_hints`,async()=>{await o({appId:f.appBundleId,values:nr(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&&a.owner.kind===`local-family`})??{}),y=c?{}:u({req:t,ref:n,sessionStore:i,platformCloseError:_});return await p(`materialized_paths`,()=>Cr(d)),{platformCloseError:_,retainExecutionHost:m,saveScriptOutcome:y,shutdownResult:v?.shutdown,shutdownPrepared:v!==void 0}}function so(e,t,n){return Tr({sessionName:e,phase:`session_close_cleanup_failed`,failures:t,...n.sessionKept?{hint:`Some session resources failed to release. The session was kept; retry close with the same options, leaving out --save-script once the script is published, to rerun the failed cleanup and release the remaining resources.`}:{}})}function co(e){if(e instanceof O)return e;let t=e instanceof Error?e.message:String(e);return new O(`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 lo=(e,t)=>(e.positionals?.length??0)>0||Qn(t);async function uo(e){let{req:t,ref:n,logPath:r,sessionStore:i,lifecycle:a}=e,o=i.requireCurrent(n),s=at(o),c=JSON.stringify(t.positionals??[]);if(s&&!tt(o,c)){let e=await po({req:t,session:o,logPath:r,lifecycle:a});if(e)return{response:to(o,co(e))};rt(i.requireCurrent(n),c)}let l=eo(i,n,t);return l.kind===`failed`?{response:to(o,l.error)}:{repairArmed:s,...l.kind===`committed`&&l.path?{healedScriptPath:l.path}:{},...l.kind===`aborted`?{aborted:!0}:{}}}async function fo(e){try{let t,n,r=e.lifecycle.operations.shutdownTarget;if(e.req.flags?.shutdown&&r&&e.lifecycle.owner.kind===`provider-runtime`){if(!e.shutdownPrepared)throw so(e.sessionName,e.cleanupFailures,{sessionKept:!0})??new O(`COMMAND_FAILED`,`Target shutdown preparation failed. Retry close.`);n=await r({releaseLease:async n=>{let r=await Qa({...e,owner:e.lifecycle.owner,leaseId:n});return t={providerData:r.provider},r.shutdown}})}if(t)return{...t,shutdownResult:n};let{endedLeaseId:i,providerData:a}=await Sn(e);return i&&kn(e.req,i),{providerData:a,shutdownResult:n}}catch(t){let n=E(t);return{response:{ok:!1,error:{...n,hint:`The target could not be shut down or released. Retry close after resolving the failure.`,details:{...n.details,session:e.sessionName},retriable:!0}}}}}async function po(e){let{req:t,session:n,logPath:r,lifecycle:i}=e;if(lo(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:ai(t,r,n.trace?.outPath)});return}catch(e){return e}}function mo(e,t){if(!e.flags?.saveScript||Pt(t))return;let n=t.scriptPublication;if(n?.kind!==`repair`)throw n===void 0||n.kind===`none`?new O(`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 O(`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 ho(e){let{session:t,app:n}=e;if(!t.device.hostApp||!n)return;let r=await B({command:`close`,device:t.device,use:f,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 go(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o}=e,s=i.lookup(n);if(!s)return await xo({req:t,sessionName:n,logPath:r,env:e.host.env,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});let c=i.requireCurrent(s);mo(t,c);let l=t.positionals?.[0],u=await ho({session:c,app:l,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice,platformServices:e.platformServices});if(u)return u;if(t.internal?.closeAppOnly===!0&&!l)return D(`INVALID_ARGS`,`App-only close requires an app target`);if(!e.platformResourceCleanup)throw new O(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let d=e.platformResourceCleanup,f=await ao({device:c.device,clearRuntimeHints:t.internal?.closeAppOnly!==!0&&!!c.appBundleId&&tr(i.getRuntimeHints(n)),inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(f.type===`response`)return f.response;if(c=i.requireCurrent(s),R(c),t.internal?.closeAppOnly===!0&&l)return await bo({req:t,session:c,logPath:r,lifecycle:f.runtime,app:l});let p=await uo({req:t,ref:s,logPath:r,sessionStore:i,lifecycle:f.runtime});if(`response`in p)return p.response;let m=await _o(i,s,()=>vo({env:e.host.env,req:t,ref:s,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o,lifecycle:f.runtime,clearRuntimeHints:f.clearRuntimeHints,repairArmed:p.repairArmed,platformResourceCleanup:d}));if(m.kind===`response`)return m.response;let h=yo({session:c,repair:p,requestedSaveScript:!!t.flags?.saveScript,shutdownResult:m.shutdownResult,providerData:m.providerData});return Lt(h,m.remoteScript)}async function _o(e,t,n){try{return await n()}finally{e.resolveCurrent(t)&&e.markCloseEffectsUnconfirmed(t)}}async function vo(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,retainExecutionHost:f,saveScriptOutcome:p,shutdownPrepared:m,shutdownResult:h}=await oo({leaseRegistry:a,req:t,ref:n,logPath:r,sessionStore:i,lifecycle:s,clearRuntimeHints:c,cleanupFailures:u,repairArmed:e.repairArmed,dispatchTargetedPlatformClose:po,finalizeOrdinaryCloseScript:no,platformResourceCleanup:e.platformResourceCleanup}),g=i.requireCurrent(n);if(g.deviceClaim){let e=so(l,u,{sessionKept:!0}),t=d??e;if(t)throw k({level:`warn`,phase:`device_claim_close_effects_unconfirmed`,data:{deviceKey:g.deviceClaim.deviceKey,session:l}}),t}let _=await fo({req:t,session:g,leaseRegistry:a,leaseLifecycleProvider:o,lifecycle:s,shutdownPrepared:m,cleanupFailures:u,sessionName:l});if(_.response)return{kind:`response`,response:_.response};g=i.resolveCurrent(n)??g;let v=so(l,u,{sessionKept:!1}),y=d??v;if(y||await Fn(g.deviceClaim,e.env),i.retire(n,{retainExecutionHost:f}),y)throw y;if(p.error)throw p.error;return{kind:`closed`,providerData:_.providerData,shutdownResult:_.shutdownResult??h,remoteScript:p.remote}}function yo(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:P({session:t.name,shutdown:i,...o,...s},c)}:{ok:!0,data:{session:t.name,...F(c),...o,...s}}}async function bo(e){let{req:t,session:n,logPath:r,lifecycle:i,app:a}=e,o=await po({req:t,session:n,logPath:r,lifecycle:i});if(o)throw o;return{ok:!0,data:{app:a,...F(`Closed: ${a}`)}}}async function xo(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 ao({device:await W({session:void 0,req:t,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:ai(t,r)}),{ok:!0,data:{app:t.positionals[0],...F(`Closed: ${t.positionals[0]}`)}})}function So(e,t){return e.operations.ensureReady(t)}function Co(e,t,n){return e.operations.listApps({device:t,filter:n})}async function wo(e){let{req:t,sessionName:n,sessionStore:r}=e;switch(t.command){case`session_list`:return To(t,r);case`devices`:return await Do(t,e.host.env);case`capabilities`:return await Po({req:t,sessionName:n,sessionStore:r,inspectFacts:e.inspectFacts,platformServices:e.platformServices});case`apps`:return await zo({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 To(e,t){let n=hr(e);return{ok:!0,data:{sessions:t.listRefs().filter(e=>gr(e.session,n)).map(e=>Eo(e,t))}}}function Eo({address:e,session:t},n){let r=n.resolveSessionDir(e);return{name:t.name,address:e,sessionStateDir:r,runnerLogPath:tn(r),platform:A(t.device),...N(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,kind:t.device.kind,...qo(t.device),createdAt:t.createdAt,...N(t.device.platform)&&!j(t.device)&&{device_udid:t.device.id,ios_simulator_device_set:t.device.simulatorSetPath??null}}}async function Do(e,t){try{let n=await Oo(t);return{ok:!0,data:{devices:(await Ao(e,t)).map(e=>({...Ko(e),...ko(e,n)}))}}}catch(e){let t=ge(e);return{ok:!1,error:{code:t.code,message:t.message,...t.details?{details:t.details}:{}}}}}async function Oo(e){return(await Pn({},e)).flatMap(e=>e.claim&&!Nn(e.classification)?[e.claim]:[])}function ko(e,t){let n=Mn(e),r=jn(n),i=t.find(e=>e.deviceKey===r)??t.find(e=>In(n,e));return i?{claimedBy:{session:i.session,workspace:i.workspace}}:{}}async function Ao(e,t){let n=e.flags?.platform;return No(await sr(jo(e,n,t)),e.flags?.platform,e.flags?.target)}function jo(e,t,n){let r=e.flags,i=Gn(e),a=Ve(i);return{leaseProvider:a,leaseId:a?i.leaseId:void 0,platform:t,target:r?.target,deviceName:r?.device,udid:r?.udid,serial:r?.serial,iosSimulatorSetPath:Mo(r?.iosSimulatorDeviceSet,t,r?.target,n),androidSerialAllowlist:oi(r??{},n)}}function Mo(e,t,n,r){return Ie({requestedSetPath:e,platform:t,target:n,env:r})}function No(e,t,n){let r=t?e.filter(e=>Jo(e,t)):e;return n?r.filter(e=>(e.target??`mobile`)===n):r}async function Po(e){let t=await Go(e);if(`response`in t)return t.response;let{device:n}=t,r=Io(n,e.sessionStore.get(e.sessionName),e.req.flags),i=await Ho(n,e.inspectFacts);return{ok:!0,data:{device:Ko(n),...n.platform===`android`&&si(`press`,i)?{targetReadiness:{press:`bounded-geometry`}}:{},availableCommands:ue().filter(e=>e===`appstate`&&r&&!Fo(i)?!0:si(e,i))}}}function Fo(e){if(!e)return!0;let t=C.required.map(t=>e.operations[t]).find(e=>!e.available);return t?.available===!1&&Ar(t.reason)}function Io(e,t,n){return!t||!M(e)&&!j(e)||!$r(n,t)?!1:Lo(t)||Ro(e,t)}function Lo(e){return!!(e.appName||e.appBundleId)}function Ro(e,t){return!!(j(e)&&t.surface!==void 0&&t.surface!==`app`&&t.surface!==`frontmost-app`)}async function zo(e){let{req:t,sessionName:n,sessionStore:r,bindDevice:i,inspectFacts:a,platformServices:o}=e,s=await Bo(t,e.providerAppCatalog);if(s)return s;let c=await Go({req:t,sessionName:n,sessionStore:r,platformServices:o});if(`response`in c)return c.response;let{device:l}=c,u=Gt(t.flags?.appsFilter),d=await Uo({device:l,inspectFacts:a,bindDevice:i,platformServices:o});if(`response`in d)return d.response;let f=d.runtime;return Wo(await Co(f,await So(f,ni({flags:t.flags??{},env:e.env})),u))}async function Bo(e,t){let n=Vo(e);if(!(!t||!n||!t.supports(n.provider)))return{ok:!0,data:{apps:[...await t.list(n,Ln(e.meta?.requestId))]}}}function Vo(e){let t=Gn(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 Ho(e,t){if(t)try{return await t(e)}catch{return}}async function Uo(e){let t=await U(e.inspectFacts)(e.device),n=[t.operations.ensureReady,t.operations.listApps].find(e=>!e.available);return n&&!n.available?{response:kr(`apps`,n)}:{runtime:await H(e.bindDevice)(e.device,h)}}function Wo(e){return{ok:!0,data:{apps:e.map(e=>e.name&&e.name!==e.id?`${e.name} (${e.id})`:e.id)}}}async function Go(e){let{req:t,sessionName:n,sessionStore:r,platformServices:i}=e,a=r.get(n),o=t.flags??{},s=G(t.command,a,o);return s?{response:s}:{device:await W({session:a,req:t,env:r.host.env,platformServices:i,androidAvdSelection:Yn(t.command)})}}function Ko({simulatorSetPath:e,iosPhysicalDeviceBackend:t,appleOs:n,...r}){return{...r,platform:A({platform:r.platform,appleOs:n}),...N(r.platform)&&n?{appleOs:n}:{}}}function qo(e){return{...e.model?{model:e.model}:{},...e.osVersion?{osVersion:e.osVersion}:{}}}function Jo(e,t){return Re(e,t)}function Yo(e,t){return{ok:!0,data:{platform:A(e),target:e.target??`mobile`,device:e.name,id:e.id,kind:e.kind,...t,...N(e.platform)&&e.appleOs?{appleOs:e.appleOs}:{}}}}function Xo(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 Zo(e,t){return!!(e?.trim()||t?.platform===`android`&&t.kind===`emulator`)}async function Qo(e,t){let{sessionName:n,sessionStore:r,req:i,platformServices:a}=e,o=r.get(n),s=i.flags??{};try{let e=await ei({session:o,req:i,env:r.host.env,androidAvdSelection:Yn(i.command),platformServices:a}),{device:t}=e;return s.target&&(t.target??`mobile`)!==s.target?{refusal:D(`DEVICE_NOT_FOUND`,`No ${t.platform} device found matching --target ${s.target}.`)}:e}catch(e){let n=ge(e);if(t&&!Zo(s.device,o?.device)&&n.code===`DEVICE_NOT_FOUND`&&n.details?.reason!==`provider_instance_unallocated`)return{refusal:D(`INVALID_ARGS`,`boot --headless requires --device <avd-name> (or an Android emulator session target).`)};throw e}}async function $o(e){let t=e.req.flags??{},n=G(e.req.command,e.sessionStore.get(e.sessionName),t);if(n)return n;let r=te({headless:t.headless===!0}),i=await Qo(e,r.kind===`boot-target-headless`);if(`refusal`in i)return i.refusal;let a=i.device,o=await jr({command:`boot`,device:a,required:r.use.required,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,unavailableResponse:Xo(r.kind===`boot-target-headless`)});if(o.type===`response`)return o.response;let s=ni({flags:t,env:e.host.env,deadlineAtMs:ci(t.timeoutMs)}),c=r.kind===`boot-target-headless`?await(await o.bind(a,r.use)).operations.bootTargetHeadless(s):await(await o.bind(a,r.use)).operations.bootTarget(s),{device:l,...u}=Qr(i);return Yo(c,{booted:!0,selection:u})}function es(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 ts(e){let t=e.error?.message??e.stderr.trim();return t.length>0?t:`Shutdown failed`}async function ns(e){let t=e.sessionStore.get(e.sessionName),n=e.req.flags??{},r=G(e.req.command,t,n);if(r)return r;let i=await W({req:e.req,session:t,env:e.sessionStore.host.env,androidAvdSelection:Yn(e.req.command),platformServices:e.platformServices}),a=es((await U(e.inspectFacts)(i)).operations.shutdownTarget);if(a)return a;let o=e.sessionStore.findByDevice(i.id);if(o){let t=gr(o.session,hr(e.req));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.`,{...t?{hint:`Run agent-device close --shutdown --session ${o.address}`,session:o.address}:{},platform:A(i),target:i.target??`mobile`,device:i.name,id:i.id,kind:i.kind})}let s=await H(e.bindDevice)(i,re),c,l=await s.operations.shutdownTarget({releaseLease:async t=>{let n=await Qa({req:e.req,owner:s.owner,leaseId:t,leaseRegistry:e.leaseRegistry,leaseLifecycleProvider:e.leaseLifecycleProvider});return c=n.provider,n.shutdown}});if(!l.success)return D(l.error?.code??`COMMAND_FAILED`,ts(l),{platform:A(i),target:i.target??`mobile`,device:i.name,id:i.id,kind:i.kind,shutdown:l});let u=Yo(i,{shutdown:l});return u.ok&&c?{...u,data:{...u.data,provider:c}}:u}function rs(e,t){return N(t)?D(`SESSION_NOT_FOUND`,`No active session "${e}". Run open with --session ${e} first.`,he(e)):D(`SESSION_NOT_FOUND`,`No active session "${e}". Run open with --session ${e} first, or omit --session to query by device selector.`,he(e))}function is(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 as(e,t){let n=await B({command:`appstate`,device:t.device,use:C,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});return n.type===`response`?Ar(n.response.error.details?.reason)?{refusal:n.response}:{}:{state:(await n.runtime.operations.appState({appBundleId:t.appBundleId})).applicationState}}function os(e){if(!(!j(e.device)||!e.surface)&&e.surface!==`app`&&e.surface!==`frontmost-app`)return{ok:!0,data:{platform:A(e.device),appName:e.surface,appBundleId:e.appBundleId,source:`session`,surface:e.surface}}}async function ss(e,t){if(!t.appName&&!t.appBundleId){let e=os(t);if(e)return e;let n=j(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 as(e,t);if(`refusal`in n)return n.refusal;let{state:r}=n,i=t.appName??t.appBundleId;return{ok:!0,data:{platform:A(t.device),appName:i??`unknown`,appBundleId:t.appBundleId,source:r?`runner`:`session`,...r?{state:r}:{},surface:t.surface??`app`,...M(t.device)?{device_udid:t.device.id,ios_simulator_device_set:t.device.simulatorSetPath??null}:{}}}}async function cs(e,t,n){if(M(t)||j(t))return n?rs(e.sessionName,t.platform):is(j(t)?`macos`:`ios`);let r=e.req.flags??{},i=await B({command:`appstate`,device:t,use:C,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(i.type===`response`)return i.response;let a=i.runtime;await a.operations.ensureReady(ni({flags:r,env:e.host.env}));let o=await a.operations.appState();return{ok:!0,data:{platform:A(t),package:o.package,activity:o.activity}}}function ls(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),a=t.flags??{},o=a.platform;if(!i&&ve(t)&&(!dr(a)||N(o)))return{refusal:rs(n,o)};let s=G(`appstate`,i,a);if(s)return{refusal:s};let c=N(i?.device.platform)&&$r(a,i);return o===`ios`&&!c?{refusal:is(`ios`)}:o===`macos`&&!c?{refusal:is(`macos`)}:c&&i?{answeredBy:`apple-session`,session:i}:{answeredBy:`device-runtime`,session:i,namedSessionMissing:!i&&ve(t)}}async function us(e){let t=ls(e);return`refusal`in t?t.refusal:t.answeredBy===`apple-session`?await ss(e,t.session):await cs(e,await W({session:t.session,req:e.req,env:e.sessionStore.host.env,platformServices:e.platformServices}),t.namedSessionMissing)}function ds(e){return un.createNextFence({admissionLedger:e.ledger,resourcePath:e.resourcePath,device:e.device})}async function fs(e){try{return await ps(e)}catch(e){return{ok:!1,error:E(e)}}}async function ps(e){let t=ms(e);if(!t.ok)return t;let n=t.ref,r=e.sessionStore.requireCurrent(n),i=o(e.req.positionals),a=await e.inspectFacts(r.device),s=a.operations.audioProbeStart,c=a.operations.audioProbeQuery,l=s.available?`capture`:c.available?`query`:void 0;if(l===void 0)return hs(s,c);let u=p({probeAction:i.probeAction,mode:l});switch(u.kind){case`query`:return{ok:!0,data:await(await e.bindDevice(r.device,u.use)).operations.audioProbeQuery({action:u.action,durationMs:i.durationMs,bucketMs:i.bucketMs})};case`capture-start`:return await gs(e,n,i,u.use);case`capture-status`:return await _s(e,n);case`capture-stop`:return await vs(e,n)}}function ms(e){let t=e.sessionStore.lookup(e.sessionName);return t?{ok:!0,ref:t}:D(`SESSION_NOT_FOUND`,`audio requires an active session`)}function hs(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 gs(e,t,n,r){let i=e.sessionStore.requireCurrent(t),a=Dr(e.sessionStore,t);i.audioProbe&&(await mn({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=q.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 fn({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 _s(e,t){let n=Dr(e.sessionStore,t),r=n.read();if(!r)return{ok:!0,data:ys()};let i=await r.handle.status();return i.state===`stopped`&&await mn({intent:`disposal`,binding:n}),{ok:!0,data:i}}async function vs(e,t){let n=Dr(e.sessionStore,t);return n.read()?{ok:!0,data:await mn({intent:`capture`,binding:n})}:{ok:!0,data:ys()}}function ys(){return li({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 bs(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(Ut(e.req.positionals?.[0]))throw new O(`INVALID_ARGS`,Wt);Bs(e.req);let t=$t({positionals:e.req.positionals,kind:Hs(e.req.flags?.kind),outPath:Hs(e.req.flags?.out)}),i=Qt(t);if(i.kind===`capture-stop`)return xs(r,await Ts(r,n,i.request));let a=await Br({device:n.device,plan:i,inspectFacts:e.inspectFacts});return a.admitted?xs(r,await Ss(r,n,a)):V(`perf`,a.fact)??D(`UNSUPPORTED_OPERATION`,`perf is not supported on this device`)}catch(e){return{ok:!1,error:E(e)}}}function xs(e,t){return t.ok&&I(e.sessionStore,e.ref,e.req,`perf`,Ee(t.data)?{...t.data}:{}),t}async function Ss(e,t,n){let{device:r,plan:i}=zr(n),a=H(e.bindDevice);switch(i.kind){case`frames`:return{ok:!0,data:js(t,await(await a(r,i.use)).operations.perfFrames({appId:t.appBundleId}))};case`memory-sample`:return{ok:!0,data:Is(t,await(await a(r,i.use)).operations.perfMemorySample({appId:t.appBundleId}))};case`memory-snapshot`:{let n=await(await a(r,i.use)).operations.perfMemorySnapshot({appId:t.appBundleId,kind:i.request.kind,outPath:i.request.outPath?L(i.request.outPath,z(e.req,e.host)):void 0,artifactsDir:q.join(e.sessionStore.ensureSessionDir(e.sessionName),`artifacts`)});return{ok:!0,data:Dt(Ls(t,n),e.req.internal?.publicNetworkOnly?`daemon`:`caller`,t.lease?.tenantId??e.req.meta?.tenantId)}}case`capture-start`:return await Cs(e,t,await a(r,i.use),i.request);case`profile-report`:{let n=await a(r,i.use),o=t.lastPerfProfile,s=i.request.tracePath??o?.outPath;if(!s)throw new O(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace or tracePath option`);if(t.perfCapture)throw new O(`INVALID_ARGS`,`perf cpu profile report requires a stopped profile trace; stop the active capture first.`);let c=zs(e,i.request.outPath,`cpu-report.json`),l=await n.operations.perfProfileReport({appId:t.appBundleId,kind:i.request.kind,tracePath:L(s,z(e.req,e.host)),outPath:c,template:i.request.template??(o?.kind===`xctrace`?o.template:void 0),profile:o});return{ok:!0,data:Dt({perf:`reported`,...l},e.req.internal?.publicNetworkOnly?`daemon`:`caller`,t.lease?.tenantId??e.req.meta?.tenantId)}}}}async function Cs(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=zs(e,r.outPath,i),o=hn.store.resolvePath(e.sessionStore.resolveSessionDir(e.sessionName)),s=hn.createNextFence({admissionLedger:ws(e),resourcePath:o,device:t.device}),c=Er(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 gn({admissionLedger:ws(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 ws(e){if(e.perfCaptureAdmissionLedger)return e.perfCaptureAdmissionLedger;throw new O(`COMMAND_FAILED`,`Perf capture admission ledger is not configured`,{reason:`runtime-gateway-missing`})}async function Ts(e,t,n){let r=t.perfCapture;if(!r)return D(`INVALID_ARGS`,`no active native perf capture`);let i=As(r.handle.inspect(),n);if(i)return D(`INVALID_ARGS`,i);n.outPath&&r.handle.setOutputPath(L(n.outPath,z(e.req,e.host)));let a=await pn({intent:`capture`,binding:Er(e.sessionStore,e.ref)});if(n.area===`cpu`){let t=Es(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:Dt({...a,...o?{clientOutPath:o}:{}},r.envelope.metadata?.remoteCaptureOutputPath===a.outPath?`daemon`:`caller`,s)}}function Es(e){if(Ds(e)||Os(e))return e;throw new O(`COMMAND_FAILED`,`Stopped CPU profile metadata is malformed.`)}function Ds(e){return e.kind===`xctrace`&&e.mode===`cpu-profile`&&typeof e.outPath==`string`&&typeof e.template==`string`}function Os(e){return e.kind===`simpleperf`&&e.mode===`cpu-profile`&&ks(e,[`outPath`,`packageName`,`appPid`,`profilerPid`,`remotePath`])}function ks(e,t){return t.every(t=>typeof e[t]==`string`)}function As(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 js(e,t){return{...Rs(e),metrics:{fps:Ms(t.metric,e)},sampling:{fps:t.sampling}}}function Ms(e,t){if(!Ee(e)||e.available!==!0)return e;let n=Ns(t.actions,e);return n.length===0?e:{...e,relatedActions:n}}function Ns(e,t){let n=Ps(t.windowStartedAt),r=Ps(t.windowEndedAt)??Ps(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:Fs(e)})).slice(-12)}function Ps(e){if(typeof e!=`string`)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Fs(e){for(let t of[`refLabel`,`ref`,`appName`,`appBundleId`]){let n=e.result?.[t];if(typeof n==`string`&&n.length>0)return n}}function Is(e,t){return{...Rs(e),metrics:{memory:t.metric},sampling:{memory:t.sampling}}}function Ls(e,t){return{...Rs(e),artifact:t.artifact,sampling:{snapshot:t.sampling},support:t.support}}function Rs(e){return{session:e.name,platform:A(e.device),device:e.device.name,deviceId:e.device.id}}function zs(e,t,n){return t?L(t,z(e.req,e.host)):q.join(e.sessionStore.ensureSessionDir(e.sessionName),`${Vs()}-${n}`)}function Bs(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 O(`INVALID_ARGS`,`--out is only supported with perf memory snapshot, perf cpu profile, or perf trace`)}function Vs(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}function Hs(e){return typeof e==`string`&&e.length>0?e:void 0}const Us=[`dump`,`log`],Ws=`network requires ${Us.join(` or `)}`,Gs=`network include mode must be one of: ${xe.join(`, `)}`,Ks=2048;async function qs(e){let t=e.sessionStore.get(e.sessionName);if(!t)return D(`SESSION_NOT_FOUND`,`network requires an active session`);try{let r=Js(e.bindDevice),i=(await r(t.device,d)).facts.networkDump;if(!i.available)return kr(`network`,i);let a=Ys(e.req);if(!a.ok)return a;let o=n({action:a.action,include:a.include}),s=await r(t.device,o.use),c=t.appLog?.handle.inspect();return $s(await s.operations.networkDump({sessionId:e.sessionName,appBundleId:t.appBundleId,...c?{appLogSnapshot:{state:c.state,startedAt:c.startedAt}}:{},maxEntries:a.maxEntries,include:o.include,maxPayloadChars:Ks,maxScanLines:4e3}),a,!!t.appLog,c?.state)}catch(e){return{ok:!1,error:E(e)}}}function Js(e){if(e)return e;throw new O(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`})}function Ys(e){let t=Xs(e);if(!t.ok)return t;let n=Zs(e);if(!n.ok)return n;let r=Qs(e);return r.ok?{ok:!0,action:t.action,include:r.include,maxEntries:n.maxEntries}:r}function Xs(e){let t=(e.positionals?.[0]??`dump`).toLowerCase();return Us.includes(t)?{ok:!0,action:t}:D(`INVALID_ARGS`,Ws)}function Zs(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 Qs(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 xe.includes(r)?{ok:!0,include:r}:D(`INVALID_ARGS`,Gs)}function $s(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:Ks,maxScanLines:e.entries.length},notes:e.notes}}}function ec(e,t){let n=qr(e);return{...n,backend:n.backend??t,notes:n.state===`failed`&&e.appLogFailure?[tc(e.appLogFailure)]:nc(n.state)}}function tc(e){return e.hint?`${e.message} ${e.hint}`:e.message}function nc(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 rc(e,t){return m([...e,...t.notes??[]])}async function ic(e){let{req:t}=e;return t.command===`perf`?await bs({...e,throwIfCanceled:e.throwIfCanceled??(()=>{})}):t.command===`logs`?oc(e):t.command===`events`?await ac(e):t.command===`network`?await qs(e):t.command===`audio`?await fs(vc(e)):null}async function ac(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:E(e)}}}async function oc(t){let{req:n,sessionName:r,sessionStore:i}=t,a=i.lookup(r);if(!a)return D(`SESSION_NOT_FOUND`,`logs requires an active session`);try{let r=i.requireCurrent(a),o=yc({...t,session:r,ref:a}),s=(await o.bindDevice(r.device,pe)).facts.appLogInspect;if(!s.available)return kr(`logs`,s);let c=lc(e({action:n.positionals?.[0],restart:!!n.flags?.restart,marker:n.positionals?.slice(1).join(` `)}),r);return`ok`in c?c:await sc(o,c)}catch(e){return{ok:!1,error:E(e)}}}async function sc(e,t){switch(t.kind){case`path`:return uc(e,(await(await e.bindDevice(e.session.device,t.use)).operations.appLogInspect()).backend);case`doctor`:return dc(e,await(await e.bindDevice(e.session.device,t.use)).operations.appLogDoctor({appBundleId:e.session.appBundleId}));case`start`:case`clear-restart`:return await cc(e,t);case`stop`:return await e.bindDevice(e.session.device,t.use),await gc(e);case`mark`:return await e.bindDevice(e.session.device,t.use),fc(t.marker,e.sessionName,e.sessionStore,e.host.env);case`clear`:return await e.bindDevice(e.session.device,t.use),pc(e)}}async function cc(e,t){let n=await e.bindDevice(e.session.device,t.use);return t.kind===`start`?await hc(e,t.appBundleId,n.owner,n.operations.appLogStart):await mc(e,t.appBundleId,n.owner,n.operations.appLogStart)}function lc(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 uc(e,t){let{session:n,sessionName:r,sessionStore:i}=e,a=i.resolveAppLogPath(r),o=Kr(a),s=ec(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 dc(e,t){let{session:n,sessionName:r,sessionStore:i}=e,a=i.resolveAppLogPath(r),o=ec(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:rc(t.notes,o)}}}function fc(e,t,n,r){let i=n.resolveAppLogPath(t);return Wr(i,e,r),{ok:!0,data:{path:i,marked:!0}}}function pc(e){return{ok:!0,data:Gr(e)}}async function mc(e,t,n,r){let{session:i,sessionStore:a}=e;i.appLog&&await Ur({intent:`disposal`,ref:e.ref,sessionStore:a});let o=Gr(e),s=await _c(e,t,r,n);return s.ok?{ok:!0,data:{...o,restarted:!0}}:s}async function hc(e,t,n,r){let{session:i}=e;return i.appLog?D(`INVALID_ARGS`,`app log already streaming; run logs stop first`):await _c(e,t,r,n)}async function gc(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 Ur({intent:`capture`,ref:e.ref,sessionStore:r}),{ok:!0,data:{path:i,stopped:!0}}}async function _c(e,t,n,r){let{session:i,sessionName:a,sessionStore:o}=e,s=o.resolveAppLogPath(a),c=ln.resolvePath(o.resolveSessionDir(a));try{let l=ds({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 Xr({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,...u.relaunched?{relaunched:!0}:{}}}}catch(t){return{ok:!1,error:Yr({ref:e.ref,sessionStore:o,error:t})}}}function vc(e){if(!e.bindDevice||!e.inspectFacts)throw new O(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`});if(!e.audioProbeAdmissionLedger)throw new O(`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 yc(e){if(!e.bindDevice)throw new O(`COMMAND_FAILED`,`Device runtime gateway is not configured`,{reason:`runtime-gateway-missing`});if(!e.appLogAdmissionLedger)throw new O(`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 bc=new WeakMap;function xc(e){return{store:t=>Sc(e,t),finalize:(t,n)=>Cc({...e,evidence:t,projection:n})}}function Sc(e,t){let{sessionStore:n,ref:r}=e;if(!r)throw Error(`Internal observation session is no longer available.`);let i=n.requireCurrent(r);Lr(i,t);let a=i.snapshotGeneration;if(a===void 0)throw Error(`Internal observation did not establish a snapshot generation.`);let o={};return bc.set(o,{ref:r,snapshot:t,snapshotGeneration:a,runtimeRevision:Dn(i),refFrame:wn(i)}),{evidence:o,refsGeneration:a}}function Cc(e){let t=bc.get(e.evidence);bc.delete(e.evidence);let n=Tc(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&&wc(e,t);return!t||!r?{published:!1,reason:`stale-capture`}:e.projection.refsGeneration!==t.snapshotGeneration||!Ec(n,t.snapshot)?{published:!1,reason:`invalid-projection`}:(Ir(r,n),{published:!0,refsGeneration:t.snapshotGeneration,refCount:n.size})}function wc(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&&Dn(n)===t.runtimeRevision&&wn(n)===t.refFrame?n:void 0}function Tc(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 Ec(e,t){let n=new Set(t.nodes.flatMap(e=>typeof e.ref==`string`?[e.ref]:[]));return[...e].every(e=>n.has(e))}function Dc(e){let t=Oc(e),n=a(t);return ki(`sha256`).update(n,`utf8`).digest(`hex`)}function Oc(e){let{actions:t,actionLines:n,metadata:r}=e;return{platform:r.platform??null,target:r.target??null,steps:t.map((e,t)=>kc(e,n[t]??null))}}function kc(e,t){return{command:e.command,positionals:e.positionals??[],flags:e.flags??{},runtime:e.runtime??null,targetEvidence:e.targetEvidence??null,targetEvidences:e.targetEvidences??null,source:{path:null,line:t}}}function Ac(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=jc({from:r,digest:i,planDigest:n,actionCount:t,pendingRecordAndHeal:a,sessionActionsLength:o});return s?{ok:!1,message:s}:{ok:!0,value:r-1}}function jc(e){let{from:t,digest:n,planDigest:r,actionCount:i,pendingRecordAndHeal:a,sessionActionsLength:o}=e,s=[()=>Mc({from:t,actionCount:i,pendingRecordAndHeal:a}),()=>Nc({from:t,pendingRecordAndHeal:a,sessionActionsLength:o}),()=>Pc(n,r)];for(let e of s){let t=e();if(t)return t}}function Mc(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 Nc(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 Pc(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 Fc(e,t){let n=e.trimStart()[0];if(n===`{`||n===`[`)throw new O(`INVALID_ARGS`,`replay accepts .ad script files. JSON replay payloads are no longer supported.`);let r=We(e),i=Ke(e),a=Dc({actions:r.actions,actionLines:r.actionLines,metadata:{platform:t?.platform??Ye(r.actions)??i.platform,target:t?.target??i.target}}),o=r.actions.length;return{actions:r.actions,actionLines:r.actionLines,metadata:i,planDigest:a,resolveEntryIndex:e=>Ac(e,o,a)}}function Ic(e){let{recorded:t,isSelectorWait:n}=e;return n?t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`deferred-landmark`,landmark:t}:{kind:`skip`}}function Lc(e){let{recorded:t,token:n}=e;return n===void 0||!n.startsWith(`@`)&&i(`positional`,[n]).kind!==`expression`?{kind:`skip`}:t.verification===`unverifiable`?{kind:`recorded-unverifiable`}:{kind:`verify`,token:n}}function Rc(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 zc(e,t,n){let{observed:r,expectedStructural:i,observedStructural:a}=t,o=Rc(i,a);return{matchCount:n,observed:r,mismatches:[...r?T(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 Bc(e,t){let{matchCount:n,observed:r,observedAncestry:i}=t;return{matchCount:n,observed:r,mismatches:r?[...T(e,r),...ie(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 Vc(e,t,n,r,i,a){if(n.targetEvidences)return Hc(e,t,n,r,i,a);let o=n.targetEvidence;if(!o)return J(e,n,r,i,a);let s=e.beginTargetVerification(n,r,i);if(s.kind===`inactive`)return J(e,n,r,i,a);if(s.kind===`post-resolution`){let c=Ic({recorded:o,isSelectorWait:s.isSelectorWait});switch(c.kind){case`skip`:return J(e,n,r,i,a);case`recorded-unverifiable`:return{status:`failed`,failure:await e.buildRecordedUnverifiableFailure(n,i,a,t)};case`deferred-landmark`:return Wc(e,t,n,r,i,a,{kind:`landmark`,landmark:c.landmark})}}let c=Lc({recorded:o,token:s.token});if(c.kind===`skip`)return J(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,Uc(u),a,t)};let{classification:d}=u;return d.verified?Wc(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 Hc(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 J(e,n,r,i,a);let d=Lc({recorded:o[c],token:u.token});if(d.kind===`skip`)return J(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,Uc(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 Wc(e,t,n,r,i,a,{kind:`targets`,guards:{source:s.source,destination:s.destination}})}function Uc(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 J(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 Wc(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=Gc(n,o,s);if(!c)return{status:`failed`,failure:s.plainFailure};let l=Kc(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 Gc(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 Kc(e,t,n){return n.status===`guard-mismatch`?zc(e,n.evidence,t):Bc(e,n.evidence)}async function qc(e,t){let{actions:n,entryIndex:r,keepSession:i}=e,a=_t(e.varSources),o=[],s=[],c=Zc(n),l=0;for(let u=r;u<n.length;u+=1){let r=n[u];if(!Xc(r)||(t.armStep(),u===c&&(i||t.isRepairArmed())))continue;if(l+=1,t.onStep){let e=t.describeStepValue(r);t.onStep(Qc(u,n.length,r,e))}let d=ft(r,a,Yc(e,u)),f=pt(a),p=t.diagnosticsMarker(),m=await Vc(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:Jc(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 Jc(e,t){return t.length===0?e:[...new Set([...e,...t])]}function Yc(e,t){return{file:e.resolvedPath,line:e.actionLines[t]??1}}function Xc(e){return!!(e&&e.command!==`replay`)}function Zc(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(Xc(n))return n.command===`close`?t:void 0}}function Qc(e,t,n,r){return{index:e+1,total:t,command:n.command,...r===void 0?{}:{value:r}}}async function $c(e){return await el({...e,snapshotDiagnostics:ke(e.snapshotDiagnosticSamples)})}async function el(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 _=tl(t.error.details?.replaySource),v=ui(t.error),y=await di({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:Ln(u.meta?.requestId)});return bi({error:v,action:n,step:r+1,replayPath:i,artifactPaths:s,snapshotDiagnostics:c,divergence:y,scrubVars:l})}function tl(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 nl(e){let{req:t,sessionName:n,action:r,resolved:i,filePath:a,line:o,step:s,tracePath:c,invoke:l,resolvedSessionScope:u,dependencies:d}=e,f=Date.now();_i(c,{type:`replay_action_start`,ts:new Date(f).toISOString(),replayPath:a,line:o,step:s,command:i.command,positionals:vn(i)??[]});let p;try{p=await il({req:t,sessionName:n,resolved:i,sourceAction:r,invoke:l,resolvedSessionScope:u,dependencies:d})}catch(e){if(!(e instanceof O))throw e;p={ok:!1,error:E(e)}}let m=Date.now();return _i(c,{type:`replay_action_stop`,ts:new Date(m).toISOString(),replayPath:a,line:o,step:s,command:i.command,ok:p.ok,durationMs:m-f,resultTiming:p.ok?ol(p.data):void 0,errorCode:p.ok?void 0:p.error.code}),rl(p,a,o)}function rl(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 il(e){let{req:t,sessionName:n,resolved:r,sourceAction:i,invoke:a,resolvedSessionScope:o,dependencies:s}=e,c=Ge(r.command,r.positionals??[],r.flags??{},`after variable substitution`);if(c)throw new O(`INVALID_ARGS`,c);let l=Oe(t.flags,{...r.flags??{}}),u=i.command===`fill`?Ot(wt(i)):void 0;return u&&(l.recordAs=u),await a(al({token:t.token,session:n,flags:l,runtime:r.runtime,meta:t.meta,dispatch:{...t.dispatch,replayPlanStep:!0,...r.command===`open`?{resolvedSessionScope:o??s.resolveSessionScope(t)}:{}}},r))}function al(e,t){let n=t.positionals??[];return t.command===`gesture`?{...e,command:t.command,positionals:[],input:He(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:Ue(n,{count:e.flags?.count,pauseMs:e.flags?.pauseMs,pattern:e.flags?.pattern})}:{...e,command:t.command,positionals:n}}function ol(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 sl(e){return ml(e.ok?ll(e.data):cl(e.error.details?.artifactPaths))}function cl(e){return Array.isArray(e)?e.filter(pl):[]}function ll(e){return e?[fl(e.path),fl(e.outPath),...ul(e.artifacts)].filter(pl):[]}function ul(e){return Array.isArray(e)?e.map(dl).filter(pl):[]}function dl(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e;return fl(t.localPath)??fl(t.path)}function fl(e){return typeof e==`string`?e:void 0}function pl(e){return typeof e==`string`}function ml(e){return[...new Set(e.filter(hl))]}function hl(e){try{return K.statSync(e).isFile()}catch{return!1}}function gl(e){let{recorded:t,token:n,nodes:r,platform:i,refLabel:a,requireRect:o,allowDisambiguation:s}=e,c=_l({token:n,nodes:r,platform:i,refLabel:a,requireRect:o,allowDisambiguation:s}),l=Rt(r),u=w(t),d=zt(c.matchedNodes,l,u,t.ancestry),f=d.filter(e=>ct(r,e)===t.sibling),p=d.filter(e=>st(e,l,t.scrollRegion)),m=ot(p)[t.viewportOrder]?.ref,h=lt({winnerRef:c.winnerRef,matchedRefs:ye(c.matchedNodes),identitySetRefs:ye(d),siblingMatchRefs:ye(f),regionMemberRefs:ye(p),viewportCandidateRef:m}),g=c.matchedNodes.find(e=>e.ref===c.winnerRef);return h.outcome===`verified`&&g?{verified:!0,winnerNode:g,matchCount:c.matchedNodes.length}:h.outcome===`verified`?{verified:!1,kind:`identity-unverifiable`,matchCount:c.matchedNodes.length,observedNode:void 0,candidateNodes:d.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,...bl({classification:h,matchCount:c.matchedNodes.length,winnerNode:g,identitySet:d,byIndex:l,recorded:t})}}function _l(e){let{token:t,nodes:n,platform:r,refLabel:i,requireRect:a,allowDisambiguation:o}=e;return t.startsWith(`@`)?vl(n,t,i,a):yl(n,t,r,a,o)}function vl(e,t,n,r){let i=e=>e!==null&&(!r||!!e.rect),a=Ce(t),o=a?we(e,a):null;if(i(o)&&o.ref!==void 0)return{matchedNodes:[o],winnerRef:o.ref};let s=n?Nr(e,n):null;return i(s)&&be(s)?{matchedNodes:[s],winnerRef:s.ref}:{matchedNodes:[],winnerRef:``}}function yl(e,t,n,r,i){let a=_(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=Mr(e,a.matchedNodes);return{matchedNodes:[...a.matchedNodes],winnerRef:o?.ref??``}}function bl(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?xl(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?xl(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?xl(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 xl(e,t,n){let r=ut(t),i=Bt(t,n,Math.max(e.ancestry.length,1)).chain;return[...T(e,r),...ie(e.ancestry,i)].slice(0,5)}function Sl(e,t){let n=e.positionals??[];if(e.command===`gesture`){let e=qe(n);return e?e[t??`source`]:void 0}if(e.command===`get`)return n[1];if(e.command===`is`){let e=i(`is`,n);return e.kind===`expression`?e.expression:void 0}if(!Je(e.command)&&e.command!==`fill`)return;let r=n[0];if(r!==void 0&&!(wl(r)&&wl(n[1])))return r}function Cl(e){let t=e.result?.refLabel;return typeof t==`string`&&t.length>0?t:void 0}function wl(e){return e!==void 0&&e.trim().length>0&&!Number.isNaN(Number(e))}function Tl(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:Fl(w(n),h),...t.observed?{observed:Fl(t.observed,h)}:{},mismatches:t.mismatches.slice(0,5).map(e=>h(e)),candidates:t.candidateNodes.slice(0,5).map(e=>Il(e,h))},_=gi({kind:t.kind,targetEvidence:n,capture:t.repairCapture}),v=mi({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(Xe(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=yi({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 bi({error:x,action:r,step:i,replayPath:s,artifactPaths:c,divergence:b,scrubVars:f})}function El(e,t,n){let r=on(e.scrubVars);return Tl(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:vi(n,r),publicationEvidence:Al(n),repairCapture:fi(n)})}async function Dl(e){let{session:t,observationStore:n,logPath:r,action:i,unavailableHint:a,signal:o}=e;return t?await hi({session:t,observationStore:n,logPath:r,action:i,signal:o}):{state:`unavailable`,reason:`no-session`,hint:a}}async function Ol(e,t){return El(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 Dl({...t,signal:e.signal,unavailableHint:`The session closed before a screen could be captured to verify the recorded target evidence.`}))}async function kl(e,t,n){return El(e,t,await Dl({...n,signal:e.signal,unavailableHint:`The session closed before a post-failure screen could be captured.`}))}function Al(e){return e.state===`available`?e.evidence:void 0}function jl(e){let{action:t,resolvedAction:n,sessionStore:r,targetRole:i}=e,a=r.get();return a?l(t.command)===`post-resolution`?{kind:`post-resolution`,isSelectorWait:c(n.positionals??[])?.kind===`selector`}:{kind:`pre-dispatch`,token:Sl(n,i),platform:a.device.platform}:{kind:`inactive`}}function Ml(e){let{recorded:t,token:n,action:r,nodes:i,platform:a}=e,o=Si(r),s=gl({recorded:t,token:n,nodes:i,platform:a,refLabel:Cl(r),requireRect:o.requiresRect,allowDisambiguation:o.allowDisambiguation});return s.verified?{verified:!0,guard:{expected:{identity:ut(s.winnerNode),structural:de(s.winnerNode,i)},matchCount:s.matchCount}}:{verified:!1,kind:s.kind,matchCount:s.matchCount,observed:s.observedNode?ut(s.observedNode):void 0,candidateNodes:s.candidateNodes,mismatches:s.mismatches,causeCode:s.causeCode,causeMessage:s.causeMessage}}function Nl(e){return!e.ok&&e.error.details?.reason===`replay_target_guard_mismatch`}function Pl(e){return!e.ok&&e.error.details?.reason===Pr}function Fl(e,t){return{...e.id===void 0?{}:{id:t(e.id)},role:t(e.role),...e.label===void 0?{}:{label:t(e.label)}}}function Il(e,t){let n=_e(e.type??`Element`),r=fr(e,n);return{...e.ref?{ref:e.ref}:{},role:t(n),...r?{label:t(r)}:{}}}function Ll(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 Rl(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 zl(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 Bl(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 Vl(e){return{...e?.targetRole===`source`||e?.targetRole===`destination`?{targetRole:e.targetRole}:{},observed:Rl(e?.observed),expectedStructural:Bl(e?.expectedStructural),observedStructural:Bl(e?.observedStructural)}}function Hl(e){return{matchCount:typeof e?.matchCount==`number`?e.matchCount:void 0,observed:Rl(e?.observed),observedAncestry:zl(e?.observedAncestry)}}function Ul(e,t){return{kind:e.error.code,message:e.error.message,artifactPaths:t}}function Wl(e,t,n){let r=Ul(e,n);return(t?.kind===`target`||t?.kind===`targets`)&&Nl(e)?{status:`guard-mismatch`,evidence:Vl(e.error.details),plainFailure:r,artifactPaths:n}:t?.kind===`landmark`&&Pl(e)?{status:`landmark-mismatch`,evidence:Hl(e.error.details),plainFailure:r,artifactPaths:n}:{status:`failed`,failure:r}}function Gl(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.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,Ul(Kl(e),sl(e))),u=async e=>{let n=t.observationStore.get();return n?await hi({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 jl({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:Ml({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 nl({req:Ll(t.replayReq,s),sessionName:t.sessionName,action:e,resolved:n,filePath:t.resolved,line:c,step:i+1,tracePath:t.actionTracePath,invoke:t.invoke,resolvedSessionScope:t.resolvedSessionScope,dependencies:t.dependencies});o=l,sl(l).forEach(e=>r.add(e));let u=[...r];return l.ok?{status:`ok`,artifactPaths:u}:Wl(l,s,u)},async buildRecordedUnverifiableFailure(e,n,r,i){let a=await Ol(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=El(c(e,t,r,i),n,a);return l(o)},async buildPostDispatchTargetBindingFailure(e,n,r,i,a){let o=await kl(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=Kl(o),u=await ql(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=>Jl(e),onStep:i,diagnosticsMarker:()=>Xl(t.sessionStore),diagnosticsSince:e=>Zl(t.sessionStore,e)},readLastResponse:()=>o}}function Kl(e){return e&&!e.ok?e:D(`COMMAND_FAILED`,`replay step reported failure with no recorded response`)}async function ql(e,t,n,r,i,a,o,s){let c=t=>e.coordinator.markSessionHeldIfArmed(t);return Yl(i)?c(i):c(await $c({response:i,action:n,index:r,replayPath:e.resolved,sourcePath: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 Jl(e){let t=e.positionals??[],n=y(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 Xl(e){return e.get()?.snapshotDiagnostics?.samples.length??0}function Zl(e,t){return e.get()?.snapshotDiagnostics?.samples.slice(t)??[]}async function Ql(e){let{resolved:t,keepSession:n,coordinator:r,command:i}=e,{request:a}=i,o=yt(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 Ci(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 $l(e){let{req:t,host:n,sessionName:r,sessionStore:i,tracePath:a,resolved:o,script:s,coordinator:c,dispatch:l}=e,u=eu(t);if(u)return{ok:!1,response:u};let{manifest:d,replayReq:f}=tu(t,s,l),{metadata:p,actions:m,actionLines:h,planDigest:g}=d,_=i.get(),v=nu({req:t,coordinator:c,manifest:d,preEntrySession:_});return v.ok?{ok:!0,value:{replayReq:f,actions:m,actionLines:h,planDigest:g,preEntrySession:_,entryIndex:v.value,varSources:iu({req:t,host:n,replayReq:f,sessionName:r,resolved:o,metadata:p}),actionTracePath:a??_?.trace?.outPath}}:{ok:!1,response:v.response}}function eu(e){let t=e.flags?.replayBackend;if(t&&!bt(t))return D(`INVALID_ARGS`,vt(t))}function tu(e,t,n){let r=Fc(t,{platform:e.flags?.platform,target:e.flags?.target});return{manifest:r,replayReq:ru({...e,flags:yr(e.flags,r.actions),...n?{dispatch:n}:{}},r.metadata)}}function nu(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 ru(e,t){return!t.platform&&!t.target?e:{...e,flags:au(e.flags,t)}}function iu(e){let{req:t,host:n,replayReq:r,sessionName:i,resolved:a,metadata:o}=e;return{builtins:xi({req:r,sessionName:i,metadata:o,resolvedPath:a,hostCwd:n.cwd}),fileEnv:o.env,shellEnv:ht(gt(t.flags?.replayShellEnv,n.env),`ad`),cliEnv:dt(mt(t.flags?.replayEnv),`ad`)}}function au(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 ou={kind:`none`,status:void 0,targetPath:void 0,targetForce:!1};function su(e){let{req:t,entryIndex:n,hostCwd:r,sessionStore:i,sourcePath:a,coordinator:o}=e,s=cu({entryIndex:n,sessionStore:i,coordinator:o});return s?{ok:!1,response:s}:(du({req:t,coordinator:o}),uu({req:t,hostCwd:r,sessionStore:i,sourcePath:a,coordinator:o}))}function cu(e){let t=fu(e);if(t)return t;if(e.entryIndex>0&&!e.sessionStore.get())return Se()}function lu(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.`):pu({saveScript:t,liveForce:n,persistedForce:i.targetForce||void 0,hostCwd:r,sourcePath:a,existingSaveScriptPath:i.targetPath})}function uu(e){let{req:t,hostCwd:n,sourcePath:r,coordinator:i}=e,{saveScript:a,force:o}=t.flags??{},s=lu({saveScript:a,force:o,hostCwd:n,preRunState:i.view()?.scriptPublication??ou,sourcePath:r});return s?{ok:!1,response:s}:(i.demoteForRerunIfArmed(),{ok:!0,armSaveScript:mu({saveScript:a,force:o,coordinator:i,sourcePath:r})})}function du(e){let{req:t,coordinator:n}=e;n.clearCorrectiveWatermarkIfExpected(t.flags?.replayFrom),t.flags?.saveScript&&n.clearTombstone()}function fu(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 pu(e){let{saveScript:t,liveForce:n,persistedForce:r,hostCwd:i,sourcePath:a,existingSaveScriptPath:o}=e;if(!t)return;let s=typeof t==`string`?Yt(t,{cwd:i}):o??pi(a);if(!(n||r&&s===o)&&K.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 mu(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 hu(e){let{request:t,host:n,session:{name:r,logPath:i,store:a,observationStore:o,coordinator:s},tracePath:c,onStep:l,invoke:u}=e,d=t.flags?.replayScriptSource;if(!d)return D(`INVALID_ARGS`,vr);let f=Date.now(),p=t.flags?.replayKeepSession===!0,m=``,h=new Set;try{if(m=d.entry,St(m)&&t.flags?.replayBackend!==`maestro`)return D(`INVALID_ARGS`,xt(`replay`,m));let g=await Ql({resolved:m,keepSession:p,coordinator:s,command:e});if(g)return g;let _=$l({req:t,host:n,sessionName:r,sessionStore:a,tracePath:c,resolved:m,script:_r(d,m),coordinator:s,dispatch:e.dispatch});if(!_.ok)return _.response;let{replayReq:v,actions:y,actionLines:b,planDigest:x,entryIndex:S,varSources:C,actionTracePath:ee}=_.value,w=su({req:t,entryIndex:S,hostCwd:n.cwd,sessionStore:a,sourcePath:m,coordinator:s});if(!w.ok)return w.response;let{runtime:T,readLastResponse:te}=Gl({ctx:{replayReq:v,sessionName:r,sessionStore:a,observationStore:o,logPath:i,resolved:m,actions:y,actionLines:b,planDigest:x,actionTracePath:ee,responseLevel:t.meta?.responseLevel,invoke:u,signal:Ln(t.meta?.requestId),coordinator:s,resolvedSessionScope:e.resolvedSessionScope,dependencies:e.dependencies},req:t,artifactPaths:h,onStep:l,armSaveScript:w.armSaveScript}),ne=await qc({actions:y,entryIndex:S,keepSession:p,actionLines:b,resolvedPath:m,varSources:C},T);return ne.status===`failed`?te()??D(`COMMAND_FAILED`,`replay step failed with no recorded response`):gu({startedAt:f,sessionName:r,sessionStore:a,replayed:ne.replayed,artifactPaths:ne.artifactPaths,snapshotDiagnosticSamples:ne.snapshotDiagnosticSamples,armSaveScript:w.armSaveScript,coordinator:s,keepSession:p})}catch(e){let t=E(e);return h.size===0?{ok:!1,error:t}:{ok:!1,error:{...t,details:{...t.details,artifactPaths:[...h]}}}}}function gu(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=vu({keepSession:l,sessionName:n,completedSession:u,artifactPaths:a});if(d)return d;let f=ke([...o]);return{ok:!0,data:{replayed:i,healed:0,session:n,sessionActive:u!==void 0,artifactPaths:[...a],...f?{snapshotDiagnostics:f}:{},message:_u(i,Date.now()-t)}}}function _u(e,t){let n=(t/1e3).toFixed(1);return`Replayed ${e} ${e===1?`step`:`steps`} in ${n}s`}function vu(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 yu(e){let{artifactsDir:t,cwd:n,suiteInvocationId:r}=e,i=q.resolve(n??`.`,t??`.agent-device/test-artifacts`);return q.join(i,r)}function bu(e,t){let n=t?q.relative(t,e):q.basename(e),r=n.length===0||n.startsWith(`..`)?q.basename(e):n;return s(r.toLowerCase().replaceAll(/[\\/]+/g,`__`).replaceAll(/[^a-z0-9._-]+/g,`-`))||`test`}function xu(e,t,n){K.mkdirSync(t,{recursive:!0}),wu(e,t,n)}function Su(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=q.join(o,`result.txt`),u=q.join(o,`failure.txt`),d=Cu([...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=>q.basename(e)).join(`, `)}`);let p=`${f.join(`
`)}\n`;K.writeFileSync(l,p),s||K.writeFileSync(u,p)}function Cu(e,t,n){let r=[],i=new Set(n.map(e=>q.basename(e).toLowerCase()));for(let n of e){if(!Eu(n))continue;let e=q.basename(n);if(q.resolve(n)===q.resolve(t,e)&&!i.has(e.toLowerCase())){r.push(n);continue}let a=Tu(e,t,i),o=q.join(t,a);K.copyFileSync(n,o),r.push(o)}return r}function wu(e,t,n){let r=q.join(t,`replay.ad`);if(K.writeFileSync(r,n),q.extname(e).toLowerCase()===`.ad`)return;let i=q.join(t,q.basename(e));q.resolve(i)!==q.resolve(r)&&K.writeFileSync(i,n)}function Tu(e,t,n){let r=q.extname(e),i=r?e.slice(0,-r.length):e,a=e,o=2;for(;n.has(a.toLowerCase())||K.existsSync(q.join(t,a));)a=`${i}-${o++}${r}`;return a}function Eu(e){try{return K.statSync(e).isFile()}catch{return!1}}function Du(e){let{platformFilter:t,discoverSources:n}=e,r=n(),i=[],a={undeclared:0,declaredOther:0};for(let e of r){let{path:n,manifest:r,sourceText:o}=e,s={kind:`run`,path:n,title:r.title,manifest:r,sourceText:o};if(!t){i.push(s);continue}let c=r.device.platform;if(c.kind===`caller-bound`){i.push(s);continue}if(c.kind===`unspecified`){a.undeclared+=1,i.push({kind:`skip`,path:n,reason:`skipped-by-filter`,message:`missing platform metadata for --platform ${t}`});continue}if(!Lu(t,c.value)){a.declaredOther+=1;continue}i.push(s)}if(i.filter(e=>e.kind===`run`).length===0)throw new O(`INVALID_ARGS`,Au({platformFilter:t,...a}));return i}const Ou={web:!0};function ku(e){return!Object.hasOwn(Ou,e)}function Au(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(`, `)}. ${ju(t,n)}`}function ju(e,t){return ku(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 Mu(e,t,n,r,i=0){let a=q.basename(n,q.extname(n)),o=s(a.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`));return`${e}:test:${t}:${r+1}${o?`-${o}`:``}:attempt-${i+1}`}function Nu(e){let t=e?.trim()||`${process.pid}-${Date.now().toString(36)}`;return s(t.toLowerCase().replaceAll(/[^a-z0-9]+/g,`-`))||`suite`}function Pu(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,q.basename(r),`attempt`,a+1].join(`:`)}function Fu(e,t){return typeof e==`number`?e:t}function Iu(e,t){let n=typeof e==`number`?e:t;return typeof n==`number`?Math.max(0,Math.min(3,n)):0}function Lu(e,t){return e===`apple`?N(t):t===e}function Ru(e){return{status:`failed`,error:e.error,artifactPaths:e.artifactPaths??[],warnings:e.warnings??[],infrastructure:e.infrastructure??!1,...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}const zu=2e3;async function Bu(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:f,finalizeAttempt:p,emitDiagnostic:m,bindAttemptCancellation:h}=e,g=h({attemptId:r,parentAttemptId:i}),_=new Set,v,y=!1,b,x=Date.now(),S=qu({artifactsDir:c,artifactPaths:_,filePath:t,sessionName:n,requestId:r,timeoutMs:a,platform:o,target:s}),C=d({filePath:t,sessionName:n,platform:o,target:s,requestId:r,artifactsDir:c,artifactPaths:_,tracePath:S,appendTimingEvent:e=>Y(S,e),shard:l,onStep:u}).catch(e=>Ru({error:E(e)})).finally(()=>{g.release()});try{b=typeof a==`number`?await Promise.race([C,new Promise(e=>{v=setTimeout(()=>{y=!0,g.cancel(),e(Ju(a,[..._]))},a)})]):await C,Y(S,{type:`replay_test_attempt_stop`,ts:new Date().toISOString(),session:n,ok:b.status===`passed`,timedOut:y,durationMs:Date.now()-x,errorCode:b.status===`passed`?void 0:b.error.code})}finally{v&&clearTimeout(v),y&&(await Hu(C)||(b=Gu(b),m({level:`warn`,phase:`test_timeout_cleanup_race`,data:{session:n,requestId:r,graceMs:zu}}),Uu({replayPromise:C,cleanupSession:f,sessionName:n,requestId:r,emitDiagnostic:m})));let e=await Wu({finalizeAttempt:p,sessionName:n,artifactPaths:_,artifactsDir:c,tracePath:S,emitDiagnostic:m});b?.status===`passed`&&e&&(b=Ku(b,`Replay test finalization failed: ${e.error.message}`));let t=Date.now();try{Y(S,{type:`replay_test_cleanup_start`,ts:new Date().toISOString(),session:n}),await f(n),Y(S,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:n,ok:!0,durationMs:Date.now()-t})}catch(e){let r=E(e);Y(S,{type:`replay_test_cleanup_stop`,ts:new Date().toISOString(),session:n,ok:!1,durationMs:Date.now()-t,errorCode:r.code}),m({level:`warn`,phase:`test_cleanup_failed`,data:{session:n,error:r.message}}),b=Vu(b,r,_)}}return b??Ru({error:{code:`COMMAND_FAILED`,message:`Unknown replay test failure`}})}function Vu(e,t,n){return e?.status===`failed`?{...e,infrastructure:!0}:Ru({error:t,artifactPaths:[...n],infrastructure:!0})}async function Hu(e){return await Promise.race([e.then(()=>!0),Mi(zu).then(()=>!1)])}async function Uu(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:E(e).message}})}}}async function Wu(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=E(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}}),Ru({error:t})}}function Gu(e){return!e||e.status===`passed`?e:{...e,infrastructure:!0,error:{...e.error,details:{...e.error.details??{},reason:`timeout_cleanup_pending`,timeoutCleanupPending:!0}}}}function Ku(e,t){return{...e,warnings:[...e.warnings,t]}}function qu(e){let{artifactsDir:t,artifactPaths:n,filePath:r,sessionName:i,requestId:a,timeoutMs:o,platform:s,target:c}=e;if(!t)return;let l=q.join(t,`replay-timing.ndjson`);return K.mkdirSync(q.dirname(l),{recursive:!0}),K.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&&K.appendFileSync(e,`${JSON.stringify(t)}\n`)}function Ju(e,t=[]){return Ru({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 Yu(e){let t=Xu(e),n=await Zu(e,t);return{result:rd(e,t,n),infrastructure:n.finalOutcome?.status===`failed`&&n.finalOutcome.infrastructure}}function Xu(e){let{entry:t,cwd:n,retries:r,suiteArtifactsDir:i,shard:a}=e;return{testStartedAt:Date.now(),testArtifactsDir:q.join(i,...a?[`shard-${a.shardIndex+1}`]:[],bu(t.path,n)),maxAttempts:r+1}}async function Zu(e,t){$u(e,t);let n={finalSessionName:``,attempts:0,finalAttemptDurationMs:0,attemptFailures:[]};for(let r=0;r<=e.retries&&!e.isCanceled();r+=1){let i=await Qu(e,t,r);if(ed(n,i),td(e,i.outcome,r))break;nd(e,t,i)}return n}async function Qu(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=Mu(i,a,r.path,o,n),h=q.join(t.testArtifactsDir,`attempt-${f}`);xu(r.path,h,r.sourceText);let g=Pu({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 Bu({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 Su({outcome:v,filePath:r.path,sessionName:m,attempts:f,maxAttempts:t.maxAttempts,attemptArtifactsDir:h}),{outcome:v,sessionName:m,attempt:f,durationMs:y}}function $u(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:Mu(r,i,n.path,a),artifactsDir:t.testArtifactsDir,...X(c)})}function ed(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 td(e,t,n){return t.status===`passed`||e.isCanceled()||t.infrastructure||t.status===`failed`&&t.stopRetries===!0||n>=e.retries}function nd(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 rd(e,t,n){let r=Date.now()-t.testStartedAt;return n.finalOutcome?.status===`passed`?id(e,t,n,r):ad(e,t,n,r)}function id(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}:{},...sd(s),...n.attemptFailures.length>0?{attemptFailures:n.attemptFailures}:{}}}function ad(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,...od(c),...sd(s)}}function od(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 sd(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 cd(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 ld(e){let{request:t,runReplay:n,cleanupSession:r,finalizeAttempt:i,emitProgress:a,isCanceled:o,emitDiagnostic:s,bindAttemptCancellation:c,discoverSources:l,resolveShardTargets:u}=e,d=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(),f=await ud(t,l,u);md(f,a);let p=f.shardPlan?hd({entries:f.entries,total:f.total,emitProgress:a}):[];return f.shardPlan?p.push(...await gd({shards:f.shardPlan.shards,sessionName:d,suiteInvocationId:f.suiteInvocationId,cwd:t.cwd,requestId:t.requestId,request:t,suiteArtifactsDir:f.suiteArtifactsDir,suiteTotal:f.total,runReplay:n,cleanupSession:r,finalizeAttempt:i,emitProgress:a,isCanceled:o,emitDiagnostic:s,bindAttemptCancellation:c})):p.push(...await bd({discoveryEntries:f.entries,sessionName:d,suiteInvocationId:f.suiteInvocationId,cwd:t.cwd,requestId:t.requestId,request:t,suiteArtifactsDir:f.suiteArtifactsDir,suiteTotal:f.total,runReplay:n,cleanupSession:r,finalizeAttempt:i,emitProgress:a,isCanceled:o,emitDiagnostic:s,bindAttemptCancellation:c})),{status:`completed`,data:Cd(f.total,p,Date.now()-e,f.suiteArtifactsDir)}}catch(e){let t=ge(e);return{status:`failed`,error:{code:t.code,message:t.message}}}}async function ud(e,t,n){let r=dd(e,t),i=fd(r),a=r.length-i.length,o=e.suiteInvocationId??Nu(e.requestId),s=await cd(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:pd(e,o),total:s?.total??r.length}}function dd(e,t){return Du({platformFilter:e.platformFilter,discoverSources:t})}function fd(e){return e.flatMap((e,t)=>e.kind===`run`?[{entry:e,suiteIndex:t+1}]:[])}function pd(e,t){return yu({artifactsDir:typeof e.artifactsDir==`string`?e.artifactsDir:void 0,cwd:e.cwd,suiteInvocationId:t})}function md(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 hd(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 gd(e){return(await Promise.allSettled(e.shards.map(async t=>await vd({...e,shard:t})))).flatMap((t,n)=>{if(t.status===`fulfilled`)return t.value;let r=e.shards[n];return r?[_d(r,e.sessionName,t.reason)]:[]})}function _d(e,t,n){let r=E(n);return{file:e.entries[0]?.entry.path??`shard-${e.shardIndex+1}`,session:yd(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 vd(e){let{shard:t,sessionName:n}=e;return await xd({...e,entries:t.entries,sessionName:yd(n,t),shard:t})}function yd(e,t){return`${e}:shard-${t.shardIndex+1}`}async function bd(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 Yu({entry:v,sessionName:n,suiteInvocationId:r,caseIndex:_-1,cwd:i,requestId:a,retries:Iu(o.retries,v.manifest.attemptDefaults?.retries),timeoutMs:Fu(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),Sd(t,o,p))break}return g}async function xd(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 Yu({entry:t,sessionName:n,suiteInvocationId:r,caseIndex:e,cwd:i,requestId:a,retries:Iu(o.retries,t.manifest.attemptDefaults?.retries),timeoutMs:Fu(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),Sd(b,o,m))break}return _}function Sd(e,t,n){return n()||t.failFast===!0&&e.result.status===`failed`||e.infrastructure}function Cd(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=je(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 wd(e,t){return async n=>(await Dd(e,n,t)).map(Td)}function Td(e){if(e.platform===`web`||!Fe(e))throw new O(`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 Ed(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 Dd(e,t,n){let r=jd(e),i=kd(await sr(Od(e,n)),r,e);if(i.length<t)throw new O(`DEVICE_NOT_FOUND`,`test sharding requires ${Ad(t)}, but only ${i.length} matched`);return i.slice(0,t)}function Od(e,t){let n=ar(e?.androidDeviceAllowlist,t);return{platform:e?.platform,target:e?.target,iosSimulatorSetPath:Ie({requestedSetPath:e?.iosSimulatorDeviceSet,platform:e?.platform,target:e?.target,env:t}),androidSerialAllowlist:n?Array.from(n).sort():void 0}}function kd(e,t,n){return t.length>0?Md(e,t,n):e.filter(e=>Nd(e,n)).sort(Id)}function Ad(e){return`${e} device${e===1?``:`s`}`}function jd(e){let t=e?.device;return typeof t!=`string`||t.trim().length===0?[]:t.split(`,`).map(e=>e.trim()).filter(Boolean)}function Md(e,t,n){return t.map(t=>{let r=Fd(t),i=e.find(e=>Pd(e,n)&&(e.id===t||Fd(e.name)===r));if(!i)throw new O(`DEVICE_NOT_FOUND`,`No shard device matched ${t}`);return i})}function Nd(e,t){return!Pd(e,t)||!Fe(e)?!1:e.booted!==!1}function Pd(e,t){return!(!Re(e,t?.platform)||t?.target&&(e.target??`mobile`)!==t.target)}function Fd(e){return e.toLowerCase().replaceAll(`_`,` `).replaceAll(/\s+/g,` `).trim()}function Id(e,t){return e.id.localeCompare(t.id)}function Ld(e){let t=Rd(e?.shardAll,`--shard-all`),n=Rd(e?.shardSplit,`--shard-split`);if(t!==void 0&&n!==void 0)throw new O(`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 Rd(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isInteger(e)||e<1)throw new O(`INVALID_ARGS`,`${t} requires a positive integer`);return e}}const zd=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 Bd(e){return zd.has(e.toUpperCase())}const Vd=new Set([`device_offline`,`device_unauthorized`]);function Hd(e){return typeof e==`string`&&Vd.has(e)}function Ud(e){if(!(`ok`in e)&&e.status===`failed`&&e.infrastructure===!0)return!0;let t=Wd(e);return t?Gd(t.details):!1}function Wd(e){return`ok`in e?e.ok?null:e.error:e.status===`failed`?e.error:null}function Gd(e){if(e?.recovery===`runner_recycle_budget_exhausted`||Hd(e?.adbFailure)||typeof e?.runnerConnectFailureReason==`string`)return!0;let t=typeof e?.reason==`string`?e.reason:``;return t===`timeout_cleanup_pending`||t===`runner_process_exited`||qt(t)?!0:t?Bd(t):!1}function Kd(e){if(!e.ok)return{status:`failed`,error:e.error,artifactPaths:Yd(e.error.details?.artifactPaths),warnings:ze(e.error.details),infrastructure:Ud(e),...e.error.details?.reason===`bounded_composite_resource_unsupported`?{stopRetries:!0}:{},...Xd(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:ze(t),artifactPaths:Yd(t?.artifactPaths),...Xd(t?.snapshotDiagnostics)}}function qd(e){if(!e||e.ok)return;let t=Kd(e);return t.status===`failed`?t:void 0}function Jd(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Yd(e){return[...new Set(Jd(e))]}function Xd(e){let t=Ae(e);return t?{snapshotDiagnostics:t}:{}}const Zd=1e3,Qd=3e3;function $d(e){if(e.req.flags?.recordVideo===!0)return{beforeDispatch:async()=>await ef(e)}}async function ef(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=Zt(o.device.platform),c=i?q.join(i,`recording${s}`):Xt(o.device.platform);Z(a,{type:`video_recording_start`,session:n,videoPath:c}),k({phase:`replay_test_video_recording_start`,data:{session:n,videoPath:c}}),e.video.throwIfCanceled();let l=await e.video.record(nf({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 Ne(Zd),Z(a,{type:`video_preroll_done`,session:n,durationMs:Date.now()-u,requestedDurationMs:Zd}),k({phase:`replay_test_video_recording_preroll_done`,durationMs:Date.now()-u,data:{session:n,requestedDurationMs:Zd}}),l}async function tf(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:Qd});let o=Date.now();await Ne(Qd);let s=Date.now(),c=await e.video.record(nf({req:t,sessionName:n,phase:`stop`}));return sl(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}),k({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 nf(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 rf=[{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.`}],af=({attemptId:e,parentAttemptId:t})=>{let n=of(zn(e,t)?.controller,t);return{cancel:()=>Hn(e),release:()=>{n(),Vn(e)}}};function of(e,t){if(!t||!e)return()=>{};let n=Ln(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 sf(e){let{platform:t,target:n,artifactsDir:r,shard:i,sourceBundle:a}=e,o=cf(e.parentFlags);return t===void 0&&n===void 0&&r===void 0&&i===void 0&&a===void 0?o:Ed({...o??{},...t===void 0?{}:{platform:t},...n===void 0?{}:{target:n},...r===void 0?{}:{artifactsDir:r},...a===void 0?{}:{replayScriptSource:a}},i)}function cf(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 lf(e){let{request:t,session:{name:n,logPath:r},createSession:i,invoke:a,cleanupSession:o,video:s}=e;if(t.flags?.recordVideo===!0&&s===void 0)return D(`COMMAND_FAILED`,`Screen-recording runtime is not configured for replay video capture`);let c=t.flags??{};for(let e of rf)if(e.requested(c))return D(`INVALID_ARGS`,e.message);let l,u;try{l={...pf(t,n,e.host.cwd),...e.publicNetworkOnly?{suiteInvocationId:Ai()}:{}},u=ff(t)}catch(e){let t=ge(e);return D(t.code,t.message)}let d=new Map(u.map(e=>[e.entry,e])),f=await ld({request:l,emitProgress:Bn,isCanceled:()=>Rn(t.meta?.requestId),emitDiagnostic:k,bindAttemptCancellation:af,runReplay:async({filePath:n,sessionName:o,platform:c,target:l,requestId:u,artifactsDir:f,artifactPaths:p,tracePath:m,appendTimingEvent:h,shard:g,onStep:_})=>{let v=e=>(p&&sl(e).forEach(e=>p.add(e)),e),y=sf({parentFlags:t.flags,platform:c,target:l,artifactsDir:f,shard:g,sourceBundle:d.get(n)}),b=i(o,r),x=s?{req:t,sessionName:o,sessionStore:b.store,artifactsDir:f,appendTimingEvent:h,video:s}:void 0,S=x?$d(x):void 0;return uf(Kd(await hu({...mf(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 ef(x):void 0;return t&&!t.ok?t:v(await a(e))}})))},finalizeAttempt:async({sessionName:e,artifactPaths:n,artifactsDir:a,appendTimingEvent:o})=>{if(s)return qd(await tf({req:t,sessionName:e,sessionStore:i(e,r).store,artifactsDir:a,appendTimingEvent:o,artifactPaths:n,video:s}))},discoverSources:await wi(u,t.flags?.replayBackend),resolveShardTargets:wd(t.flags,e.host.env),cleanupSession:o});return f.status===`completed`?{ok:!0,data:df(f.data,t)}:D(f.error.code,f.error.message)}function uf(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 df(e,t){let n=t.meta?.clientArtifactPaths?.artifactsDir,r=e.artifactsDir;if(!n||!r)return e;let i=q.join(n,q.basename(r)),a=e=>e===r||e.startsWith(r+q.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 K.existsSync(r)?{...o,artifacts:[{field:`artifactsDir`,artifactType:`test-artifacts`,path:r,localPath:n,fileName:q.basename(r)}]}:o}function ff(e){let t=e.flags?.replayScriptSources;if(!t)throw new O(`INVALID_ARGS`,vr);return t}function pf(e,t,n){let r=e.flags??{},i=e.meta?.cwd,a=gf(r.artifactsDir);return{inputs:e.positionals??[],sessionName:t,cwd:i,requestId:e.meta?.requestId,platformFilter:r.platform,artifactsDir:a===void 0?void 0:L(a,i??n),failFast:r.failFast===!0,retries:hf(r.retries),timeoutMs:hf(r.timeoutMs),shard:Ld(r)}}function mf(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 hf(e){return typeof e==`number`?e:void 0}function gf(e){return typeof e==`string`?e:void 0}function _f(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 vf(e){let{internal:t,...n}=e;return{request:n,...t?.publicNetworkOnly?{publicNetworkOnly:!0}:{},...t?.resolvedSessionScope?{resolvedSessionScope:t.resolvedSessionScope}:{}}}function yf(e,t){let n=Te({...e,...t});return Object.keys(n).length>0?n:void 0}function bf(e,t){return async({dispatch:n,...r})=>{let i=yf(t.internal,n);return await e(i?{...r,internal:i}:r)}}function xf(e){let{sessionStore:t,mutationStore:n,hostCwd:r}=e,i=()=>t.get();return{view(){let e=i();if(e)return{repairBoundary:nt(e),pendingRecordAndHeal:e.pendingRecordAndHeal,scriptPublication:Sf(e.scriptPublication??It)}},armStep(e){n.update(t=>{Ze(t,{saveScript:e.saveScript,force:e.force,sourcePath:e.sourcePath,healedSiblingPath:pi(e.sourcePath),firstArm:e.firstArm},r)})},demoteForRerunIfArmed(){nt(i())!==void 0&&n.update(et)},markCompleteIfArmed(){nt(i())!==void 0&&n.update($e)},markSessionHeldIfArmed(e){if(e.ok||!Qe(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&&wf(t)})},resumeStamper:{sessionExists:()=>i()!==void 0,stampCorrectiveWatermark(e){n.update(t=>{Cf({session:t,...e})})}}}}function Sf(e){return{kind:e.kind,status:e.kind===`none`?void 0:e.status,targetPath:Et(e),targetForce:Tt(e)}}function Cf(e){let{session:t,resume:n,repairHint:r,failedIndex:i,actions:a}=e;t.pendingRecordAndHeal=Tf({resume:n,repairHint:r,failedIndex:i,actions:a,actionsCountAtDivergence:t.actions.length})}function wf(e){e.pendingRecordAndHeal=void 0}function Tf(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 Ef(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 ti({req:Df(e),sessionName:e.sessionName,sessionStore:t,bindDevice:n,platformServices:r,bindExactDevice:i,admissionLedger:a,requestScope:o,retainDeviceExecutionLock:s,throwIfCanceled:c})}}function Df(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 Of={resolveSessionScope:hr},kf=Promise.resolve(void 0),Af=async({req:e,host:t,sessionName:n,logPath:r,sessionStore:i,invoke:a,invokeReplayAction:o,inspectFacts:s,bindDevice:c,platformServices:l})=>await hu({...vf(e),host:t,session:Mf(n,r,i,{meta:e.meta,inspectFacts:s,bindDevice:c,platformServices:l}),invoke:bf(o??a,e),dependencies:Of}),jf=async({host:e,req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider: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 O(`INTERNAL_ERROR`,`Platform resource cleanup was not supplied by root runtime composition`);let v=Ef({sessionStore:i,bindDevice:l,platformServices:u,bindExactDevice:f,screenRecordingAdmissionLedger:p,requestScope:m,retainDeviceExecutionLock:h,throwIfCanceled:g}),y={meta:t.meta,inspectFacts:d,bindDevice:l,platformServices:u};return await lf({...vf(t.internal?.publicNetworkOnly?{...t,flags:{...t.flags,artifactsDir:nn(i.resolveSessionDir(n))}}:t),host:e,session:Mf(n,r,i,y),createSession:(e,t)=>Mf(e,t,i,y),invoke:bf(c??s,t),dependencies:Of,cleanupSession:async n=>await Nf({host:e,req:t,sessionName:n,logPath:r,sessionStore:i,leaseRegistry:a,leaseLifecycleProvider:o,inspectFacts:d,bindDevice:l,platformServices:u,platformResourceCleanup:_}),...v?{video:v}:{}})};function Mf(e,t,n,r){let i=t=>{let r=n.get(e);return r?(t(r),!0):!1},a={get:()=>n.get(e),lookup:()=>n.lookup(e),getRuntimeHints:()=>n.getRuntimeHints(e),ensureSessionDir:()=>n.ensureSessionDir(e)},o,s=r?.bindDevice,c=s?(e,t)=>s(e,t,`bypass`):void 0,l=(e,t)=>{if(!r)return kf;let{device:n}=t,i=n.booted===!0,a=t.appBundleId!==void 0;if(o?.lifetime===e&&o.device===n&&o.booted===i&&o.hasApp===a)return o.binding;let s=Vr({command:`replay`,session:t,inspectFacts:r.inspectFacts,platformServices:r.platformServices,bindDevice:c}).then(e=>(e.kind===`retryable`&&o?.binding===s&&(o=void 0),e.kind===`captured`?e.capture:void 0));return o={lifetime:e,device:n,booted:i,hasApp:a,binding:s},s};return _f(e,t,a,{createCoordinator:()=>xf({sessionStore:a,mutationStore:{update:i,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})=>er({req:t,sessionStore:{getRuntimeHints:t=>t===e?n.getRuntimeHints(e):void 0},sessionName:e,device:r,platform:i}),bindAuthority:t=>{let i=n.lookup(e);return{...xc({sessionStore:n,ref:i,signal:t}),capture:async({flags:a,logPath:o})=>{if(!i)throw new O(`NO_ACTIVE_SESSION`,`Session "${e}" is no longer active.`);let s=n.requireCurrent(i),c=await l(i.lifetime,s);return await Rr({device:s.device,session:s,flags:a,logPath:o,signal:t,...c?{captureData:async()=>await c(En({flags:a,logPath:o,meta:r?.meta,session:s,snapshotScope:void 0,signal:t}))}:{}})}}}})}async function Nf(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e;if(!i.get(n))return;let a=await go({host:e.host,req:On({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,leaseLifecycleProvider:e.leaseLifecycleProvider,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice,platformResourceCleanup:e.platformResourceCleanup});if(!a.ok)throw new O(a.error.code,a.error.message,{...a.error.details??{},...a.error.hint?{hint:a.error.hint}:{}})}function Pf(e){let{req:t,sessionName:n,sessionStore:r}=e;if(t.command!==Ht.sessionSaveScript)return null;if((t.positionals?.length??0)>1)return Rf(new O(`INVALID_ARGS`,`session save-script accepts at most one output path.`));let i=r.lookup(n);if(!i)return Rf(new O(`SESSION_NOT_FOUND`,`No active session "${n}".`,{hint:`Start a fresh journey with open <app> --save-script[=<path>], then retry.`}));let a=r.requireCurrent(i),o=Lf(a);if(o)return Rf(o);let s=t.positionals?.[0]?.trim();if(t.positionals?.[0]!==void 0&&!s)return Rf(new O(`INVALID_ARGS`,`session save-script path cannot be empty.`));Ct(a,{explicitPath:s,liveForce:t.flags?.force},r.host.cwd);let c=r.writeSessionLog(i,{force:jt(a,t.flags?.force),publication:`active`});return c.written?(Mt(a,c.path),{ok:!0,data:{session:a.name,savedScript:c.path,actionCount:c.actionCount,...F(`Published script: ${c.path}`)}}):Rf(c.error??new O(`COMMAND_FAILED`,`The active session script was not published.`,{retriable:!0,hint:`The session remains armed; retry session save-script.`}))}function Ff(e){if(at(e))return`repair`;if(At(e))return`remote`;let t=e.scriptPublication;return t?.kind===`authoring`&&t.status!==`armed`?t.status:Pt(e)?void 0:`not-armed`}const If={repair:()=>new O(`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.`}),remote:()=>new O(`COMMAND_FAILED`,`A remote recording is delivered to its --save-script path, not published from the session.`,{reason:`remote_script_publication_unsupported`,hint:`The --save-script file already holds the recording through the last action, and close writes the final script there.`}),aborted:()=>new O(`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 O(`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 O(`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 Lf(e){let t=Ff(e);return t?If[t]():void 0}function Rf(e){return{ok:!1,error:E(e)}}function zf(e){let t=(e[0]??``).toLowerCase();return t===`read`||t===`write`?t:void 0}function Bf(e){return{...e.appBundleId===void 0?{}:{options:{appBundleId:e.appBundleId}},execution:Tn(e)}}async function Vf(e,t,n){if(n.length!==1)throw new O(`INVALID_ARGS`,`clipboard read does not accept additional arguments`);return{action:`read`,text:await e.operations.readClipboard(Bf(t))}}async function Hf(e,t,n){if(n.length<2)throw new O(`INVALID_ARGS`,`clipboard write requires text (use "" to clear clipboard)`);let r=n.slice(1).join(` `),i={...Bf(t),text:r};return await e.operations.writeClipboard(i),{action:`write`,textLength:Array.from(r).length,...F(`Clipboard updated`)}}async function Uf(e){let{device:t,action:n,positionals:r,inspectFacts:i,bindDevice:a,platformServices:o}=e;if(n===`read`){let n=await B({command:`clipboard`,device:t,use:u,inspectFacts:i,bindDevice:a,platformServices:o,readinessScope:e.requestScope});if(n.type===`response`)return{ok:!1,response:n.response};let s=n.runtime;return{ok:!0,execute:e=>Vf(s,e,r)}}let s=await B({command:`clipboard`,device:t,use:ne,inspectFacts:i,bindDevice:a,platformServices:o,readinessScope:e.requestScope});if(s.type===`response`)return{ok:!1,response:s.response};let c=s.runtime;return{ok:!0,execute:e=>Hf(c,e,r)}}async function Wf(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??{},d=G(Vt.clipboard,l,u);if(d)return d;let f=t.positionals??[],p=zf(f);if(!p)return D(`INVALID_ARGS`,`clipboard requires a subcommand: read or write`);let m=await W({session:l,req:t,env:i.host.env,platformServices:s});c&&i.requireCurrent(c);let h=await Uf({requestScope:Or(t),device:m,action:p,positionals:f,inspectFacts:a,bindDevice:o,platformServices:s});if(!h.ok)return h.response;let g=c?i.requireCurrent(c):void 0,_=await h.execute(pr(r,t.flags,g?.appBundleId,g?.trace?.outPath));return I(i,c,t,t.command,_),{ok:!0,data:{platform:A(m),..._}}}function Gf(e){return e.some(e=>e.status===`fail`)?`fail`:e.some(e=>e.status===`warn`)?`warn`:`pass`}function Kf(e){return e===`fail`?`Blockers found before the run.`:e===`warn`?`No hard blockers found, but warnings need attention.`:`No blockers found.`}function qf(e){let t={fail:0,warn:1,pass:2,info:3};return[...e].sort((e,n)=>t[e.status]-t[n.status])}function Jf(e,t,...n){for(let r of n)Q(e,r,t)}function Q(e,t,n){e.push(t),Bn({type:`command`,status:`progress`,message:Yf(t,n)})}function Yf(e,t){return[Di(e,{useColor:t}),...Ei(e)].join(`
`)}async function Xf(e,t){let{device:n,targetApp:r,session:i,listInstalledApps:a,useColor:o}=t;if(r)try{let t=a?Zf(r,await a(`all`))?.id:void 0;if(!t){Q(e,{id:`target-app`,status:`info`,summary:`Target app installation checks are not supported for ${A(n)}.`,evidence:{requested:r,platform:A(n)}},o);return}Q(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=E(t);Q(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 ${A(n)} --all`,evidence:{code:r.code,message:r.message}},o)}}function Zf(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 O(`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 O(`APP_NOT_INSTALLED`,`No launchable installed app matched "${e}"`)}async function Qf(e,t,n,r,i){let a=ep(t,n,r);try{let t=await np(a),n=tp(t.devices,a);return Q(e,{id:`device`,status:n.length===0?`fail`:`pass`,summary:sp(n,a,t.failures),hint:n.length===0?up(t.failures):void 0,command:n.length===0?hp(a):void 0,evidence:gp(n,t.failures)},i),n.length>0&&ip(e,t.failures,i),{devices:n,hostDevices:n.filter(e=>t.hostDevices.includes(e)),platform:a.platform,target:a.target}}catch(t){let n=E(t);return Q(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 $f(e,t,n,r){if(!n||!t)return;let i=t.devices.filter(e=>e.booted===!0);if(i.length===1)return i[0];Q(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:A(e),id:e.id,name:e.name}))}},r)}function ep(e,t,n){let r=e.flags??{};return ur({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 tp(e,t){return e.filter(e=>Le(e,t,{includeExplicitSelectors:!0}))}async function np(e){if(e.platform)return{...rp([await or(e)]),failures:[]};let t=await Promise.allSettled(Jt.map(async t=>await or({...e,platform:t}))),n=[],r=[];return t.forEach((e,t)=>{e.status===`fulfilled`?n.push(e.value):r.push(op(Jt[t],e.reason))}),{...rp(n),failures:r}}function rp(e){return{devices:e.flatMap(e=>e.devices),hostDevices:e.flatMap(e=>e.source===`local`?e.devices:[])}}function ip(e,t,n){for(let r of t)Q(e,ap(r),n)}function ap(e){return{id:`device-${e.platform}`,status:`warn`,summary:`${pp(e.platform)} device inventory could not be read: ${e.message}`,hint:e.hint??`Check the ${pp(e.platform)} toolchain, or scope with --platform to skip it.`,evidence:{platform:e.platform,code:e.code}}}function op(e,t){let n=E(t);return{platform:e,message:n.message,hint:n.hint,code:n.code}}function sp(e,t,n){if(e.length===0)return n.length>0?`No ${cp(t)} devices found; ${lp(n)}.`:`No ${cp(t)} devices found.`;let r=e.filter(e=>e.booted===!0).length,i=`${e.length} ${cp(t)} ${mp(e.length,`device`)} available; ${r} booted`,a=dp(e,t);return a?`${i} (${a}).`:`${i}.`}function cp(e){let t=e.platform?pp(e.platform):`local`;return e.target?`${t} ${e.target}`:t}function lp(e){return e.slice(0,2).map(e=>`${pp(e.platform)} inventory failed: ${e.message}`).join(`; `)}function up(e){return e.find(e=>e.hint)?.hint??`Start or create a simulator/emulator, connect a device, or adjust --platform/--target/--device selectors.`}function dp(e,t){if(t.platform||t.target)return;let n=Kt(e),r=fp();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 fp(){return{android:`Android`,harmonyos:`HarmonyOS`,apple:`Apple`,vega:`Vega`,linux:`Linux`,web:`web`}}function pp(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 mp(e,t){return e===1?t:`${t}s`}function hp(e){return e.platform?`agent-device devices --platform ${e.platform}`:`agent-device devices`}function gp(e,t){let n=new Map;for(let t of e){let e=A(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 _p=1500;async function vp(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 yp(e,t,r):void 0;return{id:`metro`,status:s?`pass`:`warn`,summary:s?bp(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 yp(e,t,n){try{return await(n.resolveProcessInfo??xp)(e,t)}catch{return}}function bp(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 xp(e,t){if(!Sp(e))return;let n=await Cp(t);if(n!==void 0)return{pid:n,cwd:await wp(n)}}function Sp(e){return e===`127.0.0.1`||e===`localhost`||e===`::1`||e===`0.0.0.0`}async function Cp(e){let t=await Pe(`lsof`,[`-nP`,`-iTCP:${e}`,`-sTCP:LISTEN`,`-Fp`],{allowFailure:!0,timeoutMs:_p});if(t.exitCode===0)return t.stdout.split(`
`).map(e=>e.startsWith(`p`)?Number.parseInt(e.slice(1),10):NaN).find(e=>Number.isInteger(e)&&e>0)}async function wp(e){let t=await Pe(`lsof`,[`-nP`,`-a`,`-p`,String(e),`-d`,`cwd`,`-Fn`],{allowFailure:!0,timeoutMs:_p});if(t.exitCode===0)return t.stdout.split(`
`).find(e=>e.startsWith(`n`)&&e.length>1)?.slice(1)}const Tp=[`daemonBaseUrl`,`tenant`,`runId`,`leaseId`,`leaseProvider`],Ep=[`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 Dp(e,t){let n=Oi(e.meta?.cwd);return{targetApp:Mp(e.flags?.targetApp)??t?.appBundleId,metroHost:Mp(e.runtime?.metroHost)??`127.0.0.1`,metroPort:Np(e.runtime?.metroPort)??8081,kind:n,remote:e.flags?.remote===!0,shouldProbeMetro:Ap(e,n)}}function Op(e,t={}){let n=jp(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 kp(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):[];if(!n)return[{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.`}];let[a]=i;return[{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:a===void 0?void 0:`Before a QA run, run agent-device close --session ${rn(a)} --platform ${A(n.device)} only if that session is yours and left from an old attempt.`,evidence:{session:t,sameDeviceSessions:i,sessionStateDir:e.resolveSessionDir(t)}}]}function Ap(e,t){return t!==`auto`||typeof e.runtime?.metroPort==`number`||typeof e.runtime?.metroHost==`string`}function jp(e){let t={...Object.fromEntries([...Tp,...Ep].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 Mp(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Np(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:void 0}async function Pp(e){let{req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,inspectFacts:a,bindDevice:o}=e;if(t.command!==Vt.doctor)return null;let s=Fp(e.hostDiagnostics),c=r.get(n),l=Dp(t,c),u=Rp(r,n),d=Ti(e.host.env,!!process.stderr.isTTY),f=[];if(Jf(f,d,{id:`agent-device`,status:`pass`,summary:`agent-device ${en()} using ${u}`,evidence:{version:en(),stateDir:u}},...Op(t,{required:l.remote}),...kp(r,n,c,{remote:l.remote})),l.remote)return Up(f,l);let p=Ip(l,u,i),m=await Qf(f,t,c,e.host.env,d),h=await s.toolchainCheck(c?.device.platform??m?.platform,p);h&&Q(f,h,d);let g=await zp({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??Lp(m,g);if(_){let e=await s.warmupCheck(_,p);e&&Q(f,e,d)}return Up(f,l,{device:g,includeMetro:!0,inventory:m})}function Fp(e){if(!e)throw new O(`COMMAND_FAILED`,`Host diagnostics gateway is not configured`,{reason:`runtime-gateway-missing`});return e}function Ip(e,t,n){return Object.freeze({stateDir:t,metroPort:e.metroPort,shouldProbeMetro:e.shouldProbeMetro,isProviderDevice:e=>xn(e),emitProgress:e=>Bn({type:`command`,status:`progress`,message:e}),listLocalDeviceInventory:async e=>await lr(e),shouldPropagateInventoryProbeError:cr,transportOverrides:Object.freeze({androidAdb:n})})}function Lp(e,t){let n=e?.hostDevices??[];if(t)return n.includes(t)?t:void 0;let r=n.filter(e=>M(e)&&e.kind===`simulator`);return r.find(e=>e.booted===!0)??r[0]}function Rp(e,t){let n=q.dirname(e.resolveSessionDir(t));return q.basename(n)===`sessions`?q.dirname(n):n}async function zp(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??$f(t,i,a.targetApp,d);return f&&await Bp(t,{context:n,hostDiagnostics:r,device:f,options:a,session:o,inspectFacts:s,bindDevice:c,req:l,env:u,useColor:d}),a.shouldProbeMetro&&Q(t,await vp(a.metroHost,a.metroPort,a.kind),d),Jf(t,d,...await r.ambientChecks(n)),f}async function Bp(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 Vp({device:i,req:l,targetApp:a.targetApp,inspectFacts:s,bindDevice:c,env:u})}catch(e){f=async()=>{throw e}}await Xf(e,{device:i,session:o,targetApp:a.targetApp,listInstalledApps:f,useColor:d}),Jf(e,d,...await r.deviceChecks(i,n))}async function Vp(e){if(e.device.platform!==`harmonyos`)return Hp(e)}async function Hp(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,h),d=await So(u,ni({flags:n.flags??{},env:o}));return async e=>await Co(u,d,e)}function Up(e,t,n={}){let r=Gf(e);return{ok:!0,data:{status:r,summary:Kf(r),kind:t.kind,platform:n.device?A(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:qf(e)}}}async function Wp(e){return await B({...e,command:`prepare`,use:S})}async function Gp(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=G(Vt.prepare,o,s);if(c)return c;let l=await Me(`prepare_resolve_device`,()=>W({session:o,req:t,env:i.host.env,platformServices:e.platformServices}),void 0,`start`),u=await Me(`prepare_admit_runtime`,()=>Wp({device:l,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice}),void 0,`start`);if(u.type===`response`)return u.response;let d=Date.now(),f=await u.runtime.operations.prepareAppleRunner({timeoutMs:Kp(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:qn(t)}});return{ok:!0,data:qp(a,l,Math.max(0,Date.now()-d),f)}}function Kp(e){let t=e.flags?.timeoutMs;return typeof t==`number`&&Number.isFinite(t)&&t>0?t:le}function qp(e,t,n,r){return{action:e,platform:A(t),deviceId:t.id,deviceName:t.name,kind:t.kind,durationMs:n,...r,timing:Jp(n,r),message:`Prepared Apple runner: ${t.name}`}}function Jp(e,t){let n=Yp(t.buildMs),r=Xp(t.connectMs),i=Xp(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 Yp(e){return e===void 0?void 0:Xp(e)}function Xp(e){return Number.isFinite(e)?Math.max(0,Math.round(e)):0}const Zp=e=>wo(e),Qp=e=>ri({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}),$p=e=>go({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}),$=async({host:e,req:t,sessionName:n,sessionStore:r,bindDevice:i,platformServices:a,inspectFacts:o,appLogAdmissionLedger:s,audioProbeAdmissionLedger:c,perfCaptureAdmissionLedger:l,throwIfCanceled:u})=>await ic({host:e,req:t,sessionName:n,sessionStore:r,bindDevice:i,platformServices:a,inspectFacts:o,appLogAdmissionLedger:s,audioProbeAdmissionLedger:c,perfCaptureAdmissionLedger:l,throwIfCanceled:u}),em={session_list:Zp,devices:Zp,capabilities:Zp,apps:Zp,doctor:async({host:e,req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,hostDiagnostics:a,inspectFacts:o,bindDevice:s})=>await Pp({host:e,req:t,sessionName:n,sessionStore:r,androidAdbExecutor:i,hostDiagnostics:a,inspectFacts:o,bindDevice:s}),boot:$o,shutdown:ns,appstate:us,session_save_script:async({req:e,sessionName:t,sessionStore:n})=>Pf({req:e,sessionName:t,sessionStore:n}),runtime:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await $i({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 Wf({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),keyboard:Na,perf:$,logs:$,events:$,network:$,audio:$,prepare:async({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o})=>await Gp({req:e,sessionName:t,logPath:n,sessionStore:r,inspectFacts:i,bindDevice:a,platformServices:o}),install:Xa,reinstall:Xa,uninstall:Xa,install_source:Xa,release_materialized_paths:async({req:e})=>await Li({req:e}),push:Xa,"trigger-app-event":Pa,open:Qp,replay:Af,test:jf,batch:async({req:e,sessionName:t,invoke:n})=>await Za(e,t,n),close:$p};async function tm(e){let{host:t,req:n,sessionName:r,logPath:i,sessionStore:a,leaseRegistry:o=new An,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:ee,platformResourceCleanup:w}=e,T=em[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:ee,platformResourceCleanup:w}):null}export{tm as handleSessionCommands};