agent-device 0.20.3 → 0.20.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.3.apk → agent-device-android-ime-helper-0.20.5.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.5.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.3.manifest.json → agent-device-android-ime-helper-0.20.5.manifest.json} +4 -4
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.5.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.5.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.3.manifest.json → agent-device-android-snapshot-helper-0.20.5.manifest.json} +6 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +57 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +45 -9
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +73 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +1 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +3 -2
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +1 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +8 -2
- package/dist/src/agent-browser-tool.js +1 -1
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/android-adb.d.ts +1 -1
- package/dist/src/android.js +1 -1
- package/dist/src/app-helpers.js +1 -1
- package/dist/src/app-inventory.d.ts +4 -0
- package/dist/src/app-lifecycle.js +7 -7
- package/dist/src/app-resolution.js +1 -1
- package/dist/src/apps.js +5 -5
- package/dist/src/boot-diagnostics.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +27 -19
- package/dist/src/cli-runner.js +1 -1
- package/dist/src/cli.js +15 -14
- package/dist/src/client-metro.js +1 -1
- package/dist/src/{tv-remote.d.ts → cloud-artifacts.d.ts} +109 -126
- package/dist/src/command-metadata.js +1 -1
- package/dist/src/command-schema.js +1 -1
- package/dist/src/command-surface.js +1 -1
- package/dist/src/context.js +1 -1
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/debug-symbols.js +4 -4
- package/dist/src/device-input-state.d.ts +2 -2
- package/dist/src/device-input-state.js +1 -1
- package/dist/src/device.js +1 -9
- package/dist/src/devices2.js +1 -1
- package/dist/src/entities.js +1 -0
- package/dist/src/find.js +1 -1
- package/dist/src/finders.d.ts +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/helper.js +2 -2
- package/dist/src/ime-lifecycle.js +9 -0
- package/dist/src/index.d.ts +592 -555
- package/dist/src/input-actions.js +4 -4
- package/dist/src/install-artifact.js +4 -4
- package/dist/src/install-artifact2.js +1 -1
- package/dist/src/install-source2.js +1 -1
- package/dist/src/interaction-snapshot.js +1 -1
- package/dist/src/interaction.d.ts +7 -4
- package/dist/src/interaction.js +1 -1
- package/dist/src/interactor.js +2 -2
- package/dist/src/interactor2.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +14 -14
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun.d.ts +103 -198
- package/dist/src/limrun.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/logcat.js +1 -1
- package/dist/src/manifest.js +1 -1
- package/dist/src/metro.d.ts +1 -1
- package/dist/src/parser.js +2 -0
- package/dist/src/path-resolution.js +1 -1
- package/dist/src/physical-device-control.js +1 -1
- package/dist/src/plist-xml.js +1 -0
- package/dist/src/plist.js +1 -1
- package/dist/src/png-worker-contract.js +1 -1
- package/dist/src/process-lock.js +1 -1
- package/dist/src/provider-limrun-runtime.js +1 -0
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/register-builtins.js +1 -1
- package/dist/src/registry.js +22 -22
- package/dist/src/remote-config2.js +1 -1
- package/dist/src/reporting.js +7 -7
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-disposal.js +1 -1
- package/dist/src/runner-lease.js +1 -1
- package/dist/src/runner-provider.js +1 -1
- package/dist/src/runner-sequence.js +1 -1
- package/dist/src/runtime-transport.js +1 -1
- package/dist/src/runtime.js +3 -3
- package/dist/src/screenshot-geometry.js +1 -0
- package/dist/src/screenshot-result.js +6 -0
- package/dist/src/sdk-android-adb.d.ts +5 -6
- package/dist/src/sdk-android-adb.js +3 -3
- package/dist/src/sdk-batch-runner.d.ts +2 -2
- package/dist/src/sdk-batch-runner.js +3 -3
- package/dist/src/sdk-contracts.d.ts +21 -25
- package/dist/src/sdk-contracts.js +2 -2
- package/dist/src/sdk-finders.d.ts +1 -1
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-io.js +1 -1
- package/dist/src/sdk-remote-config.d.ts +19 -4
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selector-vocabulary.js +1 -1
- package/dist/src/selectors.d.ts +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +2 -2
- package/dist/src/session-target-evidence.js +1 -1
- package/dist/src/session.js +9 -8
- package/dist/src/setting-state.js +1 -1
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot.js +1 -1
- package/dist/src/snapshot2.js +1 -1
- package/dist/src/src.js +1 -0
- package/dist/src/tool-provider.js +3 -3
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/tool-provider3.js +1 -1
- package/dist/src/update-check.js +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/viewport-dimension.js +14 -0
- package/package.json +21 -9
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.3.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.3.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.3.apk.sha256 +0 -1
- package/dist/src/android-input-method-overlays.js +0 -1
- package/dist/src/android-input-ownership.js +0 -1
- package/dist/src/apple-multitouch-support.js +0 -1
- package/dist/src/click-button.d.ts +0 -5
- package/dist/src/compatibility-policy.js +0 -1
- package/dist/src/gesture-plan-types.js +0 -1
- package/dist/src/gesture-plan.js +0 -1
- package/dist/src/launch-console.js +0 -1
- package/dist/src/recording-export-quality.js +0 -14
- package/dist/src/rolldown-runtime.js +0 -1
- package/dist/src/runtime2.js +0 -1
- package/dist/src/sdk-app-inventory.d.ts +0 -4
- package/dist/src/sdk-app-inventory.js +0 -1
- package/dist/src/snapshot-diagnostics.js +0 -6
- package/dist/src/xml.js +0 -2
package/dist/src/runtime.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)}function
|
|
3
|
-
`).toLowerCase(),n=D(e,jt),r=D(e,Ft),i=D(e,kt,Lt),a=D(e,At),o=Tt(t),s=Et(t);return{dismissNodes:n,minimizeNodes:r,collapsedNodes:i,detected:Ot({text:t,hasReactNativeStackFrame:o,hasOverlayControl:Dt(t,n,r),hasControllessRedBoxText:s,collapsedNodes:i,openDebuggerWarningNodes:a})}}function St(e){let t=Vt(e.dismissNodes);if(t)return Wt(t,Gt(t));let n=Kt(e.collapsedNodes.filter(Rt));return n?.rect?{action:`close-collapsed-banner`,point:Zt(n),rect:n.rect,ref:n.ref,label:O(n)}:null}function Ct(e){return[e.label,e.value,e.identifier,e.type,e.role].filter(Boolean).join(` `)}function wt(e){return ft.test(e)}function Tt(e){return pt.some(t=>t.test(e))}function Et(e){return/\buncaught\b/.test(e)&&/unable to download asset/.test(e)}function Dt(e,t,n){return t.length>0||n.length>0||/\b(reload js|copy stack)\b/.test(e)}function Ot(e){return e.collapsedNodes.length>0||e.openDebuggerWarningNodes.length>0||e.hasControllessRedBoxText||e.hasOverlayControl&&(wt(e.text)||e.hasReactNativeStackFrame)}function kt(e){let t=e?.trim().toLowerCase();return t?ht.some(e=>t.includes(e))||mt.some(e=>e.test(t)):!1}function At(e){return e.includes(`open debugger to view warnings`)||/^!,\s+open debugger\b/.test(e)}function jt(e){return Mt(e)||Nt(e)||Pt(e)}function Mt(e){return/^dismiss(?:\s*\([^)]*\))?$/i.test(e)}function Nt(e){return/^close(?:\s*\([^)]*\))?$/i.test(e)}function Pt(e){return gt.has(e)}function Ft(e){return/^minimi[sz]e(?:\b|\s|\()/i.test(e)}function It(e){return/^!,\s+/.test(e)}function Lt(e){return!e.rect||e.rect.height<=180}function Rt(e){let t=O(e)?.trim().toLowerCase()??``;return(At(t)||It(t))&&Bt(e)}function zt(e){return e?e.x<=1&&e.y<=1&&e.width>=300&&e.height>=600:!1}function Bt(e){return e.rect?e.rect.width>=120&&e.rect.height>=36&&e.rect.height<=180:!1}function D(e,t,n=()=>!0){let r=[];for(let i of e)i.ref&&n(i)&&[i.label,i.value,i.identifier].map(e=>e?.trim().toLowerCase()).filter(e=>!!e).some(e=>t(e))&&r.push(i);return r}function Vt(e){return qt(e,Ut)}function Ht(e){let t=[e.type,e.role,e.subrole].join(` `).toLowerCase();return/\b(button|menuitem|link)\b/.test(t)}function Ut(e){return[Yt(Ht(e)),Yt(e.hittable),-(e.rect?Oe(e.rect):1/0)]}function Wt(e,t){if(!e.rect)throw Error(`React Native overlay target node must have rect`);return{action:t,point:o(e.rect),rect:e.rect,ref:e.ref,label:O(e)}}function Gt(e){let t=O(e)?.trim().toLowerCase();return t&&Mt(t)?`dismiss`:`close`}function Kt(e){return qt(e,Jt)}function qt(e,t){let n=e.filter(e=>e.rect);return n.length===0?null:n.sort((e,n)=>Xt(t(n),t(e)))[0]??null}function Jt(e){return[Yt(e.hittable),e.rect?.width??0,e.rect?.y??0]}function Yt(e){return+(e===!0)}function Xt(e,t){for(let n=0;n<e.length;n+=1){let r=e[n]-t[n];if(r!==0)return r}return 0}function Zt(e){if(!e.rect)throw Error(`Collapsed React Native warning node must have rect`);let t=Math.min(e.rect.height,52),n=Math.min(36,Math.max(18,t*.45));return{x:Math.round(Qt(e.rect.x+e.rect.width-n,e.rect.x+1,e.rect.x+e.rect.width-1)),y:Math.round(e.rect.y+t/2)}}function Qt(e,t,n){return Math.min(n,Math.max(t,e))}function O(e){return e.label??e.value??e.identifier}function $t(e){let t=e?.trim().split(/\s+/,1)[0];if(!t||!t.startsWith(`@`)||t.length<3)return null;let n=t.slice(1);return/^[A-Za-z_-]*\d[\w-]*$/i.test(n)||/^(?:ref|node|element|el)[\w-]*$/i.test(n)?t:null}function en(e,t){try{let n=ut(e),r=E.extname(n)||`.js`;return[E.join(E.dirname(n),`${t}${r}`),E.join(E.dirname(n),`internal`,`${t}${r}`)].find(e=>lt.existsSync(e))??null}catch{return null}}var k=class extends Error{};let A=null,tn=!1,nn=!1,rn=0;const j=new Map;function an(e){tn=!0,!nn&&(nn=!0,l({level:`warn`,phase:`png_worker_unavailable`,data:{reason:e}}),process.emitWarning(`PNG worker unavailable, falling back to in-process PNG processing: ${e}`))}function on(e){let n=j.get(e.id);n&&(j.delete(e.id),ln(),e.ok?n.resolve(e.result):n.reject(new t(c(e.error.code),e.error.message,e.error.details)))}function sn(e,t){A===e&&(an(t.message),A=null,e.terminate().catch(()=>{}),cn(new k(`PNG worker failed: ${t.message}`)))}function cn(e){let t=[...j.values()];j.clear();for(let n of t)n.reject(e)}function ln(){A&&(j.size>0?A.ref():A.unref())}function un(){if(tn)return null;if(A)return A;let e=en(import.meta.url,`png-worker`);if(!e)return an(`worker entry module not found next to the current module`),null;try{let t=new dt(e,{execArgv:e.endsWith(`.ts`)?[`--experimental-strip-types`]:[]});return t.on(`message`,on),t.on(`error`,e=>{sn(t,e)}),t.on(`exit`,e=>{sn(t,Error(`PNG worker exited with code ${e}`))}),t.unref(),A=t,t}catch(e){return an(`failed to spawn worker: ${e instanceof Error?e.message:String(e)}`),null}}function dn(e){let t=un();if(!t)return Promise.reject(new k(`PNG worker is unavailable`));rn+=1;let n=rn;return new Promise((r,i)=>{j.set(n,{resolve:r,reject:i}),ln();try{t.postMessage({...e,id:n})}catch(e){j.delete(n),ln(),i(new k(`failed to post job to PNG worker: ${e instanceof Error?e.message:String(e)}`))}})}async function M(e,t){try{return await dn(e)}catch(e){if(e instanceof k)return t();throw e}}function fn(){un()}async function pn(){let e=A;A=null,cn(new k(`PNG worker terminated`)),e&&await e.terminate()}async function N(e,t){let n=await M({kind:`decode`,png:e,label:t},()=>{let n=at(e,t);return{kind:`decode`,width:n.width,height:n.height,data:n.data}});return new it({width:n.width,height:n.height,data:ct(n.data)})}async function P(e){return ct((await M({kind:`encode`,width:e.width,height:e.height,data:e.data},()=>({kind:`encode`,png:it.sync.write(e)}))).png)}async function mn(e,t,n){let{kind:r,...i}=await M({kind:`rgb-difference`,firstPng:e,secondPng:t,label:n},()=>({kind:`rgb-difference`,...ot(at(e,n),at(t,n))}));return i}async function hn(e){let{kind:t,...n}=await M({kind:`diff-pixels`,...e},()=>({kind:`diff-pixels`,...st(e)}));return{...n,diffData:ct(n.diffData)}}const F=[0,187,255,255];function gn(e,t){for(let n of t)n.rect.width<4||n.rect.height<4||_n(e,n.rect)}function _n(e,t){let n=vn(t);if(n==null)return;let r=L(n.x,0,e.width-1),i=L(n.y,0,e.height-1),a=L(n.right,0,e.width-1),o=L(n.bottom,0,e.height-1);for(let t=0;t<2;t+=1){for(let n=r;n<=a;n+=1)I(e,n,i+t,F),I(e,n,o-t,F);for(let n=i;n<=o;n+=1)I(e,r+t,n,F),I(e,a-t,n,F)}}function vn(e){let t=e.x+e.width-1,n=e.y+e.height-1;return[e.x,e.y,e.width,e.height,t,n].every(Number.isFinite)?{x:e.x,y:e.y,right:t,bottom:n}:null}function I(e,t,n,r){if(t<0||t>=e.width||n<0||n>=e.height)return;let i=(n*e.width+t)*4;e.data[i]=r[0],e.data[i+1]=r[1],e.data[i+2]=r[2],e.data[i+3]=r[3]}function L(e,t,n){return Number.isFinite(e)?Math.min(Math.max(e,t),n):t}const yn=[{x:-1,y:-1},{x:0,y:-1},{x:1,y:-1},{x:-1,y:0},{x:1,y:0},{x:-1,y:1},{x:0,y:1},{x:1,y:1}];function bn(e){let{mask:t,width:n,height:r,hooks:i}=e,a=new Uint8Array(t.length),o=new Int32Array(t.length),s=[];for(let e=0;e<t.length;e+=1){if(!Cn(t,a,e))continue;let c=0,l=Sn(o,a,0,e),u=i.create(e);for(;c<l;){let e=o[c];c+=1,i.visit(u,e),l=xn({mask:t,visited:a,queue:o,queueEnd:l,width:n,height:r,pixelIndex:e})}s.push(u)}return s}function xn(e){let{mask:t,visited:n,queue:r,width:i,height:a,pixelIndex:o}=e,s=o%i,c=Math.floor(o/i),l=e.queueEnd;for(let e of yn){let o=s+e.x,u=c+e.y;if(!wn(o,u,i,a))continue;let d=u*i+o;Cn(t,n,d)&&(l=Sn(r,n,l,d))}return l}function Sn(e,t,n,r){return t[r]=1,e[n]=r,n+1}function Cn(e,t,n){return e[n]===1&&t[n]!==1}function wn(e,t,n,r){return e>=0&&e<n&&t>=0&&t<r}const Tn=.4,En={icon:90,toggle:90,chevron:75,separator:45,visual:35,background:10},Dn={leading:20,trailing:20,separator:10,unknown:0,background:-30};function On(e){let t=Nn(An(kn(e.diffMask,e.width,e.height,e.ocr),e.width,e.height),10),n=Wn(e.ocr?.currentBlocksRaw??[]),r=Wn(e.ocr?.baselineBlocksRaw??[]);return t.filter(Jn).map(t=>Pn(t,e,n,r)).filter(t=>t.rect.y>=e.height*.08).filter(Rn).sort((e,t)=>t.score-e.score).slice(0,Math.max(0,e.maxDeltas??12)).map((e,t)=>Fn(e,t+1))}function kn(e,t,n,r){let i=new Uint8Array(e);if(!r)return i;for(let e of[...r.baselineBlocksRaw,...r.currentBlocksRaw])Xn(i,t,n,Ue(e.rect,8));return i}function An(e,t,n){return bn({mask:e,width:t,height:n,hooks:{create:e=>jn(e,t),visit:(e,n)=>Mn(e,n,t)}})}function jn(e,t){let n=e%t,r=Math.floor(e/t);return{minX:n,minY:r,maxX:n,maxY:r,differentPixels:0}}function Mn(e,t,n){let r=t%n,i=Math.floor(t/n);e.minX=Math.min(e.minX,r),e.minY=Math.min(e.minY,i),e.maxX=Math.max(e.maxX,r),e.maxY=Math.max(e.maxY,i),e.differentPixels+=1}function Nn(e,t){let n=[];for(let r of e.sort((e,t)=>e.minY-t.minY||e.minX-t.minX)){let e=n.find(e=>Zn(e,r,t));if(!e){n.push({...r});continue}e.minX=Math.min(e.minX,r.minX),e.minY=Math.min(e.minY,r.minY),e.maxX=Math.max(e.maxX,r.maxX),e.maxY=Math.max(e.maxY,r.maxY),e.differentPixels+=r.differentPixels}return n}function Pn(e,t,n,r){let i=Yn(e),a=Vn(i,t.regions),o=Hn(i,n,r),s=In(i,o?.block.rect,t.width),c=Ln(i,s,e.differentPixels,t),l={...a?{regionIndex:a}:{},slot:s,likelyKind:c,rect:i};return{...a?{regionIndex:a}:{},slot:s,likelyKind:c,rect:i,...o?{nearestText:qn(o.block.text)}:{},score:zn(l,e.differentPixels,t)}}function Fn(e,t){return{index:t,...e.regionIndex?{regionIndex:e.regionIndex}:{},slot:e.slot,likelyKind:e.likelyKind,rect:e.rect,...e.nearestText?{nearestText:e.nearestText}:{}}}function In(e,t,n){if(e.height<=3&&e.width>=n*.12)return`separator`;if(!t)return e.width>=n*Tn?`background`:`unknown`;if(e.width>=n*Tn)return`background`;let r=e.x+e.width/2,i=t.x+t.width/2;return r<i-t.width/2?`leading`:r>i+t.width/2?`trailing`:e.width>=n*.35?`background`:`unknown`}function Ln(e,t,n,r){let i=e.width/e.height,a=n/(e.width*e.height);return t===`separator`?`separator`:t===`background`?`background`:t===`trailing`&&i>=1.5&&i<=3.8&&a>=.35?`toggle`:t===`trailing`&&e.width<=r.width*.06&&e.height<=r.height*.04?`chevron`:t===`leading`&&i>=.55&&i<=1.8?`icon`:Bn(e,r)?`background`:`visual`}function Rn(e){return e.likelyKind!==`background`}function zn(e,t,n){let r=Bn(e.rect,n)?-35:0,i=e.regionIndex?20:0;return En[e.likelyKind]+Dn[e.slot]+i+r+Math.min(20,t/200)}function Bn(e,t){return e.width>=t.width*.25||e.height>=t.height*.06}function Vn(e,t){let n,r=0;for(let i of t){let t=Ke(e,i.rect);t<=r||(r=t,n=i)}return n?.index}function Hn(e,t,n){let r=Un(e,t);if(r)return Kn(e,r.blocks);let i=Un(e,n);return i?Kn(e,i.blocks):void 0}function Un(e,t){let n,r=0;for(let i of t){let t=Qn(e,i.rect);t<=r||(r=t,n=i)}return n}function Wn(e){let t=[];for(let n of[...e].sort((e,t)=>e.rect.y-t.rect.y)){let e=t.find(e=>Gn(e.rect,n.rect));if(!e){t.push({rect:n.rect,blocks:[n]});continue}e.blocks.push(n),e.blocks.sort((e,t)=>e.rect.x-t.rect.x),e.rect=Je([e.rect,n.rect])}return t}function Gn(e,t){return Qn(e,t)>0?!0:Math.abs(w(e).y-w(t).y)<=Math.max(e.height,t.height)*.5}function Kn(e,t){let n,r=w(e);for(let e of t){let t=Math.sqrt(We(r,w(e.rect)));n&&t>=n.distance||(n={block:e,distance:t})}return n}function qn(e){return e.trim().replace(/^[^\p{L}\p{N}]+/u,``).replace(/^\p{L}\s+/u,``)}function Jn(e){let t=Yn(e);return e.differentPixels>=24&&t.width>=3&&t.height>=3}function Yn(e){return{x:e.minX,y:e.minY,width:e.maxX-e.minX+1,height:e.maxY-e.minY+1}}function Xn(e,t,n,r){let i=Ye(Math.floor(r.x),0,t-1),a=Ye(Math.floor(r.y),0,n-1),o=Ye(Math.ceil(r.x+r.width),0,t),s=Ye(Math.ceil(r.y+r.height),0,n);for(let n=a;n<s;n+=1)for(let r=i;r<o;r+=1)e[n*t+r]=0}function Zn(e,t,n){return e.minX-n<=t.maxX&&t.minX-n<=e.maxX&&e.minY-n<=t.maxY&&t.minY-n<=e.maxY}function Qn(e,t){return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}async function $n(e){if(await d(`tesseract`))try{let[t,n]=await Promise.all([nr(e.baselinePath),nr(e.currentPath)]);if(t.exitCode!==0||n.exitCode!==0)return;let r=er(t.stdout,e.width,e.height),i=er(n.stdout,e.width,e.height),a=tr(r,i),o=lr(a);return r.length===0&&i.length===0?void 0:{provider:`tesseract`,baselineBlocks:r.length,currentBlocks:i.length,baselineBlocksRaw:r,currentBlocksRaw:i,matches:a,...o.length>0?{movementClusters:o}:{}}}catch{return}}function er(e,t,n){let[r,...i]=e.split(/\r?\n/);if(!r)return[];let a=r.split(` `),o=new Map(a.map((e,t)=>[e,t])),s=[];for(let e of i){if(!e.trim())continue;let t=e.split(` `),n=z(t,o,`level`),r=R(t,o,`text`).trim(),i=z(t,o,`conf`);if(n!==5||!fr(r)||i<0)continue;let a=z(t,o,`left`),c=z(t,o,`top`),l=z(t,o,`width`),u=z(t,o,`height`);l<=0||u<=0||s.push({key:[R(t,o,`page_num`),R(t,o,`block_num`),R(t,o,`par_num`),R(t,o,`line_num`)].join(`:`),text:r,confidence:i,rect:{x:a,y:c,width:l,height:u}})}let c=new Map;for(let e of s){let t=c.get(e.key);t?t.push(e):c.set(e.key,[e])}return Array.from(c.values()).flatMap(e=>ir(e)).map(e=>rr(e,t,n)).filter(e=>e!==null)}function tr(e,t){let n=new Set,r=[];for(let i of e){let e=ar(i,pr(i.text),t,n);if(e===null)continue;n.add(e);let a=t[e],o=or(i,a);sr(o)&&r.push(o)}return r.sort((e,t)=>cr(t)-cr(e)).slice(0,12)}function nr(e){return u(`tesseract`,[e,`stdout`,`-l`,`eng`,`tsv`],{allowFailure:!0,timeoutMs:1e4})}function rr(e,t,n){if(e.length===0)return null;let r=[...e].sort((e,t)=>e.rect.x-t.rect.x),i=Je(r.map(e=>e.rect)),a=Math.round(mr(r.map(e=>e.confidence))*100)/100;return{text:r.map(e=>e.text).join(` `),confidence:a,rect:i,normalizedRect:Xe({x:B(i.x/t),y:B(i.y/n),width:B(i.width/t),height:B(i.height/n)})}}function ir(e){let t=[...e].sort((e,t)=>e.rect.x-t.rect.x),n=[],r=[];for(let e of t){let t=r.at(-1);if(!t){r.push(e);continue}let i=e.rect.x-(t.rect.x+t.rect.width),a=Math.max(t.rect.height,e.rect.height);if(i>Math.max(48,a*2.5)){n.push(r),r=[e];continue}r.push(e)}return r.length>0&&n.push(r),n}function ar(e,t,n,r){let i=null,a=1/0;for(let o=0;o<n.length;o+=1){if(r.has(o))continue;let s=n[o];if(pr(s.text)!==t)continue;let c=We(w(e.normalizedRect),w(s.normalizedRect));c>=a||(i=o,a=c)}return i}function or(e,t){let n={x:t.rect.x-e.rect.x,y:t.rect.y-e.rect.y,width:t.rect.width-e.rect.width,height:t.rect.height-e.rect.height},r=hr(t.rect.width/e.rect.width),i=hr(t.rect.height/e.rect.height),a=Math.abs(r-1)>=.08||Math.abs(i-1)>=.12;return{text:e.text,baselineRect:e.rect,currentRect:t.rect,delta:n,confidence:Math.round(Math.min(e.confidence,t.confidence)*100)/100,possibleTextMetricMismatch:a}}function sr(e){return Math.abs(e.delta.x)>=2||Math.abs(e.delta.y)>=2||Math.abs(e.delta.width)>=2||Math.abs(e.delta.height)>=2||e.possibleTextMetricMismatch}function cr(e){return Math.abs(e.delta.x)+Math.abs(e.delta.y)+Math.abs(e.delta.width)+Math.abs(e.delta.height)+(e.possibleTextMetricMismatch?25:0)}function lr(e){let t=[];for(let n of[...e].sort((e,t)=>e.currentRect.y-t.currentRect.y)){let e=t.find(e=>Math.abs(n.delta.x-mr(e.map(e=>e.delta.x)))<=32);e?e.push(n):t.push([n])}return t.filter(e=>e.length>=2).map(ur).filter(e=>e.yRange.max-e.yRange.min<=60).sort((e,t)=>dr(t)-dr(e)).slice(0,4)}function ur(e){let t=e.map(e=>e.delta.x),n=e.map(e=>e.delta.y);return{texts:e.map(e=>e.text),xRange:{min:Math.min(...t),max:Math.max(...t)},yRange:{min:Math.min(...n),max:Math.max(...n)}}}function dr(e){let t=(e.xRange.min+e.xRange.max)/2,n=(e.yRange.min+e.yRange.max)/2;return Math.abs(t)*2+Math.abs(n)}function R(e,t,n){let r=t.get(n);return r===void 0?``:e[r]??``}function z(e,t,n){let r=Number(R(e,t,n));return Number.isFinite(r)?r:0}function fr(e){return/[\p{L}\p{N}]/u.test(e)}function pr(e){return e.trim().replace(/\s+/g,` `).toLowerCase()}function mr(e){return e.reduce((e,t)=>e+t,0)/e.length}function B(e){return Math.round(e*100*100)/100}function hr(e){return Math.round(e*1e3)/1e3}function gr(e,t){return e.flatMap(e=>_r(e,t.baseline.width,t.baseline.height)?vr(e,t,wr(t.baseline.height)):[e])}function _r(e,t,n){let r=e.maxX-e.minX+1;return e.maxY-e.minY+1>=Cr(n)&&r>=t*.35}function vr(e,t,n){let r=Sr(e,xr(br(yr(e,t.diffMask,t.baseline.width)),Math.max(1,Math.round((e.maxX-e.minX+1)*.08))),n);if(r.length<=1)return[e];let i=r.map(([n,r])=>Tr(e,n,r,t)).filter(e=>e!==null);return i.length>1?i:[e]}function yr(e,t,n){let r=[];for(let i=e.minY;i<=e.maxY;i+=1){let a=0;for(let r=e.minX;r<=e.maxX;r+=1)t[i*n+r]===1&&(a+=1);r.push(a)}return r}function br(e){return e.map((t,n)=>{let r=0,i=0,a=Math.max(0,n-3),o=Math.min(e.length-1,n+3);for(let t=a;t<=o;t+=1)r+=e[t],i+=1;return Math.round(r/i)})}function xr(e,t){let n=[],r=null;for(let i=0;i<e.length;i+=1){if(e[i]<=t){r??=i;continue}r!==null&&(i-r>=6&&n.push([r,i-1]),r=null)}return r!==null&&e.length-r>=6&&n.push([r,e.length-1]),n}function Sr(e,t,n){let r=[],i=e.minY;for(let[a,o]of t){let t=e.minY+Math.round((a+o)/2);t-i+1<n||e.maxY-t<n||(r.push([i,t]),i=t+1)}return r.push([i,e.maxY]),r}function Cr(e){return Math.max(48,Math.round(e*.07))}function wr(e){return Math.max(24,Math.round(e*.03))}function Tr(e,t,n,r){let i=null;for(let a=t;a<=n;a+=1)for(let t=e.minX;t<=e.maxX;t+=1){let e=a*r.baseline.width+t;r.diffMask[e]===1&&(i??=Er(t,a),Dr(i,e,t,a,r.baseline,r.current))}return i}function Er(e,t){return{minX:e,minY:t,maxX:e,maxY:t,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0}}function Dr(e,t,n,r,i,a){let o=t*4;e.minX=Math.min(e.minX,n),e.minY=Math.min(e.minY,r),e.maxX=Math.max(e.maxX,n),e.maxY=Math.max(e.maxY,r),e.differentPixels+=1,e.baselineRed+=i.data[o],e.baselineGreen+=i.data[o+1],e.baselineBlue+=i.data[o+2],e.currentRed+=a.data[o],e.currentGreen+=a.data[o+1],e.currentBlue+=a.data[o+2]}const Or=2.5;function kr(e){let t=Ar(e);return gr(t.length<=2e3?Nr(t,12):t,e).sort((e,t)=>{let n=t.differentPixels-e.differentPixels;if(n!==0)return n;let r=e.minY-t.minY;return r===0?e.minX-t.minX:r}).slice(0,8).map((t,n)=>Ir(t,n+1,{width:e.baseline.width,height:e.baseline.height,totalPixels:e.totalPixels,differentPixels:e.differentPixels}))}function Ar(e){let{diffMask:t,baseline:n,current:r}=e,{width:i,height:a}=n;return bn({mask:t,width:i,height:a,hooks:{create:e=>jr(e,i),visit:(e,t)=>Mr(e,t,i,n,r)}})}function jr(e,t){let n=e%t,r=Math.floor(e/t);return{minX:n,minY:r,maxX:n,maxY:r,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0}}function Mr(e,t,n,r,i){let a=t%n,o=Math.floor(t/n),s=t*4;e.minX=Math.min(e.minX,a),e.minY=Math.min(e.minY,o),e.maxX=Math.max(e.maxX,a),e.maxY=Math.max(e.maxY,o),e.differentPixels+=1,e.baselineRed+=r.data[s],e.baselineGreen+=r.data[s+1],e.baselineBlue+=r.data[s+2],e.currentRed+=i.data[s],e.currentGreen+=i.data[s+1],e.currentBlue+=i.data[s+2]}function Nr(e,t){let n=[];for(let r of e.sort((e,t)=>{let n=e.minY-t.minY;return n===0?e.minX-t.minX:n})){let e=n.find(e=>Pr(e,r,t));if(!e){n.push({...r});continue}Fr(e,r)}return n}function Pr(e,t,n){return e.minX-n<=t.maxX&&t.minX-n<=e.maxX&&e.minY-n<=t.maxY&&t.minY-n<=e.maxY}function Fr(e,t){e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e.differentPixels+=t.differentPixels,e.baselineRed+=t.baselineRed,e.baselineGreen+=t.baselineGreen,e.baselineBlue+=t.baselineBlue,e.currentRed+=t.currentRed,e.currentGreen+=t.currentGreen,e.currentBlue+=t.currentBlue}function Ir(e,t,n){let r={x:e.minX,y:e.minY,width:e.maxX-e.minX+1,height:e.maxY-e.minY+1},i={x:Math.round(e.minX+r.width/2),y:Math.round(e.minY+r.height/2)},a=Lr(e.baselineRed,e.baselineGreen,e.baselineBlue,e.differentPixels),o=Lr(e.currentRed,e.currentGreen,e.currentBlue,e.differentPixels),s=r.width*r.height,c=H(e.differentPixels/s),l=Math.round(V(a)),u=Math.round(V(o)),d=Br(r,n.width,n.height),f=Vr(s,n.totalPixels),p=zr(a,o),m=Rr(i,n.width,n.height);return{index:t,rect:r,normalizedRect:Xe({x:H(r.x/n.width),y:H(r.y/n.height),width:H(r.width/n.width),height:H(r.height/n.height)}),differentPixels:e.differentPixels,shareOfDiffPercentage:H(e.differentPixels/n.differentPixels),densityPercentage:c,shape:d,size:f,location:m,averageBaselineColorHex:Hr(a),averageCurrentColorHex:Hr(o),baselineLuminance:l,currentLuminance:u,dominantChange:p}}function Lr(e,t,n,r){return{r:Math.round(e/r),g:Math.round(t/r),b:Math.round(n/r)}}function Rr(e,t,n){let r=e.x<t/3?`left`:e.x>t*2/3?`right`:`center`,i=e.y<n/3?`top`:e.y>n*2/3?`bottom`:`middle`;return r===`center`&&i===`middle`?`center`:`${i}-${r}`}function zr(e,t){let n=V(e),r=V(t)-n;return Math.abs(r)>=12?r>0?`brighter`:`darker`:Math.max(Math.abs(t.r-e.r),Math.abs(t.g-e.g),Math.abs(t.b-e.b))>=12?`color-shift`:`mixed`}function Br(e,t,n){return e.width>=t*.55&&e.height>=n*.12?`large-area`:e.width>=e.height*Or?`horizontal-band`:e.height>=e.width*Or?`vertical-band`:`compact`}function Vr(e,t){let n=e/t;return n>=.04?`large`:n>=.01?`medium`:`small`}function V(e){return e.r*.2126+e.g*.7152+e.b*.0722}function Hr(e){return`#${Ur(e.r)}${Ur(e.g)}${Ur(e.b)}`}function Ur(e){return e.toString(16).padStart(2,`0`)}function H(e){return Math.round(e*100*100)/100}const Wr=255*Math.sqrt(3);async function Gr(e,t,n={}){await Kr(e,`Baseline image not found`),await Kr(t,`Current screenshot not found`);let r=n.outputPath,[i,a]=await Promise.all([T.readFile(e),T.readFile(t)]),[o,s]=await Promise.all([N(i,`baseline screenshot`),N(a,`current screenshot`)]);qr(o.width,o.height,`baseline screenshot`,n.maxPixels),qr(s.width,s.height,`current screenshot`,n.maxPixels);let c=n.threshold??.1;if(o.width!==s.width||o.height!==s.height){let e=o.width*o.height;return await Jr(n.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:o.width,height:o.height},actual:{width:s.width,height:s.height}}}}let l=o.width*o.height,u=c*Wr,{diffData:d,diffMask:f,differentPixels:p}=await hn({width:o.width,height:o.height,baselineData:o.data,currentData:s.data,maxColorDistance:u}),m=p>0?kr({diffMask:f,baseline:o,current:s,totalPixels:l,differentPixels:p}):[];if(p>0&&r){let e=new it({width:o.width,height:o.height,data:d});gn(e,m),await T.mkdir(E.dirname(r),{recursive:!0}),await T.writeFile(r,await P(e))}else await Jr(n.outputPath);let h=p>0?await $n({baselinePath:e,currentPath:t,width:o.width,height:o.height}):void 0,ee=h&&(h.matches.length>0||(h.movementClusters?.length??0)>0)?{provider:h.provider,baselineBlocks:h.baselineBlocks,currentBlocks:h.currentBlocks,matches:h.matches,...h.movementClusters?{movementClusters:h.movementClusters}:{}}:void 0,g=p>0&&h?On({diffMask:f,width:o.width,height:o.height,regions:m,ocr:h}):[],te=l>0?Math.round(p/l*100*100)/100:0;return{...p>0&&r?{diffPath:r}:{},...m.length>0?{regions:m}:{},...ee?{ocr:ee}:{},...g.length>0?{nonTextDeltas:g}:{},totalPixels:l,differentPixels:p,mismatchPercentage:te,match:p===0}}async function Kr(e,n){try{await T.access(e)}catch{throw new t(`INVALID_ARGS`,`${n}: ${e}`)}}function qr(e,n,r,i){if(i==null||i<=0)return;let a=e*n;if(!(a<=i))throw new t(`INVALID_ARGS`,`${r} is ${a} pixels, which exceeds the configured maxImagePixels limit of ${i}`)}async function Jr(e){if(e)try{await T.unlink(e)}catch(e){if(!Yr(e,`ENOENT`))throw e}}function Yr(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}function Xr(e,t){return e.map(e=>{let n=Zr(e,t);return n.length>0?{...e,currentOverlayMatches:n}:e})}function Zr(e,t){let n=Qr(e.rect);return t.map(t=>{let r=t.overlayRect,i=Ke(e.rect,r);return i<=0?null:{ref:t.ref,...t.label?{label:t.label}:{},rect:r,overlayCoveragePercentage:$r(i/Qr(r)),regionCoveragePercentage:$r(i/n)}}).filter(e=>e!==null).sort((e,t)=>{let n=t.regionCoveragePercentage-e.regionCoveragePercentage;return n===0?t.overlayCoveragePercentage-e.overlayCoveragePercentage:n}).slice(0,3).map(e=>({ref:e.ref,...e.label?{label:e.label}:{},rect:e.rect,regionCoveragePercentage:e.regionCoveragePercentage}))}function Qr(e){return e.width*e.height}function $r(e){return Math.round(e*100*100)/100}async function U(e,n,r){if(n.kind===`path`&&!e.policy.allowLocalInputPaths)throw new t(`INVALID_ARGS`,`Local ${r.field??`input`} paths are not allowed by command policy`);try{return await e.artifacts.resolveInput(n,r)}catch(e){throw s(e)}}async function W(e,n,r){if(n?.kind===`path`&&!e.policy.allowLocalOutputPaths)throw new t(`INVALID_ARGS`,`Local output paths are not allowed by command policy`);try{return await e.artifacts.reserveOutput(n,{...r,visibility:r.visibility??`client-visible`,requestedClientPath:n?.kind===`downloadableArtifact`?n.clientPath??r.requestedClientPath:r.requestedClientPath})}catch(e){throw s(e)}}async function ei(e,t){try{return await e.artifacts.createTempFile(t)}catch(e){throw s(e)}}const ti=async(e,n)=>{if(!n.baseline)throw new t(`INVALID_ARGS`,`diff screenshot requires a baseline image`);let r=ni(n.threshold),i=n.current??{kind:`live`};if(n.overlayRefs&&!ui(i))throw new t(`INVALID_ARGS`,`diff screenshot <current.png> cannot use --overlay-refs because saved-image comparisons have no live accessibility refs`);let a=await U(e,n.baseline,{usage:`diff screenshot baseline`,field:`baseline`}),o,s,c,l=[];try{let t;ui(i)?(s=await ri(e,n),t=s.path):(o=await U(e,i,{usage:`diff screenshot current`,field:`current`}),t=o.path),c=n.out?await W(e,n.out,{field:`diffPath`,ext:`.png`,artifactType:`screenshot-diff`}):void 0;let u=await Gr(a.path,t,{threshold:r,outputPath:c?.path,maxPixels:e.policy.maxImagePixels});ui(i)&&(u=await ii(e,n,c?.path,u,l));let d=u.diffPath?await c?.publish():void 0;return d&&l.push(d),u.diffPath||await c?.cleanup?.(),{...u,...l.length>0?{artifacts:l}:{}}}catch(e){throw await c?.cleanup?.(),e}finally{await a.cleanup?.(),await o?.cleanup?.(),await s?.cleanup?.()}};function ni(e){if(e==null||e===``)return .1;let n=Number(e);if(Number.isNaN(n)||n<0||n>1)throw new t(`INVALID_ARGS`,`--threshold must be a number between 0 and 1`);return n}async function ri(e,t){let n=await ei(e,{prefix:`agent-device-diff-current`,ext:`.png`});try{await ai(e,t,n.path,oi(t))}catch(e){throw await n.cleanup(),e}return n}async function ii(e,t,n,r,i){if(!t.overlayRefs)return r;if(r.match||r.dimensionMismatch)return n&&await li(n),r;let a=await W(e,si(t,n),{field:`currentOverlayPath`,ext:`.png`,artifactType:`screenshot`});try{let n=await ai(e,t,a.path,{overlayRefs:!0,...oi(t)}),o=await a.publish();return o&&i.push(o),{...r,currentOverlayPath:n.path??a.path,...n.overlayRefs?{currentOverlayRefCount:n.overlayRefs.length}:{},...r.regions&&n.overlayRefs?{regions:Xr(r.regions,n.overlayRefs)}:{}}}catch(e){throw await a.cleanup?.(),e}}async function ai(e,n,r,i={}){if(!e.backend.captureScreenshot)throw new t(`UNSUPPORTED_OPERATION`,`screenshot is not supported by this backend`);return await e.backend.captureScreenshot({session:n.session,requestId:n.requestId,signal:n.signal??e.signal,metadata:n.metadata},r,i)??{}}function oi(e){return{normalizeStatusBar:e.normalizeStatusBar??!0,...e.surface?{surface:e.surface}:{}}}function si(e,t){if(e.currentOverlayOut)return e.currentOverlayOut;if(e.out?.kind===`path`)return{kind:`path`,path:ci(t??e.out.path)};if(e.out?.kind===`downloadableArtifact`)return{kind:`downloadableArtifact`,...e.out.clientPath?{clientPath:ci(e.out.clientPath)}:{},...e.out.fileName?{fileName:ci(e.out.fileName)}:{}}}function ci(e){let t=E.extname(e);return`${t?e.slice(0,-t.length):e}.current-overlay${t||`.png`}`}async function li(e){try{await T.unlink(ci(e))}catch(e){if(!di(e,`ENOENT`))throw e}}function ui(e){return e.kind===`live`}function di(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}async function fi(e,n){if(!Number.isInteger(n)||n<1)throw new t(`INVALID_ARGS`,`Screenshot max size must be a positive integer`);let r=await N(await T.readFile(e),`screenshot`),i=Math.max(r.width,r.height);if(i<=n)return;let a=n/i,o=mi(r,Math.max(1,Math.round(r.width*a)),Math.max(1,Math.round(r.height*a)));await T.writeFile(e,await P(o))}async function pi(e,n,r){if(!Number.isInteger(n)||n<1||!Number.isInteger(r)||r<1)throw new t(`INVALID_ARGS`,`Screenshot resize dimensions must be positive integers`);let i=await N(await T.readFile(e),`screenshot`);i.width===n&&i.height===r||await T.writeFile(e,await P(mi(i,n,r)))}function mi(e,t,n){let r=new it({width:t,height:n});for(let i=0;i<n;i+=1){let a=i*e.height/n,o=(i+1)*e.height/n;for(let n=0;n<t;n+=1){let s=n*e.width/t,c=(n+1)*e.width/t,l=0,u=0,d=0,f=0,p=0;for(let t=Math.floor(a);t<Math.ceil(o);t+=1){let n=Math.min(t+1,o)-Math.max(t,a);for(let r=Math.floor(s);r<Math.ceil(c);r+=1){let i=n*(Math.min(r+1,c)-Math.max(r,s)),a=(t*e.width+r)*4;l+=(e.data[a]??0)*i,u+=(e.data[a+1]??0)*i,d+=(e.data[a+2]??0)*i,f+=(e.data[a+3]??0)*i,p+=i}}let m=(i*r.width+n)*4;r.data[m]=Math.round(l/p),r.data[m+1]=Math.round(u/p),r.data[m+2]=Math.round(d/p),r.data[m+3]=Math.round(f/p)}}return r}const hi=async(e,n)=>{if(!e.backend.captureScreenshot)throw new t(`UNSUPPORTED_OPERATION`,`screenshot is not supported by this backend`);let r=await W(e,n.out,{field:`path`,ext:`.png`,artifactType:`screenshot`}),i;try{await e.backend.captureScreenshot({session:n.session,requestId:n.requestId,appId:n.appId,appBundleId:n.appBundleId,signal:n.signal??e.signal,metadata:n.metadata},r.path,{fullscreen:n.fullscreen,overlayRefs:n.overlayRefs,pixelDensity:n.pixelDensity,stabilize:n.stabilize,normalizeStatusBar:n.normalizeStatusBar,surface:n.surface}),n.maxSize!==void 0&&await fi(r.path,n.maxSize),i=await r.publish()}catch(e){throw await r.cleanup?.(),e}return{path:r.path,...i?{artifacts:[i]}:{},...C(`Saved screenshot: ${r.path}`)}};function gi(e){let{nodes:t,backend:n,snapshotRaw:i}=e;if(i||!r(n))return{partial:!1,visibleNodeCount:t.length,totalNodeCount:t.length,reasons:[]};let a=De(t),o=new Set;return a.hiddenCount>0&&o.add(`offscreen-nodes`),a.nodes.some(e=>e.hiddenContentAbove)&&o.add(`scroll-hidden-above`),a.nodes.some(e=>e.hiddenContentBelow)&&o.add(`scroll-hidden-below`),{partial:o.size>0,visibleNodeCount:a.nodes.length,totalNodeCount:t.length,reasons:[...o]}}const _i=`A system surface (notification shade, quick settings, or another system overlay) covers the app, so this snapshot shows that surface. Interact with it or dismiss it (press back or swipe up) to reach app content.`;function vi(e){return e?.systemSurfaceOnly===!0?_i:void 0}function yi(e,t){return e.presentationKey?e:{...e,presentationKey:i(t)}}function bi(e){let{previous:t,current:n,options:r,identity:i}=e;if(r.forceFull===!0||r.raw===!0||!t||t.comparisonSafe===!1||n.comparisonSafe===!1||!xi(t,n,i)||!t.presentationKey||t.presentationKey!==n.presentationKey||!Si(t,n))return;let a=r.scope?.trim();return{ageMs:Math.max(0,n.createdAt-t.createdAt),nodeCount:n.nodes.length,...r.interactiveOnly===!0?{interactiveOnly:!0}:{},...a?{scope:a}:{}}}function xi(e,t,n){return!(e.backend&&t.backend&&e.backend!==t.backend||n?.previousAppBundleId&&n.currentAppBundleId&&n.previousAppBundleId!==n.currentAppBundleId)}function Si(e,t){return e.truncated===t.truncated?JSON.stringify(Ci(e.nodes))===JSON.stringify(Ci(t.nodes)):!1}function Ci(e){return e.map(e=>({index:e.index,depth:e.depth,parentIndex:e.parentIndex,type:e.type,role:e.role,subrole:e.subrole,label:e.label,value:e.value,identifier:e.identifier,enabled:e.enabled,selected:e.selected,focused:e.focused,hittable:e.hittable,rect:e.rect,bundleId:e.bundleId,appName:e.appName,windowTitle:e.windowTitle,surface:e.surface,hiddenContentAbove:e.hiddenContentAbove,hiddenContentBelow:e.hiddenContentBelow,interactionBlocked:e.interactionBlocked,presentationHints:e.presentationHints}))}const wi=async(e,t)=>{let n=await Ei(e,t),r=bi({previous:n.session?.snapshot,current:n.snapshot,options:t,identity:{previousAppBundleId:n.session?.appBundleId,currentAppBundleId:n.result.appBundleId??n.session?.appBundleId}});return await e.sessions.set(Oi(t.session,n)),{nodes:n.snapshot.nodes,truncated:n.snapshot.truncated??!1,visibility:gi({nodes:n.snapshot.nodes,backend:n.snapshot.backend,snapshotRaw:t.raw}),...qe({...n.annotations,warnings:n.warnings}),...r?{unchanged:r}:{},...n.result.snapshotDiagnostics?{snapshotDiagnostics:n.result.snapshotDiagnostics}:{},...ki(n)}},Ti=async(e,t)=>{let n=await Ei(e,t),r=t.interactiveOnly===!0,i=n.session?.snapshot,a=Oi(t.session,n);if(!i){let t=re(n.snapshot.nodes,{flatten:r});return await e.sessions.set(a),{mode:`snapshot`,baselineInitialized:!0,summary:{additions:0,removals:0,unchanged:t},lines:[],...n.warnings.length>0?{warnings:n.warnings}:{}}}let o=de(i.nodes,n.snapshot.nodes,{flatten:r});return await e.sessions.set(a),{mode:`snapshot`,baselineInitialized:!1,summary:o.summary,lines:o.lines,...n.warnings.length>0?{warnings:n.warnings}:{}}};async function Ei(e,n){if(!e.backend.captureSnapshot)throw new t(`UNSUPPORTED_OPERATION`,`snapshot is not supported by this backend`);let r=n.session??`default`,i=await e.sessions.get(r),a=await e.backend.captureSnapshot({session:r,requestId:n.requestId,appId:i?.appId,appBundleId:i?.appBundleId,signal:n.signal??e.signal,metadata:n.metadata},{interactiveOnly:n.interactiveOnly,depth:n.depth,scope:n.scope,raw:n.raw}),o=yi(Di(a,e),n),s=Ge(a),c=_(e);return{snapshot:o,result:a,session:i,annotations:s,warnings:Ai({result:a,annotations:s,snapshot:o,options:n,session:i,capturedAt:o.createdAt??c,runtimeNow:c})}}function Di(e,t){return e.snapshot?e.snapshot:{nodes:e.nodes??[],truncated:e.truncated,backend:e.backend,createdAt:_(t)}}function Oi(e,t){let n=t.session?.name??e??`default`;return{...t.session??{name:n},name:n,snapshot:t.snapshot,appName:t.result.appName??t.session?.appName,appBundleId:t.result.appBundleId??t.session?.appBundleId}}function ki(e){let t=e.result.appName??e.session?.appName,n=e.result.appBundleId??e.session?.appBundleId;return{...t||n?{appName:t??n}:{},...n?{appBundleId:n}:{}}}function Ai(e){let t=[...e.annotations.warnings??[]];e.annotations.quality&&t.push(...He(e.annotations.quality,e.snapshot.nodes)),t.push(...Pi(e)),e.annotations.quality||(t.push(...Mi(e)),t.push(...Ni(e.snapshot.nodes)));let n=_t(e.snapshot.nodes);n&&t.push(n);let r=ji(e.annotations);r&&t.push(r);let i=Fi(e);return i&&t.push(i),t.push(...zi(e.annotations.freshness,e.snapshot.backend)),Array.from(new Set(t))}function ji(e){if(e.androidSnapshot?.systemSurfaceOnly===!0)return _i}function Mi(e){return e.snapshot.backend!==`xctest`||e.options.interactiveOnly!==!0||e.snapshot.nodes.length!==1||e.snapshot.nodes[0]?.type!==`Application`?[]:[`iOS interactive snapshot exposed only the application root. XCTest accessibility queries can fail to enumerate some simulator UI trees even when screenshots and direct gestures still work. Use screenshot as visual truth, try a scoped/full snapshot for diagnostics, and prefer direct selectors when known.`]}function Ni(e){let t=new Set(e.map(e=>e.parentIndex).filter(e=>e!==void 0));return e.filter(e=>t.has(e.index)||(e.type?.toLowerCase()??``).includes(`text`)?!1:(e.label??``).split(`, `).length>10).map(e=>{let t=(e.label??``).split(`, `).length,n=e.identifier?` (${e.identifier})`:``;return`@${e.ref} [${e.type??`element`}]${n} merges ~${t} labels into a single accessibility element. The app likely marks a container as accessible, which hides every descendant from assistive tech and automation — the children cannot be addressed individually. Fix the app's accessibility (mark the rows, not the container); until then use screenshot as visual truth and coordinate taps.`})}function Pi(e){let t=e.annotations.analysis;if(e.snapshot.backend!==`android`||e.options.interactiveOnly!==!0||e.snapshot.nodes.length>0||!t||(t.rawNodeCount??0)<12)return[];let n=[`Interactive snapshot is empty after filtering ${t.rawNodeCount} raw Android nodes. Likely causes: the app content is not accessibility-visible yet, a transient route change, or depth/filter options hid the target.`];return typeof e.options.depth==`number`&&typeof t.maxDepth==`number`&&t.maxDepth>=e.options.depth+2&&n.push(`Interactive output is empty at depth ${e.options.depth}; retry without -d.`),n}function Fi(e){let t=e.session?.snapshot;if(!e.annotations.freshness&&t&&Ii(t,e.snapshot)&&Li(t,e.capturedAt,e.runtimeNow)&&Bi(t.nodes.length,e.snapshot.nodes.length))return Ri}function Ii(e,t){return e.presentationKey===void 0||t.presentationKey===void 0?!0:e.presentationKey===t.presentationKey}function Li(e,t,n){return[t,n].some(t=>{let n=t-e.createdAt;return n>=0&&n<=2e3})}const Ri=`Recent snapshots dropped sharply in node count, which suggests stale or mid-transition UI. Use screenshot as visual truth, wait briefly, then re-snapshot once.`;function zi(e,t){return!e?.staleAfterRetries||t!==`android`?[]:e.reason===`stuck-route`?[`Recent ${e.action} was followed by a nearly identical snapshot after ${e.retryCount} automatic retr${e.retryCount===1?`y`:`ies`}. If you expected navigation or submit, the tree may still be stale. Use screenshot as visual truth, wait briefly, then re-snapshot once.`]:e.reason===`sharp-drop`?[Ri]:[]}function Bi(e,t){return e<12?!1:t<=Math.floor(e*.2)}const Vi={screenshot:hi,diffScreenshot:ti,snapshot:wi,diffSnapshot:Ti},Hi=async(e,t)=>await Ki(e,t,`press`),Ui=async(e,t)=>await Ki(e,t,`click`),Wi=async(e,n)=>{if(!n.text)throw new t(`INVALID_ARGS`,`fill requires text`);let r=ve(n),i=r.needsPreActionBaseline?null:await Yi(e,n);if(i)return i;let a=await se(e,n,{action:`fill`,requireInteractive:!0,promoteToHittableAncestor:!1,captureEvidenceBaseline:r.needsPreActionBaseline,expectedResolvedTarget:n.expectedResolvedTarget});if(!e.backend.fill)throw new t(`UNSUPPORTED_OPERATION`,`fill is not supported by this backend`);let o=qi(a),s=x(await e.backend.fill(S(e,n),o,n.text,{delayMs:n.delayMs})),c=`node`in a?a.node?.type??``:``,l=c&&!Te(c,e.backend.platform)?`fill target ${Zi(a)} resolved to "${c}", attempting fill anyway.`:void 0;return await pe(e,n,a,{...a,text:n.text,...l?{warning:l}:{},...s?{backendResult:s}:{}},r)},Gi=async(e,n)=>{let r=n.text;if(!r)throw new t(`INVALID_ARGS`,`type requires text`);let i=Qi(r);if(i)throw new t(`INVALID_ARGS`,`type does not accept a target ref like "${i}"`,{hint:`Use fill ${i} "text" to target that field, or press ${i} then type "text" to append.`});if(!e.backend.typeText)throw new t(`UNSUPPORTED_OPERATION`,`type is not supported by this backend`);let a=v(n.delayMs??0,`delay-ms`,0,1e4),o=x(await e.backend.typeText(S(e,n),r,{delayMs:a}));return{kind:`text`,text:r,delayMs:a,...o?{backendResult:o}:{},...C(`Typed ${Array.from(r).length} chars`)}};async function Ki(e,n,r){let i=ve(n),a=i.needsPreActionBaseline?null:await Ji(e,n,r);if(a)return a;let o=await se(e,n,{action:r,requireInteractive:!0,promoteToHittableAncestor:!0,captureEvidenceBaseline:i.needsPreActionBaseline,expectedResolvedTarget:n.expectedResolvedTarget});if(!e.backend.tap)throw new t(`UNSUPPORTED_OPERATION`,`tap is not supported by this backend`);let s=qi(o),c=x(await e.backend.tap(S(e,n),s,{button:n.button,count:n.count,intervalMs:n.intervalMs,holdMs:n.holdMs,jitterPx:n.jitterPx,doubleTap:n.doubleTap}));return await pe(e,n,o,{...o,...c?{backendResult:c}:{}},i)}function qi(e){if(!e.point)throw new t(`COMMAND_FAILED`,`Interaction target resolved without coordinates`);return e.point}async function Ji(e,t,n){if(n!==`click`||t.target.kind!==`ref`||!e.backend.tapTarget||Xi(t)||t.expectedResolvedTarget)return null;let r=await me(e,t,t.target,n),i=x(await e.backend.tapTarget(S(e,t),{kind:`ref`,ref:t.target.ref,...t.target.fallbackLabel?{fallbackLabel:t.target.fallbackLabel}:{}}));return{kind:`ref`,target:{kind:`ref`,ref:t.target.ref},resolution:ne,...r,...i?{backendResult:i}:{}}}async function Yi(e,t){if(t.target.kind!==`ref`||!e.backend.fillTarget||t.expectedResolvedTarget)return null;let n=await me(e,t,t.target,`fill`),r=x(await e.backend.fillTarget(S(e,t),{kind:`ref`,ref:t.target.ref,...t.target.fallbackLabel?{fallbackLabel:t.target.fallbackLabel}:{}},t.text,{delayMs:t.delayMs}));return{kind:`ref`,target:{kind:`ref`,ref:t.target.ref},text:t.text,resolution:ne,...n,...r?{backendResult:r}:{}}}function Xi(e){return e.count!==void 0||e.intervalMs!==void 0||e.holdMs!==void 0||e.jitterPx!==void 0||e.doubleTap!==void 0||e.button!==void 0&&e.button!==`primary`}function Zi(e){return e.target?.kind===`ref`?e.target.ref:e.target?.kind===`selector`?e.target.selector:`point`}function Qi(e){return $t(e)}function $i(e){return{includeRects:ea(e.predicate),interactiveOnly:!1}}function ea(e){return e===`visible`||e===`hidden`}const ta=1e4,na=async(e,n)=>{let r=n.locator??`any`;if(!n.query)throw new t(`INVALID_ARGS`,m);if(n.action===`wait`)return await da(e,n,r);let{capture:i,match:a}=await fa(e,n,r);if(!a)throw new t(`COMMAND_FAILED`,`find did not match any element`);if(n.action===`exists`)return{kind:`found`,found:!0};let o=`@${a.ref}`;return n.action===`get_attrs`?{kind:`attrs`,ref:o,node:a}:{kind:`text`,ref:o,text:await le(e,i,a),node:a}},ra=async(e,t)=>{if(t.target.kind===`ref`){let n=await ie(e,t.session),r=ae(n.snapshot.nodes,t.target.ref,{fallbackLabel:t.target.fallbackLabel??``,invalidRefMessage:`get text requires a ref like @e2`,notFoundMessage:`Ref ${t.target.ref} not found`});ce(r.node,n.snapshot.nodes,t.expectedResolvedTarget,`get`);let i=Le(r.node,e.backend.platform,{action:`get`,nodes:n.snapshot.nodes}),a={kind:`ref`,ref:`@${r.ref}`},o=n.snapshot.nodes;return t.property===`attrs`?{kind:`attrs`,target:a,node:r.node,selectorChain:i,preActionNodes:o}:{kind:`text`,target:a,text:await le(e,n,r.node),node:r.node,selectorChain:i,preActionNodes:o}}let n=await xa(e,t,t.session??`default`,{selector:t.target.selector,disambiguateAmbiguous:t.property===`text`});ce(n.node,n.capture.snapshot.nodes,t.expectedResolvedTarget,`get`);let r=Le(n.node,e.backend.platform,{action:`get`,nodes:n.capture.snapshot.nodes});if(t.property===`attrs`)return{kind:`attrs`,target:{kind:`selector`,selector:n.selector},node:n.node,selectorChain:r,preActionNodes:n.capture.snapshot.nodes};let i=await le(e,n.capture,n.node);return{kind:`text`,target:{kind:`selector`,selector:n.selector},text:i,node:n.node,selectorChain:r,preActionNodes:n.capture.snapshot.nodes}},ia=async(e,n)=>{let r=await ra(e,{...n,property:`text`,target:n.target});if(r.kind!==`text`)throw new t(`COMMAND_FAILED`,`getText returned non-text result`);return r},aa=async(e,n)=>{let r=await ra(e,{...n,property:`attrs`,target:n.target});if(r.kind!==`attrs`)throw new t(`COMMAND_FAILED`,`getAttrs returned non-attrs result`);return r},oa=async(e,n)=>{let r=Ee(n.predicate);if(!r.ok)throw new t(r.code,r.message,{hint:r.hint});let i=r.predicate;if(i===`text`&&!n.expectedText)throw new t(`INVALID_ARGS`,Re);let a=f(n.selector),o=await y(e,n,{updateSession:!0,...$i({predicate:i,selectorChain:a})});if(i===`exists`){let n=ke(o.snapshot.nodes,a,{platform:e.backend.platform});if(!n)throw new t(`COMMAND_FAILED`,Fe(a,[],{unique:!1}),{hint:je([])});return{predicate:i,pass:!0,selector:n.selector.raw,matches:n.matches,selectorChain:a.selectors.map(e=>e.raw)}}let s=Me(o.snapshot.nodes,a,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:!1});if(!s)throw new t(`COMMAND_FAILED`,Fe(a,[],{unique:!0}),{command:`is`,reason:`selector_not_found`,predicate:i,selector:a.raw,hint:je([])});ce(s.node,o.snapshot.nodes,n.expectedResolvedTarget,`is`);let c=Se({predicate:i,node:s.node,nodes:o.snapshot.nodes,expectedText:n.expectedText,platform:e.backend.platform});if(!c.pass)throw new t(`COMMAND_FAILED`,`is ${i} failed for selector ${s.selector.raw}: ${c.details}`,{command:`is`,reason:`predicate_failed`,predicate:i,selector:s.selector.raw,predicateDetails:c.details});return{predicate:i,pass:!0,selector:s.selector.raw,...i===`text`?{text:c.actualText}:{},selectorChain:a.selectors.map(e=>e.raw),node:s.node,preActionNodes:o.snapshot.nodes}},sa=async(e,t)=>await oa(e,{...t,predicate:`visible`,selector:t.target.selector}),ca=async(e,t)=>await oa(e,{...t,predicate:`hidden`,selector:t.target.selector}),la=async(e,r)=>{if(r.target.kind===`sleep`)return await b(e,r.target.durationMs),{kind:`sleep`,waitedMs:r.target.durationMs};if(r.target.kind===`ref`){let i=await ie(e,r.session),o=a(r.target.ref);if(!o)throw new t(`INVALID_ARGS`,`Invalid ref: ${r.target.ref}`);let s=n(i.snapshot.nodes,o),c=s?ze(s,i.snapshot.nodes):void 0;if(!c)throw new t(`COMMAND_FAILED`,`Ref ${r.target.ref} not found or has no label`);return await va(e,r,c,r.target.timeoutMs)}if(r.target.kind===`selector`)return await ha(e,r,r.target.selector,r.target.timeoutMs,r.target.recordedLandmark);if(r.target.kind===`stable`)return await ba(e,r,r.target.quietMs,r.target.timeoutMs);let i=xe(r.target.text);if(!i.ok)throw new t(i.code,i.message);return await va(e,r,r.target.text,r.target.timeoutMs)},ua=async(e,n)=>{let r=await la(e,{...n,target:{kind:`text`,text:n.text,timeoutMs:n.timeoutMs}});if(r.kind!==`text`)throw new t(`COMMAND_FAILED`,`waitForText returned non-text result`);return r};async function da(e,n,r){let i=n.timeoutMs??ta,a=_(e);for(;_(e)-a<i;){let{match:t}=await fa(e,n,r,{includeHiddenContentHints:!1});if(t)return{kind:`found`,found:!0,waitedMs:_(e)-a};await b(e,300)}throw new t(`COMMAND_FAILED`,`find wait timed out`)}async function fa(e,t,n,r){let i=h(n,t.query),a=await y(e,t,{updateSession:!0,scope:pa(e,n,t.query,i),includeHiddenContentHints:r?.includeHiddenContentHints,...$i({selectorChain:i})});if(Ve(a.snapshot.snapshotQuality))throw ma(a.snapshot.snapshotQuality);return i?{capture:a,match:Me(a.snapshot.nodes,i,{platform:e.backend.platform,requireRect:!1,requireUnique:!1})?.node}:{capture:a,match:p(a.snapshot.nodes,n,t.query,{requireRect:!1}).matches[0]}}function pa(e,t,n,r){if(!r&&e.backend.platform!==`web`)return oe(t)?n:void 0}function ma(e){return new t(`COMMAND_FAILED`,`find could not read the current accessibility tree`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen.`})}async function ha(e,n,r,i,a){let o=i??ta,s=_(e),c=f(r),l=$i({selectorChain:c}),u,d=ga();for(;_(e)-s<o;){let t=await d.attempt(()=>y(e,n,{updateSession:!0,includeHiddenContentHints:!1,...l}));if(t){let n=t.snapshot.nodes,r=Pe(n,c,{platform:e.backend.platform});if(r){let t=_a(n,r,a);if(t.kind===`satisfied`)return{kind:`selector`,selector:r.selector.raw,waitedMs:_(e)-s,node:t.node,preActionNodes:n};u=t.evidence}}await b(e,300)}throw u?new t(`COMMAND_FAILED`,`wait matched selector ${r} but no candidate carried the recorded landmark identity`,{reason:Ne,...u}):(d.rethrowIfNeverReadable(),new t(`COMMAND_FAILED`,`wait timed out for selector: ${r}`))}function ga(){let e=!1,t;return{attempt:async n=>{try{let t=await n();return e=!0,t}catch(e){if(!Ze(e))throw e;t=e;return}},rethrowIfNeverReadable:()=>{if(!e&&t!==void 0)throw t}}}function _a(e,t,n){let r=t.matchedNodes[0];if(!n)return{kind:`satisfied`,node:r};let i=Qe(e),a=et(t.matchedNodes,i,Ae(n),n.ancestry)[0];return a?{kind:`satisfied`,node:a}:{kind:`identity-mismatch`,evidence:{matchCount:t.matchedNodes.length,observed:Ie(r),observedAncestry:$e(r,i,Math.max(n.ancestry.length,1)).chain}}}async function va(e,n,r,i){let a=i??ta,o=_(e),s=ga();for(;_(e)-o<a;){if(await s.attempt(async()=>e.backend.findText?(await e.backend.findText(S(e,n),r)).found:await ya(e,n,r)))return{kind:`text`,text:r,waitedMs:_(e)-o};await b(e,300)}throw s.rethrowIfNeverReadable(),new t(`COMMAND_FAILED`,`wait timed out for text: ${r}`)}async function ya(e,t,n){return!!Ce((await y(e,t,{updateSession:!0,includeHiddenContentHints:!1})).snapshot.nodes,n)}async function ba(e,n,r,i){let a=i??ta,o=r??500,s=await te(e,n,{quietMs:o,timeoutMs:a});if(!s.settled)throw new t(`COMMAND_FAILED`,`wait timed out waiting for a stable UI`,{reason:`wait_stable_timeout`,...s.stalled?{captureStalled:!0}:{},quietMs:o,timeoutMs:a,captures:s.captures,nodeCount:s.nodeCount,...s.stalled?{hint:`A snapshot capture stalled past the wait timeout, so no settle verdict is available. The UI may still be readable: retry, or use screenshot to inspect the surface.`}:{}});return{kind:`stable`,waitedMs:s.waitedMs,captures:s.captures,nodeCount:s.nodeCount,...s.nodeCount<5?{hint:ue}:{}}}async function xa(e,n,r,i){let a=f(i.selector),o=await y(e,{...n,session:r},{updateSession:!0,...$i({selectorChain:a})}),s=Me(o.snapshot.nodes,a,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:i.disambiguateAmbiguous});if(!s)throw new t(`COMMAND_FAILED`,Fe(a,[],{unique:!0}),{hint:je([])});return{capture:o,node:s.node,selector:s.selector.raw,ref:`@${s.node.ref}`}}function Sa(e,n){let r=e.filter(t=>we(t,e)).map(e=>e.rect).filter(Ca),i=r.length>0?r:e.map(e=>e.rect).filter(Ca);if(i.length===0)throw new t(`COMMAND_FAILED`,`Cannot infer viewport for ${n}`);let a=Math.min(...i.map(e=>e.x)),o=Math.min(...i.map(e=>e.y)),s=Math.max(...i.map(e=>e.x+e.width)),c=Math.max(...i.map(e=>e.y+e.height));return{x:a,y:o,width:s-a,height:c-o}}function Ca(e){return!!(e&&e.width>0&&e.height>0)}const wa=async(e,n)=>{if(!e.backend.performGesture)throw new t(`UNSUPPORTED_OPERATION`,`gesture is not supported by this backend`);await he(e,n,n.gesture.intent);let r=await Ta(e,n),i=rt(n.gesture,r,e.backend.platform),a=x(await e.backend.performGesture(S(e,n),i)),o=Ea(i.pointers,0),s=Ea(i.pointers,-1);return{kind:i.intent,durationMs:i.durationMs,pointerCount:i.topology===`single`?1:2,from:o,to:s,...a?{backendResult:a}:{},...C(Da(n.gesture,o,s))}};async function Ta(e,t){return await e.backend.resolveGestureViewport?.(S(e,t))||Sa((await ee(e,t,!1)).snapshot.nodes,`gesture`)}function Ea(e,n){let r=e.map(e=>n===0?e.samples[0]?.point:e.samples.at(-1)?.point);if(r.some(e=>e===void 0))throw new t(`COMMAND_FAILED`,`Gesture plan did not contain endpoint samples.`);let i=r;return{x:i.reduce((e,t)=>e+t.x,0)/i.length,y:i.reduce((e,t)=>e+t.y,0)/i.length}}function Da(e,t,n){switch(e.intent){case`pan`:{let r=`preset`in e?t:e.origin,i=`preset`in e?{x:n.x-t.x,y:n.y-t.y}:e.delta;return`Panned (${r.x}, ${r.y}) by (${i.x}, ${i.y})`}case`fling`:return`direction`in e?`Flung ${e.direction}`:`Flung`;case`pinch`:return`Pinched to scale ${e.scale}`;case`rotate`:return`Rotated gesture ${e.degrees} degrees`;case`transform`:return`Requested transform gesture by (${e.delta.x}, ${e.delta.y}), scale ${e.scale}, rotate ${e.degrees} degrees`}}const G={find:na,get:ra,getText:ia,getAttrs:aa,is:oa,isVisible:sa,isHidden:ca,wait:la,waitForText:ua},K={click:Ui,press:Hi,fill:Wi,typeText:Gi,focus:fe,longPress:_e,scroll:ye,gesture:wa};function Oa(e){return{find:t=>G.find(e,t),get:t=>G.get(e,t),getText:(t,n={})=>G.getText(e,{...n,target:t}),getAttrs:(t,n={})=>G.getAttrs(e,{...n,target:t}),is:t=>G.is(e,t),isVisible:(t,n={})=>G.isVisible(e,{...n,target:t}),isHidden:(t,n={})=>G.isHidden(e,{...n,target:t}),wait:t=>G.wait(e,t),waitForText:(t,n={})=>G.waitForText(e,{...n,text:t})}}function ka(e){return{click:(t,n={})=>K.click(e,{...n,target:t}),press:(t,n={})=>K.press(e,{...n,target:t}),fill:(t,n,r={})=>K.fill(e,{...r,target:t,text:n}),typeText:(t,n={})=>K.typeText(e,{...n,text:t}),focus:(t,n={})=>K.focus(e,{...n,target:t}),longPress:(t,n={})=>K.longPress(e,{...n,target:t}),scroll:t=>K.scroll(e,t),gesture:t=>K.gesture(e,t)}}function q(e,t){if(e!==void 0)return J(e,t)}function J(e,n){let r=e?.trim();if(!r)throw new t(`INVALID_ARGS`,`${n} must be a non-empty string`);return r}const Aa=async(e,n={})=>{if(!e.backend.listDevices)throw new t(`UNSUPPORTED_OPERATION`,`admin.devices is not supported by this backend`);return{kind:`adminDevices`,devices:await e.backend.listDevices(S(e,n),n.filter)}},ja=async(e,n={})=>{if(!e.backend.bootDevice)throw new t(`UNSUPPORTED_OPERATION`,`admin.boot is not supported by this backend`);let r=Va(n.target),i=x(await e.backend.bootDevice(S(e,n),r));return{kind:`deviceBooted`,...r?{target:r}:{},...i?{backendResult:i}:{},...C(`Booted device`)}},Ma=async(e,n={})=>{if(!e.backend.shutdownDevice)throw new t(`UNSUPPORTED_OPERATION`,`admin.shutdown is not supported by this backend`);let r=Va(n.target),i=x(await e.backend.shutdownDevice(S(e,n),r));return{kind:`deviceShutdown`,...r?{target:r}:{},...i?{backendResult:i}:{},...C(`Shutdown device`)}},Na=async(e,t)=>await Ia(e,t,`install`),Pa=async(e,t)=>await Ia(e,t,`reinstall`),Fa=async(e,t)=>await Ia(e,t,`installFromSource`);async function Ia(e,n,r){let i=r===`reinstall`?`reinstallApp`:`installApp`,a=e.backend[i];if(!a)throw new t(`UNSUPPORTED_OPERATION`,`admin.${r} is not supported by this backend`);let o=`app`in n&&n.app!==void 0?J(n.app,`app`):void 0;if(r!==`installFromSource`&&!o)throw new t(`INVALID_ARGS`,`admin.${r} requires app`);let s=S(e,n),c=await La(e,s,n.source);try{let t=await a.call(e.backend,s,{...o?{app:o}:{},source:c.source});return Ha(r,o,c.source,t)}finally{await c.cleanup?.()}}async function La(e,t,n){let r=await Ra(e,za(n));try{return{source:za(e.backend.resolveInstallSource?await e.backend.resolveInstallSource(t,r.source):r.source),...r.cleanup?{cleanup:r.cleanup}:{}}}catch(e){if(r.cleanup)try{await r.cleanup()}catch{}throw e}}async function Ra(e,t){if(t.kind===`url`)return{source:t};let n=await U(e,t,{usage:`admin.install`,field:`source`});return{source:{kind:`path`,path:n.path},...n.cleanup?{cleanup:n.cleanup}:{}}}function za(e){if(!e||typeof e!=`object`)throw new t(`INVALID_ARGS`,`install source is required`);if(e.kind===`path`)return{kind:`path`,path:J(e.path,`source.path`)};if(e.kind===`uploadedArtifact`)return{kind:`uploadedArtifact`,id:J(e.id,`source.id`)};if(e.kind===`url`){let t=J(e.url,`source.url`);return Ba(t),{kind:`url`,url:t}}throw new t(`INVALID_ARGS`,`install source kind must be path, uploadedArtifact, or url`)}function Ba(e){let n;try{n=new URL(e)}catch{throw new t(`INVALID_ARGS`,`Invalid install source URL: ${e}`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new t(`INVALID_ARGS`,`Install source URL must use http or https`)}function Va(e){if(!e)return;let t=q(e.id,`target.id`),n=q(e.name,`target.name`),r={...t?{id:t}:{},...n?{name:n}:{},...e.platform?{platform:e.platform}:{},...e.target?{target:e.target}:{},...e.headless===void 0?{}:{headless:e.headless}};return Object.keys(r).length>0?r:void 0}function Ha(e,t,n,r){let i=x(r),a=e===`reinstall`?`appReinstalled`:e===`installFromSource`?`appInstalledFromSource`:`appInstalled`,o=Y(r,`appName`),s=Y(r,`appId`),c=Y(r,`bundleId`),l=Y(r,`packageName`),u=Y(r,`launchTarget`),d=Y(r,`installablePath`),f=Y(r,`archivePath`);return{kind:a,...t?{app:t}:{},source:n,...s?{appId:s}:{},...o?{appName:o}:{},...c?{bundleId:c}:{},...l?{packageName:l}:{},...u?{launchTarget:u}:{},...d?{installablePath:d}:{},...f?{archivePath:f}:{},...i?{backendResult:i}:{},...C(`${e===`reinstall`?`Reinstalled`:`Installed`}: ${o??u??t??Ua(n)}`)}}function Y(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Ua(e){return e.kind===`path`?e.path:e.kind===`uploadedArtifact`?e.id:e.url}const Wa=/^[A-Za-z0-9_.:-]{1,64}$/,Ga=async(e,n)=>{if(!e.backend.openApp)throw new t(`UNSUPPORTED_OPERATION`,`apps.open is not supported by this backend`);let r=Za(n),i=x(await e.backend.openApp(X(e,n),r,{launchArgs:n.launchArgs,relaunch:n.relaunch}));return{kind:`appOpened`,target:r,relaunch:n.relaunch===!0,...i?{backendResult:i}:{},...C(`Opened: ${$a(r)}`)}},Ka=async(e,n={})=>{if(!e.backend.closeApp)throw new t(`UNSUPPORTED_OPERATION`,`apps.close is not supported by this backend`);let r=q(n.app,`app`),i=x(await e.backend.closeApp(X(e,n),r));return{kind:`appClosed`,...r?{app:r}:{},...i?{backendResult:i}:{},...C(r?`Closed: ${r}`:`Closed app`)}},qa=async(e,n={})=>{if(!e.backend.listApps)throw new t(`UNSUPPORTED_OPERATION`,`apps.list is not supported by this backend`);return{kind:`appsList`,apps:await e.backend.listApps(X(e,n),tt(n.filter))}},Ja=async(e,n)=>{if(!e.backend.getAppState)throw new t(`UNSUPPORTED_OPERATION`,`apps.state is not supported by this backend`);let r=J(n.app,`app`);return{kind:`appState`,app:r,state:await e.backend.getAppState(X(e,n),r)}},Ya=async(e,n)=>{if(!e.backend.pushFile)throw new t(`UNSUPPORTED_OPERATION`,`apps.push is not supported by this backend`);let r=J(n.app,`app`),i=await eo(e,n.input);try{let t=x(await e.backend.pushFile(X(e,n),i.backendInput,r));return{kind:`appPushed`,app:r,inputKind:i.inputKind,...t?{backendResult:t}:{},...C(`Pushed to ${r}`)}}finally{await i.cleanup?.()}},Xa=async(e,n)=>{if(!e.backend.triggerAppEvent)throw new t(`UNSUPPORTED_OPERATION`,`apps.triggerEvent is not supported by this backend`);let r=to(n.name);no(n.payload,`apps.triggerEvent payload for "${r}"`);let i=x(await e.backend.triggerAppEvent(X(e,n),{name:r,...n.payload?{payload:n.payload}:{}}));return{kind:`appEventTriggered`,name:r,...n.payload?{payload:n.payload}:{},...i?{backendResult:i}:{},...C(`Triggered app event: ${r}`)}};function Za(e){let n=q(e.app,`app`),r=q(e.appId,`appId`),i=q(e.bundleId,`bundleId`),a=q(e.packageName,`packageName`),o=q(e.url,`url`),s=q(e.activity,`activity`),c={...n?{app:n}:{},...r?{appId:r}:{},...i?{bundleId:i}:{},...a?{packageName:a}:{},...o?{url:o}:{},...s?{activity:s}:{}};if(!Qa(c))throw new t(`INVALID_ARGS`,`apps.open requires app, appId, bundleId, packageName, url, or activity`);return c}function Qa(e){return!!(e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity)}function $a(e){return e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity??`app`}async function eo(e,n){if(!n||typeof n!=`object`)throw new t(`INVALID_ARGS`,`apps.push requires an input`);if(n.kind===`json`)return ro(n.payload,`apps.push JSON payload`,8192),{backendInput:{kind:`json`,payload:n.payload},inputKind:`json`};let r=await U(e,n,{usage:`apps.push`,field:`input`});return{backendInput:{kind:`file`,path:r.path},inputKind:`file`,...r.cleanup?{cleanup:r.cleanup}:{}}}function to(e){let n=J(e,`name`);if(!Wa.test(n))throw new t(`INVALID_ARGS`,`Invalid apps.triggerEvent name: ${n}`,{hint:`Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash.`});return n}function no(e,t){e!==void 0&&ro(e,t,8192)}function ro(e,n,r){if(io(e,n),Buffer.byteLength(ao(e,n),`utf8`)>r)throw new t(`INVALID_ARGS`,`${n} exceeds ${r} bytes`)}function io(e,n){if(!e||typeof e!=`object`||Array.isArray(e))throw new t(`INVALID_ARGS`,`${n} must be a JSON object`)}function ao(e,n){try{let r=JSON.stringify(e);if(typeof r!=`string`)throw new t(`INVALID_ARGS`,`${n} must be JSON-serializable`);return r}catch{throw new t(`INVALID_ARGS`,`${n} must be JSON-serializable`)}}function X(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}const oo={open:Ga,close:Ka,list:qa,state:Ja,push:Ya,triggerEvent:Xa},so={devices:Aa,boot:ja,shutdown:Ma,install:Na,reinstall:Pa,installFromSource:Fa};function co(e){return{...g(oo,e),list:(t={})=>oo.list(e,{...t,filter:nt(t.filter)})}}const lo=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i,uo=/\b[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g;function fo(e){let t=!1,n=e;return n=n.replaceAll(/(authorization|token|secret|password|passwd|api[-_]?key)=([^&\s]+)/gi,(e,n)=>(t=!0,`${String(n)}=[REDACTED]`)),n=n.replaceAll(/("(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)"\s*:\s*")([^"]*)(")/gi,(e,n,r,i)=>(t=!0,`${String(n)}[REDACTED]${String(i)}`)),n=n.replaceAll(/\b(Bearer\s+)([^\s",;]+)/gi,(e,n)=>(t=!0,`${String(n)}[REDACTED]`)),n=n.replaceAll(/((?:authorization|cookie|token|secret|password|passwd|api[-_]?key)\s*[:=]\s*)([^\s,;&]+)/gi,(e,n)=>(t=!0,`${String(n)}[REDACTED]`)),n=n.replaceAll(uo,()=>(t=!0,`[REDACTED]`)),n=mo(n,()=>{t=!0}),{value:n,redacted:t}}function po(e){try{let t=new URL(e),n=ho(t);return(t.username||t.password)&&(t.username=`REDACTED`,t.password=`REDACTED`,n=!0),{value:t.toString(),redacted:n}}catch{return}}function mo(e,t){return/(https?:\/\/|token|secret|password|authorization|cookie|api[-_]?key)/i.test(e)?e.replaceAll(/https?:\/\/[^\s"'<>)]+/gi,e=>{let n=po(e);return n?(n.redacted&&t(),n.value):e}):e}function ho(e){let t=!1;for(let n of Array.from(e.searchParams.keys()))lo.test(n)&&(e.searchParams.set(n,`[REDACTED]`),t=!0);return t}const Z=2048,go=4096,_o=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i;function vo(e){let t=e.redacted===!0;return{kind:`diagnosticsLogs`,entries:e.entries.map(e=>{let n=Q(e.message,go),r=To(e.metadata);return t||=n.redacted||r.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.level?{level:e.level}:{},message:n.value??``,...e.source?{source:e.source}:{},...r.value?{metadata:r.value}:{}}}),...e.nextCursor?{nextCursor:e.nextCursor}:{},...e.timeWindow?{timeWindow:e.timeWindow}:{},...e.backend?{backend:e.backend}:{},redacted:t,...e.notes?{notes:e.notes}:{}}}function yo(e,t){let n=e.redacted===!0;return{kind:`diagnosticsNetwork`,entries:e.entries.map(e=>{let r=e.url?So(e.url):void 0,i=t===`headers`||t===`all`?xo(e.requestHeaders):void 0,a=t===`headers`||t===`all`?xo(e.responseHeaders):void 0,o=t===`body`||t===`all`?Co(e.requestBody):void 0,s=t===`body`||t===`all`?Co(e.responseBody):void 0,c=To(e.metadata);return n||=(r?.redacted??!1)||(i?.redacted??!1)||(a?.redacted??!1)||(o?.redacted??!1)||(s?.redacted??!1)||c.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.method?{method:e.method}:{},...r?{url:r.value}:{},...e.status===void 0?{}:{status:e.status},...e.durationMs===void 0?{}:{durationMs:e.durationMs},...i?.value?{requestHeaders:i.value}:{},...a?.value?{responseHeaders:a.value}:{},...o?.value===void 0?{}:{requestBody:o.value},...s?.value===void 0?{}:{responseBody:s.value},...c.value?{metadata:c.value}:{}}}),...e.nextCursor?{nextCursor:e.nextCursor}:{},...e.timeWindow?{timeWindow:e.timeWindow}:{},...e.backend?{backend:e.backend}:{},redacted:n,...e.notes?{notes:e.notes}:{}}}function bo(e){let t=e.redacted===!0;return{kind:`diagnosticsPerf`,metrics:e.metrics.map(e=>{let n=Q(e.message,go),r=To(e.metadata);return t||=n.redacted||r.redacted,{name:e.name,...e.value===void 0?{}:{value:e.value},...e.unit?{unit:e.unit}:{},...e.status?{status:e.status}:{},...n.value===void 0?{}:{message:n.value},...r.value?{metadata:r.value}:{}}}),...e.startedAt?{startedAt:e.startedAt}:{},...e.endedAt?{endedAt:e.endedAt}:{},...e.backend?{backend:e.backend}:{},redacted:t,...e.notes?{notes:e.notes}:{}}}function xo(e){if(!e)return{redacted:!1};let t=!1,n={};for(let[r,i]of Object.entries(e))if(_o.test(r))n[r]=`[REDACTED]`,t=!0;else{let e=Q(i,Z);n[r]=e.value??``,t||=e.redacted}return{value:n,redacted:t}}function So(e){return po(e)??Q(e,Z)}function Co(e){return e===void 0?{redacted:!1}:wo(e)??Q(e,Z)}function wo(e){try{let t=Eo(JSON.parse(e),fo);return Do(JSON.stringify(t.value),Z,t.redacted)}catch{return}}function To(e){return Eo(e,e=>Q(e,Z))}function Eo(e,t){if(e===void 0)return{redacted:!1};if(typeof e==`string`)return t(e);if(!e||typeof e!=`object`)return{value:e,redacted:!1};if(Array.isArray(e)){let n=!1;return{value:e.map(e=>{let r=Eo(e,t);return n||=r.redacted,r.value}),redacted:n}}let n=!1,r={};for(let[i,a]of Object.entries(e)){if(_o.test(i)){r[i]=`[REDACTED]`,n=!0;continue}let e=Eo(a,t);r[i]=e.value,n||=e.redacted}return{value:r,redacted:n}}function Q(e,t){if(e===void 0)return{redacted:!1};let n=fo(e);return Do(n.value,t,n.redacted)}function Do(e,t,n){if(e===void 0)return{redacted:n};let r=e;return r.length>t&&(r=`${r.slice(0,t)}...[truncated]`,n=!0),{value:r,redacted:n}}const Oo=async(e,n={})=>{if(!e.backend.readLogs)throw new t(`UNSUPPORTED_OPERATION`,`diagnostics.logs is not supported by this backend`);return vo(await e.backend.readLogs(await jo(e,n),Mo(n)))},ko=async(e,n={})=>{if(!e.backend.dumpNetwork)throw new t(`UNSUPPORTED_OPERATION`,`diagnostics.network is not supported by this backend`);let r=No(n);return yo(await e.backend.dumpNetwork(await jo(e,n),r),r.include??`summary`)},Ao=async(e,n={})=>{if(!e.backend.measurePerf)throw new t(`UNSUPPORTED_OPERATION`,`diagnostics.perf is not supported by this backend`);return bo(await e.backend.measurePerf(await jo(e,n),Po(n)))};async function jo(e,t){let n=S(e,t),r=t.session?await e.sessions.get(t.session):void 0;return{...n,...t.appId??r?.appId?{appId:t.appId??r?.appId}:{},...t.appBundleId??r?.appBundleId?{appBundleId:t.appBundleId??r?.appBundleId}:{}}}function Mo(e){return{...Fo(e,100,500,`logs limit`),...e.levels===void 0?{}:{levels:Ro(e.levels,`levels`)},...e.search===void 0?{}:{search:J(e.search,`search`)},...e.source===void 0?{}:{source:J(e.source,`source`)}}}function No(e){return{...Fo(e,25,200,`network limit`),include:Lo(e.include)}}function Po(e){return{...Io(e),...e.sampleMs===void 0?{}:{sampleMs:v(e.sampleMs,`sampleMs`,100,6e4)},...e.metrics===void 0?{}:{metrics:Ro(e.metrics,`metrics`,20)}}}function Fo(e,t,n,r){return{...Io(e),...e.cursor===void 0?{}:{cursor:J(e.cursor,`cursor`)},limit:e.limit===void 0?t:v(e.limit,r,1,n)}}function Io(e){return{...e.since===void 0?{}:{since:J(e.since,`since`)},...e.until===void 0?{}:{until:J(e.until,`until`)}}}function Lo(e){if(e===void 0)return`summary`;if(e===`summary`||e===`headers`||e===`body`||e===`all`)return e;throw new t(`INVALID_ARGS`,`network include must be summary, headers, body, or all`)}function Ro(e,n,r=50){if(!Array.isArray(e))throw new t(`INVALID_ARGS`,`${n} must be an array of strings`);if(e.length>r)throw new t(`INVALID_ARGS`,`${n} must contain at most ${r} entries`);return e.map((e,t)=>J(e,`${n}[${t}]`))}const zo={logs:Oo,network:ko,perf:Ao},Bo=async(e,n)=>{let r=Ko(n.action,`record`),i=r===`start`?e.backend.startRecording:e.backend.stopRecording;if(!i)throw new t(`UNSUPPORTED_OPERATION`,`record ${r} is not supported by this backend`);let a=n.out?await W(e,n.out,{field:`path`,ext:`.mp4`,artifactType:`screen-recording`}):void 0;try{let t=Ho(n,a?.path);return qo(r,await i.call(e.backend,S(e,n),t),await a?.publish())}catch(e){throw await a?.cleanup?.(),e}},Vo=async(e,n)=>{let r=Ko(n.action,`trace`),i=r===`start`?e.backend.startTrace:e.backend.stopTrace;if(!i)throw new t(`UNSUPPORTED_OPERATION`,`trace ${r} is not supported by this backend`);let a=n.out?await W(e,n.out,{field:`outPath`,ext:`.trace`,artifactType:`trace-log`}):void 0;try{let t={...a?.path?{outPath:a.path}:{}};return Jo(r,await i.call(e.backend,S(e,n),t),await a?.publish())}catch(e){throw await a?.cleanup?.(),e}};function Ho(e,t){let n={};t&&(n.outPath=t);let r=Uo(e.fps);r!==void 0&&(n.fps=r);let i=Wo(e.maxSize);i!==void 0&&(n.maxSize=i);let a=Go(e.quality);return a!==void 0&&(n.quality=a),e.hideTouches!==void 0&&(n.showTouches=e.hideTouches!==!0),n}function Uo(e){return e===void 0?void 0:v(e,`fps`,1,60)}function Wo(e){return e===void 0?void 0:v(e,`maxSize`,1,2**53-1)}function Go(e){if(e===void 0)return;let n=ge(e);if(n===void 0)throw new t(`INVALID_ARGS`,`quality must be one of: medium, high (legacy numeric values 5-10 are accepted)`);return n}function Ko(e,n){if(e===`start`||e===`stop`)return e;throw new t(`INVALID_ARGS`,`${n} action must be start or stop`)}function qo(e,t,n){return{...typeof t.path==`string`?{path:t.path}:{},...typeof t.telemetryPath==`string`?{telemetryPath:t.telemetryPath}:{},...typeof t.warning==`string`?{warning:t.warning}:{},...Yo(e,t,n,{startKind:`recordingStarted`,stopKind:`recordingStopped`,startMessage:`Recording started`,stopMessage:`Recording stopped`})}}function Jo(e,t,n){return{...typeof t.outPath==`string`?{outPath:t.outPath}:{},...Yo(e,t,n,{startKind:`traceStarted`,stopKind:`traceStopped`,startMessage:`Trace started`,stopMessage:`Trace stopped`})}}function Yo(e,t,n,r){return{kind:e===`start`?r.startKind:r.stopKind,action:e,...n?{artifact:n}:{},backendResult:t,...C(e===`start`?r.startMessage:r.stopMessage)}}const Xo={record:Bo,trace:Vo},Zo=async(e,n={})=>{if(!e.backend.pressBack)throw new t(`UNSUPPORTED_OPERATION`,`system.back is not supported by this backend`);let r=n.mode??`in-app`;if(r!==`in-app`&&r!==`system`)throw new t(`INVALID_ARGS`,`system.back mode must be in-app or system`);let i=x(await e.backend.pressBack(S(e,n),{mode:r}));return{kind:`systemBack`,mode:r,...i?{backendResult:i}:{},...C(`Back`)}},Qo=async(e,n={})=>{if(!e.backend.pressHome)throw new t(`UNSUPPORTED_OPERATION`,`system.home is not supported by this backend`);let r=x(await e.backend.pressHome(S(e,n)));return{kind:`systemHome`,...r?{backendResult:r}:{},...C(`Home`)}},$o=async(e,n)=>{if(!e.backend.pressTvRemote)throw new t(`UNSUPPORTED_OPERATION`,`system.tvRemote is not supported by this backend`);let r=Be(n.button),i=n.durationMs===void 0?void 0:v(n.durationMs,`durationMs`,0,1e4),a=x(await e.backend.pressTvRemote(S(e,n),{button:r,...i===void 0?{}:{durationMs:i}}));return{kind:`tvRemotePressed`,button:r,...i===void 0?{}:{durationMs:i},...a?{backendResult:a}:{},...C(`Pressed TV remote ${r}`)}},es=async(e,n)=>{if(!e.backend.setOrientation)throw new t(`UNSUPPORTED_OPERATION`,`system.orientation is not supported by this backend`);let r=os(n.orientation),i=x(await e.backend.setOrientation(S(e,n),r));return{kind:`systemOrientationSet`,orientation:r,...i?{backendResult:i}:{},...C(`Rotated to ${r}`)}},ts=async(e,n={})=>{if(!e.backend.setKeyboard)throw new t(`UNSUPPORTED_OPERATION`,`system.keyboard is not supported by this backend`);let r=n.action??`status`;if(!be(r))throw new t(`INVALID_ARGS`,`system.keyboard action must be status, get, dismiss, enter, or return`);let i=await e.backend.setKeyboard(S(e,n),{action:r}),a=x(i),o=ms(i)?i:{};return r===`enter`||r===`return`?cs(o,a):r===`dismiss`?ls(r,o,a):us(r,o,a)},ns=async(e,n)=>{if(n.action===`read`){if(!e.backend.getClipboard)throw new t(`UNSUPPORTED_OPERATION`,`system.clipboard read is not supported by this backend`);let r=await e.backend.getClipboard(S(e,n));return{kind:`clipboardText`,action:`read`,text:typeof r==`string`?r:r.text}}if(n.action!==`write`)throw new t(`INVALID_ARGS`,`system.clipboard action must be read or write`);if(!e.backend.setClipboard)throw new t(`UNSUPPORTED_OPERATION`,`system.clipboard write is not supported by this backend`);if(typeof n.text!=`string`)throw new t(`INVALID_ARGS`,`system.clipboard write requires text`);let r=x(await e.backend.setClipboard(S(e,n),n.text));return{kind:`clipboardUpdated`,action:`write`,textLength:Array.from(n.text).length,...r?{backendResult:r}:{},...C(`Clipboard updated`)}},rs=async(e,n={})=>{if(!e.backend.openSettings)throw new t(`UNSUPPORTED_OPERATION`,`system.settings is not supported by this backend`);let r=q(n.target,`target`),i=x(await e.backend.openSettings(S(e,n),r));return{kind:`settingsOpened`,...r?{target:r}:{},...i?{backendResult:i}:{},...C(r?`Opened settings: ${r}`:`Opened settings`)}},is=async(e,n={})=>{if(!e.backend.handleAlert)throw new t(`UNSUPPORTED_OPERATION`,`system.alert is not supported by this backend`);let r=n.action??`get`;if(r!==`get`&&r!==`accept`&&r!==`dismiss`&&r!==`wait`)throw new t(`INVALID_ARGS`,`system.alert action must be get, accept, dismiss, or wait`);let i=n.timeoutMs===void 0?void 0:v(n.timeoutMs,`timeoutMs`,0,12e4);return ss(r,await e.backend.handleAlert(S(e,n),r,{timeoutMs:i}))},as=async(e,n={})=>{if(!e.backend.openAppSwitcher)throw new t(`UNSUPPORTED_OPERATION`,`system.appSwitcher is not supported by this backend`);let r=x(await e.backend.openAppSwitcher(S(e,n)));return{kind:`appSwitcherOpened`,...r?{backendResult:r}:{},...C(`Opened app switcher`)}};function os(e){switch(e){case`portrait`:case`portrait-upside-down`:case`landscape-left`:case`landscape-right`:return e;default:throw new t(`INVALID_ARGS`,`system.orientation must be portrait, portrait-upside-down, landscape-left, or landscape-right`)}}function ss(e,t){return e===`get`?ds(t):e===`wait`?fs(t):ps(e,t)}function cs(e,t){return{kind:`keyboardEnterPressed`,action:`enter`,state:e,...t?{backendResult:t}:{},...C(`Keyboard enter pressed`)}}function ls(e,t,n){return{kind:`keyboardDismissed`,action:e,state:t,...n?{backendResult:n}:{},...C(t.dismissed===!1?`Keyboard already hidden`:`Keyboard dismissed`)}}function us(e,t,n){return{kind:`keyboardState`,action:e,state:t,...n?{backendResult:n}:{}}}function ds(e){if(e.kind!==`alertStatus`)throw new t(`COMMAND_FAILED`,`system.alert get returned an invalid backend result`);return{kind:`alertStatus`,action:`get`,alert:e.alert}}function fs(e){if(e.kind!==`alertWait`)throw new t(`COMMAND_FAILED`,`system.alert wait returned an invalid backend result`);return{kind:`alertWait`,action:`wait`,alert:e.alert,...e.waitedMs===void 0?{}:{waitedMs:e.waitedMs},...e.timedOut===void 0?{}:{timedOut:e.timedOut},...C(e.alert?`Alert visible`:`Alert wait timed out`)}}function ps(e,n){if(n.kind!==`alertHandled`)throw new t(`COMMAND_FAILED`,`system.alert ${e} returned an invalid backend result`);return{kind:`alertHandled`,action:e,handled:n.handled,...n.alert?{alert:n.alert}:{},...n.button?{button:n.button}:{},...C(n.handled?`Alert ${e}ed`:`No alert handled`)}}function ms(e){return!!(e&&typeof e==`object`)}const hs={back:Zo,home:Qo,orientation:es,keyboard:ts,clipboard:ns,settings:rs,alert:is,appSwitcher:as,tvRemote:$o};function gs(e){return{capture:g(Vi,e),selectors:Oa(e),interactions:ka(e),system:g(hs,e),apps:co(e),admin:g(so,e),recording:g(Xo,e),observability:g(zo,e)}}var _s=e({createAgentDevice:()=>vs,createMemorySessionStore:()=>ys,localCommandPolicy:()=>xs,restrictedCommandPolicy:()=>Ss});function vs(e){let t={backend:e.backend,artifacts:e.artifacts,sessions:e.sessions??ys(),policy:e.policy??Ss(),diagnostics:e.diagnostics,clock:e.clock,signal:e.signal};return{...t,...gs(t)}}function ys(e=[]){let t=new Map(e.map(e=>[e.name,$(e)]));return{get:e=>$(t.get(e)),set:e=>{t.set(e.name,$(e))},delete:e=>{t.delete(e)},list:()=>Array.from(t.values(),e=>$(e))}}function $(e){if(e)return{...e,...e.snapshot?{snapshot:structuredClone(e.snapshot)}:{},...e.metadata?{metadata:bs(e.metadata)}:{}}}function bs(e){try{return structuredClone(e)}catch{return{...e}}}function xs(e={}){return{allowLocalInputPaths:!0,allowLocalOutputPaths:!0,maxImagePixels:2e7,...e}}function Ss(e={}){return{allowLocalInputPaths:!1,allowLocalOutputPaths:!1,maxImagePixels:2e7,...e}}export{pi as a,P as c,$t as d,vt as f,Ft as g,Mt as h,vi as i,fn as l,bt as m,xs as n,mn as o,yt as p,_s as r,N as s,vs as t,pn as u};
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,t as a}from"./png-worker-contract.js";import{T as o,_ as s,d as c,g as l,l as u,p as d,u as f,v as p}from"./sdk-contracts.js";import{$ as m,A as h,B as ee,C as te,D as g,E as _,F as ne,H as re,M as ie,N as ae,O as oe,Q as v,S as se,T as ce,U as le,V as ue,Vt as de,Z as y,b as fe,c as pe,d as me,et as b,f as he,in as x,j as ge,k as _e,l as ve,m as ye,p as be,s as xe,tt as S,u as Se,v as Ce,w as we,x as Te,y as Ee}from"./viewport-dimension.js";import{C as De,et as Oe,n as ke,nt as Ae,p as je,t as Me}from"./screenshot-geometry.js";import{H as Ne,L as Pe,N as Fe,j as Ie}from"./sdk-batch-runner.js";import{M as Le}from"./screenshot-result.js";import{$ as Re,A as ze,B as Be,C as Ve,H as He,O as Ue,Y as We,_ as Ge,b as Ke,i as qe,j as Je,pt as Ye,s as Xe,t as Ze,v as Qe,x as $e,y as et,z as tt}from"./sdk-selectors.js";import{d as nt,f as rt}from"./device.js";import{j as it}from"./sdk-android-adb.js";import C from"node:path";import at,{promises as w}from"node:fs";import{fileURLToPath as ot}from"node:url";import{Worker as st}from"node:worker_threads";const ct=/\b(logbox|redbox|reload js|copy stack|component stack|call stack|runtime error|open debugger to view warnings)\b/,lt=[/\b[\w.$<>/-]+\.(?:tsx?|jsx?):\d+(?::\d+)?\b/,/\b[\w.$<>/-]+\.(?:tsx?|jsx?)\s+\(\d+:\d+\)/],ut=[/^!,\s+/,/^(warn|warning|error):\s+/,/\b(?:possible\s+)?unhandled (?:promise )?rejection\b/],dt=[`open debugger to view warnings`,`getsnapshot should be cached to avoid an infinite loop`,`unique "key" prop`,`unique 'key' prop`,`virtualizedlists should never be nested`,`failed prop type`],ft=new Set([`x`,`×`,`✕`,`✖`,`⨯`]);function pt(e){if(mt(e).detected)return[`Hint: React Native warning/error overlay detected. It overlays part of the app and should be handled before interacting.`,`Run: agent-device react-native dismiss-overlay`,`The command verifies the overlay is gone. Run agent-device snapshot -i afterward only when you need fresh refs for the next action.`].join(`
|
|
2
|
+
`)}function mt(e){let t=_t(e),n=t.detected?vt(t):null;return{detected:t.detected,dismissNodes:t.dismissNodes,minimizeNodes:t.minimizeNodes,collapsedNodes:t.collapsedNodes,primaryAction:n}}function ht(e){return Tt(e.label?.trim())&&Ft(e.rect)}function gt(e,t){let n=e.label?.trim();return!n||!ht(e)?!1:t.some(e=>e.label?.trim()===n&&It(e))}function _t(e){let t=e.map(yt).join(`
|
|
3
|
+
`).toLowerCase(),n=T(e,Dt),r=T(e,jt),i=T(e,Tt,Nt),a=T(e,Et),o=xt(t),s=St(t);return{dismissNodes:n,minimizeNodes:r,collapsedNodes:i,detected:wt({text:t,hasReactNativeStackFrame:o,hasOverlayControl:Ct(t,n,r),hasControllessRedBoxText:s,collapsedNodes:i,openDebuggerWarningNodes:a})}}function vt(e){let t=Lt(e.dismissNodes);if(t)return Bt(t,Vt(t));let n=Ht(e.collapsedNodes.filter(Pt));return n?.rect?{action:`close-collapsed-banner`,point:qt(n),rect:n.rect,ref:n.ref,label:E(n)}:null}function yt(e){return[e.label,e.value,e.identifier,e.type,e.role].filter(Boolean).join(` `)}function bt(e){return ct.test(e)}function xt(e){return lt.some(t=>t.test(e))}function St(e){return/\buncaught\b/.test(e)&&/unable to download asset/.test(e)}function Ct(e,t,n){return t.length>0||n.length>0||/\b(reload js|copy stack)\b/.test(e)}function wt(e){return e.collapsedNodes.length>0||e.openDebuggerWarningNodes.length>0||e.hasControllessRedBoxText||e.hasOverlayControl&&(bt(e.text)||e.hasReactNativeStackFrame)}function Tt(e){let t=e?.trim().toLowerCase();return t?dt.some(e=>t.includes(e))||ut.some(e=>e.test(t)):!1}function Et(e){return e.includes(`open debugger to view warnings`)||/^!,\s+open debugger\b/.test(e)}function Dt(e){return Ot(e)||kt(e)||At(e)}function Ot(e){return/^dismiss(?:\s*\([^)]*\))?$/i.test(e)}function kt(e){return/^close(?:\s*\([^)]*\))?$/i.test(e)}function At(e){return ft.has(e)}function jt(e){return/^minimi[sz]e(?:\b|\s|\()/i.test(e)}function Mt(e){return/^!,\s+/.test(e)}function Nt(e){return!e.rect||e.rect.height<=180}function Pt(e){let t=E(e)?.trim().toLowerCase()??``;return(Et(t)||Mt(t))&&It(e)}function Ft(e){return e?e.x<=1&&e.y<=1&&e.width>=300&&e.height>=600:!1}function It(e){return e.rect?e.rect.width>=120&&e.rect.height>=36&&e.rect.height<=180:!1}function T(e,t,n=()=>!0){let r=[];for(let i of e)i.ref&&n(i)&&[i.label,i.value,i.identifier].map(e=>e?.trim().toLowerCase()).filter(e=>!!e).some(e=>t(e))&&r.push(i);return r}function Lt(e){return Ut(e,zt)}function Rt(e){let t=[e.type,e.role,e.subrole].join(` `).toLowerCase();return/\b(button|menuitem|link)\b/.test(t)}function zt(e){return[Gt(Rt(e)),Gt(e.hittable),-(e.rect?Ye(e.rect):1/0)]}function Bt(e,t){if(!e.rect)throw Error(`React Native overlay target node must have rect`);return{action:t,point:f(e.rect),rect:e.rect,ref:e.ref,label:E(e)}}function Vt(e){let t=E(e)?.trim().toLowerCase();return t&&Ot(t)?`dismiss`:`close`}function Ht(e){return Ut(e,Wt)}function Ut(e,t){let n=e.filter(e=>e.rect);return n.length===0?null:n.sort((e,n)=>Kt(t(n),t(e)))[0]??null}function Wt(e){return[Gt(e.hittable),e.rect?.width??0,e.rect?.y??0]}function Gt(e){return+(e===!0)}function Kt(e,t){for(let n=0;n<e.length;n+=1){let r=e[n]-t[n];if(r!==0)return r}return 0}function qt(e){if(!e.rect)throw Error(`Collapsed React Native warning node must have rect`);let t=Math.min(e.rect.height,52),n=Math.min(36,Math.max(18,t*.45));return{x:Math.round(Jt(e.rect.x+e.rect.width-n,e.rect.x+1,e.rect.x+e.rect.width-1)),y:Math.round(e.rect.y+t/2)}}function Jt(e,t,n){return Math.min(n,Math.max(t,e))}function E(e){return e.label??e.value??e.identifier}function Yt(e){let t=e?.trim().split(/\s+/,1)[0];if(!t||!t.startsWith(`@`)||t.length<3)return null;let n=t.slice(1);return/^[A-Za-z_-]*\d[\w-]*$/i.test(n)||/^(?:ref|node|element|el)[\w-]*$/i.test(n)?t:null}function Xt(e,t){try{let n=ot(e),r=C.extname(n)||`.js`;return[C.join(C.dirname(n),`${t}${r}`),C.join(C.dirname(n),`internal`,`${t}${r}`)].find(e=>at.existsSync(e))??null}catch{return null}}var D=class extends Error{};let O=null,Zt=!1,Qt=!1,$t=0;const k=new Map;function en(e){Zt=!0,!Qt&&(Qt=!0,it({level:`warn`,phase:`png_worker_unavailable`,data:{reason:e}}),process.emitWarning(`PNG worker unavailable, falling back to in-process PNG processing: ${e}`))}function tn(e){let t=k.get(e.id);t&&(k.delete(e.id),an(),e.ok?t.resolve(e.result):t.reject(new s(o(e.error.code),e.error.message,e.error.details)))}function nn(e,t){O===e&&(en(t.message),O=null,e.terminate().catch(()=>{}),rn(new D(`PNG worker failed: ${t.message}`)))}function rn(e){let t=[...k.values()];k.clear();for(let n of t)n.reject(e)}function an(){O&&(k.size>0?O.ref():O.unref())}function on(){if(Zt)return null;if(O)return O;let e=Xt(import.meta.url,`png-worker`);if(!e)return en(`worker entry module not found next to the current module`),null;try{let t=new st(e,{execArgv:e.endsWith(`.ts`)?[`--experimental-strip-types`]:[]});return t.on(`message`,tn),t.on(`error`,e=>{nn(t,e)}),t.on(`exit`,e=>{nn(t,Error(`PNG worker exited with code ${e}`))}),t.unref(),O=t,t}catch(e){return en(`failed to spawn worker: ${e instanceof Error?e.message:String(e)}`),null}}function sn(e){let t=on();if(!t)return Promise.reject(new D(`PNG worker is unavailable`));$t+=1;let n=$t;return new Promise((r,i)=>{k.set(n,{resolve:r,reject:i}),an();try{t.postMessage({...e,id:n})}catch(e){k.delete(n),an(),i(new D(`failed to post job to PNG worker: ${e instanceof Error?e.message:String(e)}`))}})}async function A(e,t){try{return await sn(e)}catch(e){if(e instanceof D)return t();throw e}}function cn(){on()}async function ln(){let e=O;O=null,rn(new D(`PNG worker terminated`)),e&&await e.terminate()}async function j(n,r){let i=await A({kind:`decode`,png:n,label:r},()=>{let e=t(n,r);return{kind:`decode`,width:e.width,height:e.height,data:e.data}}),o=new e.PNG({width:i.width,height:i.height});return o.data=a(i.data),o}async function M(t){return a((await A({kind:`encode`,width:t.width,height:t.height,data:t.data},()=>({kind:`encode`,png:e.PNG.sync.write(t)}))).png)}async function un(e,r,i){let{kind:a,...o}=await A({kind:`rgb-difference`,firstPng:e,secondPng:r,label:i},()=>({kind:`rgb-difference`,...n(t(e,i),t(r,i))}));return o}async function dn(e){let{kind:t,...n}=await A({kind:`diff-pixels`,...e},()=>({kind:`diff-pixels`,...i(e)}));return{...n,diffData:a(n.diffData)}}const N=[0,187,255,255];function fn(e,t){for(let n of t)n.rect.width<4||n.rect.height<4||pn(e,n.rect)}function pn(e,t){let n=mn(t);if(n==null)return;let r=F(n.x,0,e.width-1),i=F(n.y,0,e.height-1),a=F(n.right,0,e.width-1),o=F(n.bottom,0,e.height-1);for(let t=0;t<2;t+=1){for(let n=r;n<=a;n+=1)P(e,n,i+t,N),P(e,n,o-t,N);for(let n=i;n<=o;n+=1)P(e,r+t,n,N),P(e,a-t,n,N)}}function mn(e){let t=e.x+e.width-1,n=e.y+e.height-1;return[e.x,e.y,e.width,e.height,t,n].every(Number.isFinite)?{x:e.x,y:e.y,right:t,bottom:n}:null}function P(e,t,n,r){if(t<0||t>=e.width||n<0||n>=e.height)return;let i=(n*e.width+t)*4;e.data[i]=r[0],e.data[i+1]=r[1],e.data[i+2]=r[2],e.data[i+3]=r[3]}function F(e,t,n){return Number.isFinite(e)?Math.min(Math.max(e,t),n):t}const hn=[{x:-1,y:-1},{x:0,y:-1},{x:1,y:-1},{x:-1,y:0},{x:1,y:0},{x:-1,y:1},{x:0,y:1},{x:1,y:1}];function gn(e){let{mask:t,width:n,height:r,hooks:i}=e,a=new Uint8Array(t.length),o=new Int32Array(t.length),s=[];for(let e=0;e<t.length;e+=1){if(!yn(t,a,e))continue;let c=0,l=vn(o,a,0,e),u=i.create(e);for(;c<l;){let e=o[c];c+=1,i.visit(u,e),l=_n({mask:t,visited:a,queue:o,queueEnd:l,width:n,height:r,pixelIndex:e})}s.push(u)}return s}function _n(e){let{mask:t,visited:n,queue:r,width:i,height:a,pixelIndex:o}=e,s=o%i,c=Math.floor(o/i),l=e.queueEnd;for(let e of hn){let o=s+e.x,u=c+e.y;if(!bn(o,u,i,a))continue;let d=u*i+o;yn(t,n,d)&&(l=vn(r,n,l,d))}return l}function vn(e,t,n,r){return t[r]=1,e[n]=r,n+1}function yn(e,t,n){return e[n]===1&&t[n]!==1}function bn(e,t,n,r){return e>=0&&e<n&&t>=0&&t<r}function xn(e,t){return e.flatMap(e=>Sn(e,t.baseline.width,t.baseline.height)?Cn(e,t,kn(t.baseline.height)):[e])}function Sn(e,t,n){let r=e.maxX-e.minX+1;return e.maxY-e.minY+1>=On(n)&&r>=t*.35}function Cn(e,t,n){let r=Dn(e,En(Tn(wn(e,t.diffMask,t.baseline.width)),Math.max(1,Math.round((e.maxX-e.minX+1)*.08))),n);if(r.length<=1)return[e];let i=r.map(([n,r])=>An(e,n,r,t)).filter(e=>e!==null);return i.length>1?i:[e]}function wn(e,t,n){let r=[];for(let i=e.minY;i<=e.maxY;i+=1){let a=0;for(let r=e.minX;r<=e.maxX;r+=1)t[i*n+r]===1&&(a+=1);r.push(a)}return r}function Tn(e){return e.map((t,n)=>{let r=0,i=0,a=Math.max(0,n-3),o=Math.min(e.length-1,n+3);for(let t=a;t<=o;t+=1)r+=e[t],i+=1;return Math.round(r/i)})}function En(e,t){let n=[],r=null;for(let i=0;i<e.length;i+=1){if(e[i]<=t){r??=i;continue}r!==null&&(i-r>=6&&n.push([r,i-1]),r=null)}return r!==null&&e.length-r>=6&&n.push([r,e.length-1]),n}function Dn(e,t,n){let r=[],i=e.minY;for(let[a,o]of t){let t=e.minY+Math.round((a+o)/2);t-i+1<n||e.maxY-t<n||(r.push([i,t]),i=t+1)}return r.push([i,e.maxY]),r}function On(e){return Math.max(48,Math.round(e*.07))}function kn(e){return Math.max(24,Math.round(e*.03))}function An(e,t,n,r){let i=null;for(let a=t;a<=n;a+=1)for(let t=e.minX;t<=e.maxX;t+=1){let e=a*r.baseline.width+t;r.diffMask[e]===1&&(i??=jn(t,a),Mn(i,e,t,a,r.baseline,r.current))}return i}function jn(e,t){return{minX:e,minY:t,maxX:e,maxY:t,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0}}function Mn(e,t,n,r,i,a){let o=t*4;e.minX=Math.min(e.minX,n),e.minY=Math.min(e.minY,r),e.maxX=Math.max(e.maxX,n),e.maxY=Math.max(e.maxY,r),e.differentPixels+=1,e.baselineRed+=i.data[o],e.baselineGreen+=i.data[o+1],e.baselineBlue+=i.data[o+2],e.currentRed+=a.data[o],e.currentGreen+=a.data[o+1],e.currentBlue+=a.data[o+2]}const Nn=2.5;function Pn(e){let t=Fn(e);return xn(t.length<=2e3?Rn(t,12):t,e).sort((e,t)=>{let n=t.differentPixels-e.differentPixels;if(n!==0)return n;let r=e.minY-t.minY;return r===0?e.minX-t.minX:r}).slice(0,8).map((t,n)=>Vn(t,n+1,{width:e.baseline.width,height:e.baseline.height,totalPixels:e.totalPixels,differentPixels:e.differentPixels}))}function Fn(e){let{diffMask:t,baseline:n,current:r}=e,{width:i,height:a}=n;return gn({mask:t,width:i,height:a,hooks:{create:e=>In(e,i),visit:(e,t)=>Ln(e,t,i,n,r)}})}function In(e,t){let n=e%t,r=Math.floor(e/t);return{minX:n,minY:r,maxX:n,maxY:r,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0}}function Ln(e,t,n,r,i){let a=t%n,o=Math.floor(t/n),s=t*4;e.minX=Math.min(e.minX,a),e.minY=Math.min(e.minY,o),e.maxX=Math.max(e.maxX,a),e.maxY=Math.max(e.maxY,o),e.differentPixels+=1,e.baselineRed+=r.data[s],e.baselineGreen+=r.data[s+1],e.baselineBlue+=r.data[s+2],e.currentRed+=i.data[s],e.currentGreen+=i.data[s+1],e.currentBlue+=i.data[s+2]}function Rn(e,t){let n=[];for(let r of e.sort((e,t)=>{let n=e.minY-t.minY;return n===0?e.minX-t.minX:n})){let e=n.find(e=>zn(e,r,t));if(!e){n.push({...r});continue}Bn(e,r)}return n}function zn(e,t,n){return e.minX-n<=t.maxX&&t.minX-n<=e.maxX&&e.minY-n<=t.maxY&&t.minY-n<=e.maxY}function Bn(e,t){e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e.differentPixels+=t.differentPixels,e.baselineRed+=t.baselineRed,e.baselineGreen+=t.baselineGreen,e.baselineBlue+=t.baselineBlue,e.currentRed+=t.currentRed,e.currentGreen+=t.currentGreen,e.currentBlue+=t.currentBlue}function Vn(e,t,n){let r={x:e.minX,y:e.minY,width:e.maxX-e.minX+1,height:e.maxY-e.minY+1},i={x:Math.round(e.minX+r.width/2),y:Math.round(e.minY+r.height/2)},a=Hn(e.baselineRed,e.baselineGreen,e.baselineBlue,e.differentPixels),o=Hn(e.currentRed,e.currentGreen,e.currentBlue,e.differentPixels),s=r.width*r.height;return{index:t,rect:r,normalizedRect:ke({x:L(r.x/n.width),y:L(r.y/n.height),width:L(r.width/n.width),height:L(r.height/n.height)}),differentPixels:e.differentPixels,shareOfDiffPercentage:L(e.differentPixels/n.differentPixels),densityPercentage:L(e.differentPixels/s),shape:Gn(r,n.width,n.height),size:Kn(s,n.totalPixels),location:Un(i,n.width,n.height),averageBaselineColorHex:qn(a),averageCurrentColorHex:qn(o),baselineLuminance:Math.round(I(a)),currentLuminance:Math.round(I(o)),dominantChange:Wn(a,o)}}function Hn(e,t,n,r){return{r:Math.round(e/r),g:Math.round(t/r),b:Math.round(n/r)}}function Un(e,t,n){let r=e.x<t/3?`left`:e.x>t*2/3?`right`:`center`,i=e.y<n/3?`top`:e.y>n*2/3?`bottom`:`middle`;return r===`center`&&i===`middle`?`center`:`${i}-${r}`}function Wn(e,t){let n=I(t)-I(e);return Math.abs(n)>=12?n>0?`brighter`:`darker`:Math.max(Math.abs(t.r-e.r),Math.abs(t.g-e.g),Math.abs(t.b-e.b))>=12?`color-shift`:`mixed`}function Gn(e,t,n){return e.width>=t*.55&&e.height>=n*.12?`large-area`:e.width>=e.height*Nn?`horizontal-band`:e.height>=e.width*Nn?`vertical-band`:`compact`}function Kn(e,t){let n=e/t;return n>=.04?`large`:n>=.01?`medium`:`small`}function I(e){return e.r*.2126+e.g*.7152+e.b*.0722}function qn(e){return`#${Jn(e.r)}${Jn(e.g)}${Jn(e.b)}`}function Jn(e){return e.toString(16).padStart(2,`0`)}function L(e){return Math.round(e*100*100)/100}const Yn=255*Math.sqrt(3);async function Xn(t,n,r={}){await Zn(t,`Baseline image not found`),await Zn(n,`Current screenshot not found`);let i=r.outputPath,[a,o]=await Promise.all([w.readFile(t),w.readFile(n)]),[s,c]=await Promise.all([j(a,`baseline screenshot`),j(o,`current screenshot`)]);Qn(s.width,s.height,`baseline screenshot`,r.maxPixels),Qn(c.width,c.height,`current screenshot`,r.maxPixels);let l=r.threshold??.1;if(s.width!==c.width||s.height!==c.height){let e=s.width*s.height;return await $n(r.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:s.width,height:s.height},actual:{width:c.width,height:c.height}}}}let u=s.width*s.height,d=l*Yn,{diffData:f,diffMask:p,differentPixels:m}=await dn({baselineData:s.data,currentData:c.data,width:s.width,height:s.height,maxColorDistance:d}),h=m>0?Pn({diffMask:p,baseline:s,current:c,totalPixels:u,differentPixels:m}):[];if(m>0&&i){let t=new e.PNG({width:s.width,height:s.height});t.data=f,fn(t,h),await w.mkdir(C.dirname(i),{recursive:!0}),await w.writeFile(i,await M(t))}else await $n(r.outputPath);let ee=u>0?Math.round(m/u*100*100)/100:0;return{...m>0&&i?{diffPath:i}:{},...h.length>0?{regions:h}:{},totalPixels:u,differentPixels:m,mismatchPercentage:ee,match:m===0}}async function Zn(e,t){try{await w.access(e)}catch{throw new s(`INVALID_ARGS`,`${t}: ${e}`)}}function Qn(e,t,n,r){if(r==null||r<=0)return;let i=e*t;if(!(i<=r))throw new s(`INVALID_ARGS`,`${n} is ${i} pixels, which exceeds the configured maxImagePixels limit of ${r}`)}async function $n(e){if(e)try{await w.unlink(e)}catch(e){if(!er(e,`ENOENT`))throw e}}function er(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}function tr(e,t){return e.map(e=>{let n=nr(e,t);return n.length>0?{...e,currentOverlayMatches:n}:e})}function nr(e,t){let n=rr(e.rect);return t.map(t=>{let r=t.overlayRect,i=Me(e.rect,r);return i<=0?null:{ref:t.ref,...t.label?{label:t.label}:{},rect:r,overlayCoveragePercentage:ir(i/rr(r)),regionCoveragePercentage:ir(i/n)}}).filter(e=>e!==null).sort((e,t)=>{let n=t.regionCoveragePercentage-e.regionCoveragePercentage;return n===0?t.overlayCoveragePercentage-e.overlayCoveragePercentage:n}).slice(0,3).map(e=>({ref:e.ref,...e.label?{label:e.label}:{},rect:e.rect,regionCoveragePercentage:e.regionCoveragePercentage}))}function rr(e){return e.width*e.height}function ir(e){return Math.round(e*100*100)/100}async function R(e,t,n){if(t.kind===`path`&&!e.policy.allowLocalInputPaths)throw new s(`INVALID_ARGS`,`Local ${n.field??`input`} paths are not allowed by command policy`);try{return await e.artifacts.resolveInput(t,n)}catch(e){throw p(e)}}async function z(e,t,n){if(t?.kind===`path`&&!e.policy.allowLocalOutputPaths)throw new s(`INVALID_ARGS`,`Local output paths are not allowed by command policy`);try{return await e.artifacts.reserveOutput(t,{...n,visibility:n.visibility??`client-visible`,requestedClientPath:t?.kind===`downloadableArtifact`?t.clientPath??n.requestedClientPath:n.requestedClientPath})}catch(e){throw p(e)}}async function ar(e,t){try{return await e.artifacts.createTempFile(t)}catch(e){throw p(e)}}const or=async(e,t)=>{if(!t.baseline)throw new s(`INVALID_ARGS`,`diff screenshot requires a baseline image`);let n=sr(t.threshold),r=t.current??{kind:`live`};if(t.overlayRefs&&!mr(r))throw new s(`INVALID_ARGS`,`diff screenshot <current.png> cannot use --overlay-refs because saved-image comparisons have no live accessibility refs`);let i=await R(e,t.baseline,{usage:`diff screenshot baseline`,field:`baseline`}),a,o,c,l=[];try{let s;mr(r)?(o=await cr(e,t),s=o.path):(a=await R(e,r,{usage:`diff screenshot current`,field:`current`}),s=a.path),c=t.out?await z(e,t.out,{field:`diffPath`,ext:`.png`,artifactType:`screenshot-diff`}):void 0;let u=await Xn(i.path,s,{threshold:n,outputPath:c?.path,maxPixels:e.policy.maxImagePixels});mr(r)&&(u=await lr(e,t,c?.path,u,l));let d=u.diffPath?await c?.publish():void 0;return d&&l.push(d),u.diffPath||await c?.cleanup?.(),{...u,...l.length>0?{artifacts:l}:{}}}catch(e){throw await c?.cleanup?.(),e}finally{await i.cleanup?.(),await a?.cleanup?.(),await o?.cleanup?.()}};function sr(e){if(e==null||e===``)return .1;let t=Number(e);if(Number.isNaN(t)||t<0||t>1)throw new s(`INVALID_ARGS`,`--threshold must be a number between 0 and 1`);return t}async function cr(e,t){let n=await ar(e,{prefix:`agent-device-diff-current`,ext:`.png`});try{await ur(e,t,n.path,dr(t))}catch(e){throw await n.cleanup(),e}return n}async function lr(e,t,n,r,i){if(!t.overlayRefs)return r;if(r.match||r.dimensionMismatch)return n&&await pr(n),r;let a=await z(e,fr(t,n),{field:`currentOverlayPath`,ext:`.png`,artifactType:`screenshot`});try{let n=await ur(e,t,a.path,{overlayRefs:!0,...dr(t)}),o=await a.publish();return o&&i.push(o),{...r,currentOverlayPath:n.path??a.path,...n.overlayRefs?{currentOverlayRefCount:n.overlayRefs.length}:{},...r.regions&&n.overlayRefs?{regions:tr(r.regions,n.overlayRefs)}:{}}}catch(e){throw await a.cleanup?.(),e}}async function ur(e,t,n,r={}){if(!e.backend.captureScreenshot)throw new s(`UNSUPPORTED_OPERATION`,`screenshot is not supported by this backend`);return await e.backend.captureScreenshot({session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata},n,r)??{}}function dr(e){return{normalizeStatusBar:e.normalizeStatusBar??!0,...e.surface?{surface:e.surface}:{}}}function fr(e,t){if(e.currentOverlayOut)return e.currentOverlayOut;if(e.out?.kind===`path`)return{kind:`path`,path:B(t??e.out.path)};if(e.out?.kind===`downloadableArtifact`)return{kind:`downloadableArtifact`,...e.out.clientPath?{clientPath:B(e.out.clientPath)}:{},...e.out.fileName?{fileName:B(e.out.fileName)}:{}}}function B(e){let t=C.extname(e);return`${t?e.slice(0,-t.length):e}.current-overlay${t||`.png`}`}async function pr(e){try{await w.unlink(B(e))}catch(e){if(!hr(e,`ENOENT`))throw e}}function mr(e){return e.kind===`live`}function hr(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}async function gr(e,t){if(!Number.isInteger(t)||t<1)throw new s(`INVALID_ARGS`,`Screenshot max size must be a positive integer`);let n=await j(await w.readFile(e),`screenshot`),r=Math.max(n.width,n.height);if(r<=t)return;let i=t/r,a=vr(n,Math.max(1,Math.round(n.width*i)),Math.max(1,Math.round(n.height*i)));await w.writeFile(e,await M(a))}async function _r(e,t,n){if(!Number.isInteger(t)||t<1||!Number.isInteger(n)||n<1)throw new s(`INVALID_ARGS`,`Screenshot resize dimensions must be positive integers`);let r=await j(await w.readFile(e),`screenshot`);r.width===t&&r.height===n||await w.writeFile(e,await M(vr(r,t,n)))}function vr(t,n,r){let i=new e.PNG({width:n,height:r});for(let e=0;e<r;e+=1){let a=e*t.height/r,o=(e+1)*t.height/r;for(let r=0;r<n;r+=1){let s=r*t.width/n,c=(r+1)*t.width/n,l=0,u=0,d=0,f=0,p=0;for(let e=Math.floor(a);e<Math.ceil(o);e+=1){let n=Math.min(e+1,o)-Math.max(e,a);for(let r=Math.floor(s);r<Math.ceil(c);r+=1){let i=n*(Math.min(r+1,c)-Math.max(r,s)),a=(e*t.width+r)*4;l+=(t.data[a]??0)*i,u+=(t.data[a+1]??0)*i,d+=(t.data[a+2]??0)*i,f+=(t.data[a+3]??0)*i,p+=i}}let m=(e*i.width+r)*4;i.data[m]=Math.round(l/p),i.data[m+1]=Math.round(u/p),i.data[m+2]=Math.round(d/p),i.data[m+3]=Math.round(f/p)}}return i}const yr=async(e,t)=>{if(!e.backend.captureScreenshot)throw new s(`UNSUPPORTED_OPERATION`,`screenshot is not supported by this backend`);let n=await z(e,t.out,{field:`path`,ext:`.png`,artifactType:`screenshot`}),r;try{await e.backend.captureScreenshot({session:t.session,requestId:t.requestId,appId:t.appId,appBundleId:t.appBundleId,signal:t.signal??e.signal,metadata:t.metadata},n.path,{fullscreen:t.fullscreen,overlayRefs:t.overlayRefs,pixelDensity:t.pixelDensity,stabilize:t.stabilize,normalizeStatusBar:t.normalizeStatusBar,surface:t.surface}),t.maxSize!==void 0&&await gr(n.path,t.maxSize),r=await n.publish()}catch(e){throw await n.cleanup?.(),e}return{path:n.path,...r?{artifacts:[r]}:{},...x(`Saved screenshot: ${n.path}`)}};function br(e){let{nodes:t,backend:n,snapshotRaw:r}=e;if(r||!l(n))return{partial:!1,visibleNodeCount:t.length,totalNodeCount:t.length,reasons:[]};let i=We(t),a=new Set;return i.hiddenCount>0&&a.add(`offscreen-nodes`),i.nodes.some(e=>e.hiddenContentAbove)&&a.add(`scroll-hidden-above`),i.nodes.some(e=>e.hiddenContentBelow)&&a.add(`scroll-hidden-below`),{partial:a.size>0,visibleNodeCount:i.nodes.length,totalNodeCount:t.length,reasons:[...a]}}const xr=`A system surface (notification shade, quick settings, or another system overlay) covers the app, so this snapshot shows that surface. Interact with it or dismiss it (press back or swipe up) to reach app content.`;function Sr(e){return e?.systemSurfaceOnly===!0?xr:void 0}function Cr(e,t){return e.presentationKey?e:{...e,presentationKey:u(t)}}function wr(e){let{previous:t,current:n,options:r,identity:i}=e;if(r.forceFull===!0||r.raw===!0||!t||t.comparisonSafe===!1||n.comparisonSafe===!1||!Tr(t,n,i)||!t.presentationKey||t.presentationKey!==n.presentationKey||!Er(t,n))return;let a=r.scope?.trim();return{ageMs:Math.max(0,n.createdAt-t.createdAt),nodeCount:n.nodes.length,...r.interactiveOnly===!0?{interactiveOnly:!0}:{},...a?{scope:a}:{}}}function Tr(e,t,n){return!(e.backend&&t.backend&&e.backend!==t.backend||n?.previousAppBundleId&&n.currentAppBundleId&&n.previousAppBundleId!==n.currentAppBundleId)}function Er(e,t){return e.truncated===t.truncated?JSON.stringify(Dr(e.nodes))===JSON.stringify(Dr(t.nodes)):!1}function Dr(e){return e.map(e=>({index:e.index,depth:e.depth,parentIndex:e.parentIndex,type:e.type,role:e.role,subrole:e.subrole,label:e.label,value:e.value,identifier:e.identifier,enabled:e.enabled,selected:e.selected,focused:e.focused,hittable:e.hittable,rect:e.rect,bundleId:e.bundleId,appName:e.appName,windowTitle:e.windowTitle,surface:e.surface,hiddenContentAbove:e.hiddenContentAbove,hiddenContentBelow:e.hiddenContentBelow,interactionBlocked:e.interactionBlocked,presentationHints:e.presentationHints}))}const Or=async(e,t)=>{let n=await Ar(e,t),r=wr({previous:n.session?.snapshot,current:n.snapshot,options:t,identity:{previousAppBundleId:n.session?.appBundleId,currentAppBundleId:n.result.appBundleId??n.session?.appBundleId}});return await e.sessions.set(Mr(t.session,n)),{nodes:n.snapshot.nodes,truncated:n.snapshot.truncated??!1,visibility:br({nodes:n.snapshot.nodes,backend:n.snapshot.backend,snapshotRaw:t.raw}),...Oe({...n.annotations,warnings:n.warnings}),...r?{unchanged:r}:{},...n.result.snapshotDiagnostics?{snapshotDiagnostics:n.result.snapshotDiagnostics}:{},...Nr(n)}},kr=async(e,t)=>{let n=await Ar(e,t),r=t.interactiveOnly===!0,i=n.session?.snapshot,a=Mr(t.session,n);if(!i){let t=Ee(n.snapshot.nodes,{flatten:r});return await e.sessions.set(a),{mode:`snapshot`,baselineInitialized:!0,summary:{additions:0,removals:0,unchanged:t},lines:[],...n.warnings.length>0?{warnings:n.warnings}:{}}}let o=Ce(i.nodes,n.snapshot.nodes,{flatten:r});return await e.sessions.set(a),{mode:`snapshot`,baselineInitialized:!1,summary:o.summary,lines:o.lines,...n.warnings.length>0?{warnings:n.warnings}:{}}};async function Ar(e,t){if(!e.backend.captureSnapshot)throw new s(`UNSUPPORTED_OPERATION`,`snapshot is not supported by this backend`);let n=t.session??`default`,r=await e.sessions.get(n),i=await e.backend.captureSnapshot({session:n,requestId:t.requestId,appId:r?.appId,appBundleId:r?.appBundleId,signal:t.signal??e.signal,metadata:t.metadata},{interactiveOnly:t.interactiveOnly,depth:t.depth,scope:t.scope,raw:t.raw}),a=Cr(jr(i,e),t),o=Ae(i),c=m(e);return{snapshot:a,result:i,session:r,annotations:o,warnings:Pr({result:i,annotations:o,snapshot:a,options:t,session:r,capturedAt:a.createdAt??c,runtimeNow:c})}}function jr(e,t){return e.snapshot?e.snapshot:{nodes:e.nodes??[],truncated:e.truncated,backend:e.backend,createdAt:m(t)}}function Mr(e,t){let n=t.session?.name??e??`default`;return{...t.session??{name:n},name:n,snapshot:t.snapshot,appName:t.result.appName??t.session?.appName,appBundleId:t.result.appBundleId??t.session?.appBundleId}}function Nr(e){let t=e.result.appName??e.session?.appName,n=e.result.appBundleId??e.session?.appBundleId;return{...t||n?{appName:t??n}:{},...n?{appBundleId:n}:{}}}function Pr(e){let t=[...e.annotations.warnings??[]];e.annotations.quality&&t.push(...ne(e.annotations.quality,e.snapshot.nodes)),t.push(...Rr(e)),e.annotations.quality||(t.push(...Ir(e)),t.push(...Lr(e.snapshot.nodes)));let n=pt(e.snapshot.nodes);n&&t.push(n);let r=Fr(e.annotations);r&&t.push(r);let i=zr(e);return i&&t.push(i),t.push(...Ur(e.annotations.freshness,e.snapshot.backend)),Array.from(new Set(t))}function Fr(e){if(e.androidSnapshot?.systemSurfaceOnly===!0)return xr}function Ir(e){return e.snapshot.backend!==`xctest`||e.options.interactiveOnly!==!0||e.snapshot.nodes.length!==1||e.snapshot.nodes[0]?.type!==`Application`?[]:[`iOS interactive snapshot exposed only the application root. XCTest accessibility queries can fail to enumerate some simulator UI trees even when screenshots and direct gestures still work. Use screenshot as visual truth, try a scoped/full snapshot for diagnostics, and prefer direct selectors when known.`]}function Lr(e){let t=new Set(e.map(e=>e.parentIndex).filter(e=>e!==void 0));return e.filter(e=>t.has(e.index)||(e.type?.toLowerCase()??``).includes(`text`)?!1:(e.label??``).split(`, `).length>10).map(e=>{let t=(e.label??``).split(`, `).length,n=e.identifier?` (${e.identifier})`:``;return`@${e.ref} [${e.type??`element`}]${n} merges ~${t} labels into a single accessibility element. The app likely marks a container as accessible, which hides every descendant from assistive tech and automation — the children cannot be addressed individually. Fix the app's accessibility (mark the rows, not the container); until then use screenshot as visual truth and coordinate taps.`})}function Rr(e){let t=e.annotations.analysis;if(e.snapshot.backend!==`android`||e.options.interactiveOnly!==!0||e.snapshot.nodes.length>0||!t||(t.rawNodeCount??0)<12)return[];let n=[`Interactive snapshot is empty after filtering ${t.rawNodeCount} raw Android nodes. Likely causes: the app content is not accessibility-visible yet, a transient route change, or depth/filter options hid the target.`];return typeof e.options.depth==`number`&&typeof t.maxDepth==`number`&&t.maxDepth>=e.options.depth+2&&n.push(`Interactive output is empty at depth ${e.options.depth}; retry without -d.`),n}function zr(e){let t=e.session?.snapshot;if(!e.annotations.freshness&&t&&Br(t,e.snapshot)&&Vr(t,e.capturedAt,e.runtimeNow)&&Wr(t.nodes.length,e.snapshot.nodes.length))return Hr}function Br(e,t){return e.presentationKey===void 0||t.presentationKey===void 0?!0:e.presentationKey===t.presentationKey}function Vr(e,t,n){return[t,n].some(t=>{let n=t-e.createdAt;return n>=0&&n<=2e3})}const Hr=`Recent snapshots dropped sharply in node count, which suggests stale or mid-transition UI. Use screenshot as visual truth, wait briefly, then re-snapshot once.`;function Ur(e,t){return!e?.staleAfterRetries||t!==`android`?[]:e.reason===`stuck-route`?[`Recent ${e.action} was followed by a nearly identical snapshot after ${e.retryCount} automatic retr${e.retryCount===1?`y`:`ies`}. If you expected navigation or submit, the tree may still be stale. Use screenshot as visual truth, wait briefly, then re-snapshot once.`]:e.reason===`sharp-drop`?[Hr]:[]}function Wr(e,t){return e<12?!1:t<=Math.floor(e*.2)}const Gr={screenshot:yr,diffScreenshot:or,snapshot:Or,diffSnapshot:kr},Kr=async(e,t)=>await Xr(e,t,`press`),qr=async(e,t)=>await Xr(e,t,`click`),Jr=async(e,t)=>{if(!t.text)throw new s(`INVALID_ARGS`,`fill requires text`);let n=me(t),r=n.needsPreActionBaseline?null:await $r(e,t);if(r)return r;let i=await ce(e,t,{action:`fill`,requireInteractive:!0,promoteToHittableAncestor:!1,captureEvidenceBaseline:n.needsPreActionBaseline,expectedResolvedTarget:t.expectedResolvedTarget});if(!e.backend.fill)throw new s(`UNSUPPORTED_OPERATION`,`fill is not supported by this backend`);let a=Zr(i),o=v(await e.backend.fill(b(e,t),a,t.text,{delayMs:t.delayMs})),c=`node`in i?i.node?.type??``:``,l=c&&!Be(c,e.backend.platform)?`fill target ${ti(i)} resolved to "${c}", attempting fill anyway.`:void 0;return await Se(e,t,i,{...i,text:t.text,...l?{warning:l}:{},...o?{backendResult:o}:{}},n)},Yr=async(e,t)=>{let n=t.text;if(!n)throw new s(`INVALID_ARGS`,`type requires text`);let r=ni(n);if(r)throw new s(`INVALID_ARGS`,`type does not accept a target ref like "${r}"`,{hint:`Use fill ${r} "text" to target that field, or press ${r} then type "text" to append.`});if(!e.backend.typeText)throw new s(`UNSUPPORTED_OPERATION`,`type is not supported by this backend`);let i=S(t.delayMs??0,`delay-ms`,0,1e4),a=v(await e.backend.typeText(b(e,t),n,{delayMs:i}));return{kind:`text`,text:n,delayMs:i,...a?{backendResult:a}:{},...x(`Typed ${Array.from(n).length} chars`)}};async function Xr(e,t,n){let r=me(t),i=r.needsPreActionBaseline?null:await Qr(e,t,n);if(i)return i;let a=await ce(e,t,{action:n,requireInteractive:!0,promoteToHittableAncestor:!0,captureEvidenceBaseline:r.needsPreActionBaseline,expectedResolvedTarget:t.expectedResolvedTarget});if(!e.backend.tap)throw new s(`UNSUPPORTED_OPERATION`,`tap is not supported by this backend`);let o=Zr(a),c=v(await e.backend.tap(b(e,t),o,{button:t.button,count:t.count,intervalMs:t.intervalMs,holdMs:t.holdMs,jitterPx:t.jitterPx,doubleTap:t.doubleTap}));return await Se(e,t,a,{...a,...c?{backendResult:c}:{}},r)}function Zr(e){if(!e.point)throw new s(`COMMAND_FAILED`,`Interaction target resolved without coordinates`);return e.point}async function Qr(e,t,n){if(n!==`click`||t.target.kind!==`ref`||!e.backend.tapTarget||ei(t)||t.expectedResolvedTarget)return null;let r=await we(e,t,t.target,n),i=v(await e.backend.tapTarget(b(e,t),{kind:`ref`,ref:t.target.ref,...t.target.fallbackLabel?{fallbackLabel:t.target.fallbackLabel}:{}}));return{kind:`ref`,target:{kind:`ref`,ref:t.target.ref},resolution:fe,...r,...i?{backendResult:i}:{}}}async function $r(e,t){if(t.target.kind!==`ref`||!e.backend.fillTarget||t.expectedResolvedTarget)return null;let n=await we(e,t,t.target,`fill`),r=v(await e.backend.fillTarget(b(e,t),{kind:`ref`,ref:t.target.ref,...t.target.fallbackLabel?{fallbackLabel:t.target.fallbackLabel}:{}},t.text,{delayMs:t.delayMs}));return{kind:`ref`,target:{kind:`ref`,ref:t.target.ref},text:t.text,resolution:fe,...n,...r?{backendResult:r}:{}}}function ei(e){return e.count!==void 0||e.intervalMs!==void 0||e.holdMs!==void 0||e.jitterPx!==void 0||e.doubleTap!==void 0||e.button!==void 0&&e.button!==`primary`}function ti(e){return e.target?.kind===`ref`?e.target.ref:e.target?.kind===`selector`?e.target.selector:`point`}function ni(e){return Yt(e)}function V(e){return{includeRects:ri(e.predicate),interactiveOnly:!1}}function ri(e){return e===`visible`||e===`hidden`}function ii(e,t,n){let r=n??1e4,i=oi(e),a=ai(),o=0,s=()=>Math.max(0,r-(oi(e)-i));return{capture:async n=>{let r=o===0;o+=1;let i=await ye(e,t,s(),async e=>await a.attempt(()=>n(e)));return i.timedOut?{timedOut:!0,deadline:r?`capture-stalled`:`capture-truncated`}:i},hasTimeRemaining:()=>s()>0,rethrowIfNeverReadable:a.rethrowIfNeverReadable,sleepUntilNextPoll:async()=>await si(e,t,Math.min(300,s())),timeoutMs:r,waitedMs:()=>oi(e)-i}}function H(e,t){return new s(`COMMAND_FAILED`,e,{reason:`wait_capture_stalled`,captureStalled:!0,timeoutMs:t,hint:`A snapshot capture stalled past the wait timeout. Retry, or use screenshot to inspect the current surface.`})}function U(e,t,n){return new s(`COMMAND_FAILED`,e,n?{reason:`wait_deadline_exceeded`,captureTruncated:!0,timeoutMs:t}:void 0)}function ai(){let e=!1,t;return{attempt:async n=>{try{let t=await n();return e=!0,t}catch(e){if(!ae(e))throw e;t=e;return}},rethrowIfNeverReadable:()=>{if(!e&&t!==void 0)throw t}}}function oi(e){return e.clock?.now()??Date.now()}async function si(e,t,n){let r=[t.signal,e.signal].filter(e=>e!==void 0);for(let e of r)e.throwIfAborted();if(n<=0)return!1;if(e.clock){await e.clock.sleep(n);for(let e of r)e.throwIfAborted();return!0}return await new Promise((e,t)=>{let i=r.length>0?AbortSignal.any(r):void 0,a=()=>i?.removeEventListener(`abort`,s),o=setTimeout(()=>{a(),e()},n),s=()=>{clearTimeout(o),a(),t(i?.reason)};i?.addEventListener(`abort`,s,{once:!0}),o.unref()}),!0}function ci(e){let t=async(t,n)=>{if(n.target.kind===`sleep`)return await hi(t,n.target.durationMs),{kind:`sleep`,waitedMs:n.target.durationMs};if(n.target.kind===`ref`){let r=await e.requireSnapshot(t,n.session),i=d(n.target.ref);if(!i)throw new s(`INVALID_ARGS`,`Invalid ref: ${n.target.ref}`);let a=c(r.snapshot.nodes,i),o=a?He(a,r.snapshot.nodes):void 0;if(!o)throw new s(`COMMAND_FAILED`,`Ref ${n.target.ref} not found or has no label`);return await di(e,t,n,o,n.target.timeoutMs)}if(n.target.kind===`selector`)return await li(e,t,n,n.target.selector,n.target.timeoutMs,n.target.recordedLandmark);if(n.target.kind===`stable`)return await pi(e,t,n,n.target.quietMs,n.target.timeoutMs);let r=Ue(n.target.text);if(!r.ok)throw new s(r.code,r.message);return await di(e,t,n,n.target.text,n.target.timeoutMs)};return{waitCommand:t,waitForTextCommand:async(e,n)=>{let r=await t(e,{...n,target:{kind:`text`,text:n.text,timeoutMs:n.timeoutMs}});if(r.kind!==`text`)throw new s(`COMMAND_FAILED`,`waitForText returned non-text result`);return r}}}async function li(e,t,n,r,i,a){let o=ii(t,n,i),c=Ne(r),l=V({selectorChain:c}),u,d;for(;o.hasTimeRemaining();){let r=await o.capture(async r=>await e.captureSnapshot(t,{...n,signal:r},{updateSession:!0,includeHiddenContentHints:!1,...l}));if(r.timedOut){d=r.deadline;break}let i=r.value;if(i){let e=i.snapshot.nodes,n=et(e,c,{platform:t.backend.platform});if(n){let t=ui(e,n,a);if(t.kind===`satisfied`)return{kind:`selector`,selector:n.selector.raw,waitedMs:o.waitedMs(),node:t.node,preActionNodes:e};u=t.evidence}}await o.sleepUntilNextPoll()}throw d===`capture-stalled`?H(`wait timed out for selector: ${r}`,o.timeoutMs):u?new s(`COMMAND_FAILED`,`wait matched selector ${r} but no candidate carried the recorded landmark identity`,{reason:qe,...u}):d===`capture-truncated`?U(`wait timed out for selector: ${r}`,o.timeoutMs,!0):(o.rethrowIfNeverReadable(),U(`wait timed out for selector: ${r}`,o.timeoutMs,!1))}function ui(e,t,n){let r=t.matchedNodes[0];if(!n)return{kind:`satisfied`,node:r};let i=ue(e),a=re(t.matchedNodes,i,le(n),n.ancestry)[0];return a?{kind:`satisfied`,node:a}:{kind:`identity-mismatch`,evidence:{matchCount:t.matchedNodes.length,observed:Xe(r),observedAncestry:ee(r,i,Math.max(n.ancestry.length,1)).chain}}}async function di(e,t,n,r,i){let a=ii(t,n,i),o;for(;a.hasTimeRemaining();){let i=await a.capture(async i=>t.backend.findText?(await t.backend.findText(mi(t,{...n,signal:i}),r)).found:await fi(e,t,{...n,signal:i},r));if(i.timedOut){o=i.deadline;break}if(i.value)return{kind:`text`,text:r,waitedMs:a.waitedMs()};await a.sleepUntilNextPoll()}throw o===`capture-stalled`?H(`wait timed out for text: ${r}`,a.timeoutMs):o===`capture-truncated`?U(`wait timed out for text: ${r}`,a.timeoutMs,!0):(a.rethrowIfNeverReadable(),U(`wait timed out for text: ${r}`,a.timeoutMs,!1))}async function fi(e,t,n,r){return!!tt((await e.captureSnapshot(t,n,{updateSession:!0,includeHiddenContentHints:!1})).snapshot.nodes,r)}async function pi(e,t,n,r,i){let a=i??1e4,o=r??e.stable.defaultQuietMs,c=await e.stable.capture(t,n,{quietMs:o,timeoutMs:a});if(!c.settled)throw new s(`COMMAND_FAILED`,`wait timed out waiting for a stable UI`,{reason:`wait_stable_timeout`,...c.stalled?{captureStalled:!0}:{},quietMs:o,timeoutMs:a,captures:c.captures,nodeCount:c.nodeCount,...c.stalled?{hint:`A snapshot capture stalled past the wait timeout, so no settle verdict is available. The UI may still be readable: retry, or use screenshot to inspect the surface.`}:{}});return{kind:`stable`,waitedMs:c.waitedMs,captures:c.captures,nodeCount:c.nodeCount,...c.nodeCount<e.stable.tinyTreeNodeCount?{hint:e.stable.tinyTreeHint}:{}}}function mi(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}async function hi(e,t){e.clock?await e.clock.sleep(t):await new Promise(e=>setTimeout(e,t))}const gi=ci({captureSnapshot:_,requireSnapshot:oe,stable:{defaultQuietMs:500,tinyTreeHint:he,tinyTreeNodeCount:5,capture:be}}),_i=gi.waitCommand,vi=gi.waitForTextCommand,yi=async(e,t)=>{let n=t.locator??`any`;if(!t.query)throw new s(`INVALID_ARGS`,Ie);if(t.action===`wait`)return await Ei(e,t,n);let{capture:r,match:i}=await Di(e,t,n);if(!i)throw new s(`COMMAND_FAILED`,`find did not match any element`);if(t.action===`exists`)return{kind:`found`,found:!0};let a=`@${i.ref}`;return t.action===`get_attrs`?{kind:`attrs`,ref:a,node:i}:{kind:`text`,ref:a,text:await g(e,r,i),node:i}},bi=async(e,t)=>{if(t.target.kind===`ref`){let n=await oe(e,t.session),r=_e(n.snapshot.nodes,t.target.ref,{fallbackLabel:t.target.fallbackLabel??``,invalidRefMessage:`get text requires a ref like @e2`,notFoundMessage:`Ref ${t.target.ref} not found`});Te(r.node,n.snapshot.nodes,t.expectedResolvedTarget,`get`);let i=Ze(r.node,e.backend.platform,{action:`get`,nodes:n.snapshot.nodes}),a={kind:`ref`,ref:`@${r.ref}`},o=n.snapshot.nodes;return t.property===`attrs`?{kind:`attrs`,target:a,node:r.node,selectorChain:i,preActionNodes:o}:{kind:`text`,target:a,text:await g(e,n,r.node),node:r.node,selectorChain:i,preActionNodes:o}}let n=await Oi(e,t,t.session??`default`,{selector:t.target.selector,disambiguateAmbiguous:t.property===`text`});Te(n.node,n.capture.snapshot.nodes,t.expectedResolvedTarget,`get`);let r=Ze(n.node,e.backend.platform,{action:`get`,nodes:n.capture.snapshot.nodes});if(t.property===`attrs`)return{kind:`attrs`,target:{kind:`selector`,selector:n.selector},node:n.node,selectorChain:r,preActionNodes:n.capture.snapshot.nodes};let i=await g(e,n.capture,n.node);return{kind:`text`,target:{kind:`selector`,selector:n.selector},text:i,node:n.node,selectorChain:r,preActionNodes:n.capture.snapshot.nodes}},xi=async(e,t)=>{let n=await bi(e,{...t,property:`text`,target:t.target});if(n.kind!==`text`)throw new s(`COMMAND_FAILED`,`getText returned non-text result`);return n},Si=async(e,t)=>{let n=await bi(e,{...t,property:`attrs`,target:t.target});if(n.kind!==`attrs`)throw new s(`COMMAND_FAILED`,`getAttrs returned non-attrs result`);return n},Ci=async(e,t)=>{let n=ze(t.predicate);if(!n.ok)throw new s(n.code,n.message,{hint:n.hint});let r=n.predicate;if(r===`text`&&!t.expectedText)throw new s(`INVALID_ARGS`,Ve);let i=Ne(t.selector),a=await _(e,t,{updateSession:!0,...V({predicate:r,selectorChain:i})});if(r===`exists`){let t=Ge(a.snapshot.nodes,i,{platform:e.backend.platform});if(!t)throw new s(`COMMAND_FAILED`,Qe(i,[],{unique:!1}),{hint:$e([])});return{predicate:r,pass:!0,selector:t.selector.raw,matches:t.matches,selectorChain:i.selectors.map(e=>e.raw)}}let o=Ke(a.snapshot.nodes,i,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:!1});if(!o)throw new s(`COMMAND_FAILED`,Qe(i,[],{unique:!0}),{command:`is`,reason:`selector_not_found`,predicate:r,selector:i.raw,hint:$e([])});Te(o.node,a.snapshot.nodes,t.expectedResolvedTarget,`is`);let c=Je({predicate:r,node:o.node,nodes:a.snapshot.nodes,expectedText:t.expectedText,platform:e.backend.platform});if(!c.pass)throw new s(`COMMAND_FAILED`,`is ${r} failed for selector ${o.selector.raw}: ${c.details}`,{command:`is`,reason:`predicate_failed`,predicate:r,selector:o.selector.raw,predicateDetails:c.details});return{predicate:r,pass:!0,selector:o.selector.raw,...r===`text`?{text:c.actualText}:{},selectorChain:i.selectors.map(e=>e.raw),node:o.node,preActionNodes:a.snapshot.nodes}},wi=async(e,t)=>await Ci(e,{...t,predicate:`visible`,selector:t.target.selector}),Ti=async(e,t)=>await Ci(e,{...t,predicate:`hidden`,selector:t.target.selector});async function Ei(e,t,n){let r=ii(e,t,t.timeoutMs),i;for(;r.hasTimeRemaining();){let a=await r.capture(async r=>await Di(e,{...t,signal:r},n,{includeHiddenContentHints:!1}));if(a.timedOut){i=a.deadline;break}if(a.value?.match)return{kind:`found`,found:!0,waitedMs:r.waitedMs()};await r.sleepUntilNextPoll()}throw i===`capture-stalled`?H(`find wait timed out`,r.timeoutMs):i===`capture-truncated`?U(`find wait timed out`,r.timeoutMs,!0):(r.rethrowIfNeverReadable(),U(`find wait timed out`,r.timeoutMs,!1))}async function Di(e,t,n,r){let i=Pe(n,t.query),a=await _(e,t,{updateSession:!0,scope:h(e.backend.platform,n,t.query,i),includeHiddenContentHints:r?.includeHiddenContentHints,...V({selectorChain:i})});if(ie(a.snapshot.snapshotQuality))throw ge(a.snapshot.snapshotQuality);return i?{capture:a,match:Ke(a.snapshot.nodes,i,{platform:e.backend.platform,requireRect:!1,requireUnique:!1})?.node}:{capture:a,match:Fe(a.snapshot.nodes,n,t.query,{requireRect:!1}).matches[0]}}async function Oi(e,t,n,r){let i=Ne(r.selector),a=await _(e,{...t,session:n},{updateSession:!0,...V({selectorChain:i})}),o=Ke(a.snapshot.nodes,i,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:r.disambiguateAmbiguous});if(!o)throw new s(`COMMAND_FAILED`,Qe(i,[],{unique:!0}),{hint:$e([])});return{capture:a,node:o.node,selector:o.selector.raw,ref:`@${o.node.ref}`}}function ki(e,t){let n=e.filter(t=>Re(t,e)).map(e=>e.rect).filter(Ai),r=n.length>0?n:e.map(e=>e.rect).filter(Ai);if(r.length===0)throw new s(`COMMAND_FAILED`,`Cannot infer viewport for ${t}`);let i=Math.min(...r.map(e=>e.x)),a=Math.min(...r.map(e=>e.y)),o=Math.max(...r.map(e=>e.x+e.width)),c=Math.max(...r.map(e=>e.y+e.height));return{x:i,y:a,width:o-i,height:c-a}}function Ai(e){return!!(e&&e.width>0&&e.height>0)}const ji=async(e,t)=>{if(!e.backend.performGesture)throw new s(`UNSUPPORTED_OPERATION`,`gesture is not supported by this backend`);await se(e,t,t.gesture.intent);let n=await Mi(e,t),r=De(t.gesture,n,e.backend.platform),i=v(await e.backend.performGesture(b(e,t),r)),a=Ni(r.pointers,0),o=Ni(r.pointers,-1);return{kind:r.intent,durationMs:r.durationMs,pointerCount:r.topology===`single`?1:2,from:a,to:o,...i?{backendResult:i}:{},...x(Pi(t.gesture,a,o))}};async function Mi(e,t){return await e.backend.resolveGestureViewport?.(b(e,t))||ki((await te(e,t,!1)).snapshot.nodes,`gesture`)}function Ni(e,t){let n=e.map(e=>t===0?e.samples[0]?.point:e.samples.at(-1)?.point);if(n.some(e=>e===void 0))throw new s(`COMMAND_FAILED`,`Gesture plan did not contain endpoint samples.`);let r=n;return{x:r.reduce((e,t)=>e+t.x,0)/r.length,y:r.reduce((e,t)=>e+t.y,0)/r.length}}function Pi(e,t,n){switch(e.intent){case`pan`:{let r=`preset`in e?t:e.origin,i=`preset`in e?{x:n.x-t.x,y:n.y-t.y}:e.delta;return`Panned (${r.x}, ${r.y}) by (${i.x}, ${i.y})`}case`fling`:return`direction`in e?`Flung ${e.direction}`:`Flung`;case`pinch`:return`Pinched to scale ${e.scale}`;case`rotate`:return`Rotated gesture ${e.degrees} degrees`;case`transform`:return`Requested transform gesture by (${e.delta.x}, ${e.delta.y}), scale ${e.scale}, rotate ${e.degrees} degrees`}}const W={find:yi,get:bi,getText:xi,getAttrs:Si,is:Ci,isVisible:wi,isHidden:Ti,wait:_i,waitForText:vi},G={click:qr,press:Kr,fill:Jr,typeText:Yr,focus:xe,longPress:pe,scroll:ve,gesture:ji};function Fi(e){return{find:t=>W.find(e,t),get:t=>W.get(e,t),getText:(t,n={})=>W.getText(e,{...n,target:t}),getAttrs:(t,n={})=>W.getAttrs(e,{...n,target:t}),is:t=>W.is(e,t),isVisible:(t,n={})=>W.isVisible(e,{...n,target:t}),isHidden:(t,n={})=>W.isHidden(e,{...n,target:t}),wait:t=>W.wait(e,t),waitForText:(t,n={})=>W.waitForText(e,{...n,text:t})}}function Ii(e){return{click:(t,n={})=>G.click(e,{...n,target:t}),press:(t,n={})=>G.press(e,{...n,target:t}),fill:(t,n,r={})=>G.fill(e,{...r,target:t,text:n}),typeText:(t,n={})=>G.typeText(e,{...n,text:t}),focus:(t,n={})=>G.focus(e,{...n,target:t}),longPress:(t,n={})=>G.longPress(e,{...n,target:t}),scroll:t=>G.scroll(e,t),gesture:t=>G.gesture(e,t)}}function K(e,t){if(e!==void 0)return q(e,t)}function q(e,t){let n=e?.trim();if(!n)throw new s(`INVALID_ARGS`,`${t} must be a non-empty string`);return n}const Li=async(e,t={})=>{if(!e.backend.listDevices)throw new s(`UNSUPPORTED_OPERATION`,`admin.devices is not supported by this backend`);return{kind:`adminDevices`,devices:await e.backend.listDevices(b(e,t),t.filter)}},Ri=async(e,t={})=>{if(!e.backend.bootDevice)throw new s(`UNSUPPORTED_OPERATION`,`admin.boot is not supported by this backend`);let n=Ji(t.target),r=v(await e.backend.bootDevice(b(e,t),n));return{kind:`deviceBooted`,...n?{target:n}:{},...r?{backendResult:r}:{},...x(`Booted device`)}},zi=async(e,t={})=>{if(!e.backend.shutdownDevice)throw new s(`UNSUPPORTED_OPERATION`,`admin.shutdown is not supported by this backend`);let n=Ji(t.target),r=v(await e.backend.shutdownDevice(b(e,t),n));return{kind:`deviceShutdown`,...n?{target:n}:{},...r?{backendResult:r}:{},...x(`Shutdown device`)}},Bi=async(e,t)=>await Ui(e,t,`install`),Vi=async(e,t)=>await Ui(e,t,`reinstall`),Hi=async(e,t)=>await Ui(e,t,`installFromSource`);async function Ui(e,t,n){let r=n===`reinstall`?`reinstallApp`:`installApp`,i=e.backend[r];if(!i)throw new s(`UNSUPPORTED_OPERATION`,`admin.${n} is not supported by this backend`);let a=`app`in t&&t.app!==void 0?q(t.app,`app`):void 0;if(n!==`installFromSource`&&!a)throw new s(`INVALID_ARGS`,`admin.${n} requires app`);let o=b(e,t),c=await Wi(e,o,t.source);try{let t=await i.call(e.backend,o,{...a?{app:a}:{},source:c.source});return Yi(n,a,c.source,t)}finally{await c.cleanup?.()}}async function Wi(e,t,n){let r=await Gi(e,Ki(n));try{return{source:Ki(e.backend.resolveInstallSource?await e.backend.resolveInstallSource(t,r.source):r.source),...r.cleanup?{cleanup:r.cleanup}:{}}}catch(e){if(r.cleanup)try{await r.cleanup()}catch{}throw e}}async function Gi(e,t){if(t.kind===`url`)return{source:t};let n=await R(e,t,{usage:`admin.install`,field:`source`});return{source:{kind:`path`,path:n.path},...n.cleanup?{cleanup:n.cleanup}:{}}}function Ki(e){if(!e||typeof e!=`object`)throw new s(`INVALID_ARGS`,`install source is required`);if(e.kind===`path`)return{kind:`path`,path:q(e.path,`source.path`)};if(e.kind===`uploadedArtifact`)return{kind:`uploadedArtifact`,id:q(e.id,`source.id`)};if(e.kind===`url`){let t=q(e.url,`source.url`);return qi(t),{kind:`url`,url:t}}throw new s(`INVALID_ARGS`,`install source kind must be path, uploadedArtifact, or url`)}function qi(e){let t;try{t=new URL(e)}catch{throw new s(`INVALID_ARGS`,`Invalid install source URL: ${e}`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new s(`INVALID_ARGS`,`Install source URL must use http or https`)}function Ji(e){if(!e)return;let t=K(e.id,`target.id`),n=K(e.name,`target.name`),r={...t?{id:t}:{},...n?{name:n}:{},...e.platform?{platform:e.platform}:{},...e.target?{target:e.target}:{},...e.headless===void 0?{}:{headless:e.headless}};return Object.keys(r).length>0?r:void 0}function Yi(e,t,n,r){let i=v(r),a=e===`reinstall`?`appReinstalled`:e===`installFromSource`?`appInstalledFromSource`:`appInstalled`,o=J(r,`appName`),s=J(r,`appId`),c=J(r,`bundleId`),l=J(r,`packageName`),u=J(r,`launchTarget`),d=J(r,`installablePath`),f=J(r,`archivePath`);return{kind:a,...t?{app:t}:{},source:n,...s?{appId:s}:{},...o?{appName:o}:{},...c?{bundleId:c}:{},...l?{packageName:l}:{},...u?{launchTarget:u}:{},...d?{installablePath:d}:{},...f?{archivePath:f}:{},...i?{backendResult:i}:{},...x(`${e===`reinstall`?`Reinstalled`:`Installed`}: ${o??u??t??Xi(n)}`)}}function J(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Xi(e){return e.kind===`path`?e.path:e.kind===`uploadedArtifact`?e.id:e.url}const Zi=/^[A-Za-z0-9_.:-]{1,64}$/,Qi=async(e,t)=>{if(!e.backend.openApp)throw new s(`UNSUPPORTED_OPERATION`,`apps.open is not supported by this backend`);let n=ia(t),r=v(await e.backend.openApp(Y(e,t),n,{launchArgs:t.launchArgs,relaunch:t.relaunch}));return{kind:`appOpened`,target:n,relaunch:t.relaunch===!0,...r?{backendResult:r}:{},...x(`Opened: ${oa(n)}`)}},$i=async(e,t={})=>{if(!e.backend.closeApp)throw new s(`UNSUPPORTED_OPERATION`,`apps.close is not supported by this backend`);let n=K(t.app,`app`),r=v(await e.backend.closeApp(Y(e,t),n));return{kind:`appClosed`,...n?{app:n}:{},...r?{backendResult:r}:{},...x(n?`Closed: ${n}`:`Closed app`)}},ea=async(e,t={})=>{if(!e.backend.listApps)throw new s(`UNSUPPORTED_OPERATION`,`apps.list is not supported by this backend`);return{kind:`appsList`,apps:await e.backend.listApps(Y(e,t),nt(t.filter))}},ta=async(e,t)=>{if(!e.backend.getAppState)throw new s(`UNSUPPORTED_OPERATION`,`apps.state is not supported by this backend`);let n=q(t.app,`app`);return{kind:`appState`,app:n,state:await e.backend.getAppState(Y(e,t),n)}},na=async(e,t)=>{if(!e.backend.pushFile)throw new s(`UNSUPPORTED_OPERATION`,`apps.push is not supported by this backend`);let n=q(t.app,`app`),r=await sa(e,t.input);try{let i=v(await e.backend.pushFile(Y(e,t),r.backendInput,n));return{kind:`appPushed`,app:n,inputKind:r.inputKind,...i?{backendResult:i}:{},...x(`Pushed to ${n}`)}}finally{await r.cleanup?.()}},ra=async(e,t)=>{if(!e.backend.triggerAppEvent)throw new s(`UNSUPPORTED_OPERATION`,`apps.triggerEvent is not supported by this backend`);let n=ca(t.name);la(t.payload,`apps.triggerEvent payload for "${n}"`);let r=v(await e.backend.triggerAppEvent(Y(e,t),{name:n,...t.payload?{payload:t.payload}:{}}));return{kind:`appEventTriggered`,name:n,...t.payload?{payload:t.payload}:{},...r?{backendResult:r}:{},...x(`Triggered app event: ${n}`)}};function ia(e){let t=K(e.app,`app`),n=K(e.appId,`appId`),r=K(e.bundleId,`bundleId`),i=K(e.packageName,`packageName`),a=K(e.url,`url`),o=K(e.activity,`activity`),c={...t?{app:t}:{},...n?{appId:n}:{},...r?{bundleId:r}:{},...i?{packageName:i}:{},...a?{url:a}:{},...o?{activity:o}:{}};if(!aa(c))throw new s(`INVALID_ARGS`,`apps.open requires app, appId, bundleId, packageName, url, or activity`);return c}function aa(e){return!!(e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity)}function oa(e){return e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity??`app`}async function sa(e,t){if(!t||typeof t!=`object`)throw new s(`INVALID_ARGS`,`apps.push requires an input`);if(t.kind===`json`)return ua(t.payload,`apps.push JSON payload`,8192),{backendInput:{kind:`json`,payload:t.payload},inputKind:`json`};let n=await R(e,t,{usage:`apps.push`,field:`input`});return{backendInput:{kind:`file`,path:n.path},inputKind:`file`,...n.cleanup?{cleanup:n.cleanup}:{}}}function ca(e){let t=q(e,`name`);if(!Zi.test(t))throw new s(`INVALID_ARGS`,`Invalid apps.triggerEvent name: ${t}`,{hint:`Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash.`});return t}function la(e,t){e!==void 0&&ua(e,t,8192)}function ua(e,t,n){if(da(e,t),Buffer.byteLength(fa(e,t),`utf8`)>n)throw new s(`INVALID_ARGS`,`${t} exceeds ${n} bytes`)}function da(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw new s(`INVALID_ARGS`,`${t} must be a JSON object`)}function fa(e,t){try{let n=JSON.stringify(e);if(typeof n!=`string`)throw new s(`INVALID_ARGS`,`${t} must be JSON-serializable`);return n}catch{throw new s(`INVALID_ARGS`,`${t} must be JSON-serializable`)}}function Y(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}const pa={open:Qi,close:$i,list:ea,state:ta,push:na,triggerEvent:ra},ma={devices:Li,boot:Ri,shutdown:zi,install:Bi,reinstall:Vi,installFromSource:Hi};function ha(e){return{...y(pa,e),list:(t={})=>pa.list(e,{...t,filter:rt(t.filter)})}}const ga=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i,_a=/\b[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g;function va(e){let t=!1,n=e;return n=n.replaceAll(/(authorization|token|secret|password|passwd|api[-_]?key)=([^&\s]+)/gi,(e,n)=>(t=!0,`${String(n)}=[REDACTED]`)),n=n.replaceAll(/("(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)"\s*:\s*")([^"]*)(")/gi,(e,n,r,i)=>(t=!0,`${String(n)}[REDACTED]${String(i)}`)),n=n.replaceAll(/\b(Bearer\s+)([^\s",;]+)/gi,(e,n)=>(t=!0,`${String(n)}[REDACTED]`)),n=n.replaceAll(/((?:authorization|cookie|token|secret|password|passwd|api[-_]?key)\s*[:=]\s*)([^\s,;&]+)/gi,(e,n)=>(t=!0,`${String(n)}[REDACTED]`)),n=n.replaceAll(_a,()=>(t=!0,`[REDACTED]`)),n=ba(n,()=>{t=!0}),{value:n,redacted:t}}function ya(e){try{let t=new URL(e),n=xa(t);return(t.username||t.password)&&(t.username=`REDACTED`,t.password=`REDACTED`,n=!0),{value:t.toString(),redacted:n}}catch{return}}function ba(e,t){return/(https?:\/\/|token|secret|password|authorization|cookie|api[-_]?key)/i.test(e)?e.replaceAll(/https?:\/\/[^\s"'<>)]+/gi,e=>{let n=ya(e);return n?(n.redacted&&t(),n.value):e}):e}function xa(e){let t=!1;for(let n of Array.from(e.searchParams.keys()))ga.test(n)&&(e.searchParams.set(n,`[REDACTED]`),t=!0);return t}const X=2048,Sa=4096,Ca=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i;function wa(e){let t=e.redacted===!0;return{kind:`diagnosticsLogs`,entries:e.entries.map(e=>{let n=Q(e.message,Sa),r=ja(e.metadata);return t||=n.redacted||r.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.level?{level:e.level}:{},message:n.value??``,...e.source?{source:e.source}:{},...r.value?{metadata:r.value}:{}}}),...e.nextCursor?{nextCursor:e.nextCursor}:{},...e.timeWindow?{timeWindow:e.timeWindow}:{},...e.backend?{backend:e.backend}:{},redacted:t,...e.notes?{notes:e.notes}:{}}}function Ta(e,t){let n=e.redacted===!0;return{kind:`diagnosticsNetwork`,entries:e.entries.map(e=>{let r=e.url?Oa(e.url):void 0,i=t===`headers`||t===`all`?Da(e.requestHeaders):void 0,a=t===`headers`||t===`all`?Da(e.responseHeaders):void 0,o=t===`body`||t===`all`?ka(e.requestBody):void 0,s=t===`body`||t===`all`?ka(e.responseBody):void 0,c=ja(e.metadata);return n||=(r?.redacted??!1)||(i?.redacted??!1)||(a?.redacted??!1)||(o?.redacted??!1)||(s?.redacted??!1)||c.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.method?{method:e.method}:{},...r?{url:r.value}:{},...e.status===void 0?{}:{status:e.status},...e.durationMs===void 0?{}:{durationMs:e.durationMs},...i?.value?{requestHeaders:i.value}:{},...a?.value?{responseHeaders:a.value}:{},...o?.value===void 0?{}:{requestBody:o.value},...s?.value===void 0?{}:{responseBody:s.value},...c.value?{metadata:c.value}:{}}}),...e.nextCursor?{nextCursor:e.nextCursor}:{},...e.timeWindow?{timeWindow:e.timeWindow}:{},...e.backend?{backend:e.backend}:{},redacted:n,...e.notes?{notes:e.notes}:{}}}function Ea(e){let t=e.redacted===!0;return{kind:`diagnosticsPerf`,metrics:e.metrics.map(e=>{let n=Q(e.message,Sa),r=ja(e.metadata);return t||=n.redacted||r.redacted,{name:e.name,...e.value===void 0?{}:{value:e.value},...e.unit?{unit:e.unit}:{},...e.status?{status:e.status}:{},...n.value===void 0?{}:{message:n.value},...r.value?{metadata:r.value}:{}}}),...e.startedAt?{startedAt:e.startedAt}:{},...e.endedAt?{endedAt:e.endedAt}:{},...e.backend?{backend:e.backend}:{},redacted:t,...e.notes?{notes:e.notes}:{}}}function Da(e){if(!e)return{redacted:!1};let t=!1,n={};for(let[r,i]of Object.entries(e))if(Ca.test(r))n[r]=`[REDACTED]`,t=!0;else{let e=Q(i,X);n[r]=e.value??``,t||=e.redacted}return{value:n,redacted:t}}function Oa(e){return ya(e)??Q(e,X)}function ka(e){return e===void 0?{redacted:!1}:Aa(e)??Q(e,X)}function Aa(e){try{let t=Z(JSON.parse(e),va);return Ma(JSON.stringify(t.value),X,t.redacted)}catch{return}}function ja(e){return Z(e,e=>Q(e,X))}function Z(e,t){if(e===void 0)return{redacted:!1};if(typeof e==`string`)return t(e);if(!e||typeof e!=`object`)return{value:e,redacted:!1};if(Array.isArray(e)){let n=!1;return{value:e.map(e=>{let r=Z(e,t);return n||=r.redacted,r.value}),redacted:n}}let n=!1,r={};for(let[i,a]of Object.entries(e)){if(Ca.test(i)){r[i]=`[REDACTED]`,n=!0;continue}let e=Z(a,t);r[i]=e.value,n||=e.redacted}return{value:r,redacted:n}}function Q(e,t){if(e===void 0)return{redacted:!1};let n=va(e);return Ma(n.value,t,n.redacted)}function Ma(e,t,n){if(e===void 0)return{redacted:n};let r=e;return r.length>t&&(r=`${r.slice(0,t)}...[truncated]`,n=!0),{value:r,redacted:n}}const Na=async(e,t={})=>{if(!e.backend.readLogs)throw new s(`UNSUPPORTED_OPERATION`,`diagnostics.logs is not supported by this backend`);return wa(await e.backend.readLogs(await Ia(e,t),La(t)))},Pa=async(e,t={})=>{if(!e.backend.dumpNetwork)throw new s(`UNSUPPORTED_OPERATION`,`diagnostics.network is not supported by this backend`);let n=Ra(t);return Ta(await e.backend.dumpNetwork(await Ia(e,t),n),n.include??`summary`)},Fa=async(e,t={})=>{if(!e.backend.measurePerf)throw new s(`UNSUPPORTED_OPERATION`,`diagnostics.perf is not supported by this backend`);return Ea(await e.backend.measurePerf(await Ia(e,t),za(t)))};async function Ia(e,t){let n=b(e,t),r=t.session?await e.sessions.get(t.session):void 0;return{...n,...t.appId??r?.appId?{appId:t.appId??r?.appId}:{},...t.appBundleId??r?.appBundleId?{appBundleId:t.appBundleId??r?.appBundleId}:{}}}function La(e){return{...Ba(e,100,500,`logs limit`),...e.levels===void 0?{}:{levels:Ua(e.levels,`levels`)},...e.search===void 0?{}:{search:q(e.search,`search`)},...e.source===void 0?{}:{source:q(e.source,`source`)}}}function Ra(e){return{...Ba(e,25,200,`network limit`),include:Ha(e.include)}}function za(e){return{...Va(e),...e.sampleMs===void 0?{}:{sampleMs:S(e.sampleMs,`sampleMs`,100,6e4)},...e.metrics===void 0?{}:{metrics:Ua(e.metrics,`metrics`,20)}}}function Ba(e,t,n,r){return{...Va(e),...e.cursor===void 0?{}:{cursor:q(e.cursor,`cursor`)},limit:e.limit===void 0?t:S(e.limit,r,1,n)}}function Va(e){return{...e.since===void 0?{}:{since:q(e.since,`since`)},...e.until===void 0?{}:{until:q(e.until,`until`)}}}function Ha(e){if(e===void 0)return`summary`;if(e===`summary`||e===`headers`||e===`body`||e===`all`)return e;throw new s(`INVALID_ARGS`,`network include must be summary, headers, body, or all`)}function Ua(e,t,n=50){if(!Array.isArray(e))throw new s(`INVALID_ARGS`,`${t} must be an array of strings`);if(e.length>n)throw new s(`INVALID_ARGS`,`${t} must contain at most ${n} entries`);return e.map((e,n)=>q(e,`${t}[${n}]`))}const Wa={logs:Na,network:Pa,perf:Fa},Ga=async(e,t)=>{let n=Za(t.action,`record`),r=n===`start`?e.backend.startRecording:e.backend.stopRecording;if(!r)throw new s(`UNSUPPORTED_OPERATION`,`record ${n} is not supported by this backend`);let i=t.out?await z(e,t.out,{field:`path`,ext:`.mp4`,artifactType:`screen-recording`}):void 0;try{let a=qa(t,i?.path);return Qa(n,await r.call(e.backend,b(e,t),a),await i?.publish())}catch(e){throw await i?.cleanup?.(),e}},Ka=async(e,t)=>{let n=Za(t.action,`trace`),r=n===`start`?e.backend.startTrace:e.backend.stopTrace;if(!r)throw new s(`UNSUPPORTED_OPERATION`,`trace ${n} is not supported by this backend`);let i=t.out?await z(e,t.out,{field:`outPath`,ext:`.trace`,artifactType:`trace-log`}):void 0;try{let a={...i?.path?{outPath:i.path}:{}};return $a(n,await r.call(e.backend,b(e,t),a),await i?.publish())}catch(e){throw await i?.cleanup?.(),e}};function qa(e,t){let n={};t&&(n.outPath=t);let r=Ja(e.fps);r!==void 0&&(n.fps=r);let i=Ya(e.maxSize);i!==void 0&&(n.maxSize=i);let a=Xa(e.quality);return a!==void 0&&(n.quality=a),e.hideTouches!==void 0&&(n.showTouches=e.hideTouches!==!0),n}function Ja(e){return e===void 0?void 0:S(e,`fps`,1,60)}function Ya(e){return e===void 0?void 0:S(e,`maxSize`,1,2**53-1)}function Xa(e){if(e===void 0)return;let t=de(e);if(t===void 0)throw new s(`INVALID_ARGS`,`quality must be one of: medium, high (legacy numeric values 5-10 are accepted)`);return t}function Za(e,t){if(e===`start`||e===`stop`)return e;throw new s(`INVALID_ARGS`,`${t} action must be start or stop`)}function Qa(e,t,n){return{...typeof t.path==`string`?{path:t.path}:{},...typeof t.telemetryPath==`string`?{telemetryPath:t.telemetryPath}:{},...typeof t.warning==`string`?{warning:t.warning}:{},...eo(e,t,n,{startKind:`recordingStarted`,stopKind:`recordingStopped`,startMessage:`Recording started`,stopMessage:`Recording stopped`})}}function $a(e,t,n){return{...typeof t.outPath==`string`?{outPath:t.outPath}:{},...eo(e,t,n,{startKind:`traceStarted`,stopKind:`traceStopped`,startMessage:`Trace started`,stopMessage:`Trace stopped`})}}function eo(e,t,n,r){return{kind:e===`start`?r.startKind:r.stopKind,action:e,...n?{artifact:n}:{},backendResult:t,...x(e===`start`?r.startMessage:r.stopMessage)}}const to={record:Ga,trace:Ka},no=async(e,t={})=>{if(!e.backend.pressBack)throw new s(`UNSUPPORTED_OPERATION`,`system.back is not supported by this backend`);let n=t.mode??`in-app`;if(n!==`in-app`&&n!==`system`)throw new s(`INVALID_ARGS`,`system.back mode must be in-app or system`);let r=v(await e.backend.pressBack(b(e,t),{mode:n}));return{kind:`systemBack`,mode:n,...r?{backendResult:r}:{},...x(`Back`)}},ro=async(e,t={})=>{if(!e.backend.pressHome)throw new s(`UNSUPPORTED_OPERATION`,`system.home is not supported by this backend`);let n=v(await e.backend.pressHome(b(e,t)));return{kind:`systemHome`,...n?{backendResult:n}:{},...x(`Home`)}},io=async(e,t)=>{if(!e.backend.pressTvRemote)throw new s(`UNSUPPORTED_OPERATION`,`system.tvRemote is not supported by this backend`);let n=je(t.button),r=t.durationMs===void 0?void 0:S(t.durationMs,`durationMs`,0,1e4),i=v(await e.backend.pressTvRemote(b(e,t),{button:n,...r===void 0?{}:{durationMs:r}}));return{kind:`tvRemotePressed`,button:n,...r===void 0?{}:{durationMs:r},...i?{backendResult:i}:{},...x(`Pressed TV remote ${n}`)}},ao=async(e,t)=>{if(!e.backend.setOrientation)throw new s(`UNSUPPORTED_OPERATION`,`system.orientation is not supported by this backend`);let n=fo(t.orientation),r=v(await e.backend.setOrientation(b(e,t),n));return{kind:`systemOrientationSet`,orientation:n,...r?{backendResult:r}:{},...x(`Rotated to ${n}`)}},oo=async(e,t={})=>{if(!e.backend.setKeyboard)throw new s(`UNSUPPORTED_OPERATION`,`system.keyboard is not supported by this backend`);let n=t.action??`status`;if(!Le(n))throw new s(`INVALID_ARGS`,`system.keyboard action must be status, get, dismiss, enter, or return`);let r=await e.backend.setKeyboard(b(e,t),{action:n}),i=v(r),a=bo(r)?r:{};return n===`enter`||n===`return`?mo(a,i):n===`dismiss`?ho(n,a,i):go(n,a,i)},so=async(e,t)=>{if(t.action===`read`){if(!e.backend.getClipboard)throw new s(`UNSUPPORTED_OPERATION`,`system.clipboard read is not supported by this backend`);let n=await e.backend.getClipboard(b(e,t));return{kind:`clipboardText`,action:`read`,text:typeof n==`string`?n:n.text}}if(t.action!==`write`)throw new s(`INVALID_ARGS`,`system.clipboard action must be read or write`);if(!e.backend.setClipboard)throw new s(`UNSUPPORTED_OPERATION`,`system.clipboard write is not supported by this backend`);if(typeof t.text!=`string`)throw new s(`INVALID_ARGS`,`system.clipboard write requires text`);let n=v(await e.backend.setClipboard(b(e,t),t.text));return{kind:`clipboardUpdated`,action:`write`,textLength:Array.from(t.text).length,...n?{backendResult:n}:{},...x(`Clipboard updated`)}},co=async(e,t={})=>{if(!e.backend.openSettings)throw new s(`UNSUPPORTED_OPERATION`,`system.settings is not supported by this backend`);let n=K(t.target,`target`),r=v(await e.backend.openSettings(b(e,t),n));return{kind:`settingsOpened`,...n?{target:n}:{},...r?{backendResult:r}:{},...x(n?`Opened settings: ${n}`:`Opened settings`)}},lo=async(e,t={})=>{if(!e.backend.handleAlert)throw new s(`UNSUPPORTED_OPERATION`,`system.alert is not supported by this backend`);let n=t.action??`get`;if(n!==`get`&&n!==`accept`&&n!==`dismiss`&&n!==`wait`)throw new s(`INVALID_ARGS`,`system.alert action must be get, accept, dismiss, or wait`);let r=t.timeoutMs===void 0?void 0:S(t.timeoutMs,`timeoutMs`,0,12e4);return po(n,await e.backend.handleAlert(b(e,t),n,{timeoutMs:r}))},uo=async(e,t={})=>{if(!e.backend.openAppSwitcher)throw new s(`UNSUPPORTED_OPERATION`,`system.appSwitcher is not supported by this backend`);let n=v(await e.backend.openAppSwitcher(b(e,t)));return{kind:`appSwitcherOpened`,...n?{backendResult:n}:{},...x(`Opened app switcher`)}};function fo(e){switch(e){case`portrait`:case`portrait-upside-down`:case`landscape-left`:case`landscape-right`:return e;default:throw new s(`INVALID_ARGS`,`system.orientation must be portrait, portrait-upside-down, landscape-left, or landscape-right`)}}function po(e,t){return e===`get`?_o(t):e===`wait`?vo(t):yo(e,t)}function mo(e,t){return{kind:`keyboardEnterPressed`,action:`enter`,state:e,...t?{backendResult:t}:{},...x(`Keyboard enter pressed`)}}function ho(e,t,n){return{kind:`keyboardDismissed`,action:e,state:t,...n?{backendResult:n}:{},...x(t.dismissed===!1?`Keyboard already hidden`:`Keyboard dismissed`)}}function go(e,t,n){return{kind:`keyboardState`,action:e,state:t,...n?{backendResult:n}:{}}}function _o(e){if(e.kind!==`alertStatus`)throw new s(`COMMAND_FAILED`,`system.alert get returned an invalid backend result`);return{kind:`alertStatus`,action:`get`,alert:e.alert}}function vo(e){if(e.kind!==`alertWait`)throw new s(`COMMAND_FAILED`,`system.alert wait returned an invalid backend result`);return{kind:`alertWait`,action:`wait`,alert:e.alert,...e.waitedMs===void 0?{}:{waitedMs:e.waitedMs},...e.timedOut===void 0?{}:{timedOut:e.timedOut},...x(e.alert?`Alert visible`:`Alert wait timed out`)}}function yo(e,t){if(t.kind!==`alertHandled`)throw new s(`COMMAND_FAILED`,`system.alert ${e} returned an invalid backend result`);return{kind:`alertHandled`,action:e,handled:t.handled,...t.alert?{alert:t.alert}:{},...t.button?{button:t.button}:{},...x(t.handled?`Alert ${e}ed`:`No alert handled`)}}function bo(e){return!!(e&&typeof e==`object`)}const xo={back:no,home:ro,orientation:ao,keyboard:oo,clipboard:so,settings:co,alert:lo,appSwitcher:uo,tvRemote:io};function So(e){return{capture:y(Gr,e),selectors:Fi(e),interactions:Ii(e),system:y(xo,e),apps:ha(e),admin:y(ma,e),recording:y(to,e),observability:y(Wa,e)}}var Co=r({createAgentDevice:()=>wo,createMemorySessionStore:()=>To,localCommandPolicy:()=>Do,restrictedCommandPolicy:()=>Oo});function wo(e){let t={backend:e.backend,artifacts:e.artifacts,sessions:e.sessions??To(),policy:e.policy??Oo(),diagnostics:e.diagnostics,clock:e.clock,signal:e.signal};return{...t,...So(t)}}function To(e=[]){let t=new Map(e.map(e=>[e.name,$(e)]));return{get:e=>$(t.get(e)),set:e=>{t.set(e.name,$(e))},delete:e=>{t.delete(e)},list:()=>Array.from(t.values(),e=>$(e))}}function $(e){if(e)return{...e,...e.snapshot?{snapshot:structuredClone(e.snapshot)}:{},...e.metadata?{metadata:Eo(e.metadata)}:{}}}function Eo(e){try{return structuredClone(e)}catch{return{...e}}}function Do(e={}){return{allowLocalInputPaths:!0,allowLocalOutputPaths:!0,maxImagePixels:2e7,...e}}function Oo(e={}){return{allowLocalInputPaths:!1,allowLocalOutputPaths:!1,maxImagePixels:2e7,...e}}export{_r as a,M as c,Yt as d,mt as f,jt as g,Ot as h,Sr as i,cn as l,gt as m,Do as n,un as o,ht as p,Co as r,j as s,wo as t,ln as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{u as t}from"./sdk-batch-runner.js";function n(e){let t=a(e.quality);return{...e.analysis?{analysis:e.analysis}:{},...e.androidSnapshot?{androidSnapshot:e.androidSnapshot}:{},...e.freshness?{freshness:e.freshness}:{},...t?{quality:t}:{},...e.warnings?{warnings:e.warnings}:{}}}function r(e){return{...e.androidSnapshot?{androidSnapshot:e.androidSnapshot}:{},...e.quality?{snapshotQuality:e.quality}:{},...e.warnings&&e.warnings.length>0?{warnings:e.warnings}:{}}}function i(e){let t=o(e.androidSnapshot),n=Array.isArray(e.warnings)?e.warnings.filter(e=>typeof e==`string`):void 0,i=a(e.snapshotQuality);return r({...t?{androidSnapshot:t}:{},...i?{quality:i}:{},...n?{warnings:n}:{}})}function a(e){if(!e||typeof e!=`object`)return;let t=e;return typeof t.state==`string`&&typeof t.backend==`string`?t:void 0}function o(e){return typeof e==`object`&&e?e:void 0}function s(t,n={message:e=>`Invalid value: ${e}`}){let r=new Set(t),i=n.normalize??(e=>e);return{is:e=>typeof e==`string`&&r.has(e),parse:t=>{let a=i(t??``);if(r.has(a))return a;throw new e(`INVALID_ARGS`,n.message(t??``))}}}const c=1e4,l=2e3,u=[`get`,`accept`,`dismiss`,`wait`],d=[`in-app`,`system`],ee=[`primary`,`secondary`,`middle`];function te(e){return e?.clickButton??`primary`}function ne(t){return t.button===`primary`?null:t.commandLabel===`click`?t.platform!==`macos`&&t.platform!==`linux`?new e(`UNSUPPORTED_OPERATION`,`click --button ${t.button} is supported only on macOS and Linux`):t.platform===`macos`&&t.button===`middle`?new e(`UNSUPPORTED_OPERATION`,`click --button middle is not supported by the macOS runner yet`):typeof t.count==`number`||typeof t.intervalMs==`number`||typeof t.holdMs==`number`||typeof t.jitterPx==`number`||t.doubleTap===!0?new e(`INVALID_ARGS`,`click --button ${t.button} does not support repeat or gesture modifier flags`):null:new e(`INVALID_ARGS`,`--button is supported only for click`)}function re(e){return e===`primary`?{}:{button:e}}const ie=[`up`,`down`,`left`,`right`,`top`,`bottom`],f=[`up`,`down`,`left`,`right`],p=[`left`,`right`,`left-edge`,`right-edge`],ae=[`one-way`,`ping-pong`],oe=1e4,se=6e4,ce=s(f,{message:e=>`Unknown direction: ${e}`});function le(e){let t=e.direction,n=t===`up`||t===`down`?e.referenceHeight:e.referenceWidth,r=ve(e.amount),i=e.pixels===void 0?Math.round(n*r):_(e.pixels),a=Math.max(1,Math.round(n*.05)),o=Math.max(1,n-a*2),s=Math.max(1,Math.min(i,o)),c=Math.round(s/2),l=Math.round(e.referenceWidth/2),u=Math.round(e.referenceHeight/2),d=(n,r,i,a)=>({direction:t,x1:n,y1:r,x2:i,y2:a,referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:s});switch(t){case`up`:return d(l,u-c,l,u+c);case`down`:return d(l,u+c,l,u-c);case`left`:return d(l-c,u,l+c,u);case`right`:return d(l+c,u,l-c,u)}}function ue(e){ve(e.amount),e.pixels!==void 0&&_(e.pixels)}function de(e,t){if(e===`left`||e===`right`){let n=m(e,t);return{preset:e,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,referenceWidth:n.referenceWidth,referenceHeight:n.referenceHeight}}let[n,r]=e===`left-edge`?[99,15]:[1,85],i=g(h(t,n,50),t,8),a=g(h(t,r,50),t,8);return{preset:e,x1:i.x,y1:i.y,x2:a.x,y2:a.y,referenceWidth:t.referenceWidth,referenceHeight:t.referenceHeight}}function fe(e,t){switch(e){case`up`:return{x:0,y:-t};case`down`:return{x:0,y:t};case`left`:return{x:-t,y:0};case`right`:return{x:t,y:0}}}function m(e,t){let n=e===`left`||e===`up`,r=n?85:15,i=n?15:85,a=e===`up`||e===`down`,o=g(h(t,a?50:r,a?r:50),t,8),s=g(h(t,a?50:i,a?i:50),t,8);return{direction:e,x1:o.x,y1:o.y,x2:s.x,y2:s.y,referenceWidth:t.referenceWidth,referenceHeight:t.referenceHeight}}function pe(e){let t=he(e);if(t)return{referenceWidth:t.width,referenceHeight:t.height}}function h(e,t,n){let r=Math.trunc(e.referenceWidth*t/100),i=Math.trunc(e.referenceHeight*n/100);return{x:Number.isFinite(r)?r:0,y:Number.isFinite(i)?i:0}}function g(e,t,n){return{x:v(e.x,n,t.referenceWidth),y:v(e.y,n,t.referenceHeight)}}function me(e){return ce.parse(e)}function he(e){let t=e.filter(e=>ge(e.type)&&_e(e.rect)).map(e=>e.rect).sort((e,t)=>(t?.width??0)*(t?.height??0)-(e?.width??0)*(e?.height??0))[0];if(t)return t;let n=e.map(e=>e.rect).filter(_e);if(n.length===0)return;let r=Math.max(...n.map(e=>e.x+e.width)),i=Math.max(...n.map(e=>e.y+e.height));if(!(r<=0||i<=0))return{x:0,y:0,width:r,height:i}}function ge(e){if(!e)return!1;let t=e.toLowerCase();return t.includes(`application`)||t.includes(`window`)}function _e(e){return!!e&&e.width>0&&e.height>0}function ve(t){if(t===void 0)return .6;if(!Number.isFinite(t)||t<=0)throw new e(`INVALID_ARGS`,`scroll amount must be a positive number`);return t}function _(t){if(!Number.isFinite(t)||t<=0)throw new e(`INVALID_ARGS`,`scroll pixels must be a positive integer`);return Math.max(1,Math.round(t))}function v(e,t,n){let r=Math.round(t);if(!Number.isFinite(r))return 0;let i=Math.max(r,Math.round(n-t));return!Number.isFinite(i)||!Number.isFinite(e)?r:Math.min(i,Math.max(r,Math.round(e)))}const y=1e4,b=[`pan`,`fling`,`swipe`,`pinch`,`rotate`,`transform`];function x(n){let r=C(n),i=D(r,`kind`,b);if(i===`pan`)return{kind:i,origin:w(r,`origin`),delta:w(r,`delta`),pointerCount:t(r,`pointerCount`,{min:1,max:2}),durationMs:S(r)};if(r.pointerCount!==void 0)throw new e(`INVALID_ARGS`,`pointerCount is supported only for gesture pan`);if(i===`fling`){if(r.durationMs!==void 0)throw new e(`INVALID_ARGS`,`gesture fling does not accept durationMs; use gesture pan for timed movement`);return{kind:i,direction:D(r,`direction`,f),origin:w(r,`origin`),distance:t(r,`distance`,{min:0})}}if(i===`swipe`){if(r.durationMs!==void 0)throw new e(`INVALID_ARGS`,`gesture swipe does not accept durationMs; use gesture pan for timed movement`);return{kind:i,preset:D(r,`preset`,p)}}if(i===`pinch`)return{kind:i,scale:E(r,`scale`),origin:T(r,`origin`)};if(i===`rotate`){if(r.velocity!==void 0)throw new e(`INVALID_ARGS`,`gesture rotate does not accept velocity; rotation pacing derives from degrees`);return{kind:i,degrees:E(r,`degrees`),origin:T(r,`origin`)}}return{kind:i,origin:w(r,`origin`),delta:w(r,`delta`),scale:E(r,`scale`),degrees:E(r,`degrees`),durationMs:S(r)}}function S(n){let r=t(n,`durationMs`);if(r!==void 0){if(r<16||r>1e4)throw new e(`INVALID_ARGS`,`Expected durationMs to be an integer between 16 and ${y}.`);return r}}function C(t){if(!t||typeof t!=`object`||Array.isArray(t))throw new e(`INVALID_ARGS`,`gesture requires structured object input`);return t}function w(e,t){let n=C(e[t]);return{x:E(n,`x`),y:E(n,`y`)}}function T(e,t){return e[t]===void 0?void 0:w(e,t)}function E(t,n){let r=t[n];if(typeof r!=`number`||!Number.isFinite(r))throw new e(`INVALID_ARGS`,`Expected ${n} to be a finite number.`);return r}function D(t,n,r){let i=t[n];if(typeof i!=`string`||!r.includes(i))throw new e(`INVALID_ARGS`,`Expected ${n} to be one of: ${r.join(`, `)}.`);return i}const O={swipe:{max:4,usage:`swipe accepts 4 arguments: x1 y1 x2 y2`,retired:{positional:`durationMs`,migrate:ye}},"gesture pan":{max:5,usage:`gesture pan accepts at most 5 arguments: x y dx dy [durationMs]`},"gesture fling":{max:4,usage:`gesture fling accepts at most 4 arguments: direction x y [distance]`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture swipe":{max:1,usage:`gesture swipe accepts 1 argument: preset`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture pinch":{max:3,usage:`gesture pinch accepts at most 3 arguments: scale [x] [y]`},"gesture rotate":{max:3,usage:`gesture rotate accepts at most 3 arguments: degrees [x] [y]`,retired:{positional:`velocity`,migrate:(e,t)=>`use "${t}"; rotation pacing derives from degrees.`}},"gesture transform":{max:7,usage:`gesture transform accepts at most 7 arguments: x y dx dy scale degrees [durationMs]`}};function ye(e,t){let[n,r,i,a,o]=e,s=k(n,i),c=k(r,a);return s===void 0||c===void 0?`use "gesture pan x1 y1 dx dy durationMs" for the same timed drag, or "${t}" for a default-duration swipe.`:`use "gesture pan ${n} ${r} ${s} ${c} ${o}" for the same timed drag, or "${t}" for a default-duration swipe.`}function k(e,t){let n=Number(t)-Number(e);return Number.isFinite(n)?n:void 0}function A(e,t){let n=O[e];if(t.length<=n.max)return;let r=n.retired;if(!r||t.length!==n.max+1||!be(t[n.max]))return{usage:n.usage};let i=`${e} ${t.slice(0,n.max).join(` `)}`;return{usage:n.usage,migration:`The trailing ${r.positional} positional was removed: ${r.migrate(t,i)}`}}function be(e){return e===void 0||e.trim().length===0?!1:e.startsWith("${")||Number.isFinite(Number(e))}function xe(t){if(!(!t||typeof t!=`object`||Array.isArray(t))&&t.durationMs!==void 0)throw new e(`INVALID_ARGS`,`swipe does not accept durationMs; use gesture pan for timed movement`)}function j(e,t){let n=t?`${e.usage} (${t})`:e.usage;return e.migration?`${n}. ${e.migration}`:`${n}.`}function M(t,n){let r=A(t,n);if(r)throw new e(`INVALID_ARGS`,j(r))}function Se(e,t,n){let r=Ce(e,t);return r?j(r,n):void 0}function Ce(e,t){if(e===`swipe`)return A(`swipe`,t);if(e!==`gesture`)return;let n=`gesture ${t[0]}`;if(Object.hasOwn(O,n))return A(n,t.slice(1))}function N(e){return{origin:{x:Number(e[0]),y:Number(e[1])},delta:{x:Number(e[2]),y:Number(e[3])}}}function we(e,t){let n=e[0],r=e.slice(1);switch(n){case`pan`:{M(`gesture pan`,r);let{origin:e,delta:i}=N(r);return x({kind:n,origin:e,delta:i,pointerCount:t,durationMs:P(r[4])})}case`fling`:return M(`gesture fling`,r),x({kind:n,direction:r[0],origin:{x:Number(r[1]),y:Number(r[2])},distance:P(r[3])});case`swipe`:return M(`gesture swipe`,r),x({kind:n,preset:r[0]});case`pinch`:return M(`gesture pinch`,r),x({kind:n,scale:Number(r[0]),origin:F(r[1],r[2])});case`rotate`:return M(`gesture rotate`,r),x({kind:n,degrees:Number(r[0]),origin:F(r[1],r[2])});case`transform`:{M(`gesture transform`,r);let{origin:e,delta:t}=N(r);return x({kind:n,origin:e,delta:t,scale:Number(r[4]),degrees:Number(r[5]),durationMs:P(r[6])})}default:return x({kind:n})}}function Te(e){switch(e.kind){case`pan`:return I([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.durationMs]);case`fling`:return I([e.kind,e.direction,e.origin.x,e.origin.y,e.distance]);case`swipe`:return[e.kind,e.preset];case`pinch`:return I([e.kind,e.scale,e.origin?.x,e.origin?.y]);case`rotate`:return e.origin?I([e.kind,e.degrees,e.origin.x,e.origin.y]):[e.kind,String(e.degrees)];case`transform`:return I([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.scale,e.degrees,e.durationMs])}}function Ee(e,t={}){return M(`swipe`,e),{from:{x:Number(e[0]),y:Number(e[1])},to:{x:Number(e[2]),y:Number(e[3])},...t.count===void 0?{}:{count:t.count},...t.pauseMs===void 0?{}:{pauseMs:t.pauseMs},...t.pattern===void 0?{}:{pattern:t.pattern}}}function De(e){switch(e.kind){case`pan`:return{gesture:{intent:`pan`,origin:e.origin,delta:e.delta,pointerCount:e.pointerCount,durationMs:e.durationMs}};case`fling`:return{gesture:{intent:`fling`,direction:e.direction,origin:e.origin,distance:e.distance}};case`swipe`:return{gesture:{intent:`fling`,preset:e.preset}};case`pinch`:return{gesture:{intent:`pinch`,origin:e.origin,scale:e.scale}};case`rotate`:return{gesture:{intent:`rotate`,origin:e.origin,degrees:e.degrees}};case`transform`:return{gesture:{intent:`transform`,origin:e.origin,delta:e.delta,scale:e.scale,degrees:e.degrees,durationMs:e.durationMs}}}}function Oe(e){return{gesture:{intent:`fling`,from:e.from,to:e.to}}}function P(e){return e===void 0?void 0:Number(e)}function F(t,n){if(t===void 0!=(n===void 0))throw new e(`INVALID_ARGS`,`gesture origin requires both x and y coordinates`);return t===void 0?void 0:{x:Number(t),y:Number(n)}}function I(e){return e.filter(e=>e!==void 0).map(String)}const L={pinchAxisDegrees:-90,frameCount:Math.floor},ke={ios:L,macos:L,android:{pinchAxisDegrees:0,frameCount:Math.round},vega:L,linux:L,web:L};function Ae(e,t,n){let r=Le(t),i=Ue(n);switch(e.intent){case`fling`:return Me(e,r,i);case`pan`:return Ne(e,r,i);case`pinch`:return z({intent:`pinch`,origin:e.origin??Be(r),delta:{x:0,y:0},scale:Re(e.scale,`gesture pinch scale`),rotationDegrees:0,durationMs:300},r,i);case`rotate`:{let t=K(e.degrees,`gesture rotate degrees`);return z({intent:`rotate`,origin:e.origin??Be(r),delta:{x:0,y:0},scale:1,rotationDegrees:t,durationMs:W(t)},r,i)}case`transform`:{let t=K(e.degrees,`gesture transform degrees`);return z({intent:`transform`,origin:e.origin,delta:e.delta,scale:Re(e.scale,`gesture transform scale`),rotationDegrees:t,durationMs:U(e.durationMs,W(t),`gesture transform durationMs`)},r,i)}}}function je(t){let n=t.pointers[0].samples[0]?.point,r=t.pointers[0].samples.at(-1)?.point;if(!n||!r)throw new e(`INVALID_ARGS`,`single-pointer gesture plan requires samples`);return{start:n,end:r}}function Me(e,t,n){if(`preset`in e){let{from:r,to:i}=He(e.preset,t);return R(`fling`,r,i,100,t,`endpoint-hold`,n)}if(`from`in e)return R(`fling`,e.from,e.to,100,t,`endpoint-hold`,n);let r=G(e.origin,`gesture fling origin`),i=ze(e.distance??180,`gesture fling distance`);return R(`fling`,r,q(r,fe(e.direction,i)),100,t,`endpoint-hold`,n)}function Ne(t,n,r){let i=U(t.durationMs,500,`gesture pan durationMs`);if((t.pointerCount??1)===1){let e=G(t.origin,`gesture pan origin`);return R(`pan`,e,q(e,G(t.delta,`gesture pan delta`)),i,n,t.executionProfile??`timed-pan`,r)}if(t.pointerCount!==2)throw new e(`INVALID_ARGS`,`gesture pan pointerCount must be 1 or 2`);return z({intent:`pan`,origin:t.origin,delta:t.delta,scale:1,rotationDegrees:0,durationMs:i},n,r)}function R(e,t,n,r,i,a,o){let s=G(t,`gesture ${e} start`),c=G(n,`gesture ${e} end`),l=B(r,o).map(e=>({offsetMs:e,point:Ve(s,c,e/r)}));return V(l,i,{intent:e,pointerId:0}),{topology:`single`,intent:e,executionProfile:a,durationMs:r,viewport:i,pointers:[{pointerId:0,samples:l}]}}function z(e,t,n){let r=G(e.origin,`gesture ${e.intent} origin`),i=q(r,G(e.delta,`gesture ${e.intent} delta`)),a=Math.min(t.width,t.height)*Ie(e.intent),o=e.scale>1?a/e.scale:a,s=o*e.scale;if(Math.min(o,s)<48)throw H({intent:e.intent,viewport:t,initialSpan:o,finalSpan:s,minimumReliableSpan:48});let c=o/2,l=B(e.durationMs,n),u=(a,o)=>{let s=l.map(t=>({offsetMs:t,point:Pe({...e,start:r,end:i,initialRadius:c,offsetMs:t,side:o,profile:n})}));return V(s,t,{intent:e.intent,pointerId:a}),{pointerId:a,samples:s}};return{topology:`two`,intent:e.intent,durationMs:e.durationMs,viewport:t,pointers:[u(0,1),u(1,-1)]}}function Pe(e){let t=e.offsetMs/e.durationMs,n=Ve(e.start,e.end,t),r=e.initialRadius*(1+(e.scale-1)*t),i=We(Fe(e.intent,e.profile)+e.rotationDegrees*t);return{x:n.x+Math.cos(i)*r*e.side,y:n.y+Math.sin(i)*r*e.side}}function Fe(e,t){return e===`pinch`?t.pinchAxisDegrees:-90}function Ie(e){return e===`pinch`?.4:.25}function B(e,t){let n=e/16,r=Math.max(3,t.frameCount(n));return Array.from({length:r+1},(t,n)=>Math.round(e*n/r))}function V(t,n,r){let i=n.x+n.width-1,a=n.y+n.height-1;for(let o of t){let{x:t,y:s}=o.point;if(!Number.isFinite(t)||!Number.isFinite(s))throw new e(`INVALID_ARGS`,`Gesture motion produces non-finite pointer coordinates`,{...r,reason:`GESTURE_TRAJECTORY_NON_FINITE`,hint:`Reduce the requested rotation, translation, or scale.`});if(t<n.x+1||t>i||s<n.y+1||s>a)throw H({...r,viewport:n,sample:o})}}function H(t){return new e(`INVALID_ARGS`,`Gesture trajectory does not fit inside the viewport`,{...t,reason:`GESTURE_TRAJECTORY_OUT_OF_BOUNDS`,hint:`Move the gesture away from the edge or reduce its translation, scale, or rotation.`})}function Le(t){let n={x:K(t.x,`gesture viewport x`),y:K(t.y,`gesture viewport y`),width:K(t.width,`gesture viewport width`),height:K(t.height,`gesture viewport height`)};if(n.width<=0||n.height<=0)throw new e(`INVALID_ARGS`,`gesture viewport width and height must be positive`);return n}function U(t,n,r){let i=t??n;if(!Number.isInteger(i)||i<16||i>1e4)throw new e(`INVALID_ARGS`,`${r} must be an integer between 16 and ${y}`);return i}function W(e){let t=Math.ceil(Math.abs(e)/3)*16;return Math.min(Math.max(300,t),2400)}function G(e,t){return{x:K(e.x,`${t} x`),y:K(e.y,`${t} y`)}}function K(t,n){if(!Number.isFinite(t))throw new e(`INVALID_ARGS`,`${n} must be a finite number`);return t}function Re(t,n){let r=K(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be greater than 0`);return r}function ze(t,n){let r=K(t,n);if(r<=0)throw new e(`INVALID_ARGS`,`${n} must be a positive number`);return r}function Be(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function q(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Ve(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function He(e,t){let n=de(e,{referenceWidth:t.width,referenceHeight:t.height});return{from:{x:t.x+n.x1,y:t.y+n.y1},to:{x:t.x+n.x2,y:t.y+n.y2}}}function Ue(e){return e===void 0?L:ke[e]}function We(e){return e*Math.PI/180}const Ge={occlusion:{kind:`runtime`,via:`src/snapshot/snapshot-occlusion.ts#isSnapshotNodeInteractionBlocked`},offscreen:{kind:`runtime`,via:`src/commands/interaction/runtime/resolution.ts#throwIfOffscreenInteractionTarget`},nonHittable:{kind:`runtime`,via:`src/core/interaction-targeting.ts#resolveActionableTouchResolution`},responseConstruction:{kind:`runtime`,via:`src/daemon/handlers/interaction-touch-response.ts#buildInteractionResponseData`},responseIdentity:{kind:`runtime`,via:`src/daemon/handlers/interaction-touch-targets.ts#interactionResultExtra`},verifyEvidence:{kind:`runtime`,via:`src/commands/interaction/runtime/interactions.ts#pressCommand`,appliesTo:[`press`,`click`,`fill`]},settleObservation:{kind:`runtime`,via:`src/commands/interaction/runtime/settle.ts#settleAfterInteraction`}};({...Ge}),{...Ge};const Ke=`tapped via non-hittable coordinate fallback`,qe=1e4;function Je(t,n=`scroll accepts either a relative amount or --pixels, not both`){if(t.amount!==void 0&&t.pixels!==void 0)throw new e(`INVALID_ARGS`,n)}function Ye(t,n={}){if(t===void 0)return;let r=n.field??`scroll durationMs`,i=n.max??1e4,a=n.invalidMessage??`${r} must be a non-negative integer`;if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new e(`INVALID_ARGS`,a);if(t>i)throw new e(`INVALID_ARGS`,`${r} must be a non-negative integer at most ${i}`);return t}function Xe(e){return typeof e?.durationMs==`number`?e.durationMs:void 0}const Ze={android:`longpress`,apple:`exact`,vega:`exact`},J={up:{aliases:[],androidKeyevent:`KEYCODE_DPAD_UP`,appleRemoteButton:`up`,vegaKey:`KEY_UP`},down:{aliases:[],androidKeyevent:`KEYCODE_DPAD_DOWN`,appleRemoteButton:`down`,vegaKey:`KEY_DOWN`},left:{aliases:[],androidKeyevent:`KEYCODE_DPAD_LEFT`,appleRemoteButton:`left`,vegaKey:`KEY_LEFT`},right:{aliases:[],androidKeyevent:`KEYCODE_DPAD_RIGHT`,appleRemoteButton:`right`,vegaKey:`KEY_RIGHT`},select:{aliases:[`ok`,`center`,`enter`],androidKeyevent:`KEYCODE_DPAD_CENTER`,appleRemoteButton:`select`,vegaKey:`KEY_ENTER`},menu:{aliases:[],androidKeyevent:`KEYCODE_MENU`,appleRemoteButton:`menu`,vegaKey:`KEY_MENU`},home:{aliases:[],androidKeyevent:`KEYCODE_HOME`,appleRemoteButton:`home`,vegaKey:`KEY_HOMEPAGE`},back:{aliases:[],androidKeyevent:`KEYCODE_BACK`,appleRemoteButton:`menu`,vegaKey:`KEY_BACK`}},Y=Object.keys(J),Qe=`<${Y.join(`|`)}>`;function $e(t){let n=t?.toLowerCase();if(et(n))return n;let r=n?at.get(n):void 0;if(r)return r;throw new e(`INVALID_ARGS`,`tv-remote button must be one of: ${Y.join(`, `)}.`)}function et(e){return typeof e==`string`&&Y.includes(e)}function tt(e){return J[e].appleRemoteButton}function nt(e){return J[e].androidKeyevent}function rt(e){return J[e].vegaKey}function it(e){return Ze[e]}const at=new Map(Y.flatMap(e=>J[e].aliases.map(t=>[t,e]))),ot=[`camera`,`microphone`,`photos`,`contacts`,`contacts-limited`,`notifications`,`calendar`,`location`,`location-always`,`media-library`,`motion`,`reminders`,`siri`],st=`<wifi|airplane|location> <on|off>`,X=`location set <lat> <lon>`,ct=`animations <on|off>`,Z=`appearance <light|dark|toggle>`,lt=`faceid <match|nonmatch|enroll|unenroll>`,ut=`touchid <match|nonmatch|enroll|unenroll>`,dt=`fingerprint <match|nonmatch>`,ft=`clear-app-state [app-id]`,pt=`permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]`,Q=`permission <grant|reset> <accessibility|screen-recording|input-monitoring>`,mt=`macOS supports only settings ${Z} and settings ${Q}. wifi|airplane|location|animations remain unsupported on macOS.`,ht=[`settings ${st}`,`settings ${X}`,`settings ${ct}`,`settings ${Z}`,`settings ${lt}`,`settings ${ut}`,`settings ${dt}`,`settings ${ft}`,`settings ${pt}`,`settings ${Q}`].join(` | `),gt=`settings requires ${st}, ${X}, ${ct}, ${Z}, ${lt}, ${ut}, ${dt}, ${ft}, ${pt}, or ${Q}`;function _t(e){let t=e.trim().toLowerCase();return t===`appearance`||t===`permission`}function vt(e){return`Unsupported macOS setting: ${e}. ${mt}`}function yt(t){let n=t.trim().toLowerCase();if(n===`grant`)return`grant`;if(n===`deny`)return`deny`;if(n===`reset`)return`reset`;throw new e(`INVALID_ARGS`,`Invalid permission action: ${t}. Use grant|deny|reset.`)}function bt(t){let n=t?.trim().toLowerCase();if(n===`camera`||n===`microphone`||n===`photos`||n===`contacts`||n===`contacts-limited`||n===`notifications`||n===`calendar`||n===`location`||n===`location-always`||n===`media-library`||n===`motion`||n===`reminders`||n===`siri`)return n;throw new e(`INVALID_ARGS`,`permission setting requires a target: ${ot.join(`|`)}`)}function xt(t,n){if(t===void 0||t.trim()===``)throw new e(`INVALID_ARGS`,`settings location set requires ${n}`);return $(Number(t),n)}function St(e){return{latitude:$(e?.latitude,`latitude`),longitude:$(e?.longitude,`longitude`)}}function $(t,n){let r=n===`latitude`?-90:-180,i=n===`latitude`?90:180;if(typeof t!=`number`||!Number.isFinite(t)||t<r||t>i)throw new e(`INVALID_ARGS`,`${n} must be a number from ${r} to ${i}`);return t}function Ct(e){return e}function wt(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width),a=Math.min(e.y+e.height,t.y+t.height);return i<=n||a<=r?0:(i-n)*(a-r)}export{s as $,Oe as A,ue as B,Ae as C,we as D,Se as E,ie as F,ee as G,le as H,ae as I,te as J,re as K,oe as L,b as M,x as N,Te as O,f as P,c as Q,p as R,Ke as S,xe as T,pe as U,m as V,me as W,u as X,d as Y,l as Z,it as _,gt as a,Xe as b,_t as c,Y as d,r as et,Qe as f,rt as g,tt as h,St as i,Ee as j,De as k,yt as l,nt as m,Ct as n,n as nt,ht as o,$e as p,ne as q,xt as r,vt as s,wt as t,i as tt,bt as u,qe as v,je as w,Ye as x,Je as y,se as z};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{E as e,_ as t,h as n}from"./sdk-contracts.js";import{Ft as r,Ht as i,Lt as a,Sn as o,Ut as s,Vt as c,in as l,vn as u,xn as ee}from"./viewport-dimension.js";import{E as te,G as ne,I as re,Y as d,d as ie}from"./screenshot-geometry.js";import{J as ae,O as oe,S as se,W as f,Y as ce,at as p,q as m}from"./sdk-batch-runner.js";import{h as le,n as ue,r as de,t as fe}from"./sdk-device.js";import{f as pe,p as me}from"./sdk-selectors.js";import{t as he}from"./device.js";import{N as h,j as g}from"./sdk-android-adb.js";import{n as ge,t as _e}from"./version.js";import{n as ve,t as ye}from"./path-resolution.js";import{a as be,n as xe,o as Se,u as Ce}from"./host-process.js";import _ from"node:path";import we from"node:crypto";import v from"node:fs";import{StringDecoder as Te}from"node:string_decoder";const y=1500;function Ee(e,t){e&&(e.snapshotDiagnostics??={samples:[]}).samples.push({...t,durationMs:Math.max(0,Math.round(t.durationMs))})}function De(e){let t=e?.snapshotDiagnostics?.samples;if(!(!t||t.length===0))return Oe(t)}function Oe(e){if(e.length===0)return;let t=je(e);return{stats:t,...t.p95Ms>=y?{warning:Fe(t)}:{}}}function ke(e){let t=e.flatMap(e=>Be(e?.stats));if(t.length===0)return;let n=je(t);return{stats:n,...n.p95Ms>=y?{warning:Fe(n)}:{}}}function Ae(e){if(!p(e))return;let t=Ie(e.stats);if(!t)return;let n=typeof e.warning==`string`?e.warning:void 0;return{stats:t,...n?{warning:n}:{}}}function je(e){let t=e.map(e=>e.durationMs).sort((e,t)=>e-t);return{count:t.length,p50Ms:Me(t,50),p95Ms:Me(t,95),maxMs:t[t.length-1]??0,slowThresholdMs:y,...Ne(e),...Pe(e)}}function Me(e,t){if(e.length===0)return 0;let n=Math.max(0,Math.ceil(t/100*e.length)-1);return e[Math.min(n,e.length-1)]??0}function Ne(e){let t=e.map(e=>e.platform).filter(e=>!!e);return new Set(t).size===1?{platform:t[0]}:{}}function Pe(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}:{}}function Fe(e){return`Warning: ${e.platform?`${e.platform} `:``}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 Ie(e){if(!p(e))return;let t=Le(e);if(t)return{...t,...ze(e)}}function Le(e){let t={count:e.count,p50Ms:e.p50Ms,p95Ms:e.p95Ms,maxMs:e.maxMs,slowThresholdMs:e.slowThresholdMs};if(!Object.values(t).some(e=>typeof e!=`number`))return t}function Re(e){let t=Object.entries(e).filter(e=>typeof e[1]==`number`);return t.length>0?Object.fromEntries(t):void 0}function ze(e){let t=typeof e.platform==`string`?e.platform:void 0,n=p(e.backends)?Re(e.backends):void 0;return{...t?{platform:t}:{},...n?{backends:n}:{}}}function Be(e){if(!e||e.count<=0)return[];let t=e.platform;return e.count===1?[{durationMs:e.maxMs,platform:t}]:e.count===2?[{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}]}function b(e){return e.startsWith(`@`)?n(e)?.base??e:e}const x=/^-?\d+(\.\d+)?$/,Ve=/^[^\s"\\]+$/,He=new Map([[`--count`,`count`],[`--interval-ms`,`intervalMs`],[`--hold-ms`,`holdMs`],[`--jitter-px`,`jitterPx`]]),Ue=new Map([[`--count`,`count`],[`--pause-ms`,`pauseMs`]]),We=new Map([[`--pointer-count`,`pointerCount`]]),Ge=new Map([[`--delay-ms`,`delayMs`]]);function S(e){return e===`click`||e===`press`}function Ke(e){return S(e)||e===`longpress`}function qe(e){return e===`type`||e===`fill`}function C(e){return Ye(e,Xe)}function Je(e){return JSON.stringify(e)}function w(e){return Ye(e,Ze)}function Ye(e,t){return t(e)?e:Je(e)}function Xe(e){return Ze(e)&&e.startsWith(`@`)||x.test(e)}function Ze(e){return Ve.test(e)}const Qe=new Set([`fill`,`type`]);function $e(e){if(!Qe.has(e.command)){let t=(e.positionals??[]).map(e=>C(e));return[e.command,...t].join(` `)}let t=et(e).map(e=>C(e)).join(` `);return[e.command,t,`<text>`].filter(e=>e.length>0).join(` `)}function et(e){if(e.command===`type`)return[];let t=e.positionals??[],n=t[0];return n===void 0?[]:n.startsWith(`@`)?[n]:t.length>=3&&x.test(n)&&x.test(t[1]??``)?[n,t[1]]:[n]}function T(e,t){let n=t.flags??{};if(S(t.command)){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.intervalMs==`number`&&e.push(`--interval-ms`,String(n.intervalMs)),typeof n.holdMs==`number`&&e.push(`--hold-ms`,String(n.holdMs)),typeof n.jitterPx==`number`&&e.push(`--jitter-px`,String(n.jitterPx)),n.doubleTap===!0&&e.push(`--double-tap`);let t=n.clickButton;t&&t!==`primary`&&e.push(`--button`,t);return}if(t.command===`swipe`){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.pauseMs==`number`&&e.push(`--pause-ms`,String(n.pauseMs)),(n.pattern===`one-way`||n.pattern===`ping-pong`)&&e.push(`--pattern`,n.pattern);return}if(t.command===`gesture`){typeof n.pointerCount==`number`&&e.push(`--pointer-count`,String(n.pointerCount));return}qe(t.command)&&typeof n.delayMs==`number`&&e.push(`--delay-ms`,String(n.delayMs))}function tt(e,t){t&&((t.platform===`ios`||t.platform===`android`)&&e.push(`--platform`,t.platform),typeof t.metroHost==`string`&&t.metroHost.length>0&&e.push(`--metro-host`,w(t.metroHost)),typeof t.metroPort==`number`&&e.push(`--metro-port`,String(t.metroPort)),typeof t.bundleUrl==`string`&&t.bundleUrl.length>0&&e.push(`--bundle-url`,w(t.bundleUrl)),typeof t.launchUrl==`string`&&t.launchUrl.length>0&&e.push(`--launch-url`,w(t.launchUrl)))}function nt(e,t){let[n,...r]=t.positionals??[];n&&e.push(w(n));for(let t of r)e.push(C(t));typeof t.flags?.fps==`number`&&e.push(`--fps`,String(t.flags.fps)),typeof t.flags?.screenshotMaxSize==`number`&&e.push(`--max-size`,String(t.flags.screenshotMaxSize)),(typeof t.flags?.quality==`number`||typeof t.flags?.quality==`string`)&&e.push(`--quality`,String(t.flags.quality)),t.flags?.hideTouches&&e.push(`--hide-touches`)}function rt(e,t){t.flags?.snapshotInteractiveOnly&&e.push(`-i`),typeof t.flags?.snapshotDepth==`number`&&e.push(`-d`,String(t.flags.snapshotDepth)),t.flags?.snapshotScope&&e.push(`-s`,C(t.flags.snapshotScope)),t.flags?.snapshotRaw&&e.push(`--raw`)}function it(e,t){for(let n of t.positionals??[])e.push(C(n));ee(e,t.flags)}function at(e,t,n={}){let r=t.positionals??[],i=n.includeAllPositionals?r:r.slice(0,1);for(let t of i)e.push(w(t));tt(e,t.flags)}function ot(e,t){for(let n of t.positionals??[])e.push(C(t.command===`wait`?b(n):n));T(e,t)}function E(e,t){let n=[],r={},i=S(e)?He:e===`swipe`?Ue:e===`gesture`?We:qe(e)?Ge:void 0;for(let a=0;a<t.length;a+=1){let o=t[a];if(S(e)&&o===`--double-tap`){r.doubleTap=!0;continue}let s=t[a+1];if(S(e)&&o===`--button`&&s!==void 0){let e=s;(e===`primary`||e===`secondary`||e===`middle`)&&(r.clickButton=e),a+=1;continue}let c=i?.get(o);if(c&&s!==void 0){let e=ct(s);if(e!==null){r[c]=e,a+=1;continue}}if(e===`swipe`&&o===`--pattern`&&s!==void 0){let e=s;(e===`one-way`||e===`ping-pong`)&&(r.pattern=e),a+=1;continue}n.push(o)}return{positionals:n,flags:r}}function st(e){let t=[],n={};for(let r=0;r<e.length;r+=1){let i=e[r],a=e[r+1];if(i===`--platform`&&a!==void 0){let e=a;(e===`ios`||e===`android`)&&(n.platform=e),r+=1;continue}if(i===`--metro-host`&&a!==void 0){n.metroHost=a,r+=1;continue}if(i===`--metro-port`&&a!==void 0){let e=ct(a);e!==null&&(n.metroPort=e),r+=1;continue}if(i===`--bundle-url`&&a!==void 0){n.bundleUrl=a,r+=1;continue}if(i===`--launch-url`&&a!==void 0){n.launchUrl=a,r+=1;continue}t.push(i)}return{positionals:t,flags:n}}function ct(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function lt(e){let t;for(let n of e){if(n.command===`runtime`&&typeof n.flags.platform==`string`){t=n.flags.platform;continue}if(n.command===`open`)return n.runtime?.platform??t}return t}function ut(e,t){for(let n of t.positionals??[])e.push(C(n));t.flags?.relaunch&&e.push(`--relaunch`),tt(e,t.runtime)}function dt(e){let t=[],n={};for(let r of e){if(r===`--relaunch`){n.relaunch=!0;continue}t.push(r)}let r=st(t);return{positionals:r.positionals,flags:n,runtime:ft(r.flags)?r.flags:void 0}}function ft(e){return!!(e.platform||e.metroHost||e.metroPort!==void 0||e.bundleUrl||e.launchUrl)}const pt=/^[A-Z_][A-Z0-9_]*$/,mt=new Set(ue.filter(e=>e!==`web`)),ht=new Set([`mobile`,`tv`,`desktop`]);function gt(e){let n=[],r=[],i=e.split(/\r?\n/),a=!1,o,s=(e,n,r)=>{throw new t(`INVALID_ARGS`,`target-v1 annotation on line ${e.line} must be immediately followed by its action line (line ${n+1} ${r}).`)};for(let[e,c]of i.entries()){let i=c.trim();if(i.length===0){o&&s(o,e,`is blank`);continue}if(i.startsWith(`#`)){let t=me(i);if(t.kind===`v1`){o&&s(o,e,`is another target-v1 annotation`),o={evidence:t.evidence,line:e+1};continue}o&&s(o,e,`is a comment`);continue}if(vt(i)){if(o&&s(o,e,`is an env directive`),a)throw new t(`INVALID_ARGS`,`env directives must precede all actions (line ${e+1}).`);continue}let l=St(c);if(!l){o&&s(o,e,`did not parse as an action`);continue}let u=te(l.command,l.positionals??[],`line ${e+1}`);if(u)throw new t(`INVALID_ARGS`,u);o&&=(l.targetEvidence=o.evidence,void 0),n.push(l),r.push(e+1),a=!0}if(o)throw new t(`INVALID_ARGS`,`target-v1 annotation on line ${o.line} must be immediately followed by its action line (end of script reached).`);return{actions:n,actionLines:r}}function _t(e){let t=e.split(/\r?\n/),n={};for(let[e,r]of t.entries()){let t=r.trim();if(t.length===0||t.startsWith(`#`))continue;if(vt(t)){xt(n,t,e+1);continue}if(!t.startsWith(`context `))break;let i=t.match(/(?:^|\s)platform=([^\s]+)/);if(i){let e=i[1];e&&mt.has(e)&&D(n,`platform`,e)}let a=t.match(/(?:^|\s)target=([^\s]+)/);if(a){let e=a[1];e&&ht.has(e)&&D(n,`target`,e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&D(n,`timeoutMs`,Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&D(n,`retries`,Math.floor(e))}}return n}function vt(e){return e===`env`||e.startsWith(`env `)||e.startsWith(`env `)}function yt(e,n){let r=e.slice(3).replace(/^[\s]+/,``),i=r.indexOf(`=`);if(i<=0)throw new t(`INVALID_ARGS`,`Invalid env directive on line ${n}: expected "env KEY=VALUE".`);let a=r.slice(0,i);if(!pt.test(a))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(a.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: the AD_* namespace is reserved for built-in variables. Rename ${a} to avoid the AD_ prefix.`);return{key:a,value:bt(r.slice(i+1),n)}}function bt(e,n){if(e.length===0)return``;if(e.startsWith(`"`))try{let t=JSON.parse(e);if(typeof t!=`string`)throw Error(`not a string literal`);return t}catch{throw new t(`INVALID_ARGS`,`Invalid quoted env value on line ${n}.`)}return e}function xt(e,n,r){let{key:i,value:a}=yt(n,r),o=e.env??{};if(Object.prototype.hasOwnProperty.call(o,i))throw new t(`INVALID_ARGS`,`Duplicate env directive "${i}" on line ${r}.`);o[i]=a,e.env=o}function D(e,n,r){let i=e[n];if(i!==void 0)throw new t(`INVALID_ARGS`,i===r?`Duplicate replay test metadata "${n}" in context header.`:`Conflicting replay test metadata "${n}" in context header: ${String(i)} vs ${String(r)}.`);e[n]=r}function St(e){let t=e.trim();if(t.length===0||t.startsWith(`#`))return null;let[n,...r]=wt(t);if(n===void 0||n===`context`)return null;let i={ts:Date.now(),command:n,positionals:[],flags:{}};if(n===`snapshot`){i.positionals=[];for(let e=0;e<r.length;e+=1){let t=r[e];if(t===`-i`){i.flags.snapshotInteractiveOnly=!0;continue}if(t!==`-c`){if(t===`--raw`){i.flags.snapshotRaw=!0;continue}if(t===`--force-full`){i.flags.snapshotForceFull=!0;continue}if((t===`-d`||t===`--depth`)&&e+1<r.length){let t=Number(r[e+1]);Number.isFinite(t)&&t>=0&&(i.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if((t===`-s`||t===`--scope`)&&e+1<r.length){i.flags.snapshotScope=r[e+1],e+=1;continue}if(t===`--backend`&&e+1<r.length){e+=1;continue}}}return i}if(n===`open`){let e=dt(r);return i.positionals=e.positionals,Object.assign(i.flags,e.flags),i.runtime=e.runtime,i}if(n===`runtime`){let e=st(r);return i.positionals=e.positionals,Object.assign(i.flags,e.flags),i}if(S(n)){let e=E(n,r);Object.assign(i.flags,e.flags);let t=e.positionals[0];if(t===void 0)return i;if(t.startsWith(`@`))return i.positionals=[b(t)],e.positionals[1]&&(i.result={refLabel:e.positionals[1]}),i;let a=e.positionals[0],o=e.positionals[1];return O(a)&&O(o)&&e.positionals.length>=2?(i.positionals=[a,o],i):(i.positionals=[e.positionals.join(` `)],i)}if(n===`fill`){let e=E(n,r);if(Object.assign(i.flags,e.flags),!Ct(e.positionals))return i.positionals=e.positionals,i;let[t,a,...o]=e.positionals;if(O(t)&&O(a))return i.positionals=[t,a,o.join(` `)],i;let[s,c,...l]=e.positionals;if(s.startsWith(`@`)){let e=b(s);return l.length>0?(i.positionals=[e,l.join(` `)],i.result={refLabel:c},i):(i.positionals=[e,c],i)}return i.positionals=[s,[c,...l].join(` `)],i}if(n===`get`){let e=r[0],t=r[1];return e===void 0||t===void 0?(i.positionals=r,i):t.startsWith(`@`)?(i.positionals=[e,b(t)],r[2]&&(i.result={refLabel:r[2]}),i):(i.positionals=[e,r.slice(1).join(` `)],i)}if(n===`swipe`||n===`type`||n===`gesture`){let e=E(n,r);return Object.assign(i.flags,e.flags),i.positionals=e.positionals,i}if(n===`record`){let e=[];for(let t=0;t<r.length;t+=1){let n=r[t];if(n===`--hide-touches`){i.flags.hideTouches=!0;continue}if(n===`--fps`&&t+1<r.length){let e=Number(r[t+1]);Number.isFinite(e)&&(i.flags.fps=Math.floor(e)),t+=1;continue}if(n===`--quality`&&t+1<r.length){let e=r[t+1],n=c(e);n!==void 0&&(i.flags.quality=n),t+=1;continue}if(n===`--max-size`&&t+1<r.length){let e=Number(r[t+1]);Number.isFinite(e)&&(i.flags.screenshotMaxSize=Math.floor(e)),t+=1;continue}e.push(n)}return i.positionals=e,i}if(n===`screenshot`){let e=[];for(let t=0;t<r.length;t+=1){let n=r[t],a=o({args:r,index:t,flags:i.flags});if(a.handled){t=a.nextIndex;continue}e.push(n)}return i.positionals=e,i}return i.positionals=n===`wait`||n===`longpress`?r.map(e=>b(e)):r,i}function Ct(e){return e.length>=2}function O(e){return e?!Number.isNaN(Number(e)):!1}function wt(e){let t=[],n=0;for(;n<e.length&&(n=Tt(e,n),!(n>=e.length));){let r=e[n]===`"`?Et(e,n):Dt(e,n);t.push(r.value),n=r.nextCursor}return t}function Tt(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}function Et(e,n){let r=n+1,i=!1,a=r;for(;a<e.length;a+=1){let t=e.charAt(a);if(t===`"`&&!i)break;if(i){i=!1;continue}i=t===`\\`}if(a>=e.length)throw new t(`INVALID_ARGS`,`Invalid replay script line: ${e}`);let o=e.slice(n,a+1),s;try{s=JSON.parse(o)}catch{throw new t(`INVALID_ARGS`,`Invalid quoted value ${o} in replay script line: ${e}`,{hint:`Quoted replay values are JSON strings: escape backslashes, quotes, tabs, and newlines (\\\\, \\", \\t, \\n).`})}return{value:s,nextCursor:a+1}}function Dt(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}function Ot(e,t={}){let n=[e.command];return e.command===`snapshot`?rt(n,e):e.command===`open`?ut(n,e):e.command===`runtime`?at(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?nt(n,e):e.command===`screenshot`?it(n,e):ot(n,e),n.join(` `)}function kt(e){return e.targetEvidence?[pe(e.targetEvidence)]:[]}const At=`/agent-device`,jt=`x-agent-device-tenant`;function Mt(e){return Nt(e,At)}function Nt(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t.replace(/^\/+/,``),n).toString()}function Pt(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function Ft(e){let t=e?.trim();return t?{[jt]:t}:{}}const It=`.webm`;function Lt(e){return e===`web`?It:`.mp4`}function Rt(e,t){return _.extname(e)?e:`${e}${t}`}function zt(e){return`./recording-${Date.now()}${Lt(e)}`}function Bt(e){return new Promise((t,n)=>{let r=``;e.setEncoding(`utf8`),e.on(`data`,e=>{r+=e}),e.on(`end`,()=>t(r)),e.on(`error`,n)})}async function Vt(e,n,r){let i=[],a=0;for await(let o of e){let e=Buffer.isBuffer(o)?o:Buffer.from(o);if(a+=e.length,a>n)throw new t(`INVALID_ARGS`,r);i.push(e)}return Buffer.concat(i)}const k={kind:`none`};function A(e,t){if(t.path===void 0){let n=e??{kind:`default`,force:!1};return t.force?{...n,force:!0}:n}let n=e?.force===!0&&(e.kind==="default"||e.path===t.path);return{kind:`explicit`,path:t.path,force:t.force||n}}function Ht(e){return e.kind===`repair`?{...e,status:`armed`}:e}function Ut(e){return e.kind===`none`?void 0:e.target}function Wt(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function Gt(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function Kt(e){return{kind:`authoring`,status:`armed`,target:A(void 0,e)}}function qt(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function Jt(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function Yt(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:A(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function Xt(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function Zt(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function Qt(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function $t(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function en(e){return e.kind===`repair`?e.boundary:void 0}function tn(e){return e.kind===`repair`?e.sourcePath:void 0}function nn(e){return e.kind===`repair`&&e.status!==`committed`}function rn(e){let t=Ut(e);return t?.kind===`explicit`?t.path:void 0}function an(e){return Ut(e)?.force===!0}function j(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function M(e,t){return ve(e,{cwd:t})}function N(e){return e?.scriptPublication??k}function on(e){let t=N(e);return t.kind===`authoring`&&t.status===`armed`}function sn(e,t){e.recordSession=!0,e.scriptPublication=Kt({path:t.path===void 0?void 0:M(t.path),force:t.force===!0})}function cn(e){e.recordSession=!1,e.scriptPublication=qt(N(e))}function ln(e,t){if(!t.saveScript)return;e.recordSession=!0;let n={path:typeof t.saveScript==`string`?M(t.saveScript):void 0,force:t.force===!0},r=N(e);if(r.kind===`repair`){e.scriptPublication=Yt(r,{requested:n,boundary:r.boundary,sourcePath:r.sourcePath});return}if(r.kind===`authoring`){e.scriptPublication={...r,target:A(r.target,n)};return}e.scriptPublication=Kt(n)}function un(e,t){let n=N(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:A(n.target,{path:t.explicitPath===void 0?void 0:M(t.explicitPath),force:t.liveForce===!0})})}function dn(e,t){e.scriptPublication=Jt(N(e),t),e.recordSession=!1}function fn(e,t){let n=N(e);n.kind===`authoring`&&(e.scriptPublication=Jt(n,t))}function pn(e,t){return t===!0||an(N(e))}function mn(e){return Gt(N(e))}function P(e){return e?.scriptPublication??k}function hn(e,t){e.recordSession=!0;let n=P(e);e.scriptPublication=Yt(n,{requested:{path:typeof t.saveScript==`string`?M(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function gn(e){e.scriptPublication=Ht(P(e))}function _n(e){e.scriptPublication=Xt(P(e))}function vn(e,t){e.scriptPublication=Zt(P(e),t)}function yn(e){e.scriptPublication=$t(P(e))}function bn(e,t){let n=P(e);return n.kind===`repair`&&n.closeReceipt===t}function xn(e){return P(e).kind===`repair`}function Sn(e){return nn(P(e))}function Cn(e){return en(P(e))}function wn(e){return tn(P(e))}function Tn(e){let t=e.result?.text;if(typeof t==`string`)return t;let n=e.positionals??[];return n.length===0?``:n[0]?.startsWith(`@`)?n.length>=3?n.slice(2).join(` `):n.slice(1).join(` `):n.length>=3&&!Number.isNaN(Number(n[0]))&&!Number.isNaN(Number(n[1]))?n.slice(2).join(` `):n.slice(1).join(` `)}const En=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function Dn(e){if(e!==e.trim()||!pt.test(e))throw new t(`INVALID_ARGS`,`Invalid --record-as variable "${e}": use uppercase letters, digits, and underscores (for example PASSWORD).`);if(e.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid --record-as variable "${e}": the AD_* namespace is reserved for built-in replay variables.`);return e}function On(e){return`\${${e}}`}function kn(e){let t=En.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}const An=new Set([`text`,`label`,`value`]),jn=new Set(`action.backend.cost.delayMs.evidence.gesture.hint.kind.maestroFallbackReason.maestroNonHittableCoordinateFallbackAllowed.maestroNonHittableCoordinateFallbackUsed.message.platform.ref.referenceHeight.referenceWidth.refLabel.resolution.selector.selectorChain.settle.targetHittable.targetKind.text.warning.x.y`.split(`.`)),Mn=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),Nn=new Set([`cost`,`evidence`,`resolution`,`settle`]),Pn=new Map([[`cost`,new Set([`nodeCount`,`runnerRoundTrips`,`wallClockMs`])],[`evidence`,new Set([`changedFromBefore`,`digest`,`foregroundApp`,`interactiveNodeCount`,`nodeCount`])],[`resolution`,new Set([`alternatives`,`kind`,`matchCount`,`phase`,`source`,`tiebreak`,`winnerDiagnostic`])],[`resolution.alternatives`,new Set([`diagnosticRef`,`label`,`role`])],[`resolution.winnerDiagnostic`,new Set([`diagnosticRef`,`label`,`role`])],[`settle`,new Set([`captures`,`diff`,`hint`,`quietMs`,`refs`,`refsGeneration`,`settled`,`tail`,`tailTruncated`,`timeoutMs`,`waitedMs`])],[`settle.diff`,new Set([`lines`,`summary`,`truncated`])],[`settle.diff.lines`,new Set([`kind`,`ref`,`text`])],[`settle.diff.summary`,new Set([`additions`,`removals`,`unchanged`])],[`settle.refs`,new Set([`ref`])],[`settle.tail`,new Set([`label`,`ref`,`role`])]]),Fn=new Set([`evidence.digest`,`evidence.foregroundApp`,`resolution.alternatives.diagnosticRef`,`resolution.alternatives.role`,`resolution.kind`,`resolution.phase`,`resolution.source`,`resolution.tiebreak`,`resolution.winnerDiagnostic.diagnosticRef`,`resolution.winnerDiagnostic.role`,`settle.diff.lines.kind`,`settle.diff.lines.ref`,`settle.refs.ref`,`settle.tail.ref`,`settle.tail.role`]);function In(e,t,n){if(!e)return e;let r=Un(e.selectorChain);return{...zn(e,t,n),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!Rn(e,t))}:{}}}function Ln(e,t,n){return e&&{...e,...e.label===t?{label:n}:{},ancestry:e.ancestry.map(e=>({...e,...e.label===t?{label:n}:{}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===t?{label:n}:{}}}:{}}}function Rn(e,t){return f(e)?.selectors.some(e=>e.terms.some(e=>An.has(e.key)&&typeof e.value==`string`&&I(e.value,t,``)!==e.value))??!1}function zn(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[jn.has(e)?e:I(e,t,n),Bn(r,e,t,n)]))}function Bn(e,t,n,r){return typeof e==`string`&&Mn.has(t)?e:t===`selectorChain`&&Hn(e)?Vn(e,n):F(e,n,r,Nn.has(t)?t:void 0)}function F(e,t,n,r){if(typeof e==`string`)return r&&Fn.has(r)?e:I(e,t,n);if(Array.isArray(e))return e.map(e=>F(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?Pn.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:I(e,t,n),F(a,t,n,o?`${r}.${e}`:void 0)]}))}function Vn(e,t){return e.filter(e=>!Rn(e,t))}function I(e,t,n){if(!t)return e===t?n:e;let r=n?e.split(n):[e];return r.every(e=>!e.includes(t))?e:t.trim()?r.map(e=>e.replaceAll(t,n)).join(n):n}function Hn(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Un(e){return Hn(e)?e:void 0}function Wn(e,t){if(t.flags?.noRecord||Yn(e,t))return;t.flags&&ln(e,t.flags);let n=Gn(t),r={ts:Date.now(),command:n.command,positionals:n.positionals,runtime:n.runtime,flags:Zn(n.flags),result:n.result,...n.targetEvidence?{targetEvidence:n.targetEvidence}:{}};return e.actions.push(r),g({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),r}function Gn(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return e;let t=On(Dn(e.flags.recordAs)),n=Tn({ts:0,command:e.command,positionals:e.positionals,flags:e.flags});return{...e,positionals:Kn(e.positionals,t),result:In(e.result,n,t),targetEvidence:Ln(e.targetEvidence,n,t)}}function Kn(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const qn=new Set([`snapshot`,`get`,`is`,`find`]);function Jn(e){return e.internal?.replayPlanStep===!0?!1:qn.has(e.command)}function Yn(e,t){return!t.interactiveObservation||Cn(e)===void 0?!1:t.flags?.record!==!0}const Xn=[`platform`,`device`,`udid`,`serial`,`out`,`verbose`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`,`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`,...u,`relaunch`,`saveScript`,`force`,`noRecord`,`record`,`fps`,`quality`,`hideTouches`,`count`,`pointerCount`,`intervalMs`,`delayMs`,`holdMs`,`jitterPx`,`doubleTap`,`clickButton`,`pauseMs`,`pattern`];function Zn(e){if(!e)return{};let t={};for(let n of Xn)e[n]!==void 0&&(t[n]=e[n]);return t}function Qn(e){let n=e.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new t(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(e.some(e=>e.command===`close`))throw new t(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[t,n]of e.entries())se({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=t);if(!e.slice(r+1).some(tr))throw new t(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function $n(e){for(let n of e){let e=nr(n),r=e??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&se(n)===`mutates-app`)throw new t(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=e;if(!(!i||!f(i)||n.targetEvidence))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function er(e,n){if(e instanceof t){if(e.details?.reason===`script_target_exists`)return new t(e.code,`A file already exists at ${String(e.details.path)}.`,{...e.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=e.details?.retriable===!0;return new t(e.code,e.message,{...e.details,retriable:n,hint:e.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function tr(e){if(e.command!==`wait`)return!1;let t=oe(e.positionals);return t?.kind!==`selector`||f(t.selectorExpression)===null?!1:e.targetEvidence?.verification===`verified`}function nr(e){if(e.command===`get`)return e.positionals[1];if(Ke(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&rr(t)&&rr(n)?void 0:t}}function rr(e){return e.trim().length>0&&Number.isFinite(Number(e))}function ir(e){let t=e.scriptPublication??k;return t.kind===`repair`?t.status===`committed`?!0:!Wt(t):!1}var ar=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=xn(e),r=t?.publication===`active`,i;try{if(!e.recordSession||ir(e))return{written:!1};let a=or(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=_.dirname(i);return v.existsSync(o)||v.mkdirSync(o,{recursive:!0}),lr({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=Qt(e.scriptPublication??k)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return sr({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=rn(e.scriptPublication??k);if(t)return M(t);let n=j(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,`-`);return _.join(this.sessionsDir,`${n}-${r}.ad`)}};function or(e,t){let n=ur(e,{strictPortableRefs:t.activePublication});return t.activePublication&&Qn(n),{script:yr(e,n,t.appendCompleteSentinel),actionCount:n.length}}function sr(e){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=e;if(g({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:cr(r,i)};if(o)return{written:!1,error:er(r,i)};if(r instanceof t)throw r;return{written:!1}}function cr(e,n){if(e instanceof t)return e;let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to write the healed script${n?` to ${n}`:``}: ${r}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function lr(e){let{scriptPath:n,script:r,force:i}=e,a=_.dirname(n),o=_.join(a,`.${_.basename(n)}.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`);v.writeFileSync(o,r);try{if(i){v.renameSync(o,n);return}v.linkSync(o,n)}catch(e){throw e.code===`EEXIST`?new t(`COMMAND_FAILED`,`A file already exists at ${n}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:n}):e}finally{v.rmSync(o,{force:!0})}}function ur(e,t={}){let n=Cn(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=fr(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&dr(n);let o=vr(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&$n(a),a}function dr(e){if(!L(e.command))return;let n=e.command===`get`?e.positionals?.[1]:e.positionals?.[0];if(n?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot write recorded step "${e.command} ${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function fr(e){let t=pr(e);if(!(!t||!L(e.command)))return S(e.command)?{...e,positionals:[t]}:e.command===`longpress`?hr(e,t):e.command===`fill`?mr(e,t):gr(e,t)}function pr(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function L(e){return Ke(e)||e===`fill`||e===`get`}function mr(e,t){let n=Tn(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function hr(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):_r(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function gr(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function _r(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function vr(e,t){if(!L(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r}}}function yr(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${le(e.device)} device=${Je(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...kt(e)),r.push(br(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
|
|
2
|
+
`)}\n`}function br(e){return xr([e.command],e)||Ot(e)}function xr(e,t){if(S(t.command))return Sr(e,t);if(t.command===`fill`)return Cr(e,t);if(t.command===`get`)return wr(e,t)}function Sr(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(C(b(n))),R(e,t),T(e,t),e.join(` `);if(t.positionals.length===1)return e.push(C(n)),T(e,t),e.join(` `)}}function Cr(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(C(b(n))),R(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(C(r)),T(e,t),e.join(` `)}function wr(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(C(n)),e.push(C(b(r))),r.startsWith(`@`)&&R(e,t),e.join(` `)}function R(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(C(n))}const Tr=[`status`,`get`,`dismiss`,`enter`,`return`];function z(e){return Tr.includes(e)}const Er=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],Dr={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function Or(e,t){let n=t??{};switch(e.command){case s.devices:return kr(n.devices);case s.apps:return Ar(n.apps,e.flags?.appsFilter);case s.boot:return jr(`Booted`,n,!0);case s.shutdown:return jr(`Shut down`,n,!1);case s.install:return Mr(`Installed`,n);case s.reinstall:return Mr(`Reinstalled`,n);case s.screenshot:return Nr(e,n);default:return{}}}function kr(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=Fr(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:Wr(`Found ${t.length} ${Gr(`device`,t.length)}`,i.map(e=>Hr(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function Ar(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=H(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:Wr(`Found ${n.length} ${Gr(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function jr(e,t,n){let r=Ir(t);if(!r)return{};let i={device:r,...Vr(t),booted:n};return{summary:`${e} ${Hr(i,!1)}`,details:i}}function Mr(e,t){let n=H(t.appName),r=H(t.bundleId),i=B(t,[`packageName`,`package`]),a=H(t.platform),o=H(t.launchTarget),s=B(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=Ur(n,s);if(!c)return{};let l={};return V(l,`appName`,n),V(l,`bundleId`,r),V(l,`packageName`,i),V(l,`platform`,a),o!==s&&V(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function Nr(e,t){let n=Pr(e,t);return n?{details:{requestedFileName:n}}:{}}function Pr(e,t){let n=J(e.meta?.clientArtifactPaths?.path)??J(t.path);if(n)return q(n)}function Fr(e){if(!m(e))return;let t=Ir(e);if(t)return{name:t,...Vr(e)}}function Ir(e){let t=B(e,[`name`,`deviceName`,`device`]);return!t||!Lr(e,t)?t:zr(e)}function Lr(e,t){let n=Rr(t);return Er.some(t=>{let r=H(e[t]);return r!==void 0&&Rr(r)===n})}function Rr(e){return e.toLowerCase()}function zr(e){let t=H(e.appleOs),n=H(e.platform),r=H(e.kind),i=Br(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function Br(e,t){let n=e??t;if(!(!n||!Object.hasOwn(Dr,n)))return Dr[n]}function Vr(e){let t=H(e.platform),n=H(e.appleOs),r=H(e.kind),i=H(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function Hr(e,t){let n=H(e.name)??H(e.device)??`device`,r=H(e.platform),i=H(e.appleOs),a=[r,i===r?void 0:i,H(e.kind),H(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function Ur(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function B(e,t){for(let n of t){let t=H(e[n]);if(t)return t}}function V(e,t,n){n&&(e[t]=n)}function Wr(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function Gr(e,t){return t===1?e:`${e}s`}function H(e){let t=J(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function U(e){return H(e)}function W(e){return typeof e==`boolean`?e:void 0}function G(e,t){let n=U(e);return n&&t.includes(n)?n:void 0}function K(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function q(e){let t=J(e);return t?H(t.split(/[\\/]/).at(-1)):void 0}function J(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function Y(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const Kr=[`up`,`down`,`left`,`right`],qr=[`top`,`bottom`];function Jr(e){return`${e.command===s.reinstall?`Reinstalled`:`Installed`} ${Qr(e.result??{})??`app`}`}function Yr(e){let t=e.result??{};switch(e.command){case s.scroll:return ei(t);case s.screenshot:return ri(t);case s.home:return`Went home`;case s.back:return ai(t);case s.appSwitcher:return`Opened app switcher`;case s.orientation:return oi(t);case s.viewport:return si(t);case s.clipboard:return ci(t);case s.keyboard:return li(t);case s.tvRemote:return di(t);case s.gesture:return fi(t);case s.swipe:return pi(t);case s.trace:return hi(`trace`,e);case s.record:return hi(`recording`,e);default:return}}function Xr(e){let t=e.result??{};switch(e.command){case s.scroll:return K({direction:G(t.direction,Kr),edge:G(t.edge,qr),passes:Y(t.passes),amount:Y(t.amount),pixels:Y(t.pixels),durationMs:Y(t.durationMs),x1:Y(t.x1),y1:Y(t.y1),x2:Y(t.x2),y2:Y(t.y2)});case s.screenshot:return K({requestedFileName:ii(t)});case s.back:return K({mode:G(t.mode,d)});case s.orientation:return K({orientation:G(t.orientation,he)});case s.viewport:return K({width:Y(t.width),height:Y(t.height)});case s.clipboard:return K({action:G(t.action,[`read`,`write`])});case s.keyboard:return ui(t);case s.tvRemote:return K({button:G(t.button,ie),durationMs:Y(t.durationMs)});case s.gesture:case s.swipe:return mi(t);case s.trace:case s.record:return K({action:G(t.action,[`start`,`stop`]),fileName:_i(e),showTouches:W(t.showTouches)});default:return{}}}function Zr(e,t){if(e.command!==s.screenshot)return t;let n=Pr(e,t);return n?{...t,requestedFileName:n}:t}function Qr(e){let t=U(e.appName),n=vi(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??$r(e)}function $r(e){let t=U(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function ei(e){let t=G(e.direction,Kr),n=G(e.edge,qr),r=Y(e.passes);return n?ti(n,r):t?ni(t,e):`Scrolled`}function ti(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function ni(e,t){let n=Y(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=Y(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function ri(e){let t=ii(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function ii(e){return q(e.requestedFileName)??q(e.path)}function ai(e){return G(e.mode,d)===`system`?`Went back using system navigation`:`Went back`}function oi(e){let t=G(e.orientation,he);return t?`Rotated to ${t}`:`Changed orientation`}function si(e){let t=Y(e.width),n=Y(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function ci(e){let t=G(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function li(e){let t=J(e.action);if(!t||!z(t))return`Used keyboard`;if(t===`dismiss`)return W(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`;if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=W(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function ui(e){let t=J(e.action);return K({action:t&&z(t)?t:void 0,platform:G(e.platform,[`ios`,`android`]),visible:W(e.visible),wasVisible:W(e.wasVisible),dismissed:W(e.dismissed),attempts:Y(e.attempts)})}function di(e){let t=G(e.button,ie);return t?`Pressed TV remote ${t}`:`Used TV remote`}function fi(e){let t=G(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function pi(e){let t=Y(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function mi(e){return K({kind:G(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:Y(e.durationMs),pointerCount:Y(e.pointerCount),x1:Y(e.x1),y1:Y(e.y1),x2:Y(e.x2),y2:Y(e.y2),count:Y(e.count),pauseMs:Y(e.pauseMs),pattern:G(e.pattern,[`one-way`,`ping-pong`]),scale:Y(e.scale)})}function hi(e,t){let n=gi(e,G(t.result?.action,[`start`,`stop`])),r=_i(t);return r?`${n} ${r}`:n}function gi(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function _i(e){let t=e.result??{};return q(t.requestedFileName)??q(t.outPath)??q(t.path)??q(e.positionals[1])}function vi(e,t){for(let n of t){let t=U(e[n]);if(t)return t}}function yi(e){switch(e.command){case s.open:return`Opened ${X(e)??`session`}`;case s.close:return`Closed ${U(e.result?.session)??`session`}`;case s.click:case s.press:return`Tapped ${X(e)??`target`}`;case s.longPress:return`Long pressed ${X(e)??`target`}`;case s.fill:return`Filled ${X(e)??`target`}`;case s.type:return`Typed text`;case s.install:case s.reinstall:case i.installSource:return Jr(e);default:return Yr(e)??`Ran ${e.command}`}}function bi(e){return K({command:e.command,positionals:ki(e),flags:Bi(e),...xi(e),...Si(e),...Ci(e),...Xr(e)})}function xi(e){if(!wi(e.command))return{};let t=e.result??{};return K({ref:Ji(t),targetLabel:X(e),selectorChainLength:Li(t.selectorChain)?.length,x:Y(t.x),y:Y(t.y),x2:Y(t.x2),y2:Y(t.y2),durationMs:Y(t.durationMs)})}function Si(e){if(!Ti(e.command))return{};let t=e.result??{};return K({platform:G(t.platform,de),target:G(t.target,fe),appName:U(t.appName),appBundleId:U(t.appBundleId),bundleId:U(t.bundleId),packageName:U(t.packageName),launchTarget:U(t.launchTarget)})}function Ci(e){let t=e.result??{};return e.command===s.snapshot?{...Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}}:e.command!==s.wait&&e.command!==s.find&&e.command!==s.get&&e.command!==s.is?{}:K({waitedMs:Y(t.waitedMs),found:W(t.found)})}function wi(e){return e===s.click||e===s.press||e===s.longPress||e===s.focus||e===s.fill}function Ti(e){return e===s.open||e===s.install||e===s.reinstall||e===i.installSource}function X(e){let t=e.result??{};return Ei(t)??Di(t)??Oi(t)??Fi(e.positionals[0])}function Ei(e){let t=Ji(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function Di(e){let t=Y(e.x),n=Y(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function Oi(e){return U(e.appName)??U(e.appBundleId)??U(e.bundleId)??U(e.packageName)}function ki(e){if(e.positionals.length!==0)return e.command===s.type?[Q(`text`)]:e.command===s.fill?Ai(e):e.command===s.find?ji(e):e.command===s.clipboard?Mi(e):e.command===s.push?Ni(e,`app`,`payload`):e.command===s.triggerAppEvent?Ni(e,`event`,`payload`):e.positionals.map(Z)}function Ai(e){let t=Q(`text`),n=e.result??{},r=Ji(n);if(r)return[`@${r}`,t];if(U(n.selector))return[Q(`target`),t];let i=Y(n.x),a=Y(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function ji(e){let t=+!!Ii(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],Q(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,Q(`text`)]:[...r,...e.positionals.slice(n).map(Pi)]:r}function Mi(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,Q(`text`)]:e.positionals.map(Z)}function Ni(e,t,n){let[r,i,...a]=e.positionals;return[...r?[Q(t)]:[],...i?[Q(n)]:[],...a.map(Z)]}function Pi(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:Z(e)}function Z(e){return Fi(e)??Q(`arg`)}function Fi(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function Q(e){return`<${e}>`}function Ii(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function Li(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const Ri={enums:[{source:`platform`,values:ue},{source:`target`,values:fe}]},zi={[s.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:r}]},[s.click]:Vi(),[s.press]:Vi(),[s.longPress]:Vi(),[s.fill]:Hi(),[s.type]:Hi(),[s.scroll]:{numbers:[{source:`pixels`},{source:`durationMs`}]},[s.gesture]:Ui(),[s.swipe]:Ui(),[s.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotMaxSize`,output:`maxSize`}]},[s.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[s.back]:{enums:[{source:`backMode`,output:`mode`,values:d}]},[s.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`},{source:`screenshotMaxSize`,output:`maxSize`}],enums:[{source:`recordingScope`,output:`scope`,values:a}]},[s.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[s.boot]:{booleans:[{source:`headless`}]},[s.close]:{booleans:[{source:`shutdown`}]}};function Bi(e){let t=e.flags??{},n={},r=Object.hasOwn(zi,e.command)?zi[e.command]:void 0;return Wi(n,t,Ri),Wi(n,t,r),Object.keys(n).length>0?n:void 0}function Vi(){return{booleans:[{source:`doubleTap`},{source:`settle`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`},{source:`settleQuietMs`}],enums:[{source:`clickButton`,values:ne}]}}function Hi(){return{booleans:[{source:`settle`}],numbers:[{source:`delayMs`},{source:`settleQuietMs`}]}}function Ui(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:re}]}}function Wi(e,t,n){n&&(Gi(e,t,n.booleans??[]),Ki(e,t,n.numbers??[]),qi(e,t,n.enums??[]))}function Gi(e,t,n){for(let r of n)Yi(e,r.output??r.source,t[r.source])}function Ki(e,t,n){for(let r of n)Xi(e,r.output??r.source,t[r.source])}function qi(e,t,n){for(let r of n)Zi(e,r.output??r.source,t[r.source],r.values)}function Ji(e){let t=U(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function Yi(e,t,n){typeof n==`boolean`&&(e[t]=n)}function Xi(e,t,n){let r=Y(n);r!==void 0&&(e[t]=r)}function Zi(e,t,n,r){let i=G(n,r);i!==void 0&&(e[t]=i)}const $=new Map,Qi=new Set;function $i(e){return _.join(e,`events.ndjson`)}function ea(e){return e.command!==s.events}function ta(t,n,r){let i=e({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});ra(t,`${JSON.stringify(i)}\n`)}async function na(e){await(e?$.get(e):Promise.all($.values()))}function ra(e,t){let n=($.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await ia(e),await v.promises.appendFile(e,t,`utf8`)}).catch(t=>{g({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{$.get(e)===n&&$.delete(e)});$.set(e,n)}async function ia(e){let t=_.dirname(e);if(!Qi.has(t))try{await v.promises.mkdir(t,{recursive:!0}),Qi.add(t)}catch(t){throw g({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function aa(e,t,n){ta(e,t,{kind:`action.recorded`,requestId:h().requestId,command:n.command,summary:yi(n),details:bi(n)})}function oa(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??h().requestId,command:t.command,summary:`Started ${t.command}`}}function sa(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=Or(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??h().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??h().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function ca(e,t={}){let n=pa(t.cursor),r=ma(t.limit);if(!v.existsSync(e))return{path:e,cursor:String(n),limit:r,events:[]};let i=la(e,n,r),a=i.lines.flatMap(e=>{let t=ha(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:a,...i.nextCursor===void 0?{}:{nextCursor:String(i.nextCursor)}}}function la(e,t,n){let r=v.openSync(e,`r`);try{let e=new Te(`utf8`),i=Buffer.allocUnsafe(65536),a=ua(t,n),o=``,s=0;do{s=v.readSync(r,i,0,i.length,null);let t=e.write(i.subarray(0,s));o=da(`${o}${t}`,a)}while(s>0&&a.nextCursor===void 0);let c=`${o}${e.end()}`;return a.nextCursor===void 0&&c.length>0&&fa(c,a),{lines:a.lines,nextCursor:a.nextCursor}}finally{v.closeSync(r)}}function ua(e,t){return{cursor:e,limit:t,lineIndex:0,lines:[]}}function da(e,t){let n=0;for(let r=e.indexOf(`
|
|
3
|
+
`);r!==-1;r=e.indexOf(`
|
|
4
|
+
`,n))if(fa(e.slice(n,r),t),n=r+1,t.nextCursor!==void 0)return``;return e.slice(n)}function fa(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0){if(t.lineIndex>=t.cursor+t.limit){t.nextCursor=t.cursor+t.limit;return}t.lineIndex>=t.cursor&&t.lines.push(n),t.lineIndex+=1}}function pa(e){if(e===void 0||e.trim()===``)return 0;let n=Number(e);if(Number.isInteger(n)&&n>=0)return n;throw new t(`INVALID_ARGS`,`events cursor must be a non-negative integer string.`)}function ma(e){if(e===void 0||typeof e==`string`&&e.trim()===``)return 100;let n=typeof e==`string`?Number(e):e;if(Number.isInteger(n)&&n>=1&&n<=500)return n;throw new t(`INVALID_ARGS`,`events limit must be between 1 and 500.`)}function ha(e){try{let t=ga(JSON.parse(e));return t?_a(t):void 0}catch{return}}function ga(e){if(m(e)&&e.version===1&&!(typeof e.ts!=`string`||typeof e.session!=`string`)&&va(e.kind))return e}function _a(e){let t=m(e.details)?e.details:void 0;return{version:1,ts:e.ts,session:e.session,kind:e.kind,...typeof e.requestId==`string`?{requestId:e.requestId}:{},...typeof e.command==`string`?{command:e.command}:{},...ya(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function va(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function ya(e){return e===`ok`||e===`error`}const ba=60*6e4;var xa=class{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new ar(e)}get(e){return this.sessions.get(e)}set(e,t){this.sessions.set(e,t)}delete(e){return this.runtimeHints.delete(e),this.sessions.delete(e)}values(){return this.sessions.values()}toArray(){return Array.from(this.sessions.values())}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){this.runtimeHints.set(e,t)}clearRuntimeHints(e){return this.runtimeHints.delete(e)}recordAction(e,t){let n=Wn(e,t);if(n){let t=this.resolveStoredSessionName(e);aa(this.resolveEventLogPath(t),t,n)}}recordEvent(e,t){ta(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return ca(this.resolveEventLogPath(e),t)}async flushEvents(e){await na(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.scriptWriter.write(e,t);return n.written&&g({level:`info`,phase:`session_script_written`,data:{session:e.name,path:n.path}}),n}finalizeRepairTeardown(e){this.recordRepairFinalizeCloseIfCommitting(e);let t=this.writeSessionLog(e,{force:pn(e,void 0)});Sn(e)&&(!t.written&&t.error?this.writeRepairTombstone(e,ba,{code:String(t.error.code),message:t.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){Wt(e.scriptPublication??k)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:e.name,...l(`Closed: ${e.name}`)}})}writeRepairTombstone(e,t=ba,n){try{let r=this.resolveSessionDir(e.name);v.mkdirSync(r,{recursive:!0});let i={owner:e.name,reapedAt:Date.now(),expiresAt:Date.now()+t,...wn(e)?{sourcePath:wn(e)}:{},...n?{commitFailure:n}:{}};v.writeFileSync(this.repairTombstonePath(e.name),`${JSON.stringify(i)}\n`)}catch(t){g({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.name,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return Sa(this.repairTombstonePath(e))}clearRepairTombstone(e){try{v.rmSync(this.repairTombstonePath(e),{force:!0})}catch{}}repairTombstonePath(e){return _.join(this.resolveSessionDir(e),`repair-tombstone.json`)}defaultTracePath(e){let t=j(e.name),n=new Date().toISOString().replace(/[:.]/g,`-`);return _.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(e){return _.join(this.sessionsDir,j(e))}resolveDaemonStateDir(){return _.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return v.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return _.join(this.resolveSessionDir(e),`app.log`)}resolveAppLogPidPath(e){return _.join(this.resolveSessionDir(e),`app-log.pid`)}resolveEventLogPath(e){return $i(this.resolveSessionDir(e))}static expandHome(e,t){return M(e,t)}resolveStoredSessionName(e){for(let[t,n]of this.sessions)if(n===e)return t;return e.name}};function Sa(e){let t;try{t=v.readFileSync(e,`utf8`)}catch{return}let n;try{n=JSON.parse(t)}catch{return}if(!(typeof n?.expiresAt!=`number`||n.expiresAt<=Date.now()))return n}function Ca(e){let t;try{t=v.readdirSync(e,{withFileTypes:!0})}catch{return}for(let n of t){if(!n.isDirectory())continue;let t=Sa(_.join(e,n.name,`repair-tombstone.json`));if(t?.commitFailure)return{sessionName:n.name,tombstone:{...t,commitFailure:t.commitFailure}}}}function wa(e){return _.join(e,`runner.log`)}function Ta(e,t){let n=j(t&&t.length>0?t:`unknown`);return _.join(e,`requests`,`${n}.ndjson`)}function Ea(e,t={}){let n=Da(e,t);return{baseDir:n,infoPath:_.join(n,`daemon.json`),lockPath:_.join(n,`daemon.lock`),logPath:_.join(n,`daemon.log`),sessionsDir:_.join(n,`sessions`)}}function Da(e,t){let n=(e??``).trim();return n?ve(n,{env:t.env}):Oa(t)}function Oa(e={}){let t=_.join(ye(`~`,{env:e.env}),`.agent-device`),n=e.projectRoot??_e();return ka(n)?_.join(t,`dev`,Aa(n)):t}function ka(e){return v.existsSync(_.join(e,`package.json`))&&v.existsSync(_.join(e,`src`,`daemon.ts`))}function Aa(e){let t=ja(e),n=_.basename(t).replaceAll(/[^a-zA-Z0-9._-]+/g,`-`),r=we.createHash(`sha1`).update(t).digest(`hex`).slice(0,12);return`${n||`agent-device`}-${r}`}function ja(e){try{return v.realpathSync.native(e)}catch{return _.resolve(e)}}function Ma(e){let t=(e??``).trim().toLowerCase();return t===`http`?`http`:t===`dual`?`dual`:`socket`}function Na(e){let t=(e??``).trim().toLowerCase();return t===`auto`?`auto`:t===`socket`?`socket`:t===`http`?`http`:`auto`}function Pa(e){return(e??``).trim().toLowerCase()===`tenant`?`tenant`:`none`}function Fa(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}const Ia=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,La=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,Ra=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`];function za(){let e=process.argv[1];return e?Ba(e):`unknown`}function Ba(e,t=_e()){try{let n=_.resolve(t),r=[_.resolve(e)],i=new Set,a=[];for(;r.length>0;){let e=r.pop();if(!e||i.has(e))continue;i.add(e);let t=v.statSync(e);if(!t.isFile())continue;let o=_.relative(n,e)||e;a.push(`${o}:${t.size}:${Math.trunc(t.mtimeMs)}`);let s=v.readFileSync(e,`utf8`);for(let t of Va(s)){let n=Ua(e,t);n&&r.push(n)}}let o=a.sort().join(`|`),s=we.createHash(`sha1`).update(o).digest(`hex`);return`graph:${a.length}:${s}`}catch{return`unknown`}}function Va(e){let t=new Set;return Ha(e,Ia,t),Ha(e,La,t),[...t]}function Ha(e,t,n){t.lastIndex=0;let r=null;for(;(r=t.exec(e))!==null;){let e=r[1]?.trim();e?.startsWith(`.`)&&n.add(e)}}function Ua(e,t){let n=_.resolve(_.dirname(e),t),r=Wa(n);if(r)return r;for(let e of Ra){let t=Wa(`${n}${e}`);if(t)return t}for(let e of Ra){let t=Wa(_.join(n,`index${e}`));if(t)return t}return null}function Wa(e){try{return v.statSync(e).isFile()?e:null}catch{return null}}const Ga=/^[A-Za-z0-9_@%+=:,./-]+$/;function Ka(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function qa(e){return Ga.test(e)?e:Ka(e)}const Ja=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])dist\/src\/internal\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function Ya(e){let t=e.toLowerCase().replaceAll(`\\`,`/`);return t.includes(`agent-device`)?Ja.some(e=>e.test(t)):!1}function Xa(e,t){if(!xe(e))return!1;if(t){let n=Se(e);if(!n||n!==t)return!1}let n=be(e);return n?Ya(n):!1}function Za(e,t){try{return process.kill(e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}async function Qa(e,t){Xa(e,t.expectedStartTime)&&Za(e,`SIGTERM`)&&(await Ce(e,t.termTimeoutMs)||Za(e,`SIGKILL`)&&await Ce(e,t.killTimeoutMs))}function $a(e,t){let n=[],r=e+t.toString(),i=r.indexOf(`
|
|
5
|
+
`);for(;i!==-1;){let e=r.slice(0,i).trim();r=r.slice(i+1),e&&n.push(e),i=r.indexOf(`
|
|
6
|
+
`)}return{lines:n,buffer:r}}function eo(e){return e.meta?.requestProgress===`replay-test`||e.meta?.requestProgress===`command`}function to(e){return!!e&&typeof e==`object`&&e.type===`progress`&&!!e.event}function no(e){return!!e&&typeof e==`object`&&e.type===`response`&&!!e.response}function ro(e){return`${JSON.stringify({type:`progress`,event:e})}\n`}function io(e){return`${JSON.stringify({type:`response`,response:e})}\n`}function ao(e){return`${JSON.stringify({type:`response`,response:e})}\n`}function oo(e,t={}){return{ok:!0,service:e,version:ge(),rpcProtocolVersion:2,...t.upstream===void 0?{}:{upstream:t.upstream}}}function so(e){return{...typeof e.path==`string`?{path:e.path}:{},...typeof e.width==`number`?{width:e.width}:{},...typeof e.height==`number`?{height:e.height}:{},...typeof e.logicalWidth==`number`?{logicalWidth:e.logicalWidth}:{},...typeof e.logicalHeight==`number`?{logicalHeight:e.logicalHeight}:{},...typeof e.pixelDensity==`number`?{pixelDensity:e.pixelDensity}:{},...e.overlayRefs?{overlayRefs:e.overlayRefs}:{}}}function co(e){if(m(e))return so({path:typeof e.path==`string`?e.path:void 0,width:typeof e.width==`number`?e.width:void 0,height:typeof e.height==`number`?e.height:void 0,logicalWidth:typeof e.logicalWidth==`number`?e.logicalWidth:void 0,logicalHeight:typeof e.logicalHeight==`number`?e.logicalHeight:void 0,pixelDensity:typeof e.pixelDensity==`number`?e.pixelDensity:void 0,overlayRefs:Array.isArray(e.overlayRefs)?e.overlayRefs.filter(po).flatMap(e=>{let t=lo(e);return t?[t]:[]}):void 0})}function lo(e){if(typeof e.ref!=`string`||e.ref.length===0)return;let t=uo(e);if(t)return{ref:e.ref,...fo(e),...t}}function uo(e){let t=ce(e.rect);if(!t)return;let n=ce(e.overlayRect);if(!n)return;let r=ae(e.center);return r?{rect:t,overlayRect:n,center:r}:void 0}function fo(e){return typeof e.label==`string`&&e.label.length>0?{label:e.label}:{}}function po(e){return m(e)}export{dn as $,ki as A,Oe as At,hn as B,xa as C,$e as Ct,sa as D,Ae as Dt,wa as E,ke as Et,kn as F,vn as G,xn as H,On as I,cn as J,Cn as K,Dn as L,z as M,Jn as N,oa as O,Ee as Ot,In as P,mn as Q,Tn as R,Pa as S,lt as St,Ta as T,Ke as Tt,Sn as U,bn as V,_n as W,pn as X,sn as Y,on as Z,za as _,Ft as _t,no as a,an as at,Ma as b,gt as bt,ao as c,Bt as ct,Xa as d,zt as dt,fn as et,Qa as f,Lt as ft,Ba as g,Mt as gt,qa as h,Pt as ht,to as i,k as it,Zr as j,ea as k,De as kt,eo as l,It as lt,Ka as m,jt as mt,co as n,M as nt,ro as o,rn as ot,Za as p,At as pt,gn as q,oo as r,j as rt,io as s,Vt as st,so as t,un as tt,$a as u,Rt as ut,Fa as v,Nt as vt,Ca as w,C as wt,Na as x,_t as xt,Ea as y,pt as yt,yn as z};
|