agent-device 0.17.7 → 0.17.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.7.apk → agent-device-android-multitouch-helper-0.17.8.apk} +0 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.8.apk.sha256 +1 -0
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.7.manifest.json → agent-device-android-multitouch-helper-0.17.8.manifest.json} +4 -4
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.7.apk → agent-device-android-snapshot-helper-0.17.8.apk} +0 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.8.apk.sha256 +1 -0
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.7.manifest.json → agent-device-android-snapshot-helper-0.17.8.manifest.json} +6 -6
- package/dist/src/2133.js +1 -1
- package/dist/src/2577.js +1 -0
- package/dist/src/4428.js +1 -1
- package/dist/src/8184.js +1 -1
- package/dist/src/8358.js +4 -0
- package/dist/src/9581.js +13 -2
- package/dist/src/9722.js +36 -36
- package/dist/src/9873.js +1 -1
- package/dist/src/9919.js +5 -5
- package/dist/src/cli-help.js +18 -7
- package/dist/src/cli.js +28 -18
- package/dist/src/interaction.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/record-trace-recording.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/session.js +1 -1
- package/dist/src/snapshot.js +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.7.apk.sha256 +0 -1
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.7.apk.sha256 +0 -1
- package/dist/src/2892.js +0 -4
- package/dist/src/368.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createDaemonRuntimeSessionStore as e,setSessionSnapshot as t,captureSnapshot as r,dispatchCommand as s,runIosRunnerCommand as n,isCommandSupportedOnDevice as o,errorResponse as i,ensureDeviceReady as a,stopIosRunnerSession as l,resolveRunnerAppBundleId as u,getActiveAndroidSnapshotFreshness as c,resolveTargetDevice as d,context_contextFromFlags as f}from"./9722.js";import{closeIosApp as p}from"./apps.js";import{emitDiagnostic as m}from"./432.js";import{asAppError as g,normalizeError as h,AppError as y}from"./733.js";import{evaluateIsPredicate as w,isSupportedPredicate as _,localCommandPolicy as S,createAgentDevice as v}from"./368.js";import{tryParseSelectorChain as x,extractNodeReadText as k,prefersValueForReadableText as I,findNodeByLabel as N,normalizeType as A,splitIsSelectorArgs as P}from"./9836.js";import{resolveRectCenter as R,isSparseSnapshotQualityVerdict as b,parseWaitPositionals as D}from"./9873.js";import{getAndroidAppState as E}from"./3340.js";import{isApplePlatform as q}from"./5910.js";import{parseFindArgs as C}from"./587.js";import{buildSnapshotPresentationKey as M,snapshotPresentationOptionsFromFlags as O}from"./4291.js";async function $(e,t,r){let s=e.get(t),n=s?.device??await d(r??{});return s||await a(n),{session:s,device:n}}async function L(e,t,r){let s=!e&&"ios"===t.platform;try{return await r()}finally{s&&(await l(t.id),await K(t))}}async function K(e){let t=u();await p(e,t).catch(r=>{m({level:"debug",phase:"ios_sessionless_runner_host_close_failed",data:{deviceId:e.id,bundleId:t,error:r instanceof Error?r.message:String(r)}})})}function U(e,t,r,s){t&&e.recordAction(t,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:s})}function F(e){let{session:t,sessionName:r,device:s,snapshot:n,appBundleId:o}=e;return t?{...t,snapshot:n,lastComparisonSafeSnapshot:n?.comparisonSafe===!0?n:t.lastComparisonSafeSnapshot}:{name:r,device:s,createdAt:Date.now(),appBundleId:o,snapshot:n,...n?.comparisonSafe===!0?{lastComparisonSafeSnapshot:n}:{},actions:[]}}function T(e,t={}){return{artifacts:function(e,t={}){let r=!0===t.plural?"do":"does";return{resolveInput:async()=>{throw new y("UNSUPPORTED_OPERATION",`${e} ${r} not resolve input artifacts`)},reserveOutput:async()=>{throw new y("UNSUPPORTED_OPERATION",`${e} ${r} not reserve output artifacts`)},createTempFile:async()=>{throw new y("UNSUPPORTED_OPERATION",`${e} ${r} not create temporary files`)}}}(e,t),policy:S()}}async function G(e){let{device:t,node:r,flags:n,appBundleId:o,traceOutPath:i,surface:a,contextFromFlags:l}=e,u=k(r),c=R(r.rect);if(!c||"ios"===t.platform&&u&&!I(r.type??""))return u;try{let e=await s(t,"read",[String(c.x),String(c.y)],void 0,{...l(n,o,i),surface:a}),d=e&&"object"==typeof e?e:void 0,f="string"==typeof d?.text?d.text:"";if(f.trim())return f;return m({level:"warn",phase:"interaction_read_fallback",data:{reason:"empty_backend_text",nodeRef:r.ref,surface:a,platform:t.platform}}),u}catch(e){return m({level:"warn",phase:"interaction_read_fallback",data:{reason:"backend_read_failed",nodeRef:r.ref,surface:a,platform:t.platform,error:e instanceof Error?e.message:String(e)}}),u}}let V=[["snapshotDepth","--depth"],["snapshotScope","--scope"],["snapshotRaw","--raw"]];function B(e,t){let r=function(e){if(!e)return[];let t=[];for(let[r,s]of V)void 0!==e[r]&&t.push(s);return t}(t);return 0===r.length?null:i("INVALID_ARGS",`${e} @ref does not support ${r.join(", ")}.`)}async function X(e,t){let r=await H(e);if(r)throw new y("COMMAND_FAILED",`press ${t} left ${e.appBundleId} and foregrounded ${r.foregroundPackage}. The tap likely escaped the app.`,r)}async function H(e){var t;if("android"!==e.device.platform||!e.appBundleId)return null;let r=await E(e.device),s=r.package?.trim();return s&&s!==e.appBundleId&&("com.android.settings"===(t=s)||"com.android.systemui"===t||"com.google.android.permissioncontroller"===t||t.includes("launcher"))?{expectedPackage:e.appBundleId,foregroundPackage:s,activity:r.activity,hint:"com.google.android.permissioncontroller"===s?"Dismiss or allow the permission prompt, then retry the smoke assertion.":"Use screenshot as visual truth, then take a fresh snapshot -i before retrying."}:null}function j(e){return"COMMAND_FAILED"===e.code&&"string"==typeof e.details?.expectedPackage&&"string"==typeof e.details?.foregroundPackage}function W(e,t){let r=Array.isArray(e.selectorChain)?e.selectorChain:void 0,s=Y(e),n=s?.kind==="ref"?Z(s.ref):void 0,o=s?.kind==="selector"?s.selector:void 0,i={...n?{ref:n}:{},...o?{selector:o}:{},...r?{selectorChain:r}:{}};if("attrs"===t)return i;let a="string"==typeof e.text?e.text:"";return{...i,text:a,refLabel:function(e){let t=e.trim();if(!(!t||t.length>80||/[\r\n]/.test(t)))return t}(a)}}function z(e){let t=Y(e);return{...t?.kind==="ref"?{ref:Z(t.ref)}:{},...t?.kind==="selector"?{selector:t.selector}:{},..."string"==typeof e.text?{text:e.text}:{},...e.node&&"object"==typeof e.node?{node:e.node}:{}}}function Q(e){let{selectorChain:t,...r}=e;return r}function J(e,t,r,s){let n=e.get(t);n&&e.recordAction(n,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:s})}function Y(e){let t=e.target;return t&&"object"==typeof t?"ref"===t.kind&&"string"==typeof t.ref?{kind:"ref",ref:t.ref}:"selector"===t.kind&&"string"==typeof t.selector?{kind:"selector",selector:t.selector}:void 0:void 0}function Z(e){return e.startsWith("@")?e.slice(1):e}let ee=["application","window","tabbar","scrollbar","image"],et=new Set(["tab bar"]);async function er(e,t){var r;if(t.ok||(r=t.error.message,!/^wait timed out for (?:selector|text): /i.test(r)))return t;let s=await es(e).catch(()=>null);return s?i(t.error.code,`${t.error.message}. Current surface: ${s.summary}.`,{...t.error.details??{},currentSurface:s.details}):t}async function es(e){let t=[...(await r({device:e.device,session:e.session,flags:{...e.req.flags,snapshotInteractiveOnly:!0},logPath:e.logPath??""})).snapshot.nodes].sort(eo),s=en(t,6,{includeIdentifiers:!0});if(0===s.length)return null;let n=en(t.filter(e=>!el(e)),4,{includeIdentifiers:!1}),o=en(t.filter(eu),4,{includeIdentifiers:!0});return{summary:(n.length>0?n:s.slice(0,4)).join(", "),details:{labels:s,...o.length>0?{buttons:o}:{}}}}function en(e,t,r){let s=new Set,n=[];for(let o of e){let e=ea(o,r);if(!(!e||s.has(e))&&(s.add(e),n.push(e),n.length>=t))break}return n}function eo(e,t){var r,s;return ei(e)-ei(t)||(r=e,s=t,r.rect&&s.rect?r.rect.y-s.rect.y||r.rect.x-s.rect.x:r.rect?-1:s.rect?1:(r.depth??0)-(s.depth??0)||r.index-s.index)}function ei(e){let t=!!ea(e,{includeIdentifiers:!1});return 2*!!el(e)+ +!t}function ea(e,t){let r=(t.includeIdentifiers?[e.label,e.value,e.identifier]:[e.label,e.value]).map(e=>"string"==typeof e?e.trim():"").find(e=>e.length>0);return r?r.replace(/\s+/g," ").slice(0,80):""}function el(e){let t=A(`${e.type??""} ${e.role??""} ${e.subrole??""}`),r=`${e.label??""} ${e.value??""}`.trim().toLowerCase();return ee.some(e=>t.includes(e))||et.has(r)||r.endsWith(".fill")}function eu(e){return A(`${e.type??""} ${e.role??""} ${e.subrole??""}`).includes("button")}function ec(e){var t;let{session:r,selectorExpression:s}=e;if(!r||"ios"!==r.device.platform||r.postGestureStabilization)return null;let n=x(s);if(!n||1!==n.selectors.length)return null;let o=n.selectors[0];if(!o||1!==o.terms.length)return null;let i=o.terms[0];return i&&"string"==typeof i.value&&("id"===(t=i.key)||"label"===t||"text"===t||"value"===t)?{key:i.key,value:i.value,raw:o.raw}:null}function ed(e,t={}){let r=g(e);if("ELEMENT_NOT_FOUND"===r.code)return!0===t.allowElementNotFound;if("COMMAND_FAILED"!==r.code)return!1;let s=r.message.toLowerCase();return s.includes("fetch failed")||s.includes("timed out")||s.includes("timeout")||s.includes("runner did not accept connection")||s.includes("invalid runner response")}async function ef(e){var t;let{req:r}=e;if("find"!==r.command)return null;let s=r.positionals??[];if(0===s.length)return i("INVALID_ARGS","find requires a locator or text");let n=C(s);if(!n.query)return i("INVALID_ARGS","find requires a value");if(r.flags?.findFirst&&r.flags?.findLast)return i("INVALID_ARGS","find accepts only one of --first or --last");let o=n.action;if("exists"!==(t=o)&&"wait"!==t&&"get_text"!==t&&"get_attrs"!==t)return null;let a=await eI(e,{requireSession:!1,capability:"find"});return a.ok?await eP(async()=>{let t=await a.runtime.selectors.find({session:e.sessionName,requestId:r.meta?.requestId,locator:n.locator,query:n.query,action:o,timeoutMs:n.timeoutMs});return J(e.sessionStore,e.sessionName,r,function(e,t){if("exists"===t)return{found:!0};if("wait"===t)return{found:!0,waitedMs:e.waitedMs};let r="string"==typeof e.ref?e.ref:void 0;return"get_attrs"===t?{ref:r,action:"get attrs"}:{ref:r,action:"get text",text:"string"==typeof e.text?e.text:""}}(t,o)),"found"===t.kind?{found:!0,..."number"==typeof t.waitedMs?{waitedMs:t.waitedMs}:{}}:{..."string"==typeof t.ref?{ref:t.ref}:{},..."string"==typeof t.text?{text:t.text}:{},...t.node&&"object"==typeof t.node?{node:t.node}:{}}}):a.response}async function ep(e){let{req:t}=e;if("get"!==t.command)return null;let r=t.positionals?.[0];if("text"!==r&&"attrs"!==r)return i("INVALID_ARGS","get only supports text or attrs");let s=function(e){let t=e.positionals?.[1]??"";if(t.startsWith("@"))return{ok:!0,target:{kind:"ref",ref:t,fallbackLabel:e.positionals.length>2?e.positionals.slice(2).join(" ").trim():""}};let r=e.positionals?.slice(1).join(" ").trim()??"";return r?{ok:!0,target:{kind:"selector",selector:r}}:{ok:!1,response:i("INVALID_ARGS","get requires @ref or selector expression")}}(t);if(!s.ok)return s.response;if("ref"===s.target.kind){let e=B("get",t.flags);if(e)return e}if("selector"===s.target.kind){let t=await eh(e,r,s.target.selector);if(t)return t}let n=await eI(e,{requireSession:!0,capability:"get"});return n.ok?await eP(async()=>{let o=await n.runtime.selectors.get({session:e.sessionName,requestId:t.meta?.requestId,property:r,target:s.target});return J(e.sessionStore,e.sessionName,t,W(o,r)),z(o)}):n.response}async function em(e){let{req:t}=e;if("is"!==t.command)return null;let r=(t.positionals?.[0]??"").toLowerCase();if(!_(r))return i("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text");let{split:s}=P(t.positionals??[]);if(!s)return i("INVALID_ARGS","is requires a selector expression");let n=s.rest.join(" ").trim();if("text"===r&&!n)return i("INVALID_ARGS","is text requires expected text value");if("text"!==r&&s.rest.length>0)return i("INVALID_ARGS",`is ${r} does not accept trailing values`);let o=await ey(e,r,s.selectorExpression,n);if(o)return o;let a=await eI(e,{requireSession:!0,capability:"is"});if(!a.ok)return a.response;let l=await eP(async()=>{let o=await a.runtime.selectors.is({session:e.sessionName,requestId:t.meta?.requestId,predicate:r,selector:s.selectorExpression,expectedText:n});return J(e.sessionStore,e.sessionName,t,o),Q(o)});return await eR(e,l,`is ${r}`)}async function eg(e){let{req:t,sessionName:r,sessionStore:s}=e,n=D(t.positionals??[]);if(!n)return i("INVALID_ARGS","wait requires a duration or text");let{session:a,device:l}=await $(s,r,t.flags);if("sleep"!==n.kind&&!o("wait",l))return i("UNSUPPORTED_OPERATION","wait is not supported on this device");if("selector"===n.kind){let t=await ew({...e,session:a,device:l,selectorExpression:n.selectorExpression,timeoutMs:n.timeoutMs});if(t)return t}let u=async()=>{let o=ek({...e,session:a,device:l}),i=await eP(async()=>{let e=await o.selectors.wait({session:r,requestId:t.meta?.requestId,target:function(e,t){if("sleep"===e.kind)return{kind:"sleep",durationMs:e.durationMs};if("selector"===e.kind)return{kind:"selector",selector:e.selectorExpression,timeoutMs:e.timeoutMs};if("ref"===e.kind){if(!t?.snapshot)throw new y("INVALID_ARGS","Ref wait requires an existing snapshot in session.");return{kind:"ref",ref:e.rawRef,timeoutMs:e.timeoutMs}}if(!e.text)throw new y("INVALID_ARGS","wait requires text");return{kind:"text",text:e.text,timeoutMs:e.timeoutMs}}(n,a)});return J(s,r,t,e),{waitedMs:e.waitedMs,..."string"==typeof e.text?{text:e.text}:{},..."string"==typeof e.selector?{selector:e.selector}:{}}}),u=await er({req:t,logPath:e.logPath,session:a,device:l},i);return await eR(e,u,"wait")};return"sleep"===n.kind?await u():await L(a,l,u)}async function eh(e,t,r){let s=e.sessionStore.get(e.sessionName),n=ec({session:s,selectorExpression:r});if(!s||!n||"text"===t&&"id"!==n.key)return null;let o=await ev(e,s,n);if(ex(o))return o.response;if(!o)return null;let i=function(e,t,r){if(!r.found||!r.node)return null;let s={target:{kind:"selector",selector:t},node:r.node,selectorChain:[t]};return"attrs"===e?{kind:"attrs",...s}:"string"!=typeof r.text?null:{kind:"text",...s,text:r.text}}(t,n.raw,o);return i?(J(e.sessionStore,e.sessionName,e.req,W(i,t)),{ok:!0,data:z(i)}):null}async function ey(e,t,r,s){var n,o,i,a,l;let u;if("hidden"===t)return null;let c=await e_(e,r);if(ex(c))return c.response;if(!c?.result.found||!c.result.node)return null;let d="exists"===t?{predicate:t,pass:!0,selector:c.selector.raw,matches:1,selectorChain:[c.selector.raw]}:(n=t,o=s,i=c.selector.raw,a=c.session,u=w({predicate:n,node:l=c.result.node,nodes:[l],expectedText:o,platform:a.device.platform}),{predicate:n,pass:u.pass,selector:i,..."text"===n?{text:u.actualText}:{},selectorChain:[i]});return d?(J(e.sessionStore,e.sessionName,e.req,d),{ok:!0,data:Q(d)}):null}async function ew(e){let t=ec({session:e.session,selectorExpression:e.selectorExpression});if(!e.session||!t)return null;let r=Date.now(),s=await ev(e,e.session,t);if(ex(s))return s.response;if(!s?.found)return null;let n={kind:"selector",selector:t.raw,waitedMs:Date.now()-r,selectorChain:[t.raw]};return J(e.sessionStore,e.sessionName,e.req,n),await er({req:e.req,logPath:e.logPath,session:e.session,device:e.device},{ok:!0,data:n})}async function e_(e,t){let r=e.sessionStore.get(e.sessionName),s=ec({session:r,selectorExpression:t});if(!r||!s)return null;let n=await ev(e,r,s);return ex(n)?n:n?{session:r,selector:s,result:n}:null}async function eS(e,t,r){let s=await n(t.device,{command:"querySelector",selectorKey:r.key,selectorValue:r.value,appBundleId:t.appBundleId},{verbose:!!e.req.flags?.verbose,logPath:e.logPath,traceLogPath:t.trace?.outPath,requestId:e.req.meta?.requestId,iosXctestrunFile:e.req.flags?.iosXctestrunFile,iosXctestDerivedDataPath:e.req.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:e.req.flags?.iosXctestEnvDir}),o=!0===s.found,i=function(e){let t=e.nodes;if(!Array.isArray(t))return;let r=t[0];if(r&&"object"==typeof r)return r}(s);return{found:o,..."string"==typeof s.text?{text:s.text}:{},...i?{node:i}:{}}}async function ev(e,t,r){try{return await eS(e,t,r)}catch(e){if(ed(e,{allowElementNotFound:!0}))return null;return{kind:"error",response:{ok:!1,error:h(e)}}}}function ex(e){return null!==e&&"kind"in e&&"error"===e.kind}function ek(s){return v({backend:function(e){let s,{req:n,session:o,device:i,logPath:a,sessionName:l,sessionStore:u}=e,d=0;return{platform:i.platform,captureSnapshot:async(e,f)=>{var p;let m,g={...n.flags,...(p=f,m={},p?.interactiveOnly!==void 0&&(m.snapshotInteractiveOnly=p.interactiveOnly),p?.scope!==void 0&&(m.snapshotScope=p.scope),p?.depth!==void 0&&(m.snapshotDepth=p.depth),p?.raw!==void 0&&(m.snapshotRaw=p.raw),m)},h=f?.scope??n.flags?.snapshotScope,y=Date.now(),w=M(O(g)),_="wait"===n.command||"find"===n.command;if(!_&&s&&y-d<750&&!c(o)&&!o?.postGestureStabilization)return s;if(!_&&o?.snapshot&&y-o.snapshot.createdAt<750&&o.snapshot.presentationKey===w&&!c(o)&&!o.postGestureStabilization)return d=o.snapshot.createdAt,s={snapshot:o.snapshot};let S=await r({device:i,session:o,flags:g,outPath:n.flags?.out,logPath:a??"",snapshotScope:h});return o&&!b(S.snapshot.snapshotQuality)&&(t(o,S.snapshot),u.set(l,o)),d=y,s={snapshot:S.snapshot}},readText:async(t,r)=>({text:await G({device:i,node:r,flags:n.flags,appBundleId:o?.appBundleId,traceOutPath:o?.trace?.outPath,surface:o?.surface,contextFromFlags:e.contextFromFlags??((e,t,r)=>f(a??"",e,t,r))})}),findText:async(t,r)=>({found:await eN(e,r)})}}(s),...T("selector commands",{plural:!0}),sessions:e({sessionName:s.sessionName,getSession:()=>s.session,recordOptions:{includeSnapshot:!0},setRecord:e=>{s.session&&e.snapshot&&(t(s.session,e.snapshot),s.sessionStore.set(s.sessionName,s.session))}})})}async function eI(e,t){let r=e.sessionStore.get(e.sessionName);if(!r&&t.requireSession)return{ok:!1,response:i("SESSION_NOT_FOUND","No active session. Run open first.")};let s=r?.device??await d(e.req.flags??{});return(r||await a(s),o(t.capability,s))?{ok:!0,runtime:ek({...e,session:r,device:s})}:{ok:!1,response:i("UNSUPPORTED_OPERATION",`${t.capability} is not supported on this device`)}}async function eN(e,t){let{device:r,session:s,req:o,logPath:i}=e;if("macos"===r.platform&&s?.surface&&"app"!==s.surface)return!!N((await eA(e)).nodes,t);if(q(r.platform)&&s?.appBundleId){let e=await n(r,{command:"findText",text:t,appBundleId:s?.appBundleId},{verbose:o.flags?.verbose,logPath:i,traceLogPath:s?.trace?.outPath,requestId:o.meta?.requestId,iosXctestrunFile:o.flags?.iosXctestrunFile,iosXctestDerivedDataPath:o.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:o.flags?.iosXctestEnvDir});return e?.found===!0}return!!N((await eA(e)).nodes,t)}async function eA(e){let s=await r({device:e.device,session:e.session,flags:{...e.req.flags,snapshotInteractiveOnly:!1},outPath:e.req.flags?.out,logPath:e.logPath??""});return e.session&&!b(s.snapshot.snapshotQuality)&&(t(e.session,s.snapshot),e.sessionStore.set(e.sessionName,e.session)),s.snapshot}async function eP(e){try{return{ok:!0,data:await e()}}catch(t){let e=g(t);return i(e.code,e.message,e.details)}}async function eR(e,t,r){var s;let n;if(t.ok)return t;let o=e.sessionStore.get(e.sessionName);if(!o)return t;try{n=await H(o)}catch{return t}return n?i(t.error.code,`${r} failed because ${"com.google.android.permissioncontroller"===(s=n).foregroundPackage?`Android permission dialog is blocking ${s.expectedPackage}`:`${s.foregroundPackage} is foreground instead of ${s.expectedPackage}`}.`,{...t.error.details??{},...n,blockedBy:"android_foreground_surface",originalMessage:t.error.message}):t}export{X as assertAndroidPressStayedInApp,F as buildSnapshotSession,T as createDaemonRuntimePolicy,ef as dispatchFindReadOnlyViaRuntime,ep as dispatchGetViaRuntime,em as dispatchIsViaRuntime,eg as dispatchWaitViaRuntime,j as isAndroidEscapeError,ed as isDirectIosSelectorFallbackError,ec as readSimpleIosSelectorTarget,G as readTextForNode,U as recordIfSession,B as refSnapshotFlagGuardResponse,$ as resolveSessionDevice,L as withSessionlessRunnerCleanup};
|
|
1
|
+
import{createDaemonRuntimeSessionStore as e,setSessionSnapshot as t,captureSnapshot as r,dispatchCommand as s,runIosRunnerCommand as n,isCommandSupportedOnDevice as o,errorResponse as i,ensureDeviceReady as a,stopIosRunnerSession as l,resolveRunnerAppBundleId as u,getActiveAndroidSnapshotFreshness as c,resolveTargetDevice as d,context_contextFromFlags as f}from"./9722.js";import{closeIosApp as p}from"./apps.js";import{emitDiagnostic as m}from"./432.js";import{asAppError as g,normalizeError as h,AppError as y}from"./733.js";import{evaluateIsPredicate as w,isSupportedPredicate as _,localCommandPolicy as S,createAgentDevice as v}from"./2577.js";import{tryParseSelectorChain as x,extractNodeReadText as k,prefersValueForReadableText as I,findNodeByLabel as N,normalizeType as A,splitIsSelectorArgs as P}from"./9836.js";import{resolveRectCenter as R,isSparseSnapshotQualityVerdict as b,parseWaitPositionals as D}from"./9873.js";import{getAndroidAppState as E}from"./3340.js";import{isApplePlatform as q}from"./5910.js";import{parseFindArgs as C}from"./587.js";import{buildSnapshotPresentationKey as M,snapshotPresentationOptionsFromFlags as O}from"./4291.js";async function $(e,t,r){let s=e.get(t),n=s?.device??await d(r??{});return s||await a(n),{session:s,device:n}}async function L(e,t,r){let s=!e&&"ios"===t.platform;try{return await r()}finally{s&&(await l(t.id),await K(t))}}async function K(e){let t=u();await p(e,t).catch(r=>{m({level:"debug",phase:"ios_sessionless_runner_host_close_failed",data:{deviceId:e.id,bundleId:t,error:r instanceof Error?r.message:String(r)}})})}function U(e,t,r,s){t&&e.recordAction(t,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:s})}function F(e){let{session:t,sessionName:r,device:s,snapshot:n,appBundleId:o}=e;return t?{...t,snapshot:n,lastComparisonSafeSnapshot:n?.comparisonSafe===!0?n:t.lastComparisonSafeSnapshot}:{name:r,device:s,createdAt:Date.now(),appBundleId:o,snapshot:n,...n?.comparisonSafe===!0?{lastComparisonSafeSnapshot:n}:{},actions:[]}}function T(e,t={}){return{artifacts:function(e,t={}){let r=!0===t.plural?"do":"does";return{resolveInput:async()=>{throw new y("UNSUPPORTED_OPERATION",`${e} ${r} not resolve input artifacts`)},reserveOutput:async()=>{throw new y("UNSUPPORTED_OPERATION",`${e} ${r} not reserve output artifacts`)},createTempFile:async()=>{throw new y("UNSUPPORTED_OPERATION",`${e} ${r} not create temporary files`)}}}(e,t),policy:S()}}async function G(e){let{device:t,node:r,flags:n,appBundleId:o,traceOutPath:i,surface:a,contextFromFlags:l}=e,u=k(r),c=R(r.rect);if(!c||"ios"===t.platform&&u&&!I(r.type??""))return u;try{let e=await s(t,"read",[String(c.x),String(c.y)],void 0,{...l(n,o,i),surface:a}),d=e&&"object"==typeof e?e:void 0,f="string"==typeof d?.text?d.text:"";if(f.trim())return f;return m({level:"warn",phase:"interaction_read_fallback",data:{reason:"empty_backend_text",nodeRef:r.ref,surface:a,platform:t.platform}}),u}catch(e){return m({level:"warn",phase:"interaction_read_fallback",data:{reason:"backend_read_failed",nodeRef:r.ref,surface:a,platform:t.platform,error:e instanceof Error?e.message:String(e)}}),u}}let V=[["snapshotDepth","--depth"],["snapshotScope","--scope"],["snapshotRaw","--raw"]];function B(e,t){let r=function(e){if(!e)return[];let t=[];for(let[r,s]of V)void 0!==e[r]&&t.push(s);return t}(t);return 0===r.length?null:i("INVALID_ARGS",`${e} @ref does not support ${r.join(", ")}.`)}async function X(e,t){let r=await H(e);if(r)throw new y("COMMAND_FAILED",`press ${t} left ${e.appBundleId} and foregrounded ${r.foregroundPackage}. The tap likely escaped the app.`,r)}async function H(e){var t;if("android"!==e.device.platform||!e.appBundleId)return null;let r=await E(e.device),s=r.package?.trim();return s&&s!==e.appBundleId&&("com.android.settings"===(t=s)||"com.android.systemui"===t||"com.google.android.permissioncontroller"===t||t.includes("launcher"))?{expectedPackage:e.appBundleId,foregroundPackage:s,activity:r.activity,hint:"com.google.android.permissioncontroller"===s?"Dismiss or allow the permission prompt, then retry the smoke assertion.":"Use screenshot as visual truth, then take a fresh snapshot -i before retrying."}:null}function j(e){return"COMMAND_FAILED"===e.code&&"string"==typeof e.details?.expectedPackage&&"string"==typeof e.details?.foregroundPackage}function W(e,t){let r=Array.isArray(e.selectorChain)?e.selectorChain:void 0,s=Y(e),n=s?.kind==="ref"?Z(s.ref):void 0,o=s?.kind==="selector"?s.selector:void 0,i={...n?{ref:n}:{},...o?{selector:o}:{},...r?{selectorChain:r}:{}};if("attrs"===t)return i;let a="string"==typeof e.text?e.text:"";return{...i,text:a,refLabel:function(e){let t=e.trim();if(!(!t||t.length>80||/[\r\n]/.test(t)))return t}(a)}}function z(e){let t=Y(e);return{...t?.kind==="ref"?{ref:Z(t.ref)}:{},...t?.kind==="selector"?{selector:t.selector}:{},..."string"==typeof e.text?{text:e.text}:{},...e.node&&"object"==typeof e.node?{node:e.node}:{}}}function Q(e){let{selectorChain:t,...r}=e;return r}function J(e,t,r,s){let n=e.get(t);n&&e.recordAction(n,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:s})}function Y(e){let t=e.target;return t&&"object"==typeof t?"ref"===t.kind&&"string"==typeof t.ref?{kind:"ref",ref:t.ref}:"selector"===t.kind&&"string"==typeof t.selector?{kind:"selector",selector:t.selector}:void 0:void 0}function Z(e){return e.startsWith("@")?e.slice(1):e}let ee=["application","window","tabbar","scrollbar","image"],et=new Set(["tab bar"]);async function er(e,t){var r;if(t.ok||(r=t.error.message,!/^wait timed out for (?:selector|text): /i.test(r)))return t;let s=await es(e).catch(()=>null);return s?i(t.error.code,`${t.error.message}. Current surface: ${s.summary}.`,{...t.error.details??{},currentSurface:s.details}):t}async function es(e){let t=[...(await r({device:e.device,session:e.session,flags:{...e.req.flags,snapshotInteractiveOnly:!0},logPath:e.logPath??""})).snapshot.nodes].sort(eo),s=en(t,6,{includeIdentifiers:!0});if(0===s.length)return null;let n=en(t.filter(e=>!el(e)),4,{includeIdentifiers:!1}),o=en(t.filter(eu),4,{includeIdentifiers:!0});return{summary:(n.length>0?n:s.slice(0,4)).join(", "),details:{labels:s,...o.length>0?{buttons:o}:{}}}}function en(e,t,r){let s=new Set,n=[];for(let o of e){let e=ea(o,r);if(!(!e||s.has(e))&&(s.add(e),n.push(e),n.length>=t))break}return n}function eo(e,t){var r,s;return ei(e)-ei(t)||(r=e,s=t,r.rect&&s.rect?r.rect.y-s.rect.y||r.rect.x-s.rect.x:r.rect?-1:s.rect?1:(r.depth??0)-(s.depth??0)||r.index-s.index)}function ei(e){let t=!!ea(e,{includeIdentifiers:!1});return 2*!!el(e)+ +!t}function ea(e,t){let r=(t.includeIdentifiers?[e.label,e.value,e.identifier]:[e.label,e.value]).map(e=>"string"==typeof e?e.trim():"").find(e=>e.length>0);return r?r.replace(/\s+/g," ").slice(0,80):""}function el(e){let t=A(`${e.type??""} ${e.role??""} ${e.subrole??""}`),r=`${e.label??""} ${e.value??""}`.trim().toLowerCase();return ee.some(e=>t.includes(e))||et.has(r)||r.endsWith(".fill")}function eu(e){return A(`${e.type??""} ${e.role??""} ${e.subrole??""}`).includes("button")}function ec(e){var t;let{session:r,selectorExpression:s}=e;if(!r||"ios"!==r.device.platform||r.postGestureStabilization)return null;let n=x(s);if(!n||1!==n.selectors.length)return null;let o=n.selectors[0];if(!o||1!==o.terms.length)return null;let i=o.terms[0];return i&&"string"==typeof i.value&&("id"===(t=i.key)||"label"===t||"text"===t||"value"===t)?{key:i.key,value:i.value,raw:o.raw}:null}function ed(e,t={}){let r=g(e);if("ELEMENT_NOT_FOUND"===r.code)return!0===t.allowElementNotFound;if("COMMAND_FAILED"!==r.code)return!1;let s=r.message.toLowerCase();return s.includes("fetch failed")||s.includes("timed out")||s.includes("timeout")||s.includes("runner did not accept connection")||s.includes("invalid runner response")}async function ef(e){var t;let{req:r}=e;if("find"!==r.command)return null;let s=r.positionals??[];if(0===s.length)return i("INVALID_ARGS","find requires a locator or text");let n=C(s);if(!n.query)return i("INVALID_ARGS","find requires a value");if(r.flags?.findFirst&&r.flags?.findLast)return i("INVALID_ARGS","find accepts only one of --first or --last");let o=n.action;if("exists"!==(t=o)&&"wait"!==t&&"get_text"!==t&&"get_attrs"!==t)return null;let a=await eI(e,{requireSession:!1,capability:"find"});return a.ok?await eP(async()=>{let t=await a.runtime.selectors.find({session:e.sessionName,requestId:r.meta?.requestId,locator:n.locator,query:n.query,action:o,timeoutMs:n.timeoutMs});return J(e.sessionStore,e.sessionName,r,function(e,t){if("exists"===t)return{found:!0};if("wait"===t)return{found:!0,waitedMs:e.waitedMs};let r="string"==typeof e.ref?e.ref:void 0;return"get_attrs"===t?{ref:r,action:"get attrs"}:{ref:r,action:"get text",text:"string"==typeof e.text?e.text:""}}(t,o)),"found"===t.kind?{found:!0,..."number"==typeof t.waitedMs?{waitedMs:t.waitedMs}:{}}:{..."string"==typeof t.ref?{ref:t.ref}:{},..."string"==typeof t.text?{text:t.text}:{},...t.node&&"object"==typeof t.node?{node:t.node}:{}}}):a.response}async function ep(e){let{req:t}=e;if("get"!==t.command)return null;let r=t.positionals?.[0];if("text"!==r&&"attrs"!==r)return i("INVALID_ARGS","get only supports text or attrs");let s=function(e){let t=e.positionals?.[1]??"";if(t.startsWith("@"))return{ok:!0,target:{kind:"ref",ref:t,fallbackLabel:e.positionals.length>2?e.positionals.slice(2).join(" ").trim():""}};let r=e.positionals?.slice(1).join(" ").trim()??"";return r?{ok:!0,target:{kind:"selector",selector:r}}:{ok:!1,response:i("INVALID_ARGS","get requires @ref or selector expression")}}(t);if(!s.ok)return s.response;if("ref"===s.target.kind){let e=B("get",t.flags);if(e)return e}if("selector"===s.target.kind){let t=await eh(e,r,s.target.selector);if(t)return t}let n=await eI(e,{requireSession:!0,capability:"get"});return n.ok?await eP(async()=>{let o=await n.runtime.selectors.get({session:e.sessionName,requestId:t.meta?.requestId,property:r,target:s.target});return J(e.sessionStore,e.sessionName,t,W(o,r)),z(o)}):n.response}async function em(e){let{req:t}=e;if("is"!==t.command)return null;let r=(t.positionals?.[0]??"").toLowerCase();if(!_(r))return i("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text");let{split:s}=P(t.positionals??[]);if(!s)return i("INVALID_ARGS","is requires a selector expression");let n=s.rest.join(" ").trim();if("text"===r&&!n)return i("INVALID_ARGS","is text requires expected text value");if("text"!==r&&s.rest.length>0)return i("INVALID_ARGS",`is ${r} does not accept trailing values`);let o=await ey(e,r,s.selectorExpression,n);if(o)return o;let a=await eI(e,{requireSession:!0,capability:"is"});if(!a.ok)return a.response;let l=await eP(async()=>{let o=await a.runtime.selectors.is({session:e.sessionName,requestId:t.meta?.requestId,predicate:r,selector:s.selectorExpression,expectedText:n});return J(e.sessionStore,e.sessionName,t,o),Q(o)});return await eR(e,l,`is ${r}`)}async function eg(e){let{req:t,sessionName:r,sessionStore:s}=e,n=D(t.positionals??[]);if(!n)return i("INVALID_ARGS","wait requires a duration or text");let{session:a,device:l}=await $(s,r,t.flags);if("sleep"!==n.kind&&!o("wait",l))return i("UNSUPPORTED_OPERATION","wait is not supported on this device");if("selector"===n.kind){let t=await ew({...e,session:a,device:l,selectorExpression:n.selectorExpression,timeoutMs:n.timeoutMs});if(t)return t}let u=async()=>{let o=ek({...e,session:a,device:l}),i=await eP(async()=>{let e=await o.selectors.wait({session:r,requestId:t.meta?.requestId,target:function(e,t){if("sleep"===e.kind)return{kind:"sleep",durationMs:e.durationMs};if("selector"===e.kind)return{kind:"selector",selector:e.selectorExpression,timeoutMs:e.timeoutMs};if("ref"===e.kind){if(!t?.snapshot)throw new y("INVALID_ARGS","Ref wait requires an existing snapshot in session.");return{kind:"ref",ref:e.rawRef,timeoutMs:e.timeoutMs}}if(!e.text)throw new y("INVALID_ARGS","wait requires text");return{kind:"text",text:e.text,timeoutMs:e.timeoutMs}}(n,a)});return J(s,r,t,e),{waitedMs:e.waitedMs,..."string"==typeof e.text?{text:e.text}:{},..."string"==typeof e.selector?{selector:e.selector}:{}}}),u=await er({req:t,logPath:e.logPath,session:a,device:l},i);return await eR(e,u,"wait")};return"sleep"===n.kind?await u():await L(a,l,u)}async function eh(e,t,r){let s=e.sessionStore.get(e.sessionName),n=ec({session:s,selectorExpression:r});if(!s||!n||"text"===t&&"id"!==n.key)return null;let o=await ev(e,s,n);if(ex(o))return o.response;if(!o)return null;let i=function(e,t,r){if(!r.found||!r.node)return null;let s={target:{kind:"selector",selector:t},node:r.node,selectorChain:[t]};return"attrs"===e?{kind:"attrs",...s}:"string"!=typeof r.text?null:{kind:"text",...s,text:r.text}}(t,n.raw,o);return i?(J(e.sessionStore,e.sessionName,e.req,W(i,t)),{ok:!0,data:z(i)}):null}async function ey(e,t,r,s){var n,o,i,a,l;let u;if("hidden"===t)return null;let c=await e_(e,r);if(ex(c))return c.response;if(!c?.result.found||!c.result.node)return null;let d="exists"===t?{predicate:t,pass:!0,selector:c.selector.raw,matches:1,selectorChain:[c.selector.raw]}:(n=t,o=s,i=c.selector.raw,a=c.session,u=w({predicate:n,node:l=c.result.node,nodes:[l],expectedText:o,platform:a.device.platform}),{predicate:n,pass:u.pass,selector:i,..."text"===n?{text:u.actualText}:{},selectorChain:[i]});return d?(J(e.sessionStore,e.sessionName,e.req,d),{ok:!0,data:Q(d)}):null}async function ew(e){let t=ec({session:e.session,selectorExpression:e.selectorExpression});if(!e.session||!t)return null;let r=Date.now(),s=await ev(e,e.session,t);if(ex(s))return s.response;if(!s?.found)return null;let n={kind:"selector",selector:t.raw,waitedMs:Date.now()-r,selectorChain:[t.raw]};return J(e.sessionStore,e.sessionName,e.req,n),await er({req:e.req,logPath:e.logPath,session:e.session,device:e.device},{ok:!0,data:n})}async function e_(e,t){let r=e.sessionStore.get(e.sessionName),s=ec({session:r,selectorExpression:t});if(!r||!s)return null;let n=await ev(e,r,s);return ex(n)?n:n?{session:r,selector:s,result:n}:null}async function eS(e,t,r){let s=await n(t.device,{command:"querySelector",selectorKey:r.key,selectorValue:r.value,appBundleId:t.appBundleId},{verbose:!!e.req.flags?.verbose,logPath:e.logPath,traceLogPath:t.trace?.outPath,requestId:e.req.meta?.requestId,iosXctestrunFile:e.req.flags?.iosXctestrunFile,iosXctestDerivedDataPath:e.req.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:e.req.flags?.iosXctestEnvDir}),o=!0===s.found,i=function(e){let t=e.nodes;if(!Array.isArray(t))return;let r=t[0];if(r&&"object"==typeof r)return r}(s);return{found:o,..."string"==typeof s.text?{text:s.text}:{},...i?{node:i}:{}}}async function ev(e,t,r){try{return await eS(e,t,r)}catch(e){if(ed(e,{allowElementNotFound:!0}))return null;return{kind:"error",response:{ok:!1,error:h(e)}}}}function ex(e){return null!==e&&"kind"in e&&"error"===e.kind}function ek(s){return v({backend:function(e){let s,{req:n,session:o,device:i,logPath:a,sessionName:l,sessionStore:u}=e,d=0;return{platform:i.platform,captureSnapshot:async(e,f)=>{var p;let m,g={...n.flags,...(p=f,m={},p?.interactiveOnly!==void 0&&(m.snapshotInteractiveOnly=p.interactiveOnly),p?.scope!==void 0&&(m.snapshotScope=p.scope),p?.depth!==void 0&&(m.snapshotDepth=p.depth),p?.raw!==void 0&&(m.snapshotRaw=p.raw),m)},h=f?.includeRects===!0,y=f?.scope??n.flags?.snapshotScope,w=Date.now(),_=M(O(g)),S="wait"===n.command||"find"===n.command||h&&"web"===i.platform;if(!S&&s&&w-d<750&&!c(o)&&!o?.postGestureStabilization)return s;if(!S&&o?.snapshot&&w-o.snapshot.createdAt<750&&o.snapshot.presentationKey===_&&!c(o)&&!o.postGestureStabilization)return d=o.snapshot.createdAt,s={snapshot:o.snapshot};let v=await r({device:i,session:o,flags:g,outPath:n.flags?.out,logPath:a??"",snapshotScope:y,includeRects:h});return o&&!b(v.snapshot.snapshotQuality)&&(t(o,v.snapshot),u.set(l,o)),d=w,s={snapshot:v.snapshot}},readText:async(t,r)=>({text:await G({device:i,node:r,flags:n.flags,appBundleId:o?.appBundleId,traceOutPath:o?.trace?.outPath,surface:o?.surface,contextFromFlags:e.contextFromFlags??((e,t,r)=>f(a??"",e,t,r))})}),findText:async(t,r)=>({found:await eN(e,r)})}}(s),...T("selector commands",{plural:!0}),sessions:e({sessionName:s.sessionName,getSession:()=>s.session,recordOptions:{includeSnapshot:!0},setRecord:e=>{s.session&&e.snapshot&&(t(s.session,e.snapshot),s.sessionStore.set(s.sessionName,s.session))}})})}async function eI(e,t){let r=e.sessionStore.get(e.sessionName);if(!r&&t.requireSession)return{ok:!1,response:i("SESSION_NOT_FOUND","No active session. Run open first.")};let s=r?.device??await d(e.req.flags??{});return(r||await a(s),o(t.capability,s))?{ok:!0,runtime:ek({...e,session:r,device:s})}:{ok:!1,response:i("UNSUPPORTED_OPERATION",`${t.capability} is not supported on this device`)}}async function eN(e,t){let{device:r,session:s,req:o,logPath:i}=e;if("macos"===r.platform&&s?.surface&&"app"!==s.surface)return!!N((await eA(e)).nodes,t);if(q(r.platform)&&s?.appBundleId){let e=await n(r,{command:"findText",text:t,appBundleId:s?.appBundleId},{verbose:o.flags?.verbose,logPath:i,traceLogPath:s?.trace?.outPath,requestId:o.meta?.requestId,iosXctestrunFile:o.flags?.iosXctestrunFile,iosXctestDerivedDataPath:o.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:o.flags?.iosXctestEnvDir});return e?.found===!0}return!!N((await eA(e)).nodes,t)}async function eA(e){let s=await r({device:e.device,session:e.session,flags:{...e.req.flags,snapshotInteractiveOnly:!1},outPath:e.req.flags?.out,logPath:e.logPath??""});return e.session&&!b(s.snapshot.snapshotQuality)&&(t(e.session,s.snapshot),e.sessionStore.set(e.sessionName,e.session)),s.snapshot}async function eP(e){try{return{ok:!0,data:await e()}}catch(t){let e=g(t);return i(e.code,e.message,e.details)}}async function eR(e,t,r){var s;let n;if(t.ok)return t;let o=e.sessionStore.get(e.sessionName);if(!o)return t;try{n=await H(o)}catch{return t}return n?i(t.error.code,`${r} failed because ${"com.google.android.permissioncontroller"===(s=n).foregroundPackage?`Android permission dialog is blocking ${s.expectedPackage}`:`${s.foregroundPackage} is foreground instead of ${s.expectedPackage}`}.`,{...t.error.details??{},...n,blockedBy:"android_foreground_surface",originalMessage:t.error.message}):t}export{X as assertAndroidPressStayedInApp,F as buildSnapshotSession,T as createDaemonRuntimePolicy,ef as dispatchFindReadOnlyViaRuntime,ep as dispatchGetViaRuntime,em as dispatchIsViaRuntime,eg as dispatchWaitViaRuntime,j as isAndroidEscapeError,ed as isDirectIosSelectorFallbackError,ec as readSimpleIosSelectorTarget,G as readTextForNode,U as recordIfSession,B as refSnapshotFlagGuardResponse,$ as resolveSessionDevice,L as withSessionlessRunnerCleanup};
|
package/dist/src/session.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__webpack_require__ as e}from"./rslib-runtime.js";import t from"node:fs";import r from"node:path";import a from"node:vm";import{setTimeout as n}from"node:timers/promises";import{asAppError as i,normalizeError as o,AppError as s}from"./733.js";import{startAndroidSimpleperfProfile as l,APPLE_MEMGRAPH_SNAPSHOT_DESCRIPTION as u,dispatchCommand as p,sessionMatchesScope as d,selectorTargetsSessionDevice as c,appendAppLogMarker as f,resolveCommandDevice as m,hasRuntimeTransportHints as h,sampleAppleFramePerf as g,captureAppleMemorySnapshot as w,getSessionCommandKind as y,inferFillText as v,startAndroidPerfettoTrace as A,stopIosRunnerSession as S,captureAndroidHeapSnapshot as I,stopAppleXctracePerfCapture as b,resolvePublicSessionName as _,writeAppleXctracePerfReport as k,requireSessionOrExplicitSelector as N,cleanupUploadedArtifact as D,resolveSessionRequestLogPath as x,ANDROID_FRAME_SAMPLE_METHOD as R,refreshSessionDeviceIfNeeded as M,buildAppleFrameSamplingMetadata as P,createRequestCanceledError as L,registerRequestAbort as O,errorResponse as E,settleIosSimulator as C,readReplayTestActionProgress as $,buildSessionRecoveryHint as V,applyRuntimeHintsToApp as U,withKeyedLock as F,resolveTargetDevice as q,getAppLogPathMetadata as G,uniqueStrings as T,setSessionSnapshot as B,sampleAndroidMemoryPerf as H,shutdownDeviceTarget as K,ANDROID_HPROF_SNAPSHOT_DESCRIPTION as j,sampleAndroidCpuPerf as z,clearRuntimeHintsFromApp as W,ANDROID_HPROF_SNAPSHOT_METHOD as J,startAppleXctracePerfCapture as X,buildAppleSamplingMetadata as Y,getSnapshotReferenceFrame as Z,clearAppLogFiles as Q,handleCloseCommand as ee,prepareIosRunner as et,session_device_utils_hasExplicitSessionFlag as er,readSessionNetworkCapture as ea,cleanupRetainedMaterializedPaths as en,isImplicitSessionScopeConflict as ei,resolveSessionRunnerLogPath as eo,ANDROID_CPU_SAMPLE_DESCRIPTION as es,buildSnapshotState as el,resolveLogBackend as eu,stopAndroidSimpleperfProfile as ep,context_contextFromFlags as ed,listDeviceInventory as ec,SessionStore as ef,ANDROID_CPU_SAMPLE_METHOD as em,buildAppleMemorySnapshotSupport as eh,stopAndroidPerfettoTrace as eg,isRequestCanceled as ew,resolveRequestTrackingId as ey,retainMaterializedPaths as ev,runAppLogDoctor as eA,resolvePayloadInput as eS,prepareUploadedArtifact as eI,resetAndroidFramePerfStats as eb,ANDROID_FRAME_SAMPLE_DESCRIPTION as e_,withReplayTestActionProgress as ek,markRequestCanceled as eN,stopAppLog as eD,resolveImplicitSessionScope as ex,APPLE_MEMGRAPH_SNAPSHOT_METHOD as eR,ensureDeviceReady as eM,ANDROID_MEMORY_SAMPLE_DESCRIPTION as eP,prewarmIosRunnerSession as eL,clearRequestCanceled as eO,resolveAndroidEmulatorAvdName as eE,writeAndroidSimpleperfReport as eC,resolveFrontmostMacOsApp as e$,isCommandSupportedOnDevice as eV,sampleApplePerfMetrics as eU,sampleAndroidFramePerf as eF,ANDROID_MEMORY_SAMPLE_METHOD as eq,getRequestSignal as eG,markAndroidSnapshotFreshness as eT,startAppLog as eB,emitRequestProgress as eH}from"./9722.js";import{isPerfAction as eK,isPerfSubject as ej,pointFromPercent as ez,PERF_AREA_ERROR_MESSAGE as eW,buildSwipeGesturePlan as eJ,PERF_ACTION_ERROR_MESSAGE as eX,isPerfKind as eY,isPerfMemoryKind as eZ,pointInsideRect as eQ,successText as e0,clampGesturePoint as e1,resolveDeployResultTarget as e3,PERF_MEMORY_KIND_ERROR_MESSAGE as e2,PERF_KIND_ERROR_MESSAGE as e5,isPerfArea as e4,LOG_ACTION_VALUES as e6,withSuccessText as e8,clampToRange as e7,parseSessionSurface as e9,resolveInstallFromSourceResultTarget as te,readReactNativeOverlayActionNodes as tt,detectReactNativeOverlay as tr,PERF_SUBJECT_ERROR_MESSAGE as ta}from"./9873.js";import{isApplePlatform as tn,resolveAppleSimulatorSetPathForSelector as ti,normalizePlatformSelector as to,matchesPlatformSelector as ts}from"./5910.js";import{resolveIosSimulatorDeviceSetPath as tl,classifyAndroidAppTarget as tu,resolveIosDeviceDeepLinkBundleId as tp,isInfrastructureBootFailureReason as td,isWebUrl as tc,resolveAndroidSerialAllowlist as tf,isDeepLinkTarget as tm,formatAndroidInstalledPackageRequiredMessage as th,listAndroidApps as tg}from"./3340.js";import{getDiagnosticsMeta as tw,emitDiagnostic as ty}from"./432.js";import{runBatch as tv,mergeParentFlags as tA}from"./6918.js";import{assertResolvedAppsFilter as tS}from"./2748.js";import{listIosApps as tI}from"./apps.js";import{resolveWebProvider as tb}from"./provider.js";import{NETWORK_INCLUDE_MODES as t_}from"./4291.js";import{unsupportedCommand as tk,readEnvMap as tN,parseReplayScriptDetailed as tD,readReplayShellEnvSource as tx,normalizeCommandList as tR,normalizePlatform as tM,readReplayCliEnvEntries as tP,parseMaestroYamlDocuments as tL,parseAbsolutePoint as tO,readReplayScriptMetadata as tE,parseReplayCliEnvEntries as tC,collectReplayShellEnv as t$,support_action as tV,isPlainRecord as tU,requireAppId as tF,assertOnlyKeys as tq,resolveMaestroString as tG,requireStringValue as tT,parseMaestroPoint as tB,unsupportedMaestroSyntax as tH,readTimeoutMs as tK,writeReplayScript as tj,buildReplayVarScope as tz,resolveReplayAction as tW,mergeReplayVarScopeValues as tJ}from"./4428.js";import{runCmdSync as tX}from"./8875.js";import{readSnapshotDiagnosticsSummary as tY,summarizeSnapshotTimingSamples as tZ,mergeSnapshotDiagnostics as tQ}from"./2892.js";import{splitSelectorFromArgs as t0,extractNodeText as t1,findSnapshotAncestor as t3,isDescendantOfSnapshotNode as t2,parseSelectorChain as t5,tryParseSelectorChain as t4,splitIsSelectorArgs as t6,resolveSelectorChain as t8,buildSelectorChainForNode as t7,buildSnapshotNodeByIndex as t9,matchesSelector as re,normalizeType as rt}from"./9836.js";import{formatScriptActionSummary as rr,evaluateIsPredicate as ra,isTouchTargetCommand as rn}from"./368.js";import{normalizeText as ri}from"./587.js";import{sleep as ro}from"./5560.js";import{buildSnapshotDisplayLines as rs}from"./7244.js";import{handleRecordCommand as rl}from"./record-trace-recording.js";import{INTERNAL_COMMANDS as ru,PUBLIC_COMMANDS as rp}from"./2133.js";import{trimRuntimeValue as rd}from"./5628.js";var rc={};async function rf(e){var t;let r="ios"===(t=e.flags?.platform)||"android"===t?t:void 0;if(e.session){if(r&&e.session.device.platform!==r)throw new s("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await eM(e.session.device),e.session.device}if(!r)throw new s("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let a=await q(e.flags??{});return await eM(a),a}async function rm(e){let{prepared:t,retention:r,req:a,session:n,sessionName:i}=e;if(r.enabled)return await ev({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:a.meta?.tenantId,sessionName:n?i:void 0,ttlMs:r.ttlMs})}function rh(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function rg(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);try{let e,i,o=(e=function(e){let t=e.meta?.installSource;if(!t)throw new s("INVALID_ARGS","install_from_source requires a source payload");switch(t.kind){case"url":if(!t.url||0===t.url.trim().length)throw new s("INVALID_ARGS","install_from_source url source requires a non-empty url");return t;case"path":if(!t.path||0===t.path.trim().length)throw new s("INVALID_ARGS","install_from_source path source requires a non-empty path");return t;case"github-actions-artifact":throw new s("UNSUPPORTED_OPERATION","install_from_source github-actions-artifact sources require a compatible remote daemon");default:throw new s("UNSUPPORTED_OPERATION",`install_from_source ${String(t.kind)} sources require a compatible remote daemon`)}}(t),(i=t.meta?.uploadedArtifactId)&&"path"===e.kind?{source:{kind:"path",path:eI(i,t.meta?.tenantId)},cleanup:()=>{D(i)}}:{source:e,cleanup:()=>{}}),l=function(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(void 0!==r&&r<=0)throw new s("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),u=await rf({session:n,flags:t.flags});if(!eV("install",u))return E("UNSUPPORTED_OPERATION","install_from_source is not supported on this device");let p=eG(t.meta?.requestId),d=async(e,i)=>{let s;try{var u;s=await rm({prepared:e,retention:l,req:t,session:n,sessionName:r});let o=await i(s),p=e8(o,(u=o,`Installed: ${te(u)}`));return!function(e){let{session:t,sessionStore:r,req:a,data:n}=e;t&&r.recordAction(t,{command:"install_source",positionals:[],flags:a.flags??{},result:n})}({session:n,sessionStore:a,req:t,data:p}),{ok:!0,data:p}}catch(e){throw s&&await en(s.materializationId,t.meta?.tenantId).catch(()=>{}),e}finally{await e.cleanup(),o.cleanup()}};if("ios"===u.platform){let{installIosInstallablePath:e}=await import("./apps.js"),{prepareIosInstallArtifact:t}=await import("./apps.js"),r=await t(o.source,{signal:p});return await d(r,async t=>{if(await e(u,r.installablePath),!r.bundleId)throw new s("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact");return{...rh(t),bundleId:r.bundleId,...r.appName?{appName:r.appName}:{},launchTarget:r.bundleId}})}let{prepareAndroidInstallArtifact:c}=await import("./3340.js"),{installAndroidInstallablePathAndResolvePackageName:f}=await import("./3340.js"),m=await c(o.source,{signal:p});return await d(m,async e=>{let t=await f(u,m.installablePath,m.packageName);if(!t)throw new s("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");let{inferAndroidAppName:r}=await import("./3340.js"),a=r(t);return{...rh(e),packageName:t,...a?{appName:a}:{},launchTarget:t}})}catch(e){return{ok:!1,error:o(e)}}}async function rw(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new s("INVALID_ARGS","release_materialized_paths requires a materializationId");return await en(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:o(e)}}}e.r(rc),e.d(rc,{handleSessionCommands:()=>oV});let ry=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function rv(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function rA(e,t){if(void 0!==e){if("string"!=typeof e)throw new s("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return rd(e)}}function rS(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new s("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function rI(e){if("ios"===e||"android"===e)return e}async function rb(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:a,session:n}=e;!t||!n?.appBundleId||!h(r)||h(a)||await W({device:n.device,appId:n.appBundleId})}async function r_(e){var t,r;let{req:a,sessionName:n,sessionStore:i}=e,o=(a.positionals?.[0]??"show").toLowerCase(),s=i.get(n),l=i.getRuntimeHints(n);if(!["set","show","clear"].includes(o))return E("INVALID_ARGS","runtime requires set, show, or clear");if("clear"===o){h(l)&&s?.appBundleId&&await W({device:s.device,appId:s.appBundleId});let e=i.clearRuntimeHints(n);return{ok:!0,data:{session:n,cleared:e}}}if("show"===o)return{ok:!0,data:{session:n,configured:!!l,runtime:l}};let u=rI(to(a.flags?.platform)??l?.platform??s?.device.platform);if(!u)return E("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(s&&s.device.platform!==u)return E("INVALID_ARGS",`runtime set targets ${u}, but session "${n}" is already bound to ${s.device.platform}.`);let p={platform:(t=a.flags,r={platform:u,metroHost:rd(t?.metroHost),metroPort:rS(t?.metroPort),bundleUrl:rd(t?.bundleUrl),launchUrl:rd(t?.launchUrl)}).platform??l?.platform,metroHost:r.metroHost??l?.metroHost,metroPort:r.metroPort??l?.metroPort,bundleUrl:r.bundleUrl??l?.bundleUrl,launchUrl:r.launchUrl??l?.launchUrl};return 0===rv(p)?E("INVALID_ARGS","runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."):(i.setRuntimeHints(n,p),{ok:!0,data:{session:n,configured:!0,runtime:p}})}let rk="open-command-roundtrip",rN="Not implemented for this platform in this release.";function rD(e){let{existingSession:t,sessionName:r,sessionScope:a,device:n,surface:i,appBundleId:o,appName:s,saveScript:l}=e;return t?{...t,device:n,surface:i,appBundleId:o,appName:s,recordSession:t.recordSession||l,snapshot:void 0}:{name:r,sessionScope:a,device:n,createdAt:Date.now(),surface:i,appBundleId:o,appName:s,recordSession:l,actions:[]}}let rx=new Set(["app","desktop","frontmost-app"]);async function rR(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await e$();return{appBundleId:t.bundleId,appName:t.appName}}async function rM(e,t,r){if(("ios"===e.platform||"macos"===e.platform)&&t)return tm(t)?"macos"===e.platform?void 0:"device"===e.kind?tp(r,t):tc(t)?void 0:r??await rP(e,t):await rL(e,t)}async function rP(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rL(e,t){try{let{resolveIosApp:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rO(e,t){if(!("android"!==e.platform||!t||tm(t)))try{let{resolveAndroidApp:r}=await import("./3340.js"),a=await r(e,t);return"package"===a.type?a.value:void 0}catch{return}}async function rE(e,t,r){if(r||"android"!==e.platform||!t||!tm(t))return r;try{let{getAndroidAppState:t}=await import("./3340.js"),a=await t(e);return a.package?.trim()||r}catch{return r}}async function rC(e,t,r,a){return await rM(e,t,r)??await a(e,t)??("android"===e.platform&&t&&tm(t)?r:void 0)}function r$(e){return E("INVALID_ARGS",e)}function rV(e,t,r,a){try{return function(e){let{device:t,surfaceFlag:r,openTarget:a,existingSurface:n}=e;if(("macos"===t.platform||"linux"===t.platform)&&!r)return n??"app";if("linux"===t.platform){if(!r)return"app";let e=e9(r);if(!rx.has(e))throw new s("INVALID_ARGS",`Linux supports --surface app, desktop, and frontmost-app (got "${r}")`);if("app"!==e&&a)throw new s("INVALID_ARGS",`open --surface ${e} does not accept an app target`);return e}if("macos"!==t.platform){if(r)throw new s("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let i=r?e9(r):"app";if("app"!==i&&"menubar"!==i&&a)throw new s("INVALID_ARGS",`open --surface ${i} does not accept an app target`);return i}({device:e,surfaceFlag:t,openTarget:r,existingSurface:a})}catch(e){return E(e instanceof s?e.code:"INVALID_ARGS",String(e.message))}}function rU(e){let{shouldRelaunch:t,openTarget:r,surface:a,device:n}=e;return t?r&&tm(r)?r$("open --relaunch does not support URL targets."):"app"!==a?r$("open --relaunch is supported only for app surfaces."):"android"===n.platform&&r&&"binary"===tu(r)?r$(th(r)):null:null}async function rF(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:o,openTarget:l,existingSession:u}=e;await eM(n,{deviceHub:t.flags?.deviceHub===!0});let{appBundleId:p,appName:d}=await rq({device:n,surface:o,openTarget:l,existingAppBundleId:u?.appBundleId}),c=function(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:a,device:n}=e,i=r.getRuntimeHints(a),o=function(e){let{runtime:t,sessionName:r,platform:a}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new s("INVALID_ARGS","open runtime must be an object.");let n=Object.keys(t).find(e=>!ry.includes(e));if(n)throw new s("INVALID_ARGS",`Invalid open runtime field: ${n}. Supported fields are ${ry.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new s("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new s("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,a),metroHost:rA(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new s("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return rS(e)}}(t.metroPort),bundleUrl:rA(t.bundleUrl,"bundleUrl"),launchUrl:rA(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:rI(n.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let a=e.getRuntimeHints(t);if(!a)return;let n=r?.platform,i=rI(n);if(a.platform&&r&&!i)throw new s("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${n}.`);if(a.platform&&i&&a.platform!==i)throw new s("INVALID_ARGS",`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${n}. Clear the runtime hints or use a different session.`);return i&&a.platform!==i?{...a,platform:i}:a}(r,a,n),previousRuntime:i,replacedStoredRuntime:!1}:{runtime:o&&rv(o)>0?o:void 0,previousRuntime:i,replacedStoredRuntime:!0}}(e)}}catch(t){let e=i(t);return E(e.code,e.message,e.details)}}({req:t,sessionStore:a,sessionName:r,device:n});if(!c.ok)return{type:"response",response:c};if(u){let{runtime:e,previousRuntime:t,replacedStoredRuntime:r}=c.data;await rb({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:u})}return{type:"details",details:{appBundleId:p,appName:d,runtime:c.data.runtime}}}async function rq(e){let{device:t,surface:r,openTarget:a,existingAppBundleId:n}=e,i=await rR(r);return{appBundleId:i.appBundleId??await rC(t,a,n,rO),appName:i.appName??a}}let rG=new Map;async function rT(e){let{device:t,closeTarget:r,outFlag:a,context:n}=e;"android"!==t.platform&&await S(t.id),await p(t,"close",[r],a,n),await C(t,300)}async function rB(e){var t,r;let a,{runtime:n,device:i,req:o,logPath:s,appBundleId:l,traceLogPath:u,openPositionals:d}=e,c=n?.launchUrl;if(!c||0===d.length||d.length>1)return;let f=d[0]?.trim();!f||tm(f)||await p(i,"open",[c],o.flags?.out,{...(t=s,r=o.flags,a=ed(t,r,l,u),delete a.launchConsole,delete a.launchArgs,a)})}async function rH(e){var t,r,a,n;let i,{req:o,sessionName:s,sessionStore:l,logPath:u,device:d,openTarget:c,openPositionals:f,appName:m,surface:h,appBundleId:g,runtime:w,existingSession:y}=e,v=o.flags?.relaunch===!0,A=y?.trace?.outPath,S=g,I=Date.now(),b={};if(v&&c){let e=S??c,t=Date.now();await rT({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...ed(u,o.flags,S??y?.appBundleId,A)}}),b.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let k=Date.now();await U({device:d,appId:S,runtime:w}),b.runtimeHintsDurationMs=Math.max(0,Date.now()-k);let N="ios"===d.platform&&"app"===h&&f.length>0,D={verbose:o.flags?.verbose,logPath:u,traceLogPath:A,requestId:o.meta?.requestId,iosXctestrunFile:o.flags?.iosXctestrunFile,iosXctestDerivedDataPath:o.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:o.flags?.iosXctestEnvDir},R=o.flags?.maestro?.prewarmRunnerBeforeOpen===!0;if(N&&S&&(b.runnerPrewarmKind="session",b.runnerPrewarmScheduled=!0,R)){i=eL(d,{...D,propagateError:!0});let e=Date.now();await i,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}let M=Date.now(),P=await rK({req:o,sessionName:s,sessionStore:l,device:d,surface:h,sessionAppBundleId:S,appName:m,existingSession:y});if("response"===P.type)return P.response;let O=P.session??y;await p(d,"open",f,o.flags?.out,{...ed(u,o.flags,S)}),b.openDispatchDurationMs=Math.max(0,Date.now()-M);let $=Date.now();if(await rB({runtime:w,device:d,req:o,logPath:u,appBundleId:S,traceLogPath:A,openPositionals:f}),b.launchUrlDurationMs=Math.max(0,Date.now()-$),N&&S&&!i&&(i=eL(d,D)),v&&i&&!0!==b.runnerPrewarmWaited){let e=Date.now();await i,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}else i&&!0!==b.runnerPrewarmWaited&&(b.runnerPrewarmWaited=!1);S=await rE(d,c,S),"android"===d.platform&&S&&await eb(d,S);let V=c?(t=S,{durationMs:Math.max(0,Date.now()-M),measuredAt:new Date().toISOString(),method:rk,appTarget:c,appBundleId:t}):void 0,F=Date.now();if(await C(d,300),b.postOpenSettleDurationMs=Math.max(0,Date.now()-F),ew(o.meta?.requestId)){let e=L();return E(e.code,e.message,e.details)}y&&eT(y,"open",y.snapshot);let q=rD({existingSession:O,sessionName:y?.name??_(o),sessionScope:y?.sessionScope??ex(o),device:d,surface:h,appBundleId:S,appName:m,saveScript:!!o.flags?.saveScript});void 0!==o.runtime&&(r=l,a=s,(n=w)&&(0===rv(n)?r.clearRuntimeHints(a):r.setRuntimeHints(a,n)));let G=l.ensureSessionDir(s),T=x(G,o.meta?.requestId??tw().requestId);b.totalDurationMs=Math.max(0,Date.now()-I);let B=function(e){let{sessionName:t,sessionStateDir:r,runnerLogPath:a,requestLogPath:n,appName:i,appBundleId:o,surface:s,startup:l,timing:u,device:p,runtime:d,runtimeHintCount:c}=e,f={session:t,surface:s,sessionStateDir:r,runnerLogPath:a,requestLogPath:n};return i&&(f.appName=i),o&&(f.appBundleId=o),l&&(f.startup=l),u&&(f.timing=u),d&&c(d)>0&&(f.runtime=d),p&&(f.platform=p.platform,f.target=p.target??"mobile",f.device=p.name,f.id=p.id,f.kind=p.kind,"android"===p.platform&&(f.serial=p.id)),p?.platform==="ios"&&(f.device_udid=p.id,f.ios_simulator_device_set=p.simulatorSetPath??null),{...f,...e0(`Opened: ${i??o??t}`)}}({sessionName:q.name,sessionStateDir:G,runnerLogPath:eo(G),requestLogPath:T,appName:m,appBundleId:S,surface:h,startup:V,timing:b,device:d,runtime:w,runtimeHintCount:rv});return l.recordAction(q,{command:"open",positionals:f,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:B}),l.set(s,q),{ok:!0,data:B}}async function rK(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:i,sessionAppBundleId:o,appName:s,existingSession:l}=e,u=t.internal?.openLifecycle?.beforeDispatch;if(!u)return{type:"session",session:l};let p=rD({existingSession:l,sessionName:l?.name??_(t),sessionScope:l?.sessionScope??ex(t),device:n,surface:i,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});a.set(r,p);let d=await u(p);return d&&!d.ok?{type:"response",response:d}:{type:"session",session:a.get(r)??p}}async function rj(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r);if(i){let e=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(e?i.appName:void 0),l=rV(i.device,t.flags?.surface,s,i.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return e?r$("open --relaunch requires an app name or an active session app."):r$("Session already active. Close it first or pass a new --session name.");let u=rU({shouldRelaunch:e,openTarget:s,surface:l,device:i.device});if(u)return u;let p=await M(i.device),d=await rF({req:t,sessionName:r,sessionStore:n,device:p,surface:l,openTarget:s,existingSession:i});return"response"===d.type?d.response:await rH({req:t,sessionName:r,sessionStore:n,logPath:a,device:p,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:d.details.appBundleId,appName:d.details.appName,runtime:d.details.runtime,surface:l,existingSession:i})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return r$("open --relaunch requires an app argument.");let l=function(e){let{shouldRelaunch:t,openTarget:r,platform:a}=e;return t?r&&tm(r)?r$("open --relaunch does not support URL targets."):"android"===a&&r&&"binary"===tu(r)?r$(th(r)):null:null}({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform==="android"?"android":void 0});if(l)return l;let u=await q(t.flags??{}),p=rV(u,t.flags?.surface,s);if("string"!=typeof p)return p;let d=rU({shouldRelaunch:o,openTarget:s,surface:p,device:u});return d||await F(rG,u.id,async()=>{let e=n.toArray().find(e=>e.device.id===u.id);if(e)return ei(t,e)?E("DEVICE_IN_USE","Device is already in use by another workspace session.",{deviceId:u.id,deviceName:u.name,hint:"Use a different device selector, wait for the other workspace to close its session, or run agent-device devices to choose another target."}):E("DEVICE_IN_USE",`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:u.id,deviceName:u.name,hint:V(e,"device-in-use")});let i=await rF({req:t,sessionName:r,sessionStore:n,device:u,surface:p,openTarget:s});return"response"===i.type?i.response:await rH({req:t,sessionName:r,sessionStore:n,logPath:a,device:u,openTarget:s,openPositionals:t.positionals??[],appBundleId:i.details.appBundleId,appName:i.details.appName,runtime:i.details.runtime,surface:p})})}let rz={ios:async(e,t,r)=>{let{reinstallIosApp:a}=await import("./apps.js");return await a(e,t,r)},android:async(e,t,r)=>{let{reinstallAndroidApp:a}=await import("./3340.js");return await a(e,t,r)}},rW={ios:async(e,t,r)=>{let{installIosApp:a}=await import("./apps.js"),n=await a(e,r,{appIdentifierHint:t});return{bundleId:n.bundleId,appName:n.appName,launchTarget:n.launchTarget}},android:async(e,t,r)=>{let{installAndroidApp:a}=await import("./3340.js"),n=await a(e,r);return{package:n.packageName,appName:n.appName,launchTarget:n.launchTarget}}};async function rJ(e){let{req:r,command:a,sessionName:n,sessionStore:i,deployOps:o}=e,s=i.get(n),l=r.flags??{},u=N(a,s,l);if(u)return u;let p=r.positionals?.[0]?.trim(),d=r.positionals?.[1]?.trim();if(!p||!d)return E("INVALID_ARGS",`${a} requires: ${a} <app> <path-to-app-binary>`);let c=r.meta?.uploadedArtifactId;try{var f;let e,n=c?eI(c,r.meta?.tenantId):ef.expandHome(d);if(!t.existsSync(n))return E("INVALID_ARGS",`App binary not found: ${n}`);let u=await m({session:s,flags:l,ensureReady:!1});if(!eV(a,u))return E("UNSUPPORTED_OPERATION",`${a} is not supported on this device`);if("ios"===u.platform){let t=await o.ios(u,p,n),r=t.bundleId;e=r?{app:p,appPath:n,platform:"ios",appId:r,bundleId:r,appName:t.appName,launchTarget:t.launchTarget}:{app:p,appPath:n,platform:"ios",appName:t.appName,launchTarget:t.launchTarget}}else{let t=await o.android(u,p,n),r=t.package;e=r?{app:p,appPath:n,platform:"android",appId:r,package:r,packageName:r,appName:t.appName,launchTarget:t.launchTarget}:{app:p,appPath:n,platform:"android",appName:t.appName,launchTarget:t.launchTarget}}let h=e8(e,(f=e,`Installed: ${f.appName??e3(f)}`));return s&&i.recordAction(s,{command:a,positionals:r.positionals??[],flags:r.flags??{},result:h??{}}),{ok:!0,data:h}}finally{c&&D(c)}}async function rX(e,t,r){return await tv(e,t,r)}async function rY(e){let{req:t,sessionName:r,sessionStore:a}=e;if("session_list"===t.command){let e=ex(t);return{ok:!0,data:{sessions:a.toArray().filter(t=>d(t,e)).map(e=>{let t=a.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:eo(t),platform:e.device.platform,target:e.device.target??"mobile",surface:e.surface??"app",device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,..."ios"===e.device.platform&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if("devices"===t.command)try{let e=tf(t.flags?.androidDeviceAllowlist),r=to(t.flags?.platform),a=ti({simulatorSetPath:tl(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),n=await ec({platform:r,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:a,androidSerialAllowlist:e?Array.from(e).sort():void 0}),i=r?n.filter(e=>{var t,a;return t=e,!(a=r)||("apple"===a?tn(t.platform):t.platform===a)}):n,o=(t.flags?.target?i.filter(e=>(e.target??"mobile")===t.flags?.target):i).map(({simulatorSetPath:e,...t})=>t);return{ok:!0,data:{devices:o}}}catch(t){let e=i(t);return E(e.code,e.message,e.details)}if("apps"===t.command){let e=a.get(r),n=t.flags??{},i=N(t.command,e,n);if(i)return i;let o=await m({session:e,flags:n,ensureReady:!0});if(!eV("apps",o))return E("UNSUPPORTED_OPERATION","apps is not supported on this device");let s=tS(t.flags?.appsFilter);return tn(o.platform)?{ok:!0,data:{apps:(await tI(o,s)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await tg(o,s)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function rZ(e){let{ensureAndroidEmulatorBooted:t}=await import("./3340.js");return await t(e)}let rQ='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',r0='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function r1(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r),i=t.flags??{},o=to(i.platform);if(!n&&er(i))return E("SESSION_NOT_FOUND","ios"===o?`No active session "${r}". Run open with --session ${r} first.`:`No active session "${r}". Run open with --session ${r} first, or omit --session to query by device selector.`);let s=N("appstate",n,i);if(s)return s;let l=tn(n?.device.platform)&&c(i,n);if("ios"===o&&!l)return E("SESSION_NOT_FOUND",rQ);if("macos"===o&&!l)return E("SESSION_NOT_FOUND",r0);if(l&&n){let e=n.appName??n.appBundleId;if(!n.appName&&!n.appBundleId){if("macos"===n.device.platform&&n.surface&&"app"!==n.surface&&"frontmost-app"!==n.surface)return{ok:!0,data:{platform:n.device.platform,appName:n.surface,appBundleId:n.appBundleId,source:"session",surface:n.surface}};let e="macos"===n.device.platform?"macOS":"iOS";return E("COMMAND_FAILED",`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`)}return{ok:!0,data:{platform:n.device.platform,appName:e??"unknown",appBundleId:n.appBundleId,source:"session",surface:n.surface??"app",..."ios"===n.device.platform?{device_udid:n.device.id,ios_simulator_device_set:n.device.simulatorSetPath??null}:{}}}}let u=await m({session:n,flags:i,ensureReady:!0});if("ios"===u.platform)return E("SESSION_NOT_FOUND",rQ);if("macos"===u.platform)return E("SESSION_NOT_FOUND",r0);if("web"===u.platform)return E("UNSUPPORTED_OPERATION","appstate is not supported on web.");let{getAndroidAppState:p}=await import("./3340.js"),d=await p(u);return{ok:!0,data:{platform:"android",package:d.package,activity:d.activity}}}async function r3(e){let{req:t,sessionName:r,sessionStore:a}=e;if("boot"===t.command){let e,n=a.get(r),o=t.flags??{},s=N(t.command,n,o);if(s)return s;let l="android"===(to(o.platform)??n?.device.platform),u=!0===o.headless;if(u&&!l)return E("INVALID_ARGS","boot --headless is supported only for Android emulators.");let p=eE({flags:o,sessionDevice:n?.device}),d=l&&!!p,c=!1;try{e=await m({session:n,flags:o,ensureReady:!1})}catch(r){let t=i(r);if(l&&u&&!p&&"DEVICE_NOT_FOUND"===t.code)return E("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");if(!d||"DEVICE_NOT_FOUND"!==t.code||!p)throw r;e=await rZ({avdName:p,serial:o.serial,headless:u}),c=!0}if(o.target&&(e.target??"mobile")!==o.target)return E("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${o.target}.`);if(l&&u){if("android"!==e.platform||"emulator"!==e.kind)return E("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!c){let t=eE({flags:o,sessionDevice:n?.device,resolvedDevice:e});if(!t)return E("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await rZ({avdName:t,serial:o.serial,headless:!0})}await eM(e)}else("android"!==e.platform||!0!==e.booted)&&await eM(e);return eV("boot",e)?{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}:E("UNSUPPORTED_OPERATION","boot is not supported on this device")}if("shutdown"===t.command){var n;let e,i=a.get(r),o=t.flags??{},s=N(t.command,i,o);if(s)return s;let l=await m({ensureReady:!1,flags:o,session:i});if(!eV("shutdown",l))return E("UNSUPPORTED_OPERATION","shutdown is supported only for Apple simulators and Android emulators.");if(i&&i.device.platform===l.platform&&i.device.id===l.id)return E("DEVICE_IN_USE","Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.",{hint:`Run agent-device close --shutdown --session ${r}`,session:r,platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind});let u=await K(l);return u.success?{ok:!0,data:{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u}}:E(u.error?.code??"COMMAND_FAILED",(n=u,(e=n.error?.message??n.stderr.trim()).length>0?e:"Shutdown failed"),{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u})}return"appstate"===t.command?await r1({req:t,sessionName:r,sessionStore:a}):null}async function r2(e,t={}){var r,a,n;let i,o,s,l,u=(s=(o=(i=function(e){let t=[];for(let r of e){if("open"!==r.command)continue;let e=r.result?.startup;e&&"object"==typeof e&&"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&"string"==typeof e.measuredAt&&0!==e.measuredAt.trim().length&&e.method===rk&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:rk,appTarget:"string"==typeof e.appTarget&&e.appTarget.length>0?e.appTarget:void 0,appBundleId:"string"==typeof e.appBundleId&&e.appBundleId.length>0?e.appBundleId:void 0})}return t.slice(-20)}((r=e).actions)).at(-1))?{available:!0,lastDurationMs:o.durationMs,lastMeasuredAt:o.measuredAt,method:rk,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:rk},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,...{fps:r6(),memory:{available:!1,reason:rN},cpu:{available:!1,reason:rN}}},sampling:{startup:{method:rk,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"},..."android"===(a=r).device.platform?{memory:{method:eq,description:eP,unit:"kB"},cpu:{method:em,description:es,unit:"percent"},fps:{method:R,description:e_,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}}:Y(a.device)}});return at(e)&&(e.appBundleId?"android"===e.device.platform?await r8(u,e,e.appBundleId,t):await r7(u,e,e.appBundleId):(n=u,l=ar(e),n.metrics.fps={available:!1,reason:l},n.metrics.memory={available:!1,reason:l},n.metrics.cpu={available:!1,reason:l})),u}async function r5(e,t={}){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{fps:r6()},sampling:{fps:"android"===(a=r).device.platform?{method:R,description:e_,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}:P(a.device)}};return at(e)&&(e.appBundleId?await ae(n,e,e.appBundleId,t):n.metrics.fps={available:!1,reason:ar(e)}),n}async function r4(e,t){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,sampling:{memory:"android"===(a=r).device.platform?{method:eq,description:eP,unit:"kB",topConsumerLimit:5}:Y(a.device).memory,snapshot:"android"===r.device.platform?{method:J,description:j,defaultKind:"android-hprof",artifactOnly:!0}:{method:eR,description:u,defaultKind:"memgraph",artifactOnly:!0}}};if(!at(e)){if("snapshot"===t.action){let r=al(e,t.kind);return n.artifact=au(e,r),n.support=ad(n.artifact.support)??ap(e),n}return n.metrics={memory:{available:!1,reason:rN}},n}return"sample"===t.action?n.metrics={memory:await ai(e,t)}:(n.artifact=await as(e,t),n.support=ad(n.artifact.support)??ap(e)),n}function r6(){return{available:!1,reason:"Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions."}}async function r8(e,t,r,a){let n=await aa(t,r,a);r9(e,t,n)}async function r7(e,t,r){let a=await an(t,r);r9(e,t,a)}function r9(e,t,r){e.metrics.memory=af(r.memory),e.metrics.cpu=af(r.cpu),e.metrics.fps=am(af(r.fps),t)}async function ae(e,t,r,a){let n="android"===t.device.platform?await ac(eF(t.device,r,{adb:a.androidAdb})):await ac(g(t.device,r));e.metrics.fps=am(af(n),t)}function at(e){return"android"===e.device.platform||"ios"===e.device.platform||"macos"===e.device.platform}function ar(e){return"android"===e.device.platform?"No Android app package is associated with this session. Run open <app> first.":"No Apple app bundle ID is associated with this session. Run open <app> first."}async function aa(e,t,r){let a={adb:r.androidAdb},[n,i,o]=await Promise.allSettled([H(e.device,t,a),z(e.device,t,a),eF(e.device,t,a)]);return{memory:n,cpu:i,fps:o}}async function an(e,t){let r=await ac(g(e.device,t)),a=await ac(eU(e.device,t));if("fulfilled"===a.status){let e=a.value;return{memory:{status:"fulfilled",value:e.memory},cpu:{status:"fulfilled",value:e.cpu},fps:r}}return{memory:{status:"rejected",reason:a.reason},cpu:{status:"rejected",reason:a.reason},fps:r}}async function ai(e,t){return e.appBundleId?af("android"===e.device.platform?await ac(H(e.device,e.appBundleId,{adb:t.androidAdb})):await ac(ao(e))):{available:!1,reason:ar(e)}}async function ao(e){if(!e.appBundleId)throw new s("INVALID_ARGS",ar(e));return(await eU(e.device,e.appBundleId)).memory}async function as(e,t){if(!e.appBundleId)throw new s("INVALID_ARGS",ar(e),{hint:"Run open <app> first so perf memory snapshot can resolve the app process."});let a=al(e,t.kind),n=function(e,t){if(e.out)return ef.expandHome(e.out,e.cwd);let a=new Date().toISOString().replace(/[:.]/g,"-"),n=e.sessionStore.ensureSessionDir(e.sessionName);return r.join(n,"artifacts",`memory-${t}-${a}.${"android-hprof"===t?"hprof":"memgraph"===t?"memgraph":"artifact"}`)}(t,a);return"android"===e.device.platform?"android-hprof"!==a?au(e,a):await I(e.device,e.appBundleId,n,{adb:t.androidAdb}):"memgraph"!==a?au(e,a):await w(e.device,e.appBundleId,n)}function al(e,t){return t||("android"===e.device.platform?"android-hprof":"memgraph")}function au(e,t){var r,a;let n=ap(e),i=(r=e,a=t,"android"===r.device.platform?{reason:`Android perf memory snapshot supports android-hprof, not ${a}.`,hint:"Use perf memory snapshot --kind android-hprof for Android Java heap artifacts."}:"ios"===r.device.platform||"macos"===r.device.platform?{reason:`Apple perf memory snapshot supports memgraph, not ${a}.`,hint:"Use perf memory snapshot --kind memgraph for supported Apple app sessions."}:{reason:`Memory snapshot artifacts are not supported on ${r.device.platform}.`,hint:"Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS."});return{available:!1,kind:t,reason:i.reason,hint:i.hint,support:n}}function ap(e){return"android"===e.device.platform?{platform:e.device.platform,defaultKind:"android-hprof",androidHprof:!0,memgraph:!1,heapprofd:!1,heapprofdDecision:"Deferred until Android Perfetto/heapprofd plumbing is available in the perf trace slice."}:"ios"!==e.device.platform&&"macos"!==e.device.platform?{platform:e.device.platform,defaultKind:"memgraph",androidHprof:!1,memgraph:!1,heapprofd:!1,reason:"Memory snapshot artifacts are available only on Android, iOS simulator, and macOS.",hint:"Use perf memory sample where supported, or switch to a platform with memory artifact support.",heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}:{...eh(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}}function ad(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}async function ac(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function af(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=o(e.reason);return{available:!1,reason:t.message,error:t}}function am(e,t){var r,a;let n,i;if(!0!==e.available)return e;let o=(r=t.actions,n=ah((a=e).windowStartedAt),i=ah(a.windowEndedAt)??ah(a.measuredAt),void 0===n||void 0===i?[]:r.filter(e=>e.ts>=n&&e.ts<=i).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:function(e){let t=e.result;if(t)for(let e of["refLabel","ref","appName","appBundleId"]){let r=t[e];if("string"==typeof r&&r.length>0)return r}}(e)})).slice(-12));return 0===o.length?e:{...e,relatedActions:o}}function ah(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}async function ag(e){var t,r,a,n,i,s,l,u,p,d;let c,f,m,h,g,w,y=(t=e.req,r=e.area,c=(a=t,n=r,"string"==typeof a.flags?.out&&a.flags.out.length>0?a.flags.out:(a.positionals??[])["cpu"===n?5:4]||void 0),"cpu"===r?(i=t,s=c,f=aw(i,1),m=aw(i,2),h=aw(i,3),ej(f)?"start"!==(l=m)&&"stop"!==l&&"report"!==l?E("INVALID_ARGS","perf cpu profile action must be start, stop, or report"):"simpleperf"!==h?E("INVALID_ARGS","perf cpu profile requires --kind simpleperf"):{ok:!0,area:"cpu",subject:f,action:m,kind:h,outPath:s}:E("INVALID_ARGS",ta)):(u=t,p=c,g=aw(u,1),w=aw(u,2),"start"!==(d=g)&&"stop"!==d?E("INVALID_ARGS","perf trace action must be start or stop"):eY(w)?"perfetto"!==w?E("INVALID_ARGS","perf trace requires --kind perfetto"):{ok:!0,area:"trace",action:g,kind:w,outPath:p}:E("INVALID_ARGS",e5)));if(!y.ok)return y;let{session:v}=e;if("android"!==v.device.platform)return E("UNSUPPORTED_OPERATION","Android native perf collectors are supported only on Android sessions.");if(!v.appBundleId)return E("COMMAND_FAILED","No Android app package is associated with this session.",{hint:"Run open <app> first so perf can resolve the package and process identity."});try{let t="cpu"===y.area?await aA(e,v,v.appBundleId,y):await aS(e,v,v.appBundleId,y);return{ok:!0,data:t}}catch(e){return{ok:!1,error:o(e)}}}function aw(e,t){return(e.positionals?.[t]??"").toLowerCase()}function ay(e,t){var r;return e.sessionStore.set(e.sessionName,{...e.session,nativePerf:{android:t}}),{action:(r=t).action,platform:"android",type:r.type,kind:r.kind,packageName:r.packageName,appPid:r.appPid,profilerPid:r.profilerPid,state:r.state,startedAt:new Date(r.startedAt).toISOString(),stoppedAt:"number"==typeof r.stoppedAt?new Date(r.stoppedAt).toISOString():void 0,durationMs:r.durationMs,outPath:r.outPath,sizeBytes:r.sizeBytes,remotePath:r.remotePath,method:r.method,summary:r.summary,message:r.message}}function av(e,t,a){var n,i,o;let s;return t?ef.expandHome(t,e.req.meta?.cwd):(n=e.sessionStore,i=e.sessionName,o=a,s=new Date().toISOString().replace(/[:.]/g,"-"),r.join(n.ensureSessionDir(i),`${s}-${o}`))}async function aA(e,t,r,a){if("start"===a.action){aI(t);let n=av(e,a.outPath,"cpu.perf.data"),i=await l(t.device,r,n,{adb:e.androidAdbExecutor});return ay(e,i)}let n=a_(t,"cpu-profile",a.kind);if("report"===a.action){await function(e){if("running"===e.state)throw new s("COMMAND_FAILED","Stop the Android Simpleperf CPU profile before generating a report.",{hint:"Run perf cpu profile stop --kind simpleperf, then retry perf cpu profile report --kind simpleperf."})}(n);let r=av(e,a.outPath,"cpu-report.json");return await eC(t.device,n,r,{adb:e.androidAdbExecutor})}let i=ab(e,a.outPath,n),o=await ep(t.device,n,i,{adb:e.androidAdbExecutor});return ay(e,o)}async function aS(e,t,r,a){if("start"===a.action){aI(t);let n=av(e,a.outPath,"app.perfetto-trace"),i=await A(t.device,r,n,{adb:e.androidAdbExecutor});return ay(e,i)}let n=a_(t,"trace",a.kind),i=ab(e,a.outPath,n),o=await eg(t.device,n,i,{adb:e.androidAdbExecutor});return ay(e,o)}function aI(e){let t=e.nativePerf?.android;if(t?.state==="running")throw new s("COMMAND_FAILED",`Android ${t.kind} ${t.type} is already running for this session.`,{hint:"cpu-profile"===t.type?"Run perf cpu profile stop --kind simpleperf before starting another Android native perf capture.":"Run perf trace stop --kind perfetto before starting another Android native perf capture."})}function ab(e,t,r){return t?av(e,t,r.outPath):r.outPath}function a_(e,t,r){let a=e.nativePerf?.android;if(a?.type===t&&a.kind===r)return a;throw new s("COMMAND_FAILED",`No Android ${r} ${t} is active for this session.`,{hint:"cpu-profile"===t?"Run perf cpu profile start --kind simpleperf first, then stop or report in the same session.":"Run perf trace start --kind perfetto first, then stop in the same session."})}async function ak(e,t){let r,a,n=(r=e.req.positionals??[],"cpu"===(a=r[0]?.toLowerCase())?function(e){if(e[1]?.toLowerCase()!=="profile")return E("INVALID_ARGS","perf cpu requires profile");let t=aN(e[2],"perf cpu profile",!0);if(!t.ok)return t;let r=aD(e[3]);return r.ok?{ok:!0,area:"cpu",mode:"cpu-profile",action:t.value,kind:"xctrace",template:e[4]||void 0,outPath:e[5]||void 0,tracePath:e[6]||void 0}:r}(r):"trace"===a?function(e){let t=aN(e[1],"perf trace",!1);if(!t.ok)return t;let r=aD(e[2]);return r.ok?{ok:!0,area:"trace",mode:"trace",action:t.value,kind:"xctrace",template:e[3]||void 0,outPath:e[4]||void 0,tracePath:e[5]||void 0}:r}(r):E("INVALID_ARGS",eW));if(!n.ok)return n;if("android"===t.device.platform)return E("UNSUPPORTED_OPERATION","Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.");if("ios"!==t.device.platform&&"macos"!==t.device.platform)return E("UNSUPPORTED_OPERATION",`Apple xctrace perf is not supported on ${t.device.platform}.`);if(!t.appBundleId)return E("INVALID_ARGS","Apple xctrace perf requires an active app session. Run open <app> first.");try{if("start"===n.action)return await ax(e,t,n);if("stop"===n.action)return await aR(e,t,n);return await aM(e,t,n)}catch(e){return{ok:!1,error:o(e)}}}function aN(e,t,r){let a=e?.toLowerCase();return"start"===a||"stop"===a||r&&"report"===a?{ok:!0,value:a}:E("INVALID_ARGS",r?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function aD(e){return e?.toLowerCase()==="xctrace"?{ok:!0}:E("INVALID_ARGS","perf native collection currently supports --kind xctrace")}async function ax(e,t,r){if(t.applePerf?.active)return E("INVALID_ARGS","Apple xctrace perf capture already in progress");let a=r.template??("cpu-profile"===r.mode?"Time Profiler":"Animation Hitches"),n=aL(e,r),i=await X({device:t.device,appBundleId:t.appBundleId,mode:r.mode,template:a,outPath:n});t.applePerf={...t.applePerf??{},active:i},e.sessionStore.set(e.sessionName,t);let o=aO("started",i);return aP(e,t,o),{ok:!0,data:o}}async function aR(e,t,r){var a,n,o,s,l,u,p;let d,c=t.applePerf?.active;if(!c)return E("INVALID_ARGS","no active Apple xctrace perf capture");let f=r.outPath?ef.expandHome(r.outPath,e.req.meta?.cwd):c.outPath;try{d=await b(c,f)}catch(r){throw a=r,i(a).details?.captureCleanedUp===!0&&(n=e,(o=t).applePerf={...o.applePerf??{},active:void 0},n.sessionStore.set(n.sessionName,o)),r}s=e,l=t,u=d,l.applePerf={...l.applePerf??{},active:void 0,lastMode:u.mode,..."cpu-profile"===(p=u).mode?{lastProfileTracePath:p.outPath,lastProfileTemplate:p.template}:{lastTracePath:p.outPath}},s.sessionStore.set(s.sessionName,l);let m=aO("stopped",d);return aP(e,t,m),{ok:!0,data:m}}async function aM(e,t,r){var a;let n;if("cpu-profile"!==r.mode)return E("INVALID_ARGS","perf trace does not support report");if(t.applePerf?.active)return E("INVALID_ARGS","perf cpu profile report requires a stopped profile trace; stop the active capture first.");let i=aL(e,r),o=(a=t,(n=r.tracePath??a.applePerf?.lastProfileTracePath??a.applePerf?.active?.outPath)?{ok:!0,value:n}:E("INVALID_ARGS","perf cpu profile report requires a stopped profile trace or tracePath option"));if(!o.ok)return o;let s={perf:"reported",...await k({tracePath:ef.expandHome(o.value,e.req.meta?.cwd),outPath:i,mode:r.mode,template:t.applePerf?.lastProfileTemplate??r.template,appBundleId:t.appBundleId})};return aP(e,t,s),{ok:!0,data:s}}function aP(e,t,r){e.sessionStore.recordAction(t,{command:"perf",positionals:e.req.positionals??[],flags:e.req.flags??{},result:r})}function aL(e,t){if(t.outPath)return ef.expandHome(t.outPath,e.req.meta?.cwd);let r=e.sessionStore.ensureSessionDir(e.sessionName),a=new Date().toISOString().replace(/[:.]/g,"-"),n="report"===t.action?"json":"trace";return`${r}/perf-${t.mode}-${a}.${n}`}function aO(e,t){return{perf:e,kind:t.kind,mode:t.mode,template:t.template,outPath:t.outPath,appBundleId:t.appBundleId,deviceId:t.deviceId,platform:t.platform,targetPids:t.targetPids,targetProcesses:t.targetProcesses,startedAt:t.startedAt,endedAt:t.endedAt}}let aE=`logs requires ${e6.slice(0,-1).join(", ")}, or ${e6.at(-1)}`,aC=["dump","log"],a$=`network requires ${aC.join(" or ")}`,aV=`network include mode must be one of: ${t_.join(", ")}`,aU={path:({session:e,sessionName:t,sessionStore:r})=>(function(e,t,r){let a=r.resolveAppLogPath(t),n=G(a);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?.backend??eu(e.device),sizeBytes:n.sizeBytes,modifiedAt:n.modifiedAt,startedAt:e.appLog?.startedAt?new Date(e.appLog.startedAt).toISOString():void 0,hint:'Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>'}}})(e,t,r),doctor:({session:e,sessionName:t,sessionStore:r})=>aH(e,t,r),mark:({req:e,sessionName:t,sessionStore:r})=>{var a,n,i;let o,s;return a=e,n=t,i=r,o=a.positionals?.slice(1).join(" ")??"",f(s=i.resolveAppLogPath(n),o),{ok:!0,data:{path:s,marked:!0}}},clear:({session:e,sessionName:t,sessionStore:r,restart:a})=>aK(e,t,r,a),start:({session:e,sessionName:t,sessionStore:r})=>aj(e,t,r),stop:({session:e,sessionName:t,sessionStore:r})=>az(e,t,r)};async function aF(e){let{req:t}=e;return"perf"===t.command?aq(e):"logs"===t.command?aB(e):"network"===t.command?aW(e):null}async function aq(e){var t;let{req:r,sessionName:a,sessionStore:n,androidAdbExecutor:i}=e,l=n.get(a);if(!l)return E("SESSION_NOT_FOUND","perf requires an active session. Run open first.");let u=(r.positionals?.[0]??"metrics").toLowerCase();if("cpu"===(t=u)||"trace"===t)return"android"===l.device.platform?await ag({req:r,sessionName:a,sessionStore:n,session:l,androidAdbExecutor:i,area:u}):await ak(e,l);let p=function(e){var t,r,a,n,i,l,u,p,d,c;let f,m,h=e4(f=(e.positionals?.[0]??"metrics").toString().toLowerCase())?f:void 0;if(!h)return E("INVALID_ARGS",eW);if("cpu"===h||"trace"===h)return{ok:!0,native:!0};let g=eK(m=(e.positionals?.[1]??"sample").toString().toLowerCase())?m:void 0;if(!g)return E("INVALID_ARGS",eX);let w=function(e){if(void 0!==e)return"string"==typeof e&&eY(e)?e:new s("INVALID_ARGS",e5)}(e.flags?.kind);if(w instanceof s)return{ok:!1,error:o(w)};let y=(t=h,r=g,("memory"===t?aT(r)?void 0:E("INVALID_ARGS","perf memory requires sample or snapshot"):"sample"!==r?E("INVALID_ARGS","perf metrics and perf frames only support sample"):void 0)??(a=e,n=h,i=g,l=w,function(e,t,r){if(e&&("memory"!==t||"snapshot"!==r))return E("INVALID_ARGS","--out is only supported with perf memory snapshot")}(a.flags?.out,n,i)??(u=l,p=n,d=i,u?"memory"!==p||"snapshot"!==d?E("INVALID_ARGS","--kind is only supported with perf memory snapshot"):eZ(u)?void 0:E("INVALID_ARGS",e2):void 0)));return y||{ok:!0,native:!1,area:h,action:g,kind:w,out:"string"==typeof(c=e.flags?.out)&&c.length>0?c:void 0}}(r);if(!p.ok)return p;if(p.native)return await ak(e,l);try{return{ok:!0,data:await aG(e,l,p)}}catch(e){return{ok:!1,error:o(e)}}}async function aG(e,t,r){let{sessionName:a,sessionStore:n,androidAdbExecutor:i}=e;return"memory"===r.area?await r4(t,{action:function(e){if(aT(e))return e;throw new s("INVALID_ARGS","perf memory requires sample or snapshot")}(r.action),kind:r.kind,out:r.out,cwd:e.req.meta?.cwd,sessionName:a,sessionStore:n,androidAdb:i}):"frames"===r.area?await r5(t,{androidAdb:i}):await r2(t,{androidAdb:i})}function aT(e){return"sample"===e||"snapshot"===e}async function aB(e){var t;let r,a,{req:n,sessionName:i,sessionStore:o}=e,s=o.get(i);if(!s)return E("SESSION_NOT_FOUND","logs requires an active session");if(!eV("logs",s.device))return E("UNSUPPORTED_OPERATION","logs is not supported on this device");let l=(t=n,r=(t.positionals?.[0]??"path").toLowerCase(),a=!!t.flags?.restart,e6.includes(r)?a&&"clear"!==r?E("INVALID_ARGS","logs --restart is only supported with logs clear"):{ok:!0,action:r,restart:a}:E("INVALID_ARGS",aE));return l.ok?await aU[l.action]({...e,session:s,restart:l.restart}):l}async function aH(e,t,r){let a=r.resolveAppLogPath(t),n=await eA(e.device,e.appBundleId);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:n.checks,notes:n.notes}}}async function aK(e,t,r,a){if(e.appLog&&!a)return E("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");let n=r.resolveAppLogPath(t);if(!a)return{ok:!0,data:Q(n)};let i=e.appBundleId;if(!i)return E("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");e.appLog&&await eD(e.appLog);let s=Q(n),l=r.resolveAppLogPidPath(t);try{let a=await eB(e.device,i,n,l);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:a.backend,outPath:n,startedAt:a.startedAt,getState:a.getState,stop:a.stop,wait:a.wait}}),{ok:!0,data:{...s,restarted:!0}}}catch(a){return r.set(t,{...e,appLog:void 0}),{ok:!1,error:o(a)}}}async function aj(e,t,r){if(e.appLog)return E("INVALID_ARGS","app log already streaming; run logs stop first");if(!e.appBundleId)return E("INVALID_ARGS","logs start requires an app session; run open <app> first");let a=r.resolveAppLogPath(t),n=r.resolveAppLogPidPath(t);try{let i=await eB(e.device,e.appBundleId,a,n);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:i.backend,outPath:a,startedAt:i.startedAt,getState:i.getState,stop:i.stop,wait:i.wait}}),{ok:!0,data:{path:a,started:!0}}}catch(e){return{ok:!1,error:o(e)}}}async function az(e,t,r){if(!e.appLog)return E("INVALID_ARGS","no app log stream active");let a=e.appLog.outPath;return await eD(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:a,stopped:!0}}}async function aW(e){let t=function(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);if(!n)return E("SESSION_NOT_FOUND","network requires an active session");if(!eV("network",n.device))return E("UNSUPPORTED_OPERATION","network is not supported on this device");let i=(t.positionals?.[0]??"dump").toLowerCase();if(!aC.includes(i))return E("INVALID_ARGS",a$);let o=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(o)||o<1||o>200)return E("INVALID_ARGS","network dump limit must be an integer in range 1..200");let s=function(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return E("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let a=(r??t??"summary").toLowerCase();return t_.includes(a)?{ok:!0,include:a}:E("INVALID_ARGS",aV)}(t);return s.ok?{ok:!0,session:n,maxEntries:o,include:s.include}:s}(e);if(!t.ok)return t;let{include:r,maxEntries:a,session:n}=t;if("web"===n.device.platform)return await aJ({include:r,maxEntries:a});let i=await ea({device:n.device,appBundleId:n.appBundleId,appLogState:n.appLog?.getState(),appLogStartedAt:n.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:a,include:r,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...i.dump,active:!!n.appLog,state:n.appLog?.getState()??"inactive",backend:i.backend,notes:i.notes}}}async function aJ(e){let t=tb();if(!t.dumpNetwork)return E("UNSUPPORTED_OPERATION","network is not supported by this web provider");try{let r=await t.dumpNetwork({include:e.include,limit:e.maxEntries});return{ok:!0,data:{entries:r.entries,active:!0,state:"active",backend:r.backend??"agent-browser",include:e.include,matchedLines:r.entries.length,scannedLines:r.entries.length,limits:{maxEntries:e.maxEntries,maxPayloadChars:2048,maxScanLines:r.entries.length},notes:r.notes}}}catch(e){return{ok:!1,error:o(e)}}}function aX(e,t,r){var a,n;if(null==e)return tV("open",[tG(tF(t,"launchApp"),r)]);if("string"==typeof e)return tV("open",[tG(e,r)]);if(!tU(e))throw new s("INVALID_ARGS","launchApp expects a string or map.");tq(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),a0(e,"permissions"),a0(e,"clearKeychain");let i=tG("string"==typeof e.appId?e.appId:tF(t,"launchApp"),r),o=(a=e,n=r,[...aZ(a.arguments,"launchApp.arguments",n),...aZ(a.launchArguments,"launchApp.launchArguments",n)]),l=!0===e.clearState;return tV("open",[i],{...!l&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...l?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function aY(e,t,r){if(null==e)return tV("close",[tG(tF(t,"stopApp"),r)]);if("string"==typeof e)return tV("close",[tG(e,r)]);throw new s("INVALID_ARGS","stopApp expects a string appId or no value.")}function aZ(e,t,r){if(null==e)return[];if("string"==typeof e)return[tG(e,r)];if(Array.isArray(e))return e.map((e,a)=>aQ(e,`${t}[${a}]`,r));if(tU(e))return Object.entries(e).flatMap(([e,a])=>[tG(e,r),aQ(a,`${t}.${e}`,r)]);throw new s("INVALID_ARGS",`${t} expects a string, list, or map.`)}function aQ(e,t,r){if("string"==typeof e)return tG(e,r);if("number"==typeof e||"boolean"==typeof e)return String(e);throw new s("INVALID_ARGS",`${t} must be a string, number, or boolean.`)}function a0(e,t){if(void 0!==e[t])throw tH(`Maestro launchApp field "${t}" is not supported yet.`)}let a1="__maestroRunScript",a3="__maestroAssertVisible",a2="__maestroAssertNotVisible",a5="__maestroPressEnter",a4="__maestroWaitForAnimationToEnd",a6="__maestroScrollUntilVisible",a8="__maestroSwipeScreen",a7="__maestroSwipeOn",a9="__maestroTapOn",ne="__maestroTapPointPercent";function nt(e){if(null==e)return tV("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return tV("type",["\b".repeat(e)]);if(!tU(e))throw new s("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(tq(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return tV("type",["\b".repeat(50)]);if("number"!=typeof e.charactersToErase||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new s("INVALID_ARGS","eraseText.charactersToErase must be a positive integer.");return tV("type",["\b".repeat(e.charactersToErase)])}function nr(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function na(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw tH(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function nn(e){return na(e,"swipe direction")}function ni(e,t,r=[],a){if("string"==typeof e)return no(tG(e,a));if(!tU(e))throw new s("INVALID_ARGS",`${t} expects a string or selector map.`);tq(e,t,["id","text","enabled","selected",...r]);let n=[],i=[];if("boolean"==typeof e.enabled&&i.push(nl("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(nl("selected",String(e.selected))),"string"==typeof e.id&&n.push(nl("id",tG(e.id,a)),...i),"string"==typeof e.text&&0===n.length)return no(tG(e.text,a),i);if("string"==typeof e.label&&0===n.length&&n.push(nl("label",tG(e.label,a)),...i),0===n.length&&i.length>0&&n.push(...i),0===n.length)throw new s("INVALID_ARGS",`${t} selector map must include one of id, text, label, enabled, or selected.`);return n.join(" ")}function no(e,t=[]){return[[nl("label",e),...t].join(" "),[nl("text",e),...t].join(" "),[nl("id",e),...t].join(" ")].join(" || ")}function ns(e){let t=nr(e.duration);return t?[t]:[]}function nl(e,t){return`${e}=${JSON.stringify(t)}`}function nu(e){var t,r;if(!tU(e))return;let a={},n="number"==typeof(t=e.repeat)&&Number.isInteger(t)&&t>0?t:void 0,i="number"==typeof(r=e.delay)&&Number.isInteger(r)&&r>=0?r:void 0;return n&&n>1&&(a.count=n),void 0!==i&&(a.intervalMs=i),!0===e.optional&&(a.maestro={optional:!0}),Object.keys(a).length>0?a:void 0}function np(e){let t=nu(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function nd(e){let t={doubleTap:!0};return tU(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class nc{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new s("INVALID_ARGS","Unsupported trailing runFlow.when.true expression.");return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator("||");)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator("&&");)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new s("INVALID_ARGS","Incomplete runFlow.when.true expression.");if("boolean"===e.type)return this.index+=1,e.value;if("paren"===e.type&&"("===e.value){this.index+=1;let e=this.parseOr();if(!this.consumeParen(")"))throw new s("INVALID_ARGS","Unclosed runFlow.when.true parenthesis.");return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),r=this.context.platform;return"=="===e?r===t:r!==t}expectPlatform(){if(this.peek()?.type!=="platform")throw new s("INVALID_ARGS","runFlow.when.true supports maestro.platform comparisons.");this.index+=1}expectEqualityOperator(){let e=this.peek();if(e?.type==="operator"&&("=="===e.value||"!="===e.value))return this.index+=1,e.value;throw new s("INVALID_ARGS","runFlow.when.true comparison requires == or !=.")}expectString(){let e=this.peek();if(e?.type==="string")return this.index+=1,e.value;throw new s("INVALID_ARGS","runFlow.when.true comparison requires a string literal.")}consumeOperator(e){let t=this.peek();return t?.type==="operator"&&t.value===e&&(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type==="paren"&&t.value===e&&(this.index+=1,!0)}peek(){return this.tokens[this.index]}}function nf(e,t,r){return{...tV(e,t),replayControl:r}}function nm(e,t,r){let a="string"==typeof e?tG(e,t):e,n="number"==typeof a?a:"string"==typeof a&&/^\d+$/.test(a)?Number(a):void 0;if(void 0===n||!Number.isInteger(n)||n<0)throw new s("INVALID_ARGS",`${r} must be a non-negative integer or \${VAR} resolving to one.`);return n}let nh=`
|
|
1
|
+
import{__webpack_require__ as e}from"./rslib-runtime.js";import t from"node:fs";import r from"node:path";import a from"node:vm";import{setTimeout as n}from"node:timers/promises";import{asAppError as i,normalizeError as o,AppError as s}from"./733.js";import{startAndroidSimpleperfProfile as l,APPLE_MEMGRAPH_SNAPSHOT_DESCRIPTION as u,dispatchCommand as p,sessionMatchesScope as d,selectorTargetsSessionDevice as c,appendAppLogMarker as f,resolveCommandDevice as m,hasRuntimeTransportHints as h,sampleAppleFramePerf as g,captureAppleMemorySnapshot as w,getSessionCommandKind as y,inferFillText as v,startAndroidPerfettoTrace as A,stopIosRunnerSession as S,captureAndroidHeapSnapshot as I,stopAppleXctracePerfCapture as b,resolvePublicSessionName as _,writeAppleXctracePerfReport as k,requireSessionOrExplicitSelector as N,cleanupUploadedArtifact as D,resolveSessionRequestLogPath as x,ANDROID_FRAME_SAMPLE_METHOD as R,refreshSessionDeviceIfNeeded as M,buildAppleFrameSamplingMetadata as P,createRequestCanceledError as L,registerRequestAbort as O,errorResponse as E,settleIosSimulator as C,readReplayTestActionProgress as $,buildSessionRecoveryHint as V,applyRuntimeHintsToApp as U,withKeyedLock as F,resolveTargetDevice as q,getAppLogPathMetadata as G,uniqueStrings as T,setSessionSnapshot as B,sampleAndroidMemoryPerf as H,shutdownDeviceTarget as K,ANDROID_HPROF_SNAPSHOT_DESCRIPTION as j,sampleAndroidCpuPerf as z,clearRuntimeHintsFromApp as W,ANDROID_HPROF_SNAPSHOT_METHOD as J,startAppleXctracePerfCapture as X,buildAppleSamplingMetadata as Y,getSnapshotReferenceFrame as Z,clearAppLogFiles as Q,handleCloseCommand as ee,prepareIosRunner as et,session_device_utils_hasExplicitSessionFlag as er,readSessionNetworkCapture as ea,cleanupRetainedMaterializedPaths as en,isImplicitSessionScopeConflict as ei,resolveSessionRunnerLogPath as eo,ANDROID_CPU_SAMPLE_DESCRIPTION as es,buildSnapshotState as el,resolveLogBackend as eu,stopAndroidSimpleperfProfile as ep,context_contextFromFlags as ed,listDeviceInventory as ec,SessionStore as ef,ANDROID_CPU_SAMPLE_METHOD as em,buildAppleMemorySnapshotSupport as eh,stopAndroidPerfettoTrace as eg,isRequestCanceled as ew,resolveRequestTrackingId as ey,retainMaterializedPaths as ev,runAppLogDoctor as eA,resolvePayloadInput as eS,prepareUploadedArtifact as eI,resetAndroidFramePerfStats as eb,ANDROID_FRAME_SAMPLE_DESCRIPTION as e_,withReplayTestActionProgress as ek,markRequestCanceled as eN,stopAppLog as eD,resolveImplicitSessionScope as ex,APPLE_MEMGRAPH_SNAPSHOT_METHOD as eR,ensureDeviceReady as eM,ANDROID_MEMORY_SAMPLE_DESCRIPTION as eP,prewarmIosRunnerSession as eL,clearRequestCanceled as eO,resolveAndroidEmulatorAvdName as eE,writeAndroidSimpleperfReport as eC,resolveFrontmostMacOsApp as e$,isCommandSupportedOnDevice as eV,sampleApplePerfMetrics as eU,sampleAndroidFramePerf as eF,ANDROID_MEMORY_SAMPLE_METHOD as eq,getRequestSignal as eG,markAndroidSnapshotFreshness as eT,startAppLog as eB,emitRequestProgress as eH}from"./9722.js";import{isPerfAction as eK,isPerfSubject as ej,pointFromPercent as ez,PERF_AREA_ERROR_MESSAGE as eW,buildSwipeGesturePlan as eJ,PERF_ACTION_ERROR_MESSAGE as eX,isPerfKind as eY,isPerfMemoryKind as eZ,pointInsideRect as eQ,successText as e0,clampGesturePoint as e1,resolveDeployResultTarget as e3,PERF_MEMORY_KIND_ERROR_MESSAGE as e2,PERF_KIND_ERROR_MESSAGE as e5,isPerfArea as e4,LOG_ACTION_VALUES as e6,withSuccessText as e8,clampToRange as e7,parseSessionSurface as e9,resolveInstallFromSourceResultTarget as te,readReactNativeOverlayActionNodes as tt,detectReactNativeOverlay as tr,PERF_SUBJECT_ERROR_MESSAGE as ta}from"./9873.js";import{isApplePlatform as tn,resolveAppleSimulatorSetPathForSelector as ti,normalizePlatformSelector as to,matchesPlatformSelector as ts}from"./5910.js";import{resolveIosSimulatorDeviceSetPath as tl,classifyAndroidAppTarget as tu,resolveIosDeviceDeepLinkBundleId as tp,isInfrastructureBootFailureReason as td,isWebUrl as tc,resolveAndroidSerialAllowlist as tf,isDeepLinkTarget as tm,formatAndroidInstalledPackageRequiredMessage as th,listAndroidApps as tg}from"./3340.js";import{getDiagnosticsMeta as tw,emitDiagnostic as ty}from"./432.js";import{runBatch as tv,mergeParentFlags as tA}from"./6918.js";import{assertResolvedAppsFilter as tS}from"./2748.js";import{listIosApps as tI}from"./apps.js";import{resolveWebProvider as tb}from"./provider.js";import{NETWORK_INCLUDE_MODES as t_}from"./4291.js";import{unsupportedCommand as tk,readEnvMap as tN,parseReplayScriptDetailed as tD,readReplayShellEnvSource as tx,normalizeCommandList as tR,normalizePlatform as tM,readReplayCliEnvEntries as tP,parseMaestroYamlDocuments as tL,parseAbsolutePoint as tO,readReplayScriptMetadata as tE,parseReplayCliEnvEntries as tC,collectReplayShellEnv as t$,support_action as tV,isPlainRecord as tU,requireAppId as tF,assertOnlyKeys as tq,resolveMaestroString as tG,requireStringValue as tT,parseMaestroPoint as tB,unsupportedMaestroSyntax as tH,readTimeoutMs as tK,writeReplayScript as tj,buildReplayVarScope as tz,resolveReplayAction as tW,mergeReplayVarScopeValues as tJ}from"./4428.js";import{runCmdSync as tX}from"./8875.js";import{readSnapshotDiagnosticsSummary as tY,summarizeSnapshotTimingSamples as tZ,mergeSnapshotDiagnostics as tQ}from"./8358.js";import{splitSelectorFromArgs as t0,extractNodeText as t1,findSnapshotAncestor as t3,isDescendantOfSnapshotNode as t2,parseSelectorChain as t5,tryParseSelectorChain as t4,splitIsSelectorArgs as t6,resolveSelectorChain as t8,buildSelectorChainForNode as t7,buildSnapshotNodeByIndex as t9,matchesSelector as re,normalizeType as rt}from"./9836.js";import{formatScriptActionSummary as rr,evaluateIsPredicate as ra,isTouchTargetCommand as rn}from"./2577.js";import{normalizeText as ri}from"./587.js";import{sleep as ro}from"./5560.js";import{buildSnapshotDisplayLines as rs}from"./7244.js";import{handleRecordCommand as rl}from"./record-trace-recording.js";import{INTERNAL_COMMANDS as ru,PUBLIC_COMMANDS as rp}from"./2133.js";import{trimRuntimeValue as rd}from"./5628.js";var rc={};async function rf(e){var t;let r="ios"===(t=e.flags?.platform)||"android"===t?t:void 0;if(e.session){if(r&&e.session.device.platform!==r)throw new s("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await eM(e.session.device),e.session.device}if(!r)throw new s("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let a=await q(e.flags??{});return await eM(a),a}async function rm(e){let{prepared:t,retention:r,req:a,session:n,sessionName:i}=e;if(r.enabled)return await ev({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:a.meta?.tenantId,sessionName:n?i:void 0,ttlMs:r.ttlMs})}function rh(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function rg(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);try{let e,i,o=(e=function(e){let t=e.meta?.installSource;if(!t)throw new s("INVALID_ARGS","install_from_source requires a source payload");switch(t.kind){case"url":if(!t.url||0===t.url.trim().length)throw new s("INVALID_ARGS","install_from_source url source requires a non-empty url");return t;case"path":if(!t.path||0===t.path.trim().length)throw new s("INVALID_ARGS","install_from_source path source requires a non-empty path");return t;case"github-actions-artifact":throw new s("UNSUPPORTED_OPERATION","install_from_source github-actions-artifact sources require a compatible remote daemon");default:throw new s("UNSUPPORTED_OPERATION",`install_from_source ${String(t.kind)} sources require a compatible remote daemon`)}}(t),(i=t.meta?.uploadedArtifactId)&&"path"===e.kind?{source:{kind:"path",path:eI(i,t.meta?.tenantId)},cleanup:()=>{D(i)}}:{source:e,cleanup:()=>{}}),l=function(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(void 0!==r&&r<=0)throw new s("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),u=await rf({session:n,flags:t.flags});if(!eV("install",u))return E("UNSUPPORTED_OPERATION","install_from_source is not supported on this device");let p=eG(t.meta?.requestId),d=async(e,i)=>{let s;try{var u;s=await rm({prepared:e,retention:l,req:t,session:n,sessionName:r});let o=await i(s),p=e8(o,(u=o,`Installed: ${te(u)}`));return!function(e){let{session:t,sessionStore:r,req:a,data:n}=e;t&&r.recordAction(t,{command:"install_source",positionals:[],flags:a.flags??{},result:n})}({session:n,sessionStore:a,req:t,data:p}),{ok:!0,data:p}}catch(e){throw s&&await en(s.materializationId,t.meta?.tenantId).catch(()=>{}),e}finally{await e.cleanup(),o.cleanup()}};if("ios"===u.platform){let{installIosInstallablePath:e}=await import("./apps.js"),{prepareIosInstallArtifact:t}=await import("./apps.js"),r=await t(o.source,{signal:p});return await d(r,async t=>{if(await e(u,r.installablePath),!r.bundleId)throw new s("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact");return{...rh(t),bundleId:r.bundleId,...r.appName?{appName:r.appName}:{},launchTarget:r.bundleId}})}let{prepareAndroidInstallArtifact:c}=await import("./3340.js"),{installAndroidInstallablePathAndResolvePackageName:f}=await import("./3340.js"),m=await c(o.source,{signal:p});return await d(m,async e=>{let t=await f(u,m.installablePath,m.packageName);if(!t)throw new s("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");let{inferAndroidAppName:r}=await import("./3340.js"),a=r(t);return{...rh(e),packageName:t,...a?{appName:a}:{},launchTarget:t}})}catch(e){return{ok:!1,error:o(e)}}}async function rw(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new s("INVALID_ARGS","release_materialized_paths requires a materializationId");return await en(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:o(e)}}}e.r(rc),e.d(rc,{handleSessionCommands:()=>oV});let ry=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function rv(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function rA(e,t){if(void 0!==e){if("string"!=typeof e)throw new s("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return rd(e)}}function rS(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new s("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function rI(e){if("ios"===e||"android"===e)return e}async function rb(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:a,session:n}=e;!t||!n?.appBundleId||!h(r)||h(a)||await W({device:n.device,appId:n.appBundleId})}async function r_(e){var t,r;let{req:a,sessionName:n,sessionStore:i}=e,o=(a.positionals?.[0]??"show").toLowerCase(),s=i.get(n),l=i.getRuntimeHints(n);if(!["set","show","clear"].includes(o))return E("INVALID_ARGS","runtime requires set, show, or clear");if("clear"===o){h(l)&&s?.appBundleId&&await W({device:s.device,appId:s.appBundleId});let e=i.clearRuntimeHints(n);return{ok:!0,data:{session:n,cleared:e}}}if("show"===o)return{ok:!0,data:{session:n,configured:!!l,runtime:l}};let u=rI(to(a.flags?.platform)??l?.platform??s?.device.platform);if(!u)return E("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(s&&s.device.platform!==u)return E("INVALID_ARGS",`runtime set targets ${u}, but session "${n}" is already bound to ${s.device.platform}.`);let p={platform:(t=a.flags,r={platform:u,metroHost:rd(t?.metroHost),metroPort:rS(t?.metroPort),bundleUrl:rd(t?.bundleUrl),launchUrl:rd(t?.launchUrl)}).platform??l?.platform,metroHost:r.metroHost??l?.metroHost,metroPort:r.metroPort??l?.metroPort,bundleUrl:r.bundleUrl??l?.bundleUrl,launchUrl:r.launchUrl??l?.launchUrl};return 0===rv(p)?E("INVALID_ARGS","runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."):(i.setRuntimeHints(n,p),{ok:!0,data:{session:n,configured:!0,runtime:p}})}let rk="open-command-roundtrip",rN="Not implemented for this platform in this release.";function rD(e){let{existingSession:t,sessionName:r,sessionScope:a,device:n,surface:i,appBundleId:o,appName:s,saveScript:l}=e;return t?{...t,device:n,surface:i,appBundleId:o,appName:s,recordSession:t.recordSession||l,snapshot:void 0}:{name:r,sessionScope:a,device:n,createdAt:Date.now(),surface:i,appBundleId:o,appName:s,recordSession:l,actions:[]}}let rx=new Set(["app","desktop","frontmost-app"]);async function rR(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await e$();return{appBundleId:t.bundleId,appName:t.appName}}async function rM(e,t,r){if(("ios"===e.platform||"macos"===e.platform)&&t)return tm(t)?"macos"===e.platform?void 0:"device"===e.kind?tp(r,t):tc(t)?void 0:r??await rP(e,t):await rL(e,t)}async function rP(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rL(e,t){try{let{resolveIosApp:r}=await import("./apps.js");return await r(e,t)}catch{return}}async function rO(e,t){if(!("android"!==e.platform||!t||tm(t)))try{let{resolveAndroidApp:r}=await import("./3340.js"),a=await r(e,t);return"package"===a.type?a.value:void 0}catch{return}}async function rE(e,t,r){if(r||"android"!==e.platform||!t||!tm(t))return r;try{let{getAndroidAppState:t}=await import("./3340.js"),a=await t(e);return a.package?.trim()||r}catch{return r}}async function rC(e,t,r,a){return await rM(e,t,r)??await a(e,t)??("android"===e.platform&&t&&tm(t)?r:void 0)}function r$(e){return E("INVALID_ARGS",e)}function rV(e,t,r,a){try{return function(e){let{device:t,surfaceFlag:r,openTarget:a,existingSurface:n}=e;if(("macos"===t.platform||"linux"===t.platform)&&!r)return n??"app";if("linux"===t.platform){if(!r)return"app";let e=e9(r);if(!rx.has(e))throw new s("INVALID_ARGS",`Linux supports --surface app, desktop, and frontmost-app (got "${r}")`);if("app"!==e&&a)throw new s("INVALID_ARGS",`open --surface ${e} does not accept an app target`);return e}if("macos"!==t.platform){if(r)throw new s("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let i=r?e9(r):"app";if("app"!==i&&"menubar"!==i&&a)throw new s("INVALID_ARGS",`open --surface ${i} does not accept an app target`);return i}({device:e,surfaceFlag:t,openTarget:r,existingSurface:a})}catch(e){return E(e instanceof s?e.code:"INVALID_ARGS",String(e.message))}}function rU(e){let{shouldRelaunch:t,openTarget:r,surface:a,device:n}=e;return t?r&&tm(r)?r$("open --relaunch does not support URL targets."):"app"!==a?r$("open --relaunch is supported only for app surfaces."):"android"===n.platform&&r&&"binary"===tu(r)?r$(th(r)):null:null}async function rF(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:o,openTarget:l,existingSession:u}=e;await eM(n,{deviceHub:t.flags?.deviceHub===!0});let{appBundleId:p,appName:d}=await rq({device:n,surface:o,openTarget:l,existingAppBundleId:u?.appBundleId}),c=function(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:a,device:n}=e,i=r.getRuntimeHints(a),o=function(e){let{runtime:t,sessionName:r,platform:a}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new s("INVALID_ARGS","open runtime must be an object.");let n=Object.keys(t).find(e=>!ry.includes(e));if(n)throw new s("INVALID_ARGS",`Invalid open runtime field: ${n}. Supported fields are ${ry.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new s("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new s("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,a),metroHost:rA(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new s("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return rS(e)}}(t.metroPort),bundleUrl:rA(t.bundleUrl,"bundleUrl"),launchUrl:rA(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:a,platform:rI(n.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let a=e.getRuntimeHints(t);if(!a)return;let n=r?.platform,i=rI(n);if(a.platform&&r&&!i)throw new s("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${n}.`);if(a.platform&&i&&a.platform!==i)throw new s("INVALID_ARGS",`Session runtime hints target ${a.platform}, but session "${t}" is bound to ${n}. Clear the runtime hints or use a different session.`);return i&&a.platform!==i?{...a,platform:i}:a}(r,a,n),previousRuntime:i,replacedStoredRuntime:!1}:{runtime:o&&rv(o)>0?o:void 0,previousRuntime:i,replacedStoredRuntime:!0}}(e)}}catch(t){let e=i(t);return E(e.code,e.message,e.details)}}({req:t,sessionStore:a,sessionName:r,device:n});if(!c.ok)return{type:"response",response:c};if(u){let{runtime:e,previousRuntime:t,replacedStoredRuntime:r}=c.data;await rb({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:u})}return{type:"details",details:{appBundleId:p,appName:d,runtime:c.data.runtime}}}async function rq(e){let{device:t,surface:r,openTarget:a,existingAppBundleId:n}=e,i=await rR(r);return{appBundleId:i.appBundleId??await rC(t,a,n,rO),appName:i.appName??a}}let rG=new Map;async function rT(e){let{device:t,closeTarget:r,outFlag:a,context:n}=e;"android"!==t.platform&&await S(t.id),await p(t,"close",[r],a,n),await C(t,300)}async function rB(e){var t,r;let a,{runtime:n,device:i,req:o,logPath:s,appBundleId:l,traceLogPath:u,openPositionals:d}=e,c=n?.launchUrl;if(!c||0===d.length||d.length>1)return;let f=d[0]?.trim();!f||tm(f)||await p(i,"open",[c],o.flags?.out,{...(t=s,r=o.flags,a=ed(t,r,l,u),delete a.launchConsole,delete a.launchArgs,a)})}async function rH(e){var t,r,a,n;let i,{req:o,sessionName:s,sessionStore:l,logPath:u,device:d,openTarget:c,openPositionals:f,appName:m,surface:h,appBundleId:g,runtime:w,existingSession:y}=e,v=o.flags?.relaunch===!0,A=y?.trace?.outPath,S=g,I=Date.now(),b={};if(v&&c){let e=S??c,t=Date.now();await rT({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...ed(u,o.flags,S??y?.appBundleId,A)}}),b.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let k=Date.now();await U({device:d,appId:S,runtime:w}),b.runtimeHintsDurationMs=Math.max(0,Date.now()-k);let N="ios"===d.platform&&"app"===h&&f.length>0,D={verbose:o.flags?.verbose,logPath:u,traceLogPath:A,requestId:o.meta?.requestId,iosXctestrunFile:o.flags?.iosXctestrunFile,iosXctestDerivedDataPath:o.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:o.flags?.iosXctestEnvDir},R=o.flags?.maestro?.prewarmRunnerBeforeOpen===!0;if(N&&S&&(b.runnerPrewarmKind="session",b.runnerPrewarmScheduled=!0,R)){i=eL(d,{...D,propagateError:!0});let e=Date.now();await i,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}let M=Date.now(),P=await rK({req:o,sessionName:s,sessionStore:l,device:d,surface:h,sessionAppBundleId:S,appName:m,existingSession:y});if("response"===P.type)return P.response;let O=P.session??y;await p(d,"open",f,o.flags?.out,{...ed(u,o.flags,S)}),b.openDispatchDurationMs=Math.max(0,Date.now()-M);let $=Date.now();if(await rB({runtime:w,device:d,req:o,logPath:u,appBundleId:S,traceLogPath:A,openPositionals:f}),b.launchUrlDurationMs=Math.max(0,Date.now()-$),N&&S&&!i&&(i=eL(d,D)),v&&i&&!0!==b.runnerPrewarmWaited){let e=Date.now();await i,b.runnerPrewarmWaited=!0,b.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}else i&&!0!==b.runnerPrewarmWaited&&(b.runnerPrewarmWaited=!1);S=await rE(d,c,S),"android"===d.platform&&S&&await eb(d,S);let V=c?(t=S,{durationMs:Math.max(0,Date.now()-M),measuredAt:new Date().toISOString(),method:rk,appTarget:c,appBundleId:t}):void 0,F=Date.now();if(await C(d,300),b.postOpenSettleDurationMs=Math.max(0,Date.now()-F),ew(o.meta?.requestId)){let e=L();return E(e.code,e.message,e.details)}y&&eT(y,"open",y.snapshot);let q=rD({existingSession:O,sessionName:y?.name??_(o),sessionScope:y?.sessionScope??ex(o),device:d,surface:h,appBundleId:S,appName:m,saveScript:!!o.flags?.saveScript});void 0!==o.runtime&&(r=l,a=s,(n=w)&&(0===rv(n)?r.clearRuntimeHints(a):r.setRuntimeHints(a,n)));let G=l.ensureSessionDir(s),T=x(G,o.meta?.requestId??tw().requestId);b.totalDurationMs=Math.max(0,Date.now()-I);let B=function(e){let{sessionName:t,sessionStateDir:r,runnerLogPath:a,requestLogPath:n,appName:i,appBundleId:o,surface:s,startup:l,timing:u,device:p,runtime:d,runtimeHintCount:c}=e,f={session:t,surface:s,sessionStateDir:r,runnerLogPath:a,requestLogPath:n};return i&&(f.appName=i),o&&(f.appBundleId=o),l&&(f.startup=l),u&&(f.timing=u),d&&c(d)>0&&(f.runtime=d),p&&(f.platform=p.platform,f.target=p.target??"mobile",f.device=p.name,f.id=p.id,f.kind=p.kind,"android"===p.platform&&(f.serial=p.id)),p?.platform==="ios"&&(f.device_udid=p.id,f.ios_simulator_device_set=p.simulatorSetPath??null),{...f,...e0(`Opened: ${i??o??t}`)}}({sessionName:q.name,sessionStateDir:G,runnerLogPath:eo(G),requestLogPath:T,appName:m,appBundleId:S,surface:h,startup:V,timing:b,device:d,runtime:w,runtimeHintCount:rv});return l.recordAction(q,{command:"open",positionals:f,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:B}),l.set(s,q),{ok:!0,data:B}}async function rK(e){let{req:t,sessionName:r,sessionStore:a,device:n,surface:i,sessionAppBundleId:o,appName:s,existingSession:l}=e,u=t.internal?.openLifecycle?.beforeDispatch;if(!u)return{type:"session",session:l};let p=rD({existingSession:l,sessionName:l?.name??_(t),sessionScope:l?.sessionScope??ex(t),device:n,surface:i,appBundleId:o,appName:s,saveScript:!!t.flags?.saveScript});a.set(r,p);let d=await u(p);return d&&!d.ok?{type:"response",response:d}:{type:"session",session:a.get(r)??p}}async function rj(e){let{req:t,sessionName:r,logPath:a,sessionStore:n}=e,i=n.get(r);if(i){let e=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(e?i.appName:void 0),l=rV(i.device,t.flags?.surface,s,i.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return e?r$("open --relaunch requires an app name or an active session app."):r$("Session already active. Close it first or pass a new --session name.");let u=rU({shouldRelaunch:e,openTarget:s,surface:l,device:i.device});if(u)return u;let p=await M(i.device),d=await rF({req:t,sessionName:r,sessionStore:n,device:p,surface:l,openTarget:s,existingSession:i});return"response"===d.type?d.response:await rH({req:t,sessionName:r,sessionStore:n,logPath:a,device:p,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:d.details.appBundleId,appName:d.details.appName,runtime:d.details.runtime,surface:l,existingSession:i})}let o=t.flags?.relaunch===!0,s=t.positionals?.[0];if(o&&!s)return r$("open --relaunch requires an app argument.");let l=function(e){let{shouldRelaunch:t,openTarget:r,platform:a}=e;return t?r&&tm(r)?r$("open --relaunch does not support URL targets."):"android"===a&&r&&"binary"===tu(r)?r$(th(r)):null:null}({shouldRelaunch:o,openTarget:s,platform:t.flags?.platform==="android"?"android":void 0});if(l)return l;let u=await q(t.flags??{}),p=rV(u,t.flags?.surface,s);if("string"!=typeof p)return p;let d=rU({shouldRelaunch:o,openTarget:s,surface:p,device:u});return d||await F(rG,u.id,async()=>{let e=n.toArray().find(e=>e.device.id===u.id);if(e)return ei(t,e)?E("DEVICE_IN_USE","Device is already in use by another workspace session.",{deviceId:u.id,deviceName:u.name,hint:"Use a different device selector, wait for the other workspace to close its session, or run agent-device devices to choose another target."}):E("DEVICE_IN_USE",`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:u.id,deviceName:u.name,hint:V(e,"device-in-use")});let i=await rF({req:t,sessionName:r,sessionStore:n,device:u,surface:p,openTarget:s});return"response"===i.type?i.response:await rH({req:t,sessionName:r,sessionStore:n,logPath:a,device:u,openTarget:s,openPositionals:t.positionals??[],appBundleId:i.details.appBundleId,appName:i.details.appName,runtime:i.details.runtime,surface:p})})}let rz={ios:async(e,t,r)=>{let{reinstallIosApp:a}=await import("./apps.js");return await a(e,t,r)},android:async(e,t,r)=>{let{reinstallAndroidApp:a}=await import("./3340.js");return await a(e,t,r)}},rW={ios:async(e,t,r)=>{let{installIosApp:a}=await import("./apps.js"),n=await a(e,r,{appIdentifierHint:t});return{bundleId:n.bundleId,appName:n.appName,launchTarget:n.launchTarget}},android:async(e,t,r)=>{let{installAndroidApp:a}=await import("./3340.js"),n=await a(e,r);return{package:n.packageName,appName:n.appName,launchTarget:n.launchTarget}}};async function rJ(e){let{req:r,command:a,sessionName:n,sessionStore:i,deployOps:o}=e,s=i.get(n),l=r.flags??{},u=N(a,s,l);if(u)return u;let p=r.positionals?.[0]?.trim(),d=r.positionals?.[1]?.trim();if(!p||!d)return E("INVALID_ARGS",`${a} requires: ${a} <app> <path-to-app-binary>`);let c=r.meta?.uploadedArtifactId;try{var f;let e,n=c?eI(c,r.meta?.tenantId):ef.expandHome(d);if(!t.existsSync(n))return E("INVALID_ARGS",`App binary not found: ${n}`);let u=await m({session:s,flags:l,ensureReady:!1});if(!eV(a,u))return E("UNSUPPORTED_OPERATION",`${a} is not supported on this device`);if("ios"===u.platform){let t=await o.ios(u,p,n),r=t.bundleId;e=r?{app:p,appPath:n,platform:"ios",appId:r,bundleId:r,appName:t.appName,launchTarget:t.launchTarget}:{app:p,appPath:n,platform:"ios",appName:t.appName,launchTarget:t.launchTarget}}else{let t=await o.android(u,p,n),r=t.package;e=r?{app:p,appPath:n,platform:"android",appId:r,package:r,packageName:r,appName:t.appName,launchTarget:t.launchTarget}:{app:p,appPath:n,platform:"android",appName:t.appName,launchTarget:t.launchTarget}}let h=e8(e,(f=e,`Installed: ${f.appName??e3(f)}`));return s&&i.recordAction(s,{command:a,positionals:r.positionals??[],flags:r.flags??{},result:h??{}}),{ok:!0,data:h}}finally{c&&D(c)}}async function rX(e,t,r){return await tv(e,t,r)}async function rY(e){let{req:t,sessionName:r,sessionStore:a}=e;if("session_list"===t.command){let e=ex(t);return{ok:!0,data:{sessions:a.toArray().filter(t=>d(t,e)).map(e=>{let t=a.resolveSessionDir(e.name);return{name:e.name,sessionStateDir:t,runnerLogPath:eo(t),platform:e.device.platform,target:e.device.target??"mobile",surface:e.surface??"app",device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,..."ios"===e.device.platform&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}})}}}if("devices"===t.command)try{let e=tf(t.flags?.androidDeviceAllowlist),r=to(t.flags?.platform),a=ti({simulatorSetPath:tl(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),n=await ec({platform:r,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:a,androidSerialAllowlist:e?Array.from(e).sort():void 0}),i=r?n.filter(e=>{var t,a;return t=e,!(a=r)||("apple"===a?tn(t.platform):t.platform===a)}):n,o=(t.flags?.target?i.filter(e=>(e.target??"mobile")===t.flags?.target):i).map(({simulatorSetPath:e,...t})=>t);return{ok:!0,data:{devices:o}}}catch(t){let e=i(t);return E(e.code,e.message,e.details)}if("apps"===t.command){let e=a.get(r),n=t.flags??{},i=N(t.command,e,n);if(i)return i;let o=await m({session:e,flags:n,ensureReady:!0});if(!eV("apps",o))return E("UNSUPPORTED_OPERATION","apps is not supported on this device");let s=tS(t.flags?.appsFilter);return tn(o.platform)?{ok:!0,data:{apps:(await tI(o,s)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await tg(o,s)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function rZ(e){let{ensureAndroidEmulatorBooted:t}=await import("./3340.js");return await t(e)}let rQ='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',r0='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function r1(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r),i=t.flags??{},o=to(i.platform);if(!n&&er(i))return E("SESSION_NOT_FOUND","ios"===o?`No active session "${r}". Run open with --session ${r} first.`:`No active session "${r}". Run open with --session ${r} first, or omit --session to query by device selector.`);let s=N("appstate",n,i);if(s)return s;let l=tn(n?.device.platform)&&c(i,n);if("ios"===o&&!l)return E("SESSION_NOT_FOUND",rQ);if("macos"===o&&!l)return E("SESSION_NOT_FOUND",r0);if(l&&n){let e=n.appName??n.appBundleId;if(!n.appName&&!n.appBundleId){if("macos"===n.device.platform&&n.surface&&"app"!==n.surface&&"frontmost-app"!==n.surface)return{ok:!0,data:{platform:n.device.platform,appName:n.surface,appBundleId:n.appBundleId,source:"session",surface:n.surface}};let e="macos"===n.device.platform?"macOS":"iOS";return E("COMMAND_FAILED",`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`)}return{ok:!0,data:{platform:n.device.platform,appName:e??"unknown",appBundleId:n.appBundleId,source:"session",surface:n.surface??"app",..."ios"===n.device.platform?{device_udid:n.device.id,ios_simulator_device_set:n.device.simulatorSetPath??null}:{}}}}let u=await m({session:n,flags:i,ensureReady:!0});if("ios"===u.platform)return E("SESSION_NOT_FOUND",rQ);if("macos"===u.platform)return E("SESSION_NOT_FOUND",r0);if("web"===u.platform)return E("UNSUPPORTED_OPERATION","appstate is not supported on web.");let{getAndroidAppState:p}=await import("./3340.js"),d=await p(u);return{ok:!0,data:{platform:"android",package:d.package,activity:d.activity}}}async function r3(e){let{req:t,sessionName:r,sessionStore:a}=e;if("boot"===t.command){let e,n=a.get(r),o=t.flags??{},s=N(t.command,n,o);if(s)return s;let l="android"===(to(o.platform)??n?.device.platform),u=!0===o.headless;if(u&&!l)return E("INVALID_ARGS","boot --headless is supported only for Android emulators.");let p=eE({flags:o,sessionDevice:n?.device}),d=l&&!!p,c=!1;try{e=await m({session:n,flags:o,ensureReady:!1})}catch(r){let t=i(r);if(l&&u&&!p&&"DEVICE_NOT_FOUND"===t.code)return E("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");if(!d||"DEVICE_NOT_FOUND"!==t.code||!p)throw r;e=await rZ({avdName:p,serial:o.serial,headless:u}),c=!0}if(o.target&&(e.target??"mobile")!==o.target)return E("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${o.target}.`);if(l&&u){if("android"!==e.platform||"emulator"!==e.kind)return E("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!c){let t=eE({flags:o,sessionDevice:n?.device,resolvedDevice:e});if(!t)return E("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await rZ({avdName:t,serial:o.serial,headless:!0})}await eM(e)}else("android"!==e.platform||!0!==e.booted)&&await eM(e);return eV("boot",e)?{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}:E("UNSUPPORTED_OPERATION","boot is not supported on this device")}if("shutdown"===t.command){var n;let e,i=a.get(r),o=t.flags??{},s=N(t.command,i,o);if(s)return s;let l=await m({ensureReady:!1,flags:o,session:i});if(!eV("shutdown",l))return E("UNSUPPORTED_OPERATION","shutdown is supported only for Apple simulators and Android emulators.");if(i&&i.device.platform===l.platform&&i.device.id===l.id)return E("DEVICE_IN_USE","Cannot shut down an active session device directly. Use close --shutdown to end the session and turn off the simulator/emulator.",{hint:`Run agent-device close --shutdown --session ${r}`,session:r,platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind});let u=await K(l);return u.success?{ok:!0,data:{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u}}:E(u.error?.code??"COMMAND_FAILED",(n=u,(e=n.error?.message??n.stderr.trim()).length>0?e:"Shutdown failed"),{platform:l.platform,target:l.target??"mobile",device:l.name,id:l.id,kind:l.kind,shutdown:u})}return"appstate"===t.command?await r1({req:t,sessionName:r,sessionStore:a}):null}async function r2(e,t={}){var r,a,n;let i,o,s,l,u=(s=(o=(i=function(e){let t=[];for(let r of e){if("open"!==r.command)continue;let e=r.result?.startup;e&&"object"==typeof e&&"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&"string"==typeof e.measuredAt&&0!==e.measuredAt.trim().length&&e.method===rk&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:rk,appTarget:"string"==typeof e.appTarget&&e.appTarget.length>0?e.appTarget:void 0,appBundleId:"string"==typeof e.appBundleId&&e.appBundleId.length>0?e.appBundleId:void 0})}return t.slice(-20)}((r=e).actions)).at(-1))?{available:!0,lastDurationMs:o.durationMs,lastMeasuredAt:o.measuredAt,method:rk,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:rk},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,...{fps:r6(),memory:{available:!1,reason:rN},cpu:{available:!1,reason:rN}}},sampling:{startup:{method:rk,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"},..."android"===(a=r).device.platform?{memory:{method:eq,description:eP,unit:"kB"},cpu:{method:em,description:es,unit:"percent"},fps:{method:R,description:e_,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}}:Y(a.device)}});return at(e)&&(e.appBundleId?"android"===e.device.platform?await r8(u,e,e.appBundleId,t):await r7(u,e,e.appBundleId):(n=u,l=ar(e),n.metrics.fps={available:!1,reason:l},n.metrics.memory={available:!1,reason:l},n.metrics.cpu={available:!1,reason:l})),u}async function r5(e,t={}){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{fps:r6()},sampling:{fps:"android"===(a=r).device.platform?{method:R,description:e_,unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}:P(a.device)}};return at(e)&&(e.appBundleId?await ae(n,e,e.appBundleId,t):n.metrics.fps={available:!1,reason:ar(e)}),n}async function r4(e,t){var r,a;let n={session:(r=e).name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,sampling:{memory:"android"===(a=r).device.platform?{method:eq,description:eP,unit:"kB",topConsumerLimit:5}:Y(a.device).memory,snapshot:"android"===r.device.platform?{method:J,description:j,defaultKind:"android-hprof",artifactOnly:!0}:{method:eR,description:u,defaultKind:"memgraph",artifactOnly:!0}}};if(!at(e)){if("snapshot"===t.action){let r=al(e,t.kind);return n.artifact=au(e,r),n.support=ad(n.artifact.support)??ap(e),n}return n.metrics={memory:{available:!1,reason:rN}},n}return"sample"===t.action?n.metrics={memory:await ai(e,t)}:(n.artifact=await as(e,t),n.support=ad(n.artifact.support)??ap(e)),n}function r6(){return{available:!1,reason:"Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions."}}async function r8(e,t,r,a){let n=await aa(t,r,a);r9(e,t,n)}async function r7(e,t,r){let a=await an(t,r);r9(e,t,a)}function r9(e,t,r){e.metrics.memory=af(r.memory),e.metrics.cpu=af(r.cpu),e.metrics.fps=am(af(r.fps),t)}async function ae(e,t,r,a){let n="android"===t.device.platform?await ac(eF(t.device,r,{adb:a.androidAdb})):await ac(g(t.device,r));e.metrics.fps=am(af(n),t)}function at(e){return"android"===e.device.platform||"ios"===e.device.platform||"macos"===e.device.platform}function ar(e){return"android"===e.device.platform?"No Android app package is associated with this session. Run open <app> first.":"No Apple app bundle ID is associated with this session. Run open <app> first."}async function aa(e,t,r){let a={adb:r.androidAdb},[n,i,o]=await Promise.allSettled([H(e.device,t,a),z(e.device,t,a),eF(e.device,t,a)]);return{memory:n,cpu:i,fps:o}}async function an(e,t){let r=await ac(g(e.device,t)),a=await ac(eU(e.device,t));if("fulfilled"===a.status){let e=a.value;return{memory:{status:"fulfilled",value:e.memory},cpu:{status:"fulfilled",value:e.cpu},fps:r}}return{memory:{status:"rejected",reason:a.reason},cpu:{status:"rejected",reason:a.reason},fps:r}}async function ai(e,t){return e.appBundleId?af("android"===e.device.platform?await ac(H(e.device,e.appBundleId,{adb:t.androidAdb})):await ac(ao(e))):{available:!1,reason:ar(e)}}async function ao(e){if(!e.appBundleId)throw new s("INVALID_ARGS",ar(e));return(await eU(e.device,e.appBundleId)).memory}async function as(e,t){if(!e.appBundleId)throw new s("INVALID_ARGS",ar(e),{hint:"Run open <app> first so perf memory snapshot can resolve the app process."});let a=al(e,t.kind),n=function(e,t){if(e.out)return ef.expandHome(e.out,e.cwd);let a=new Date().toISOString().replace(/[:.]/g,"-"),n=e.sessionStore.ensureSessionDir(e.sessionName);return r.join(n,"artifacts",`memory-${t}-${a}.${"android-hprof"===t?"hprof":"memgraph"===t?"memgraph":"artifact"}`)}(t,a);return"android"===e.device.platform?"android-hprof"!==a?au(e,a):await I(e.device,e.appBundleId,n,{adb:t.androidAdb}):"memgraph"!==a?au(e,a):await w(e.device,e.appBundleId,n)}function al(e,t){return t||("android"===e.device.platform?"android-hprof":"memgraph")}function au(e,t){var r,a;let n=ap(e),i=(r=e,a=t,"android"===r.device.platform?{reason:`Android perf memory snapshot supports android-hprof, not ${a}.`,hint:"Use perf memory snapshot --kind android-hprof for Android Java heap artifacts."}:"ios"===r.device.platform||"macos"===r.device.platform?{reason:`Apple perf memory snapshot supports memgraph, not ${a}.`,hint:"Use perf memory snapshot --kind memgraph for supported Apple app sessions."}:{reason:`Memory snapshot artifacts are not supported on ${r.device.platform}.`,hint:"Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS."});return{available:!1,kind:t,reason:i.reason,hint:i.hint,support:n}}function ap(e){return"android"===e.device.platform?{platform:e.device.platform,defaultKind:"android-hprof",androidHprof:!0,memgraph:!1,heapprofd:!1,heapprofdDecision:"Deferred until Android Perfetto/heapprofd plumbing is available in the perf trace slice."}:"ios"!==e.device.platform&&"macos"!==e.device.platform?{platform:e.device.platform,defaultKind:"memgraph",androidHprof:!1,memgraph:!1,heapprofd:!1,reason:"Memory snapshot artifacts are available only on Android, iOS simulator, and macOS.",hint:"Use perf memory sample where supported, or switch to a platform with memory artifact support.",heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}:{...eh(e.device),androidHprof:!1,heapprofd:!1,heapprofdDecision:"Deferred because heapprofd is Android/Perfetto-specific and outside this memory artifact slice."}}function ad(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}async function ac(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function af(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=o(e.reason);return{available:!1,reason:t.message,error:t}}function am(e,t){var r,a;let n,i;if(!0!==e.available)return e;let o=(r=t.actions,n=ah((a=e).windowStartedAt),i=ah(a.windowEndedAt)??ah(a.measuredAt),void 0===n||void 0===i?[]:r.filter(e=>e.ts>=n&&e.ts<=i).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-n)),target:function(e){let t=e.result;if(t)for(let e of["refLabel","ref","appName","appBundleId"]){let r=t[e];if("string"==typeof r&&r.length>0)return r}}(e)})).slice(-12));return 0===o.length?e:{...e,relatedActions:o}}function ah(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}async function ag(e){var t,r,a,n,i,s,l,u,p,d;let c,f,m,h,g,w,y=(t=e.req,r=e.area,c=(a=t,n=r,"string"==typeof a.flags?.out&&a.flags.out.length>0?a.flags.out:(a.positionals??[])["cpu"===n?5:4]||void 0),"cpu"===r?(i=t,s=c,f=aw(i,1),m=aw(i,2),h=aw(i,3),ej(f)?"start"!==(l=m)&&"stop"!==l&&"report"!==l?E("INVALID_ARGS","perf cpu profile action must be start, stop, or report"):"simpleperf"!==h?E("INVALID_ARGS","perf cpu profile requires --kind simpleperf"):{ok:!0,area:"cpu",subject:f,action:m,kind:h,outPath:s}:E("INVALID_ARGS",ta)):(u=t,p=c,g=aw(u,1),w=aw(u,2),"start"!==(d=g)&&"stop"!==d?E("INVALID_ARGS","perf trace action must be start or stop"):eY(w)?"perfetto"!==w?E("INVALID_ARGS","perf trace requires --kind perfetto"):{ok:!0,area:"trace",action:g,kind:w,outPath:p}:E("INVALID_ARGS",e5)));if(!y.ok)return y;let{session:v}=e;if("android"!==v.device.platform)return E("UNSUPPORTED_OPERATION","Android native perf collectors are supported only on Android sessions.");if(!v.appBundleId)return E("COMMAND_FAILED","No Android app package is associated with this session.",{hint:"Run open <app> first so perf can resolve the package and process identity."});try{let t="cpu"===y.area?await aA(e,v,v.appBundleId,y):await aS(e,v,v.appBundleId,y);return{ok:!0,data:t}}catch(e){return{ok:!1,error:o(e)}}}function aw(e,t){return(e.positionals?.[t]??"").toLowerCase()}function ay(e,t){var r;return e.sessionStore.set(e.sessionName,{...e.session,nativePerf:{android:t}}),{action:(r=t).action,platform:"android",type:r.type,kind:r.kind,packageName:r.packageName,appPid:r.appPid,profilerPid:r.profilerPid,state:r.state,startedAt:new Date(r.startedAt).toISOString(),stoppedAt:"number"==typeof r.stoppedAt?new Date(r.stoppedAt).toISOString():void 0,durationMs:r.durationMs,outPath:r.outPath,sizeBytes:r.sizeBytes,remotePath:r.remotePath,method:r.method,summary:r.summary,message:r.message}}function av(e,t,a){var n,i,o;let s;return t?ef.expandHome(t,e.req.meta?.cwd):(n=e.sessionStore,i=e.sessionName,o=a,s=new Date().toISOString().replace(/[:.]/g,"-"),r.join(n.ensureSessionDir(i),`${s}-${o}`))}async function aA(e,t,r,a){if("start"===a.action){aI(t);let n=av(e,a.outPath,"cpu.perf.data"),i=await l(t.device,r,n,{adb:e.androidAdbExecutor});return ay(e,i)}let n=a_(t,"cpu-profile",a.kind);if("report"===a.action){await function(e){if("running"===e.state)throw new s("COMMAND_FAILED","Stop the Android Simpleperf CPU profile before generating a report.",{hint:"Run perf cpu profile stop --kind simpleperf, then retry perf cpu profile report --kind simpleperf."})}(n);let r=av(e,a.outPath,"cpu-report.json");return await eC(t.device,n,r,{adb:e.androidAdbExecutor})}let i=ab(e,a.outPath,n),o=await ep(t.device,n,i,{adb:e.androidAdbExecutor});return ay(e,o)}async function aS(e,t,r,a){if("start"===a.action){aI(t);let n=av(e,a.outPath,"app.perfetto-trace"),i=await A(t.device,r,n,{adb:e.androidAdbExecutor});return ay(e,i)}let n=a_(t,"trace",a.kind),i=ab(e,a.outPath,n),o=await eg(t.device,n,i,{adb:e.androidAdbExecutor});return ay(e,o)}function aI(e){let t=e.nativePerf?.android;if(t?.state==="running")throw new s("COMMAND_FAILED",`Android ${t.kind} ${t.type} is already running for this session.`,{hint:"cpu-profile"===t.type?"Run perf cpu profile stop --kind simpleperf before starting another Android native perf capture.":"Run perf trace stop --kind perfetto before starting another Android native perf capture."})}function ab(e,t,r){return t?av(e,t,r.outPath):r.outPath}function a_(e,t,r){let a=e.nativePerf?.android;if(a?.type===t&&a.kind===r)return a;throw new s("COMMAND_FAILED",`No Android ${r} ${t} is active for this session.`,{hint:"cpu-profile"===t?"Run perf cpu profile start --kind simpleperf first, then stop or report in the same session.":"Run perf trace start --kind perfetto first, then stop in the same session."})}async function ak(e,t){let r,a,n=(r=e.req.positionals??[],"cpu"===(a=r[0]?.toLowerCase())?function(e){if(e[1]?.toLowerCase()!=="profile")return E("INVALID_ARGS","perf cpu requires profile");let t=aN(e[2],"perf cpu profile",!0);if(!t.ok)return t;let r=aD(e[3]);return r.ok?{ok:!0,area:"cpu",mode:"cpu-profile",action:t.value,kind:"xctrace",template:e[4]||void 0,outPath:e[5]||void 0,tracePath:e[6]||void 0}:r}(r):"trace"===a?function(e){let t=aN(e[1],"perf trace",!1);if(!t.ok)return t;let r=aD(e[2]);return r.ok?{ok:!0,area:"trace",mode:"trace",action:t.value,kind:"xctrace",template:e[3]||void 0,outPath:e[4]||void 0,tracePath:e[5]||void 0}:r}(r):E("INVALID_ARGS",eW));if(!n.ok)return n;if("android"===t.device.platform)return E("UNSUPPORTED_OPERATION","Android native profiling belongs to the Android perf rollout; Apple xctrace perf supports iOS and macOS sessions only.");if("ios"!==t.device.platform&&"macos"!==t.device.platform)return E("UNSUPPORTED_OPERATION",`Apple xctrace perf is not supported on ${t.device.platform}.`);if(!t.appBundleId)return E("INVALID_ARGS","Apple xctrace perf requires an active app session. Run open <app> first.");try{if("start"===n.action)return await ax(e,t,n);if("stop"===n.action)return await aR(e,t,n);return await aM(e,t,n)}catch(e){return{ok:!1,error:o(e)}}}function aN(e,t,r){let a=e?.toLowerCase();return"start"===a||"stop"===a||r&&"report"===a?{ok:!0,value:a}:E("INVALID_ARGS",r?`${t} requires start, stop, or report`:`${t} requires start or stop`)}function aD(e){return e?.toLowerCase()==="xctrace"?{ok:!0}:E("INVALID_ARGS","perf native collection currently supports --kind xctrace")}async function ax(e,t,r){if(t.applePerf?.active)return E("INVALID_ARGS","Apple xctrace perf capture already in progress");let a=r.template??("cpu-profile"===r.mode?"Time Profiler":"Animation Hitches"),n=aL(e,r),i=await X({device:t.device,appBundleId:t.appBundleId,mode:r.mode,template:a,outPath:n});t.applePerf={...t.applePerf??{},active:i},e.sessionStore.set(e.sessionName,t);let o=aO("started",i);return aP(e,t,o),{ok:!0,data:o}}async function aR(e,t,r){var a,n,o,s,l,u,p;let d,c=t.applePerf?.active;if(!c)return E("INVALID_ARGS","no active Apple xctrace perf capture");let f=r.outPath?ef.expandHome(r.outPath,e.req.meta?.cwd):c.outPath;try{d=await b(c,f)}catch(r){throw a=r,i(a).details?.captureCleanedUp===!0&&(n=e,(o=t).applePerf={...o.applePerf??{},active:void 0},n.sessionStore.set(n.sessionName,o)),r}s=e,l=t,u=d,l.applePerf={...l.applePerf??{},active:void 0,lastMode:u.mode,..."cpu-profile"===(p=u).mode?{lastProfileTracePath:p.outPath,lastProfileTemplate:p.template}:{lastTracePath:p.outPath}},s.sessionStore.set(s.sessionName,l);let m=aO("stopped",d);return aP(e,t,m),{ok:!0,data:m}}async function aM(e,t,r){var a;let n;if("cpu-profile"!==r.mode)return E("INVALID_ARGS","perf trace does not support report");if(t.applePerf?.active)return E("INVALID_ARGS","perf cpu profile report requires a stopped profile trace; stop the active capture first.");let i=aL(e,r),o=(a=t,(n=r.tracePath??a.applePerf?.lastProfileTracePath??a.applePerf?.active?.outPath)?{ok:!0,value:n}:E("INVALID_ARGS","perf cpu profile report requires a stopped profile trace or tracePath option"));if(!o.ok)return o;let s={perf:"reported",...await k({tracePath:ef.expandHome(o.value,e.req.meta?.cwd),outPath:i,mode:r.mode,template:t.applePerf?.lastProfileTemplate??r.template,appBundleId:t.appBundleId})};return aP(e,t,s),{ok:!0,data:s}}function aP(e,t,r){e.sessionStore.recordAction(t,{command:"perf",positionals:e.req.positionals??[],flags:e.req.flags??{},result:r})}function aL(e,t){if(t.outPath)return ef.expandHome(t.outPath,e.req.meta?.cwd);let r=e.sessionStore.ensureSessionDir(e.sessionName),a=new Date().toISOString().replace(/[:.]/g,"-"),n="report"===t.action?"json":"trace";return`${r}/perf-${t.mode}-${a}.${n}`}function aO(e,t){return{perf:e,kind:t.kind,mode:t.mode,template:t.template,outPath:t.outPath,appBundleId:t.appBundleId,deviceId:t.deviceId,platform:t.platform,targetPids:t.targetPids,targetProcesses:t.targetProcesses,startedAt:t.startedAt,endedAt:t.endedAt}}let aE=`logs requires ${e6.slice(0,-1).join(", ")}, or ${e6.at(-1)}`,aC=["dump","log"],a$=`network requires ${aC.join(" or ")}`,aV=`network include mode must be one of: ${t_.join(", ")}`,aU={path:({session:e,sessionName:t,sessionStore:r})=>(function(e,t,r){let a=r.resolveAppLogPath(t),n=G(a);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?.backend??eu(e.device),sizeBytes:n.sizeBytes,modifiedAt:n.modifiedAt,startedAt:e.appLog?.startedAt?new Date(e.appLog.startedAt).toISOString():void 0,hint:'Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>'}}})(e,t,r),doctor:({session:e,sessionName:t,sessionStore:r})=>aH(e,t,r),mark:({req:e,sessionName:t,sessionStore:r})=>{var a,n,i;let o,s;return a=e,n=t,i=r,o=a.positionals?.slice(1).join(" ")??"",f(s=i.resolveAppLogPath(n),o),{ok:!0,data:{path:s,marked:!0}}},clear:({session:e,sessionName:t,sessionStore:r,restart:a})=>aK(e,t,r,a),start:({session:e,sessionName:t,sessionStore:r})=>aj(e,t,r),stop:({session:e,sessionName:t,sessionStore:r})=>az(e,t,r)};async function aF(e){let{req:t}=e;return"perf"===t.command?aq(e):"logs"===t.command?aB(e):"network"===t.command?aW(e):null}async function aq(e){var t;let{req:r,sessionName:a,sessionStore:n,androidAdbExecutor:i}=e,l=n.get(a);if(!l)return E("SESSION_NOT_FOUND","perf requires an active session. Run open first.");let u=(r.positionals?.[0]??"metrics").toLowerCase();if("cpu"===(t=u)||"trace"===t)return"android"===l.device.platform?await ag({req:r,sessionName:a,sessionStore:n,session:l,androidAdbExecutor:i,area:u}):await ak(e,l);let p=function(e){var t,r,a,n,i,l,u,p,d,c;let f,m,h=e4(f=(e.positionals?.[0]??"metrics").toString().toLowerCase())?f:void 0;if(!h)return E("INVALID_ARGS",eW);if("cpu"===h||"trace"===h)return{ok:!0,native:!0};let g=eK(m=(e.positionals?.[1]??"sample").toString().toLowerCase())?m:void 0;if(!g)return E("INVALID_ARGS",eX);let w=function(e){if(void 0!==e)return"string"==typeof e&&eY(e)?e:new s("INVALID_ARGS",e5)}(e.flags?.kind);if(w instanceof s)return{ok:!1,error:o(w)};let y=(t=h,r=g,("memory"===t?aT(r)?void 0:E("INVALID_ARGS","perf memory requires sample or snapshot"):"sample"!==r?E("INVALID_ARGS","perf metrics and perf frames only support sample"):void 0)??(a=e,n=h,i=g,l=w,function(e,t,r){if(e&&("memory"!==t||"snapshot"!==r))return E("INVALID_ARGS","--out is only supported with perf memory snapshot")}(a.flags?.out,n,i)??(u=l,p=n,d=i,u?"memory"!==p||"snapshot"!==d?E("INVALID_ARGS","--kind is only supported with perf memory snapshot"):eZ(u)?void 0:E("INVALID_ARGS",e2):void 0)));return y||{ok:!0,native:!1,area:h,action:g,kind:w,out:"string"==typeof(c=e.flags?.out)&&c.length>0?c:void 0}}(r);if(!p.ok)return p;if(p.native)return await ak(e,l);try{return{ok:!0,data:await aG(e,l,p)}}catch(e){return{ok:!1,error:o(e)}}}async function aG(e,t,r){let{sessionName:a,sessionStore:n,androidAdbExecutor:i}=e;return"memory"===r.area?await r4(t,{action:function(e){if(aT(e))return e;throw new s("INVALID_ARGS","perf memory requires sample or snapshot")}(r.action),kind:r.kind,out:r.out,cwd:e.req.meta?.cwd,sessionName:a,sessionStore:n,androidAdb:i}):"frames"===r.area?await r5(t,{androidAdb:i}):await r2(t,{androidAdb:i})}function aT(e){return"sample"===e||"snapshot"===e}async function aB(e){var t;let r,a,{req:n,sessionName:i,sessionStore:o}=e,s=o.get(i);if(!s)return E("SESSION_NOT_FOUND","logs requires an active session");if(!eV("logs",s.device))return E("UNSUPPORTED_OPERATION","logs is not supported on this device");let l=(t=n,r=(t.positionals?.[0]??"path").toLowerCase(),a=!!t.flags?.restart,e6.includes(r)?a&&"clear"!==r?E("INVALID_ARGS","logs --restart is only supported with logs clear"):{ok:!0,action:r,restart:a}:E("INVALID_ARGS",aE));return l.ok?await aU[l.action]({...e,session:s,restart:l.restart}):l}async function aH(e,t,r){let a=r.resolveAppLogPath(t),n=await eA(e.device,e.appBundleId);return{ok:!0,data:{path:a,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:n.checks,notes:n.notes}}}async function aK(e,t,r,a){if(e.appLog&&!a)return E("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");let n=r.resolveAppLogPath(t);if(!a)return{ok:!0,data:Q(n)};let i=e.appBundleId;if(!i)return E("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");e.appLog&&await eD(e.appLog);let s=Q(n),l=r.resolveAppLogPidPath(t);try{let a=await eB(e.device,i,n,l);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:a.backend,outPath:n,startedAt:a.startedAt,getState:a.getState,stop:a.stop,wait:a.wait}}),{ok:!0,data:{...s,restarted:!0}}}catch(a){return r.set(t,{...e,appLog:void 0}),{ok:!1,error:o(a)}}}async function aj(e,t,r){if(e.appLog)return E("INVALID_ARGS","app log already streaming; run logs stop first");if(!e.appBundleId)return E("INVALID_ARGS","logs start requires an app session; run open <app> first");let a=r.resolveAppLogPath(t),n=r.resolveAppLogPidPath(t);try{let i=await eB(e.device,e.appBundleId,a,n);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:i.backend,outPath:a,startedAt:i.startedAt,getState:i.getState,stop:i.stop,wait:i.wait}}),{ok:!0,data:{path:a,started:!0}}}catch(e){return{ok:!1,error:o(e)}}}async function az(e,t,r){if(!e.appLog)return E("INVALID_ARGS","no app log stream active");let a=e.appLog.outPath;return await eD(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:a,stopped:!0}}}async function aW(e){let t=function(e){let{req:t,sessionName:r,sessionStore:a}=e,n=a.get(r);if(!n)return E("SESSION_NOT_FOUND","network requires an active session");if(!eV("network",n.device))return E("UNSUPPORTED_OPERATION","network is not supported on this device");let i=(t.positionals?.[0]??"dump").toLowerCase();if(!aC.includes(i))return E("INVALID_ARGS",a$);let o=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(o)||o<1||o>200)return E("INVALID_ARGS","network dump limit must be an integer in range 1..200");let s=function(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return E("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let a=(r??t??"summary").toLowerCase();return t_.includes(a)?{ok:!0,include:a}:E("INVALID_ARGS",aV)}(t);return s.ok?{ok:!0,session:n,maxEntries:o,include:s.include}:s}(e);if(!t.ok)return t;let{include:r,maxEntries:a,session:n}=t;if("web"===n.device.platform)return await aJ({include:r,maxEntries:a});let i=await ea({device:n.device,appBundleId:n.appBundleId,appLogState:n.appLog?.getState(),appLogStartedAt:n.appLog?.startedAt,appLogPath:e.sessionStore.resolveAppLogPath(e.sessionName),maxEntries:a,include:r,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...i.dump,active:!!n.appLog,state:n.appLog?.getState()??"inactive",backend:i.backend,notes:i.notes}}}async function aJ(e){let t=tb();if(!t.dumpNetwork)return E("UNSUPPORTED_OPERATION","network is not supported by this web provider");try{let r=await t.dumpNetwork({include:e.include,limit:e.maxEntries});return{ok:!0,data:{entries:r.entries,active:!0,state:"active",backend:r.backend??"agent-browser",include:e.include,matchedLines:r.entries.length,scannedLines:r.entries.length,limits:{maxEntries:e.maxEntries,maxPayloadChars:2048,maxScanLines:r.entries.length},notes:r.notes}}}catch(e){return{ok:!1,error:o(e)}}}function aX(e,t,r){var a,n;if(null==e)return tV("open",[tG(tF(t,"launchApp"),r)]);if("string"==typeof e)return tV("open",[tG(e,r)]);if(!tU(e))throw new s("INVALID_ARGS","launchApp expects a string or map.");tq(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),a0(e,"permissions"),a0(e,"clearKeychain");let i=tG("string"==typeof e.appId?e.appId:tF(t,"launchApp"),r),o=(a=e,n=r,[...aZ(a.arguments,"launchApp.arguments",n),...aZ(a.launchArguments,"launchApp.launchArguments",n)]),l=!0===e.clearState;return tV("open",[i],{...!l&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...l?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function aY(e,t,r){if(null==e)return tV("close",[tG(tF(t,"stopApp"),r)]);if("string"==typeof e)return tV("close",[tG(e,r)]);throw new s("INVALID_ARGS","stopApp expects a string appId or no value.")}function aZ(e,t,r){if(null==e)return[];if("string"==typeof e)return[tG(e,r)];if(Array.isArray(e))return e.map((e,a)=>aQ(e,`${t}[${a}]`,r));if(tU(e))return Object.entries(e).flatMap(([e,a])=>[tG(e,r),aQ(a,`${t}.${e}`,r)]);throw new s("INVALID_ARGS",`${t} expects a string, list, or map.`)}function aQ(e,t,r){if("string"==typeof e)return tG(e,r);if("number"==typeof e||"boolean"==typeof e)return String(e);throw new s("INVALID_ARGS",`${t} must be a string, number, or boolean.`)}function a0(e,t){if(void 0!==e[t])throw tH(`Maestro launchApp field "${t}" is not supported yet.`)}let a1="__maestroRunScript",a3="__maestroAssertVisible",a2="__maestroAssertNotVisible",a5="__maestroPressEnter",a4="__maestroWaitForAnimationToEnd",a6="__maestroScrollUntilVisible",a8="__maestroSwipeScreen",a7="__maestroSwipeOn",a9="__maestroTapOn",ne="__maestroTapPointPercent";function nt(e){if(null==e)return tV("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return tV("type",["\b".repeat(e)]);if(!tU(e))throw new s("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(tq(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return tV("type",["\b".repeat(50)]);if("number"!=typeof e.charactersToErase||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new s("INVALID_ARGS","eraseText.charactersToErase must be a positive integer.");return tV("type",["\b".repeat(e.charactersToErase)])}function nr(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function na(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw tH(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function nn(e){return na(e,"swipe direction")}function ni(e,t,r=[],a){if("string"==typeof e)return no(tG(e,a));if(!tU(e))throw new s("INVALID_ARGS",`${t} expects a string or selector map.`);tq(e,t,["id","text","enabled","selected",...r]);let n=[],i=[];if("boolean"==typeof e.enabled&&i.push(nl("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(nl("selected",String(e.selected))),"string"==typeof e.id&&n.push(nl("id",tG(e.id,a)),...i),"string"==typeof e.text&&0===n.length)return no(tG(e.text,a),i);if("string"==typeof e.label&&0===n.length&&n.push(nl("label",tG(e.label,a)),...i),0===n.length&&i.length>0&&n.push(...i),0===n.length)throw new s("INVALID_ARGS",`${t} selector map must include one of id, text, label, enabled, or selected.`);return n.join(" ")}function no(e,t=[]){return[[nl("label",e),...t].join(" "),[nl("text",e),...t].join(" "),[nl("id",e),...t].join(" ")].join(" || ")}function ns(e){let t=nr(e.duration);return t?[t]:[]}function nl(e,t){return`${e}=${JSON.stringify(t)}`}function nu(e){var t,r;if(!tU(e))return;let a={},n="number"==typeof(t=e.repeat)&&Number.isInteger(t)&&t>0?t:void 0,i="number"==typeof(r=e.delay)&&Number.isInteger(r)&&r>=0?r:void 0;return n&&n>1&&(a.count=n),void 0!==i&&(a.intervalMs=i),!0===e.optional&&(a.maestro={optional:!0}),Object.keys(a).length>0?a:void 0}function np(e){let t=nu(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function nd(e){let t={doubleTap:!0};return tU(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class nc{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new s("INVALID_ARGS","Unsupported trailing runFlow.when.true expression.");return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator("||");)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator("&&");)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new s("INVALID_ARGS","Incomplete runFlow.when.true expression.");if("boolean"===e.type)return this.index+=1,e.value;if("paren"===e.type&&"("===e.value){this.index+=1;let e=this.parseOr();if(!this.consumeParen(")"))throw new s("INVALID_ARGS","Unclosed runFlow.when.true parenthesis.");return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),r=this.context.platform;return"=="===e?r===t:r!==t}expectPlatform(){if(this.peek()?.type!=="platform")throw new s("INVALID_ARGS","runFlow.when.true supports maestro.platform comparisons.");this.index+=1}expectEqualityOperator(){let e=this.peek();if(e?.type==="operator"&&("=="===e.value||"!="===e.value))return this.index+=1,e.value;throw new s("INVALID_ARGS","runFlow.when.true comparison requires == or !=.")}expectString(){let e=this.peek();if(e?.type==="string")return this.index+=1,e.value;throw new s("INVALID_ARGS","runFlow.when.true comparison requires a string literal.")}consumeOperator(e){let t=this.peek();return t?.type==="operator"&&t.value===e&&(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type==="paren"&&t.value===e&&(this.index+=1,!0)}peek(){return this.tokens[this.index]}}function nf(e,t,r){return{...tV(e,t),replayControl:r}}function nm(e,t,r){let a="string"==typeof e?tG(e,t):e,n="number"==typeof a?a:"string"==typeof a&&/^\d+$/.test(a)?Number(a):void 0;if(void 0===n||!Number.isInteger(n)||n<0)throw new s("INVALID_ARGS",`${r} must be a non-negative integer or \${VAR} resolving to one.`);return n}let nh=`
|
|
2
2
|
const fs = require('node:fs');
|
|
3
3
|
const input = JSON.parse(fs.readFileSync(0, 'utf8'));
|
|
4
4
|
if (typeof fetch !== 'function') {
|
package/dist/src/snapshot.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__webpack_require__ as e}from"./rslib-runtime.js";import{promises as t}from"node:fs";import a from"node:os";import n from"node:path";import{centerOfRect as s}from"./4291.js";import{normalizeError as o,AppError as r}from"./733.js";import{withDiagnosticTimer as i,emitDiagnostic as l}from"./432.js";import{pressAndroid as d,backAndroid as p}from"./input-actions.js";import{createDaemonRuntimeSessionStore as u,captureSnapshot as c,dispatchCommand as f,resolveSnapshotScope as m,runMacOsAlertAction as h,errorResponse as w,runIosRunnerCommand as g,isCommandSupportedOnDevice as y,snapshotAndroid as _,annotateScreenshotWithRefs as v,context_contextFromFlags as S}from"./9722.js";import{SETTINGS_INVALID_ARGS_MESSAGE as b,parseTimeout as I,getUnsupportedMacOsSettingMessage as A,successText as R,isMacOsSettingSupported as C,snapshotCaptureAnnotationsFrom as N}from"./9873.js";import{sleep as D}from"./5560.js";import{buildSnapshotSession as P,dispatchWaitViaRuntime as k,createDaemonRuntimePolicy as M,recordIfSession as E,resolveSessionDevice as O,withSessionlessRunnerCleanup as K}from"./selector-runtime.js";import{createAgentDevice as U}from"./
|
|
1
|
+
import{__webpack_require__ as e}from"./rslib-runtime.js";import{promises as t}from"node:fs";import a from"node:os";import n from"node:path";import{centerOfRect as s}from"./4291.js";import{normalizeError as o,AppError as r}from"./733.js";import{withDiagnosticTimer as i,emitDiagnostic as l}from"./432.js";import{pressAndroid as d,backAndroid as p}from"./input-actions.js";import{createDaemonRuntimeSessionStore as u,captureSnapshot as c,dispatchCommand as f,resolveSnapshotScope as m,runMacOsAlertAction as h,errorResponse as w,runIosRunnerCommand as g,isCommandSupportedOnDevice as y,snapshotAndroid as _,annotateScreenshotWithRefs as v,context_contextFromFlags as S}from"./9722.js";import{SETTINGS_INVALID_ARGS_MESSAGE as b,parseTimeout as I,getUnsupportedMacOsSettingMessage as A,successText as R,isMacOsSettingSupported as C,snapshotCaptureAnnotationsFrom as N}from"./9873.js";import{sleep as D}from"./5560.js";import{buildSnapshotSession as P,dispatchWaitViaRuntime as k,createDaemonRuntimePolicy as M,recordIfSession as E,resolveSessionDevice as O,withSessionlessRunnerCleanup as K}from"./selector-runtime.js";import{createAgentDevice as U}from"./2577.js";import{summarizeSnapshotDiagnostics as x}from"./8358.js";var L={};e.r(L),e.d(L,{handleSnapshotCommands:()=>ew});let B=new Set(["com.android.permissioncontroller","com.google.android.permissioncontroller","com.google.android.packageinstaller","com.android.packageinstaller"]),$=new Set(["android","com.android.systemui"]),H=/^android:id\/(?:alertTitle|message|button[123]|parentPanel|buttonPanel|contentPanel)$/i,q=/^android:id\/button[123]$/i,F=/(?:^|:)id\/permission_/i,T=/\b(?:is(?:n't| not) responding|keeps stopping|has stopped|close app|app info)\b/i,j=/^(?:ok|allow|allow all|while using the app|only this time|yes|continue|save|confirm|turn on|open settings)$/i,X=/^(?:cancel|deny|don.t allow|don’t allow|not now|no|dismiss|close|close app|later|skip)$/i;function z(e,t){let a=t[0];if(!a)return;let n=G(e,a.index);for(let a of t.slice(1)){let t=new Set(G(e,a.index));for(let e=n.length-1;e>=0;e-=1)t.has(n[e])||n.splice(e,1)}return n[n.length-1]}function G(e,t){let a=new Map(e.map(e=>[e.index,e])),n=[],s=a.get(t);for(;s;)n.push(s.index),s=void 0===s.parentIndex?void 0:a.get(s.parentIndex);return n.reverse()}function V(e,t){let a=new Map;for(let t of e){if(void 0===t.parentIndex)continue;let e=a.get(t.parentIndex)??[];e.push(t),a.set(t.parentIndex,e)}let n=new Set([t]),s=[t];for(let e of s)for(let t of a.get(e)??[])n.has(t.index)||(n.add(t.index),s.push(t.index));return e.filter(e=>n.has(e.index))}function W(e){let t=e.type??"",a=e.identifier??"";return!!(e.hittable||/\bbutton\b/i.test(t)||q.test(a)||/(?:^|:)id\/permission_(?:allow|deny)/i.test(a))}function J(e){if(!e)return"";let t=[e.label,e.value].filter(e=>"string"==typeof e&&e.trim().length>0);return t[0]?.trim()??""}async function Q(e,t,a={}){if("wait"===t)return await Y(e,a.timeoutMs??1e4);if("get"===t){var n;let t=await et(e);return{kind:"alertStatus",platform:"android",action:"get",alert:n=t?.alert??null,...n?R("Alert visible"):R("No alert visible")}}return await Z(e,t)}async function Y(e,t){let a=Date.now(),n=await ee(e,t);if(!n)throw new r("COMMAND_FAILED","alert wait timed out");return{kind:"alertWait",platform:"android",action:"wait",alert:n.alert,waitedMs:Date.now()-a,...R("Alert visible")}}async function Z(e,t){var a;let n,s,o=await ee(e,2e3);if(!o)throw new r("COMMAND_FAILED","alert not found",{hint:"If a sheet is visible in snapshot but alert reports no alert, it is likely app-owned UI. Use snapshot -i and press the visible label/ref."});let i=(a=o.buttons,n="accept"===t?"accept":"dismiss",(s=a.find(e=>e.role===n))||("dismiss"===t?a.find(e=>"neutral"===e.role)??null:1===a.length?a[0]??null:null));if(i)return await d(e,i.x,i.y),ea(t,o.alert,i.label);if("dismiss"===t)return await p(e),ea(t,o.alert,"Back");throw new r("COMMAND_FAILED","alert accept found an alert but no accept button",{alert:o.alert,hint:"Inspect alert get --json for visible buttons, then use press by visible label/ref if needed."})}async function ee(e,t){let a=Date.now();for(;Date.now()-a<t;){let t=await et(e);if(t)return t;await D(300)}return null}async function et(e){return function(e){var t,a,n,o;let r,i=function(e){let t=e.filter(e=>{var t;let a;return a=(t=e).bundleId??"",B.has(a)||F.test(t.identifier??"")});if(t.length)return{nodes:t,source:"permission"};let a=function(e){let t=e.filter(e=>{var t;let a;return a=(t=e).bundleId??"",$.has(a)&&T.test(J(t))});if(0===t.length)return[];let a=z(e,t);return void 0===a?t:V(e,a).filter(e=>e.bundleId&&$.has(e.bundleId))}(e);return a.length?{nodes:a,source:"system-dialog"}:{nodes:function(e){var t;let a,n,s=e.filter(e=>{var t;return t=e.type??"",/(?:^|[.$])[^.]*Dialog$/i.test(t)}),o=e.filter(e=>H.test(e.identifier??"")),r=s.length?[...s,...o]:(a=(t=o).some(e=>q.test(e.identifier??"")),n=t.some(e=>!q.test(e.identifier??"")),a&&n?t:[]);if(0===r.length)return[];let i=z(e,r);return void 0===i?r:V(e,i)}(e),source:"native-dialog"}}(e),l=i.nodes;if(0===l.length)return null;let d=function(e){let t=new Set,a=[];for(let n of e){let e=J(n);if(!e||!n.rect||!W(n))continue;let o=e.trim().toLowerCase();if(!o||t.has(o))continue;t.add(o);let r=s(n.rect);a.push({label:e,x:r.x,y:r.y,role:function(e,t){var a;let n=(a=e.identifier??"",/(?:^|:)id\/button1$/i.test(a)?"accept":/(?:^|:)id\/button2$/i.test(a)?"dismiss":/(?:^|:)id\/button3$/i.test(a)?"neutral":/(?:^|:)id\/permission_allow/i.test(a)?"accept":/(?:^|:)id\/permission_deny/i.test(a)?"dismiss":null);return n||(j.test(t.trim())?"accept":X.test(t.trim())?"dismiss":"neutral")}(n,e)})}return a}(l),p=l.filter(e=>J(e)&&!W(e)),u=J((t=p).find(e=>/(?:^|:)id\/(?:alertTitle|permission_message)$/i.test(e.identifier??"")))||J(t[0]),c=(a=p,n=u,(r=a.map(e=>J(e)).filter(e=>e&&e!==n)).length?[...new Set(r)].join("\n"):void 0),f=(o=l,o.find(e=>e.bundleId)?.bundleId);return{alert:{...u?{title:u}:{},...c?{message:c}:{},buttons:d.map(e=>e.label),platform:"android",source:i.source,...f?{packageName:f}:{}},buttons:d}}((await i("snapshot_capture",async()=>await _(e,{helperWaitForIdleTimeoutMs:0,includeHiddenContentHints:!1}),{backend:"android",purpose:"alert"})).nodes)}function ea(e,t,a){return{kind:"alertHandled",platform:"android",action:e,handled:!0,alert:t,button:a,...R(`Alert ${e}ed`)}}async function en(e){var t;let{req:a,logPath:n,session:s,device:o}=e,r="accept"===(t=a.positionals?.[0])||"dismiss"===t||"wait"===t?t:"get",i=s?"frontmost-app"===s.surface?{surface:"frontmost-app"}:{bundleId:s.appBundleId,surface:s.surface}:{};if(!y("alert",o))return w("UNSUPPORTED_OPERATION","alert is not supported on this device");if("android"===o.platform){let t=I(a.positionals?.[1])??1e4;return ei(e,await Q(o,r,{timeoutMs:t}))}if("macos"===o.platform){let t=async e=>await h(e,i);return await es(e,r,t)}let l={verbose:a.flags?.verbose,logPath:n,traceLogPath:s?.trace?.outPath,requestId:a.meta?.requestId,iosXctestrunFile:a.flags?.iosXctestrunFile,iosXctestDerivedDataPath:a.flags?.iosXctestDerivedDataPath,iosXctestEnvDir:a.flags?.iosXctestEnvDir},d=async e=>await g(o,{command:"alert",action:e,appBundleId:s?.appBundleId},l);return await es(e,r,d)}async function es(e,t,a){if("wait"===t)return await eo(e,a);let n="accept"===t||"dismiss"===t?t:"get";return"accept"===n||"dismiss"===n?await er(e,n,a):ei(e,await a("get"))}async function eo(e,t){let a=I(e.req.positionals?.[1])??1e4,n=Date.now();for(;Date.now()-n<a;){try{return ei(e,await t("get"))}catch{}await D(300)}return w("COMMAND_FAILED","alert wait timed out")}async function er(e,t,a){var n,s;let o,i,l=Date.now();for(;Date.now()-l<2e3;){try{return ei(e,await a(t))}catch(t){i=t;let e=String(t?.message??"").toLowerCase();if(!e.includes("alert not found")&&!e.includes("no alert"))break}await D(300)}throw(n=i)instanceof r&&(s=n,(o=String(s?.message??"").toLowerCase()).includes("alert not found")||o.includes("no alert"))?new r(n.code,n.message,{...n.details??{},hint:"If the permission sheet is visible in snapshot or screenshot but alert reports no alert, take a scoped snapshot around the visible button label and use press @ref."}):n}function ei(e,t){return E(e.sessionStore,e.session,e.req,t),{ok:!0,data:t}}async function el(e){let{req:t,logPath:a,sessionStore:n,session:s,device:o,parsed:r}=e,{setting:i,state:l,appBundleId:d,permissionTarget:p,latitude:u,longitude:c}=r;if(!y("settings",o))return w("UNSUPPORTED_OPERATION","settings is not supported on this device");if("macos"===o.platform&&!C(i))return w("INVALID_ARGS",A(i));let m=d??s?.appBundleId;if("clear-app-state"===i&&!m)return w("INVALID_ARGS","settings clear-app-state requires an app id when no app is bound to the session");let h="clear-app-state"===i?[i,l,m??""]:"permission"===i?[i,l,p??"",t.positionals?.[3]??"",m??""]:"location"===i&&"set"===l?[i,l,u??"",c??"",m??""]:[i,l,m??""],g=await f(o,"settings",h,t.flags?.out,{...S(a,t.flags,m,s?.trace?.outPath)});return E(n,s,t,g??{setting:i,state:l}),{ok:!0,data:g??{setting:i,state:l}}}async function ed(e){var t,a;let n;if("snapshot"!==e.command||"android"!==e.device.platform)return;let s=o(e.error);if("COMMAND_FAILED"===(t=s).code&&(a=t,n=`${a.message}
|
|
2
2
|
${a.hint??""}`,/Android UI hierarchy dump timed out/i.test(n)||/Stock UIAutomator fallback was skipped/i.test(n)||/Android accessibility snapshots can be blocked/i.test(n)||function(e){if(!e||"object"!=typeof e)return!1;let t=String(e.errorType??""),a=String(e.message??"");return/TimeoutException/i.test(t)||/timed out/i.test(a)}(t.details?.helper)||function(e){var t;if(!e)return!1;let a=e?.timeoutMs,n=e?.cmd,s=Array.isArray(t=e?.args)?t.map(String):"string"==typeof t?t.split(/\s+/):[];return"number"==typeof a&&"adb"===n&&s.includes("uiautomator")&&s.includes("dump")}(t.details)))return{ok:!1,error:{...s,details:{...s.details??{},androidSnapshotTimeoutScreenshot:await ep(e)}}}}async function ep(e){try{var s,r,i;let o=await t.mkdtemp(n.join(a.tmpdir(),"agent-device-android-snapshot-timeout-")),d=n.join(o,"snapshot-timeout-overlay-refs.png"),p=(s=await f(e.device,"screenshot",[d],void 0,{...S(e.logPath,{screenshotNoStabilize:!0},e.session?.appBundleId,e.session?.trace?.outPath),surface:e.session?.surface}),r=d,(i=s,"object"==typeof i&&null!==i&&"path"in i&&"string"==typeof i.path)?s.path:r);await t.access(p);let u=await eu(p,e.session);return l({level:"warn",phase:"android_snapshot_timeout_screenshot_captured",data:{path:p,overlayRefCount:"overlayRefCount"in u?u.overlayRefCount:void 0,overlayRefsAnnotated:"overlayRefsAnnotated"in u?u.overlayRefsAnnotated:void 0}}),u}catch(t){let e=o(t);return l({level:"warn",phase:"android_snapshot_timeout_screenshot_failed",data:{error:e.message}}),{captureFailed:!0,error:e.message}}}async function eu(e,t){if(!t?.snapshot)return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:"unavailable",overlayRefCount:0};try{let a=await v({screenshotPath:e,snapshot:t.snapshot});return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:a.length>0,overlayRefCount:a.length,overlayRefSource:"session-snapshot",overlayRefs:a}}catch(a){let t=o(a);return l({level:"warn",phase:"android_snapshot_timeout_screenshot_overlay_failed",data:{path:e,error:t.message}}),{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:"session-snapshot",overlayRefCount:0,overlayAnnotationError:t.message}}}async function ec(e){return await em({...e,command:"snapshot",unsupportedMessage:"snapshot is not supported on this device",execute:async({runtime:e,sessionName:t,req:a,snapshotScope:n})=>{let s=await e.capture.snapshot({session:t,interactiveOnly:a.flags?.snapshotInteractiveOnly,depth:a.flags?.snapshotDepth,scope:n,raw:a.flags?.snapshotRaw,forceFull:a.flags?.snapshotForceFull});return{data:s,record:{kind:"snapshot",nodes:s.nodes.length,truncated:s.truncated}}}})}async function ef(e){return await em({...e,command:"diff",unsupportedMessage:"diff is not supported on this device",execute:async({runtime:e,sessionName:t,req:a,snapshotScope:n})=>{let s=await e.capture.diffSnapshot({session:t,interactiveOnly:a.flags?.snapshotInteractiveOnly,depth:a.flags?.snapshotDepth,scope:n,raw:a.flags?.snapshotRaw});return{data:s,record:{kind:"diff",mode:"snapshot",baselineInitialized:s.baselineInitialized,summary:s.summary}}}})}async function em(e){var t,a;let{req:n,sessionName:s,logPath:o,sessionStore:i}=e,{session:l,device:d}=await O(i,s,n.flags);if(!y(e.command,d))return w("UNSUPPORTED_OPERATION",e.unsupportedMessage);let p=m(n.flags?.snapshotScope,l);if(!p.ok)return p;let f=(t=e.command,a=l,"ios"!==d.platform||a?.appBundleId?null:w("SESSION_NOT_FOUND",`iOS ${t} requires an active app session on the target device. Run open first (for example: open --session ${a?.name??"sim"} --platform ios --device "<name>" <app>).`));return f||await K(l,d,async()=>{var t,a;let f,m,h=function(e){let{req:t,sessionName:a,logPath:n,sessionStore:s,session:o,device:i,snapshotScope:l}=e;return U({backend:function(e){let{req:t,logPath:a,session:n,device:s,snapshotScope:o}=e;return{platform:s.platform,captureSnapshot:async(e,r)=>{let i=await c({device:s,session:n,flags:t.flags,outPath:r?.outPath??t.flags?.out,logPath:a,snapshotScope:o}),l=x(n);return{snapshot:i.snapshot,...N(i),...l?{snapshotDiagnostics:l}:{},appName:n?.appBundleId?n.appName??n.appBundleId:void 0,appBundleId:n?.appBundleId}}}}({req:t,logPath:n,session:o,device:i,snapshotScope:l}),...M("snapshot"),sessions:u({sessionName:a,getSession:()=>s.get(a),recordOptions:{includeSnapshot:!0},setRecord:e=>{var n;let o=function(e){if(!e.snapshot)throw new r("UNKNOWN","snapshot runtime did not produce session state");return e}(e),l=s.get(a);s.set(a,function(e){var t,a;let{current:n,sessionName:s,device:o,record:r,refScopedSnapshot:i}=e,l=(t=n,a=r,i&&a.snapshot?.nodes.length===0&&t?.snapshot!==void 0),d=l?n.snapshot:r.snapshot,p=P({session:n,sessionName:s,device:o,snapshot:d,appBundleId:r.appBundleId});return p.snapshotScopeSource=function(e){let{current:t,keepCurrentSnapshot:a,refScopedSnapshot:n}=e;if(n)return a?t?.snapshotScopeSource:t?.snapshotScopeSource??t?.snapshot}({current:n,keepCurrentSnapshot:l,refScopedSnapshot:i}),r.appName&&(p.appName=r.appName),p}({current:l,sessionName:a,device:i,record:o,refScopedSnapshot:(n=t,n.flags?.snapshotScope?.trim().startsWith("@")===!0)}))}})})}({req:n,sessionName:s,logPath:o,sessionStore:i,session:l,device:d,snapshotScope:p.scope});try{m=await e.execute({runtime:h,sessionName:s,req:n,snapshotScope:p.scope})}catch(a){let t=await ed({error:a,command:e.command,logPath:o,session:l,device:d});if(!t)throw a;return t}return(f=(t={req:n,sessionName:s,sessionStore:i,result:m.record}).sessionStore.get(t.sessionName))&&t.sessionStore.recordAction(f,{command:t.req.command,positionals:t.req.positionals??[],flags:t.req.flags??{},result:"snapshot"===(a=t.result).kind?{nodes:a.nodes,truncated:a.truncated}:{mode:a.mode,baselineInitialized:a.baselineInitialized,summary:a.summary}}),{ok:!0,data:m.data}})}let eh={snapshot:async({req:e,sessionName:t,logPath:a,sessionStore:n})=>await ec({req:e,sessionName:t,logPath:a,sessionStore:n}),diff:async({req:e,sessionName:t,logPath:a,sessionStore:n})=>e.positionals?.[0]!=="snapshot"?w("INVALID_ARGS","diff currently supports only: diff snapshot"):await ef({req:e,sessionName:t,logPath:a,sessionStore:n}),wait:async({req:e,sessionName:t,logPath:a,sessionStore:n})=>await k({req:e,sessionName:t,logPath:a,sessionStore:n}),alert:async({req:e,sessionName:t,logPath:a,sessionStore:n})=>{let{session:s,device:o}=await O(n,t,e.flags);return await K(s,o,async()=>await en({req:e,logPath:a,sessionStore:n,session:s,device:o}))},settings:async({req:e,sessionName:t,logPath:a,sessionStore:n})=>{let s,o,r,i=(s=e.positionals?.[0]?.toLowerCase(),o=e.positionals?.[1]?.toLowerCase(),r=e.positionals?.[2]?.toLowerCase(),"clear-app-state"===s?{ok:!0,parsed:{setting:s,state:"clear",appBundleId:"clear"===o?e.positionals?.[2]:e.positionals?.[1]}}:s&&o&&("permission"!==s||r)&&("location"!==s||"set"!==o||e.positionals?.[2]&&e.positionals?.[3])?{ok:!0,parsed:{setting:s,state:o,permissionTarget:r,latitude:e.positionals?.[2],longitude:e.positionals?.[3]}}:w("INVALID_ARGS",b));if(!i.ok)return i;let{session:l,device:d}=await O(n,t,e.flags);return await K(l,d,async()=>await el({req:e,logPath:a,sessionStore:n,session:l,device:d,parsed:i.parsed}))}};async function ew(e){let t=eh[e.req.command];return t?await t(e):null}export{L as snapshot_namespaceObject};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-device",
|
|
3
|
-
"version": "0.17.
|
|
3
|
+
"version": "0.17.8",
|
|
4
4
|
"description": "Agent-native CLI for AI app automation across iOS, Android, tvOS, Android TV, macOS, Linux, and web.",
|
|
5
5
|
"mcpName": "io.github.callstackincubator/agent-device",
|
|
6
6
|
"license": "MIT",
|
package/server.json
CHANGED
|
@@ -7,12 +7,12 @@
|
|
|
7
7
|
"url": "https://github.com/callstack/agent-device",
|
|
8
8
|
"source": "github"
|
|
9
9
|
},
|
|
10
|
-
"version": "0.17.
|
|
10
|
+
"version": "0.17.8",
|
|
11
11
|
"packages": [
|
|
12
12
|
{
|
|
13
13
|
"registryType": "npm",
|
|
14
14
|
"identifier": "agent-device",
|
|
15
|
-
"version": "0.17.
|
|
15
|
+
"version": "0.17.8",
|
|
16
16
|
"transport": {
|
|
17
17
|
"type": "stdio"
|
|
18
18
|
}
|
package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.7.apk.sha256
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
cc41db9a5e5f7df8bdf302c3d4e6130ed7b35f1012bd37d2db583b70a0104ee8 agent-device-android-multitouch-helper-0.17.7.apk
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
a8d1788b652e75d6542891763afee0213d38d02825f453a1b5d0edfca6ad8cd4 agent-device-android-snapshot-helper-0.17.7.apk
|
package/dist/src/2892.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import e from"node:crypto";import t from"node:fs";import n from"node:path";import{resolveUserPath as r,expandUserHomePath as o}from"./9612.js";import{findProjectRoot as s}from"./7244.js";function i(a,u={}){var l,c;let p,f=(l=a,c=u,(p=(l??"").trim())?r(p,{env:c.env}):function(r={}){var i;let a,u,l,c=n.join(o("~",{env:r.env}),".agent-device"),p=r.projectRoot??s();return(i=p,t.existsSync(n.join(i,"package.json"))&&t.existsSync(n.join(i,"src","daemon.ts")))?n.join(c,"dev",(a=function(e){try{return t.realpathSync.native(e)}catch{return n.resolve(e)}}(p),u=n.basename(a).replaceAll(/[^a-zA-Z0-9._-]+/g,"-"),l=e.createHash("sha1").update(a).digest("hex").slice(0,12),`${u||"agent-device"}-${l}`)):c}(c));return{baseDir:f,infoPath:n.join(f,"daemon.json"),lockPath:n.join(f,"daemon.lock"),logPath:n.join(f,"daemon.log"),sessionsDir:n.join(f,"sessions")}}function a(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function u(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function l(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function c(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let p=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,f=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,m=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function h(){let e=process.argv[1];return e?d(e):"unknown"}function d(r,o=s()){try{let s=n.resolve(o),i=[n.resolve(r)],a=new Set,u=[];for(;i.length>0;){let e=i.pop();if(!e||a.has(e))continue;a.add(e);let r=t.statSync(e);if(!r.isFile())continue;let o=n.relative(s,e)||e;u.push(`${o}:${r.size}:${Math.trunc(r.mtimeMs)}`);let l=t.readFileSync(e,"utf8");for(let t of function(e){let t=new Set;return g(e,p,t),g(e,f,t),[...t]}(l)){let r=function(e,t){let r=n.resolve(n.dirname(e),t),o=M(r);if(o)return o;for(let e of m){let t=M(`${r}${e}`);if(t)return t}for(let e of m){let t=M(n.join(r,`index${e}`));if(t)return t}return null}(e,t);r&&i.push(r)}}let l=u.sort().join("|"),c=e.createHash("sha1").update(l).digest("hex");return`graph:${u.length}:${c}`}catch{return"unknown"}}function g(e,t,n){t.lastIndex=0;let r=null;for(;null!==(r=t.exec(e));){let e=r[1]?.trim();e?.startsWith(".")&&n.add(e)}}function M(e){try{return t.statSync(e).isFile()?e:null}catch{return null}}let v=/^[A-Za-z0-9_@%+=:,./-]+$/;function y(e){return`'${e.replaceAll("'","'\\''")}'`}function S(e){return v.test(e)?e:y(e)}function j(e,t){let n=[],r=e+t.toString(),o=r.indexOf("\n");for(;-1!==o;){let e=r.slice(0,o).trim();r=r.slice(o+1),e&&n.push(e),o=r.indexOf("\n")}return{lines:n,buffer:r}}function x(e){return e.meta?.requestProgress==="replay-test"}function $(e){return!!e&&"object"==typeof e&&"progress"===e.type&&!!e.event}function b(e){return!!e&&"object"==typeof e&&"response"===e.type&&!!e.response}function w(e){return`${JSON.stringify({type:"progress",event:e})}
|
|
2
|
-
`}function D(e){return`${JSON.stringify({type:"response",response:e})}
|
|
3
|
-
`}function k(e){return`${JSON.stringify({type:"response",response:e})}
|
|
4
|
-
`}function _(e,t){e&&(e.snapshotDiagnostics??={samples:[]}).samples.push({...t,durationMs:Math.max(0,Math.round(t.durationMs))})}function A(e){let t=e?.snapshotDiagnostics?.samples;if(t&&0!==t.length)return P(t)}function P(e){if(0===e.length)return;let t=O(e);return{stats:t,...t.p95Ms>=1500?{warning:R(t)}:{}}}function z(e){let t=e.flatMap(e=>(function(e){if(!e||e.count<=0)return[];let t=e.platform;return 1===e.count?[{durationMs:e.maxMs,platform:t}]:2===e.count?[{durationMs:e.p50Ms,platform:t},{durationMs:e.maxMs,platform:t}]:[...Array.from({length:e.count-3},()=>({durationMs:e.p50Ms,platform:t})),{durationMs:e.p50Ms,platform:t},{durationMs:e.p95Ms,platform:t},{durationMs:e.maxMs,platform:t}]})(e?.stats));if(0===t.length)return;let n=O(t);return{stats:n,...n.p95Ms>=1500?{warning:R(n)}:{}}}function C(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=function(e){let t=T(e);if(!t)return;let n=function(e){let t={count:e.count,p50Ms:e.p50Ms,p95Ms:e.p95Ms,maxMs:e.maxMs,slowThresholdMs:e.slowThresholdMs};if(!Object.values(t).some(e=>"number"!=typeof e))return t}(t);if(n){var r;let e,o,s,i;return{...n,...(o="string"==typeof(r=t).platform?r.platform:void 0,i=(s=T(r.backends))&&(e=Object.entries(s).filter(e=>"number"==typeof e[1])).length>0?Object.fromEntries(e):void 0,{...o?{platform:o}:{},...i?{backends:i}:{}})}}}(e.stats);if(!t)return;let n="string"==typeof e.warning?e.warning:void 0;return{stats:t,...n?{warning:n}:{}}}function O(e){let t,n=e.map(e=>e.durationMs).sort((e,t)=>e-t);return{count:n.length,p50Ms:E(n,50),p95Ms:E(n,95),maxMs:n[n.length-1]??0,slowThresholdMs:1500,...1===new Set(t=e.map(e=>e.platform).filter(e=>!!e)).size?{platform:t[0]}:{},...function(e){let t={};for(let n of e)n.backend&&(t[n.backend]=(t[n.backend]??0)+1);return Object.keys(t).length>0?{backends:t}:{}}(e)}}function E(e,t){if(0===e.length)return 0;let n=Math.max(0,Math.ceil(t/100*e.length)-1);return e[Math.min(n,e.length-1)]??0}function R(e){let t=e.platform?`${e.platform} `:"";return`Warning: ${t}snapshots are slow in this run: p95 ${e.p95Ms}ms over ${e.count} captures. Possible causes: device load, app or dev server stuck, helper fallback, or stale daemon.`}function T(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}export{d as computeDaemonCodeSignature,j as consumeTextLines,$ as isDaemonProgressEnvelope,b as isDaemonResponseEnvelope,z as mergeSnapshotDiagnostics,c as normalizeTenantId,C as readSnapshotDiagnosticsSummary,_ as recordSnapshotTiming,h as resolveDaemonCodeSignature,i as resolveDaemonPaths,a as resolveDaemonServerMode,u as resolveDaemonTransportPreference,l as resolveSessionIsolationMode,w as serializeDaemonProgressEnvelope,D as serializeDaemonResponseEnvelope,k as serializeDaemonRpcResponseEnvelope,y as shellQuote,S as shellQuoteIfNeeded,x as shouldStreamRequestProgress,A as summarizeSnapshotDiagnostics,P as summarizeSnapshotTimingSamples};
|