agent-device 0.19.1 → 0.19.3

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.
Files changed (88) hide show
  1. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.19.3.apk +0 -0
  2. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.19.3.apk.sha256 +1 -0
  3. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.19.1.manifest.json → agent-device-android-multitouch-helper-0.19.3.manifest.json} +4 -4
  4. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.19.1.apk → agent-device-android-snapshot-helper-0.19.3.apk} +0 -0
  5. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.19.3.apk.sha256 +1 -0
  6. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.19.1.manifest.json → agent-device-android-snapshot-helper-0.19.3.manifest.json} +6 -6
  7. package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +7 -0
  8. package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +99 -30
  9. package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +9 -1
  10. package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +21 -8
  11. package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +10 -0
  12. package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +1 -0
  13. package/dist/src/agent-browser-tool.js +1 -1
  14. package/dist/src/android-adb.js +1 -1
  15. package/dist/src/android-input-ownership.js +1 -1
  16. package/dist/src/android.js +1 -1
  17. package/dist/src/app-lifecycle.js +1 -1
  18. package/dist/src/apple-runner-options.js +1 -1
  19. package/dist/src/apps.js +5 -5
  20. package/dist/src/audio-probe.js +1 -1
  21. package/dist/src/cli-help.js +34 -19
  22. package/dist/src/cli-runner.js +1 -1
  23. package/dist/src/cli.js +11 -11
  24. package/dist/src/client.js +2 -2
  25. package/dist/src/contracts.js +1 -1
  26. package/dist/src/debug-symbols.js +1 -1
  27. package/dist/src/device-input-state.js +1 -1
  28. package/dist/src/devices2.js +1 -1
  29. package/dist/src/find.js +1 -1
  30. package/dist/src/generic.js +1 -1
  31. package/dist/src/helper.js +1 -1
  32. package/dist/src/index.d.ts +29 -0
  33. package/dist/src/index.js +1 -1
  34. package/dist/src/input-actions.js +1 -1
  35. package/dist/src/input-actions2.js +1 -1
  36. package/dist/src/install-source2.js +1 -1
  37. package/dist/src/interaction-snapshot.js +1 -1
  38. package/dist/src/interaction.js +1 -1
  39. package/dist/src/interactor.js +2 -2
  40. package/dist/src/internal/bin.js +1 -1
  41. package/dist/src/internal/daemon.js +20 -16
  42. package/dist/src/internal/png-worker.js +1 -1
  43. package/dist/src/lease.js +1 -1
  44. package/dist/src/linux.js +1 -1
  45. package/dist/src/notifications.js +1 -1
  46. package/dist/src/png-worker-contract.js +1 -1
  47. package/dist/src/points.js +3 -3
  48. package/dist/src/providers.js +1 -1
  49. package/dist/src/react-native.js +1 -1
  50. package/dist/src/record-trace-recording.js +2 -2
  51. package/dist/src/record-trace.js +1 -1
  52. package/dist/src/registry.js +24 -24
  53. package/dist/src/reporting.js +3 -3
  54. package/dist/src/runner-client.js +1 -1
  55. package/dist/src/runner-sequence.js +1 -1
  56. package/dist/src/runtime-transport.js +1 -1
  57. package/dist/src/runtime.js +2 -2
  58. package/dist/src/sdk-android-adb.js +3 -3
  59. package/dist/src/sdk-app-inventory.js +1 -1
  60. package/dist/src/sdk-batch-runner.js +2 -2
  61. package/dist/src/sdk-batch.js +2 -2
  62. package/dist/src/sdk-contracts.js +2 -2
  63. package/dist/src/sdk-device.js +1 -0
  64. package/dist/src/sdk-finders.js +1 -1
  65. package/dist/src/sdk-io.js +1 -1
  66. package/dist/src/sdk-remote-config.js +1 -1
  67. package/dist/src/sdk-selectors.js +1 -1
  68. package/dist/src/selector-runtime.js +1 -1
  69. package/dist/src/selectors.js +1 -1
  70. package/dist/src/server.js +2 -2
  71. package/dist/src/session.js +10 -10
  72. package/dist/src/setting-state.js +1 -1
  73. package/dist/src/simctl.js +1 -1
  74. package/dist/src/simulator.js +1 -1
  75. package/dist/src/snapshot-diagnostics.js +1 -1
  76. package/dist/src/snapshot.js +1 -1
  77. package/dist/src/snapshot2.js +2 -2
  78. package/dist/src/tool-provider.js +2 -2
  79. package/dist/src/tool-provider2.js +1 -1
  80. package/dist/src/tv-remote.js +9 -9
  81. package/dist/src/version.js +1 -1
  82. package/dist/src/web.js +1 -1
  83. package/package.json +11 -3
  84. package/server.json +2 -2
  85. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.19.1.apk +0 -0
  86. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.19.1.apk.sha256 +0 -1
  87. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.19.1.apk.sha256 +0 -1
  88. package/dist/src/snapshot-helper.js +0 -5
@@ -1,3 +1,3 @@
1
- import{t as e}from"./rolldown-runtime.js";import{D as t,F as n,H as r,I as i,O as a,P as o,j as s,k as c}from"./sdk-contracts.js";import{j as l,v as u,w as d}from"./sdk-android-adb.js";import{b as f}from"./sdk-batch.js";import{A as p,B as m,C as h,D as g,E as _,H as ee,L as te,M as ne,N as re,O as ie,P as ae,Q as v,R as oe,S as se,T as ce,U as le,V as y,X as b,Y as x,Z as S,_ as ue,b as de,d as fe,hn as pe,j as me,k as he,nt as C,pn as ge,r as _e,v as ve,w as ye,wn as w,x as be,y as xe,z as Se}from"./tv-remote.js";import{_ as Ce,a as we,b as Te,i as Ee,m as De,n as Oe,y as ke}from"./sdk-selectors.js";import{r as Ae,t as je}from"./snapshot-quality.js";import{o as Me,r as Ne}from"./sdk-finders.js";import{a as Pe,i as Fe,o as Ie,r as Le,t as Re}from"./selectors2.js";import{n as ze,r as Be}from"./sdk-app-inventory.js";import{i as Ve,n as He,r as Ue,t as We}from"./png-worker-contract.js";import Ge,{promises as T}from"node:fs";import E from"node:path";import{fileURLToPath as Ke}from"node:url";import{Worker as qe}from"node:worker_threads";const Je=/\b(logbox|redbox|reload js|copy stack|component stack|call stack|runtime error|open debugger to view warnings)\b/,Ye=/\b(redbox|runtime error|reload js|copy stack|component stack|call stack)\b/,Xe=[/\b[\w.$<>/-]+\.(?:tsx?|jsx?):\d+(?::\d+)?\b/,/\b[\w.$<>/-]+\.(?:tsx?|jsx?)\s+\(\d+:\d+\)/],Ze=[/^!,\s+/,/^(warn|warning|error):\s+/,/\b(?:possible\s+)?unhandled (?:promise )?rejection\b/],Qe=[`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`],$e=new Set([`x`,`×`,`✕`,`✖`,`⨯`]);function et(e){if(nt(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(`
1
+ import{t as e}from"./rolldown-runtime.js";import{_ as t,d as n,g as r,l as i,p as a,u as o,v as s,w as c}from"./sdk-contracts.js";import{j as l,v as u,w as d}from"./sdk-android-adb.js";import{C as f}from"./sdk-batch.js";import{A as p,B as m,C as h,D as g,E as _,H as ee,L as te,M as ne,N as re,O as ie,P as ae,Q as v,R as oe,S as se,Sn as y,T as ce,U as le,V as b,X as x,Y as S,Z as C,_ as ue,b as de,d as fe,dn as pe,j as me,k as he,nt as w,pn as ge,r as _e,v as ve,w as ye,x as be,y as xe,z as Se}from"./tv-remote.js";import{_ as Ce,a as we,b as Te,i as Ee,m as De,n as Oe,y as ke}from"./sdk-selectors.js";import{r as Ae,t as je}from"./snapshot-quality.js";import{o as Me,r as Ne}from"./sdk-finders.js";import{a as Pe,i as Fe,o as Ie,r as Le,t as Re}from"./selectors2.js";import{n as ze,r as Be}from"./sdk-app-inventory.js";import{i as Ve,n as He,r as Ue,t as We}from"./png-worker-contract.js";import Ge,{promises as T}from"node:fs";import E from"node:path";import{fileURLToPath as Ke}from"node:url";import{Worker as qe}from"node:worker_threads";const Je=/\b(logbox|redbox|reload js|copy stack|component stack|call stack|runtime error|open debugger to view warnings)\b/,Ye=/\b(redbox|runtime error|reload js|copy stack|component stack|call stack)\b/,Xe=[/\b[\w.$<>/-]+\.(?:tsx?|jsx?):\d+(?::\d+)?\b/,/\b[\w.$<>/-]+\.(?:tsx?|jsx?)\s+\(\d+:\d+\)/],Ze=[/^!,\s+/,/^(warn|warning|error):\s+/,/\b(?:possible\s+)?unhandled (?:promise )?rejection\b/],Qe=[`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`],$e=new Set([`x`,`×`,`✕`,`✖`,`⨯`]);function et(e){if(nt(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
2
  `)}function tt(e){return nt(e)}function nt(e){let t=ot(e),n=t.detected?st(t):null;return{detected:t.detected,redBox:t.redBox,dismissNodes:t.dismissNodes,minimizeNodes:t.minimizeNodes,collapsedNodes:t.collapsedNodes,primaryAction:n}}function rt(e){return[...e.dismissNodes,...e.minimizeNodes,...e.collapsedNodes]}function it(e){return ht(e.label?.trim())&&Tt(e.rect)}function at(e,t){let n=e.label?.trim();return!n||!it(e)?!1:t.some(e=>e.label?.trim()===n&&Et(e))}function ot(e){let t=e.map(ct).join(`
3
- `).toLowerCase(),n=D(e,_t),r=D(e,xt),i=D(e,ht,Ct),a=D(e,gt),o=ut(t),s=dt(t),c=ft(t,n,r);return{dismissNodes:n,minimizeNodes:r,collapsedNodes:i,redBox:pt(t,o,c),detected:mt({text:t,hasReactNativeStackFrame:o,hasOverlayControl:c,hasControllessRedBoxText:s,collapsedNodes:i,openDebuggerWarningNodes:a})}}function st(e){let t=Dt(e.dismissNodes);if(t)return jt(t,Mt(t));let n=Nt(e.collapsedNodes.filter(wt));return n?.rect?{action:`close-collapsed-banner`,point:Rt(n),rect:n.rect,ref:n.ref,label:Bt(n)}:null}function ct(e){return[e.label,e.value,e.identifier,e.type,e.role].filter(Boolean).join(` `)}function lt(e){return Je.test(e)}function ut(e){return Xe.some(t=>t.test(e))}function dt(e){return/\buncaught\b/.test(e)&&/unable to download asset/.test(e)}function ft(e,t,n){return t.length>0||n.length>0||/\b(reload js|copy stack)\b/.test(e)}function pt(e,t,n){return Ye.test(e)||dt(e)||t&&n}function mt(e){return e.collapsedNodes.length>0||e.openDebuggerWarningNodes.length>0||e.hasControllessRedBoxText||e.hasOverlayControl&&(lt(e.text)||e.hasReactNativeStackFrame)}function ht(e){let t=e?.trim().toLowerCase();return t?Qe.some(e=>t.includes(e))||Ze.some(e=>e.test(t)):!1}function gt(e){return e.includes(`open debugger to view warnings`)||/^!,\s+open debugger\b/.test(e)}function _t(e){return vt(e)||yt(e)||bt(e)}function vt(e){return/^dismiss(?:\s*\([^)]*\))?$/i.test(e)}function yt(e){return/^close(?:\s*\([^)]*\))?$/i.test(e)}function bt(e){return $e.has(e)}function xt(e){return/^minimi[sz]e(?:\b|\s|\()/i.test(e)}function St(e){return/^!,\s+/.test(e)}function Ct(e){return!e.rect||e.rect.height<=180}function wt(e){let t=Bt(e)?.trim().toLowerCase()??``;return(gt(t)||St(t))&&Et(e)}function Tt(e){return e?e.x<=1&&e.y<=1&&e.width>=300&&e.height>=600:!1}function Et(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 Dt(e){return Pt(e,At)}function Ot(e){let t=[e.type,e.role,e.subrole].join(` `).toLowerCase();return/\b(button|menuitem|link)\b/.test(t)}function kt(e){return e?e.width*e.height:1/0}function At(e){return[It(Ot(e)),It(e.hittable),-kt(e.rect)]}function jt(e,t){if(!e.rect)throw Error(`React Native overlay target node must have rect`);return{action:t,point:a(e.rect),rect:e.rect,ref:e.ref,label:Bt(e)}}function Mt(e){let t=Bt(e)?.trim().toLowerCase();return t&&vt(t)?`dismiss`:`close`}function Nt(e){return Pt(e,Ft)}function Pt(e,t){let n=e.filter(e=>e.rect);return n.length===0?null:n.sort((e,n)=>Lt(t(n),t(e)))[0]??null}function Ft(e){return[It(e.hittable),e.rect?.width??0,e.rect?.y??0]}function It(e){return+(e===!0)}function Lt(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 Rt(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(zt(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 zt(e,t,n){return Math.min(n,Math.max(t,e))}function Bt(e){return e.label??e.value??e.identifier}const Vt=[`status`,`get`,`dismiss`,`enter`,`return`];function Ht(e){return Vt.includes(e)}function Ut(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 Wt(e){let{nodes:t,backend:n,snapshotRaw:r}=e;if(r||!o(n))return{partial:!1,visibleNodeCount:t.length,totalNodeCount:t.length,reasons:[]};let i=Te(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]}}function Gt(e,t){try{let n=Ke(e),r=E.extname(n)||`.js`;return[E.join(E.dirname(n),`${t}${r}`),E.join(E.dirname(n),`internal`,`${t}${r}`)].find(e=>Ge.existsSync(e))??null}catch{return null}}var O=class extends Error{};let k=null,Kt=!1,qt=!1,Jt=0;const A=new Map;function Yt(e){Kt=!0,!qt&&(qt=!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 Xt(e){let t=A.get(e.id);t&&(A.delete(e.id),$t(),e.ok?t.resolve(e.result):t.reject(new n(r(e.error.code),e.error.message,e.error.details)))}function Zt(e,t){k===e&&(Yt(t.message),k=null,e.terminate().catch(()=>{}),Qt(new O(`PNG worker failed: ${t.message}`)))}function Qt(e){let t=[...A.values()];A.clear();for(let n of t)n.reject(e)}function $t(){k&&(A.size>0?k.ref():k.unref())}function en(){if(Kt)return null;if(k)return k;let e=Gt(import.meta.url,`png-worker`);if(!e)return Yt(`worker entry module not found next to the current module`),null;try{let t=new qe(e,{execArgv:e.endsWith(`.ts`)?[`--experimental-strip-types`]:[]});return t.on(`message`,Xt),t.on(`error`,e=>{Zt(t,e)}),t.on(`exit`,e=>{Zt(t,Error(`PNG worker exited with code ${e}`))}),t.unref(),k=t,t}catch(e){return Yt(`failed to spawn worker: ${e instanceof Error?e.message:String(e)}`),null}}function tn(e){let t=en();if(!t)return Promise.reject(new O(`PNG worker is unavailable`));Jt+=1;let n=Jt;return new Promise((r,i)=>{A.set(n,{resolve:r,reject:i}),$t();try{t.postMessage({...e,id:n})}catch(e){A.delete(n),$t(),i(new O(`failed to post job to PNG worker: ${e instanceof Error?e.message:String(e)}`))}})}async function nn(e,t){try{return await tn(e)}catch(e){if(e instanceof O)return t();throw e}}function rn(){en()}async function an(){let e=k;k=null,Qt(new O(`PNG worker terminated`)),e&&await e.terminate()}async function j(e,t){let n=await nn({kind:`decode`,png:e,label:t},()=>{let n=Ue(e,t);return{kind:`decode`,width:n.width,height:n.height,data:n.data}});return new Ve({width:n.width,height:n.height,data:We(n.data)})}async function M(e){return We((await nn({kind:`encode`,width:e.width,height:e.height,data:e.data},()=>({kind:`encode`,png:Ve.sync.write(e)}))).png)}async function on(e){let{kind:t,...n}=await nn({kind:`diff-pixels`,...e},()=>({kind:`diff-pixels`,...He(e)}));return{...n,diffData:We(n.diffData)}}const sn=[0,187,255,255];function cn(e,t){for(let n of t)n.rect.width<4||n.rect.height<4||ln(e,n.rect)}function ln(e,t){let n=N(t.x,0,e.width-1),r=N(t.y,0,e.height-1),i=N(t.x+t.width-1,0,e.width-1),a=N(t.y+t.height-1,0,e.height-1);for(let t=0;t<2;t+=1){for(let o=n;o<=i;o+=1)un(e,o,r+t,sn),un(e,o,a-t,sn);for(let o=r;o<=a;o+=1)un(e,n+t,o,sn),un(e,i-t,o,sn)}}function un(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 N(e,t,n){return Math.min(Math.max(e,t),n)}const dn=[{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 fn(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(!hn(t,a,e))continue;let c=0,l=mn(o,a,0,e),u=i.create(e);for(;c<l;){let e=o[c];c+=1,i.visit(u,e),l=pn({mask:t,visited:a,queue:o,queueEnd:l,width:n,height:r,pixelIndex:e})}s.push(u)}return s}function pn(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 dn){let o=s+e.x,u=c+e.y;if(!gn(o,u,i,a))continue;let d=u*i+o;hn(t,n,d)&&(l=mn(r,n,l,d))}return l}function mn(e,t,n,r){return t[r]=1,e[n]=r,n+1}function hn(e,t,n){return e[n]===1&&t[n]!==1}function gn(e,t,n,r){return e>=0&&e<n&&t>=0&&t<r}const _n=.4,vn={icon:90,toggle:90,chevron:75,separator:45,visual:35,background:10},yn={leading:20,trailing:20,separator:10,unknown:0,background:-30};function bn(e){let t=Tn(Sn(xn(e.diffMask,e.width,e.height,e.ocr),e.width,e.height),10),n=In(e.ocr?.currentBlocksRaw??[]),r=In(e.ocr?.baselineBlocksRaw??[]);return t.filter(Bn).map(t=>En(t,e,n,r)).filter(t=>t.rect.y>=e.height*.08).filter(An).sort((e,t)=>t.score-e.score).slice(0,Math.max(0,e.maxDeltas??12)).map((e,t)=>Dn(e,t+1))}function xn(e,t,n,r){let i=new Uint8Array(e);if(!r)return i;for(let e of[...r.baselineBlocksRaw,...r.currentBlocksRaw])Hn(i,t,n,oe(e.rect,8));return i}function Sn(e,t,n){return fn({mask:e,width:t,height:n,hooks:{create:e=>Cn(e,t),visit:(e,n)=>wn(e,n,t)}})}function Cn(e,t){let n=e%t,r=Math.floor(e/t);return{minX:n,minY:r,maxX:n,maxY:r,differentPixels:0}}function wn(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 Tn(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=>Un(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 En(e,t,n,r){let i=Vn(e),a=Nn(i,t.regions),o=Pn(i,n,r),s=On(i,o?.block.rect,t.width),c=kn(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:zn(o.block.text)}:{},score:jn(l,e.differentPixels,t)}}function Dn(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 On(e,t,n){if(e.height<=3&&e.width>=n*.12)return`separator`;if(!t)return e.width>=n*_n?`background`:`unknown`;if(e.width>=n*_n)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 kn(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`:Mn(e,r)?`background`:`visual`}function An(e){return e.likelyKind!==`background`}function jn(e,t,n){let r=Mn(e.rect,n)?-35:0,i=e.regionIndex?20:0;return vn[e.likelyKind]+yn[e.slot]+i+r+Math.min(20,t/200)}function Mn(e,t){return e.width>=t.width*.25||e.height>=t.height*.06}function Nn(e,t){let n,r=0;for(let i of t){let t=Se(e,i.rect);t<=r||(r=t,n=i)}return n?.index}function Pn(e,t,n){let r=Fn(e,t);if(r)return Rn(e,r.blocks);let i=Fn(e,n);return i?Rn(e,i.blocks):void 0}function Fn(e,t){let n,r=0;for(let i of t){let t=Wn(e,i.rect);t<=r||(r=t,n=i)}return n}function In(e){let t=[];for(let n of[...e].sort((e,t)=>e.rect.y-t.rect.y)){let e=t.find(e=>Ln(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=le([e.rect,n.rect])}return t}function Ln(e,t){return Wn(e,t)>0?!0:Math.abs(y(e).y-y(t).y)<=Math.max(e.height,t.height)*.5}function Rn(e,t){let n,r=y(e);for(let e of t){let t=Math.sqrt(ee(r,y(e.rect)));n&&t>=n.distance||(n={block:e,distance:t})}return n}function zn(e){return e.trim().replace(/^[^\p{L}\p{N}]+/u,``).replace(/^\p{L}\s+/u,``)}function Bn(e){let t=Vn(e);return e.differentPixels>=24&&t.width>=3&&t.height>=3}function Vn(e){return{x:e.minX,y:e.minY,width:e.maxX-e.minX+1,height:e.maxY-e.minY+1}}function Hn(e,t,n,r){let i=te(Math.floor(r.x),0,t-1),a=te(Math.floor(r.y),0,n-1),o=te(Math.ceil(r.x+r.width),0,t),s=te(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 Un(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 Wn(e,t){return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}async function Gn(e){if(await d(`tesseract`))try{let[t,n]=await Promise.all([Jn(e.baselinePath),Jn(e.currentPath)]);if(t.exitCode!==0||n.exitCode!==0)return;let r=Kn(t.stdout,e.width,e.height),i=Kn(n.stdout,e.width,e.height),a=qn(r,i),o=tr(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 Kn(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=F(t,o,`level`),r=P(t,o,`text`).trim(),i=F(t,o,`conf`);if(n!==5||!ir(r)||i<0)continue;let a=F(t,o,`left`),c=F(t,o,`top`),l=F(t,o,`width`),u=F(t,o,`height`);l<=0||u<=0||s.push({key:[P(t,o,`page_num`),P(t,o,`block_num`),P(t,o,`par_num`),P(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=>Xn(e)).map(e=>Yn(e,t,n)).filter(e=>e!==null)}function qn(e,t){let n=new Set,r=[];for(let i of e){let e=Zn(i,ar(i.text),t,n);if(e===null)continue;n.add(e);let a=t[e],o=Qn(i,a);$n(o)&&r.push(o)}return r.sort((e,t)=>er(t)-er(e)).slice(0,12)}function Jn(e){return u(`tesseract`,[e,`stdout`,`-l`,`eng`,`tsv`],{allowFailure:!0,timeoutMs:1e4})}function Yn(e,t,n){if(e.length===0)return null;let r=[...e].sort((e,t)=>e.rect.x-t.rect.x),i=le(r.map(e=>e.rect)),a=Math.round(or(r.map(e=>e.confidence))*100)/100;return{text:r.map(e=>e.text).join(` `),confidence:a,rect:i,normalizedRect:m({x:I(i.x/t),y:I(i.y/n),width:I(i.width/t),height:I(i.height/n)})}}function Xn(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 Zn(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(ar(s.text)!==t)continue;let c=ee(y(e.normalizedRect),y(s.normalizedRect));c>=a||(i=o,a=c)}return i}function Qn(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=sr(t.rect.width/e.rect.width),i=sr(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 $n(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 er(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 tr(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-or(e.map(e=>e.delta.x)))<=32);e?e.push(n):t.push([n])}return t.filter(e=>e.length>=2).map(nr).filter(e=>e.yRange.max-e.yRange.min<=60).sort((e,t)=>rr(t)-rr(e)).slice(0,4)}function nr(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 rr(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 P(e,t,n){let r=t.get(n);return r===void 0?``:e[r]??``}function F(e,t,n){let r=Number(P(e,t,n));return Number.isFinite(r)?r:0}function ir(e){return/[\p{L}\p{N}]/u.test(e)}function ar(e){return e.trim().replace(/\s+/g,` `).toLowerCase()}function or(e){return e.reduce((e,t)=>e+t,0)/e.length}function I(e){return Math.round(e*100*100)/100}function sr(e){return Math.round(e*1e3)/1e3}function cr(e,t){return e.flatMap(e=>lr(e,t.baseline.width,t.baseline.height)?ur(e,t,gr(t.baseline.height)):[e])}function lr(e,t,n){let r=e.maxX-e.minX+1;return e.maxY-e.minY+1>=hr(n)&&r>=t*.35}function ur(e,t,n){let r=mr(e,pr(fr(dr(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])=>_r(e,n,r,t)).filter(e=>e!==null);return i.length>1?i:[e]}function dr(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 fr(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 pr(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 mr(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 hr(e){return Math.max(48,Math.round(e*.07))}function gr(e){return Math.max(24,Math.round(e*.03))}function _r(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??=vr(t,a),yr(i,e,t,a,r.baseline,r.current))}return i}function vr(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 yr(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 br=2.5;function xr(e){let t=Sr(e);return cr(t.length<=2e3?Tr(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,Math.max(0,e.maxRegions??8)).map((t,n)=>Or(t,n+1,{width:e.baseline.width,height:e.baseline.height,totalPixels:e.totalPixels,differentPixels:e.differentPixels}))}function Sr(e){let{diffMask:t,baseline:n,current:r}=e,{width:i,height:a}=n;return fn({mask:t,width:i,height:a,hooks:{create:e=>Cr(e,i),visit:(e,t)=>wr(e,t,i,n,r)}})}function Cr(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 wr(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 Tr(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=>Er(e,r,t));if(!e){n.push({...r});continue}Dr(e,r)}return n}function Er(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 Dr(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 Or(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=kr(e.baselineRed,e.baselineGreen,e.baselineBlue,e.differentPixels),o=kr(e.currentRed,e.currentGreen,e.currentBlue,e.differentPixels),s=r.width*r.height,c=R(e.differentPixels/s),l=Math.round(L(a)),u=Math.round(L(o)),d=Mr(r,n.width,n.height),f=Nr(s,n.totalPixels),p=jr(a,o),h=Ar(i,n.width,n.height);return{index:t,rect:r,normalizedRect:m({x:R(r.x/n.width),y:R(r.y/n.height),width:R(r.width/n.width),height:R(r.height/n.height)}),differentPixels:e.differentPixels,shareOfDiffPercentage:R(e.differentPixels/n.differentPixels),densityPercentage:c,shape:d,size:f,location:h,averageBaselineColorHex:Pr(a),averageCurrentColorHex:Pr(o),baselineLuminance:l,currentLuminance:u,dominantChange:p}}function kr(e,t,n,r){return{r:Math.round(e/r),g:Math.round(t/r),b:Math.round(n/r)}}function Ar(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 jr(e,t){let n=L(e),r=L(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 Mr(e,t,n){return e.width>=t*.55&&e.height>=n*.12?`large-area`:e.width>=e.height*br?`horizontal-band`:e.height>=e.width*br?`vertical-band`:`compact`}function Nr(e,t){let n=e/t;return n>=.04?`large`:n>=.01?`medium`:`small`}function L(e){return e.r*.2126+e.g*.7152+e.b*.0722}function Pr(e){return`#${Fr(e.r)}${Fr(e.g)}${Fr(e.b)}`}function Fr(e){return e.toString(16).padStart(2,`0`)}function R(e){return Math.round(e*100*100)/100}const Ir=255*Math.sqrt(3);async function Lr(e,t,n={}){await Rr(e,`Baseline image not found`),await Rr(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([j(i,`baseline screenshot`),j(a,`current screenshot`)]);zr(o.width,o.height,`baseline screenshot`,n.maxPixels),zr(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 Br(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*Ir,{diffData:d,diffMask:f,differentPixels:p}=await on({width:o.width,height:o.height,baselineData:o.data,currentData:s.data,maxColorDistance:u}),m=p>0?xr({diffMask:f,baseline:o,current:s,totalPixels:l,differentPixels:p,maxRegions:n.maxRegions}):[];if(p>0&&r){let e=new Ve({width:o.width,height:o.height,data:d});cn(e,m),await T.mkdir(E.dirname(r),{recursive:!0}),await T.writeFile(r,await M(e))}else await Br(n.outputPath);let h=p>0?await Gn({baselinePath:e,currentPath:t,width:o.width,height:o.height}):void 0,g=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,_=p>0&&h?bn({diffMask:f,width:o.width,height:o.height,regions:m,ocr:h}):[],ee=l>0?Math.round(p/l*100*100)/100:0;return{...p>0&&r?{diffPath:r}:{},...m.length>0?{regions:m}:{},...g?{ocr:g}:{},..._.length>0?{nonTextDeltas:_}:{},totalPixels:l,differentPixels:p,mismatchPercentage:ee,match:p===0}}async function Rr(e,t){try{await T.access(e)}catch{throw new n(`INVALID_ARGS`,`${t}: ${e}`)}}function zr(e,t,r,i){if(i==null||i<=0)return;let a=e*t;if(!(a<=i))throw new n(`INVALID_ARGS`,`${r} is ${a} pixels, which exceeds the configured maxImagePixels limit of ${i}`)}async function Br(e){if(e)try{await T.unlink(e)}catch(e){if(!Vr(e,`ENOENT`))throw e}}function Vr(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}function Hr(e,t){return e.map(e=>{let n=Ur(e,t);return n.length>0?{...e,currentOverlayMatches:n}:e})}function Ur(e,t){let n=Wr(e.rect);return t.map(t=>{let r=t.overlayRect,i=Se(e.rect,r);return i<=0?null:{ref:t.ref,...t.label?{label:t.label}:{},rect:r,overlayCoveragePercentage:Gr(i/Wr(r)),regionCoveragePercentage:Gr(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 Wr(e){return e.width*e.height}function Gr(e){return Math.round(e*100*100)/100}async function z(e,t,r){if(t.kind===`path`&&!e.policy.allowLocalInputPaths)throw new n(`INVALID_ARGS`,`Local ${r.field??`input`} paths are not allowed by command policy`);try{return await e.artifacts.resolveInput(t,r)}catch(e){throw i(e)}}async function B(e,t,r){if(t?.kind===`path`&&!e.policy.allowLocalOutputPaths)throw new n(`INVALID_ARGS`,`Local output paths are not allowed by command policy`);try{return await e.artifacts.reserveOutput(t,{...r,visibility:r.visibility??`client-visible`,requestedClientPath:t?.kind===`downloadableArtifact`?t.clientPath??r.requestedClientPath:r.requestedClientPath})}catch(e){throw i(e)}}async function Kr(e,t){try{return await e.artifacts.createTempFile(t)}catch(e){throw i(e)}}const qr=async(e,t)=>{if(!t.baseline)throw new n(`INVALID_ARGS`,`diff screenshot requires a baseline image`);let r=Jr(t.threshold),i=t.current??{kind:`live`};if(t.overlayRefs&&!ti(i))throw new n(`INVALID_ARGS`,`diff screenshot <current.png> cannot use --overlay-refs because saved-image comparisons have no live accessibility refs`);let a=await z(e,t.baseline,{usage:`diff screenshot baseline`,field:`baseline`}),o,s,c,l=[];try{let n;ti(i)?(s=await Yr(e,t),n=s.path):(o=await z(e,i,{usage:`diff screenshot current`,field:`current`}),n=o.path),c=t.out?await B(e,t.out,{field:`diffPath`,ext:`.png`,artifactType:`screenshot-diff`}):void 0;let u=await Lr(a.path,n,{threshold:r,outputPath:c?.path,maxPixels:e.policy.maxImagePixels});ti(i)&&(u=await Xr(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 a.cleanup?.(),await o?.cleanup?.(),await s?.cleanup?.()}};function Jr(e){if(e==null||e===``)return .1;let t=Number(e);if(Number.isNaN(t)||t<0||t>1)throw new n(`INVALID_ARGS`,`--threshold must be a number between 0 and 1`);return t}async function Yr(e,t){let n=await Kr(e,{prefix:`agent-device-diff-current`,ext:`.png`});try{await Zr(e,t,n.path,Qr(t))}catch(e){throw await n.cleanup(),e}return n}async function Xr(e,t,n,r,i){if(!t.overlayRefs)return r;if(r.match||r.dimensionMismatch)return n&&await ei(n),r;let a=await B(e,$r(t,n),{field:`currentOverlayPath`,ext:`.png`,artifactType:`screenshot`});try{let n=await Zr(e,t,a.path,{overlayRefs:!0,...Qr(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:Hr(r.regions,n.overlayRefs)}:{}}}catch(e){throw await a.cleanup?.(),e}}async function Zr(e,t,r,i={}){if(!e.backend.captureScreenshot)throw new n(`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},r,i)??{}}function Qr(e){return{normalizeStatusBar:e.normalizeStatusBar??!0,...e.surface?{surface:e.surface}:{}}}function $r(e,t){if(e.currentOverlayOut)return e.currentOverlayOut;if(e.out?.kind===`path`)return{kind:`path`,path:V(t??e.out.path)};if(e.out?.kind===`downloadableArtifact`)return{kind:`downloadableArtifact`,...e.out.clientPath?{clientPath:V(e.out.clientPath)}:{},...e.out.fileName?{fileName:V(e.out.fileName)}:{}}}function V(e){let t=E.extname(e);return`${t?e.slice(0,-t.length):e}.current-overlay${t||`.png`}`}async function ei(e){try{await T.unlink(V(e))}catch(e){if(!ni(e,`ENOENT`))throw e}}function ti(e){return e.kind===`live`}function ni(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}async function ri(e,t){if(!Number.isInteger(t)||t<1)throw new n(`INVALID_ARGS`,`Screenshot max size must be a positive integer`);let r=await j(await T.readFile(e),`screenshot`),i=Math.max(r.width,r.height);if(i<=t)return;let a=t/i,o=ai(r,Math.max(1,Math.round(r.width*a)),Math.max(1,Math.round(r.height*a)));await T.writeFile(e,await M(o))}async function ii(e,t,r){if(!Number.isInteger(t)||t<1||!Number.isInteger(r)||r<1)throw new n(`INVALID_ARGS`,`Screenshot resize dimensions must be positive integers`);let i=await j(await T.readFile(e),`screenshot`);i.width===t&&i.height===r||await T.writeFile(e,await M(ai(i,t,r)))}function ai(e,t,n){let r=new Ve({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 oi=async(e,t)=>{if(!e.backend.captureScreenshot)throw new n(`UNSUPPORTED_OPERATION`,`screenshot is not supported by this backend`);let r=await B(e,t.out,{field:`path`,ext:`.png`,artifactType:`screenshot`}),i;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},r.path,{fullscreen:t.fullscreen,overlayRefs:t.overlayRefs,pixelDensity:t.pixelDensity,stabilize:t.stabilize,normalizeStatusBar:t.normalizeStatusBar,surface:t.surface}),t.maxSize!==void 0&&await ri(r.path,t.maxSize),i=await r.publish()}catch(e){throw await r.cleanup?.(),e}return{path:r.path,...i?{artifacts:[i]}:{},...w(`Saved screenshot: ${r.path}`)}};function si(e,n){return e.presentationKey?e:{...e,presentationKey:t(n)}}function ci(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||!li(t,n,i)||!t.presentationKey||t.presentationKey!==n.presentationKey||!ui(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 li(e,t,n){return!(e.backend&&t.backend&&e.backend!==t.backend||n?.previousAppBundleId&&n.currentAppBundleId&&n.previousAppBundleId!==n.currentAppBundleId)}function ui(e,t){return e.truncated===t.truncated?JSON.stringify(di(e.nodes))===JSON.stringify(di(t.nodes)):!1}function di(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 fi=async(e,t)=>{let n=await mi(e,t),r=ci({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(gi(t.session,n)),{nodes:n.snapshot.nodes,truncated:n.snapshot.truncated??!1,visibility:Wt({nodes:n.snapshot.nodes,backend:n.snapshot.backend,snapshotRaw:t.raw}),...ge({...n.annotations,warnings:n.warnings}),...r?{unchanged:r}:{},...n.result.snapshotDiagnostics?{snapshotDiagnostics:n.result.snapshotDiagnostics}:{},..._i(n)}},pi=async(e,t)=>{let n=await mi(e,t),r=t.interactiveOnly===!0,i=n.session?.snapshot,a=gi(t.session,n);if(!i){let t=ne(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=me(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 mi(e,t){if(!e.backend.captureSnapshot)throw new n(`UNSUPPORTED_OPERATION`,`snapshot is not supported by this backend`);let r=t.session??`default`,i=await e.sessions.get(r),a=await e.backend.captureSnapshot({session:r,requestId:t.requestId,appId:i?.appId,appBundleId:i?.appBundleId,signal:t.signal??e.signal,metadata:t.metadata},{interactiveOnly:t.interactiveOnly,depth:t.depth,scope:t.scope,raw:t.raw}),o=si(hi(a,e),t),s=pe(a),c=b(e);return{snapshot:o,result:a,session:i,annotations:s,warnings:vi({result:a,annotations:s,snapshot:o,options:t,session:i,capturedAt:o.createdAt??c,runtimeNow:c})}}function hi(e,t){return e.snapshot?e.snapshot:{nodes:e.nodes??[],truncated:e.truncated,backend:e.backend,createdAt:b(t)}}function gi(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 _i(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 vi(e){let t=[...e.annotations.warnings??[]];e.annotations.quality&&t.push(...Ae(e.annotations.quality,e.snapshot.nodes)),t.push(...xi(e)),e.annotations.quality||(t.push(...yi(e)),t.push(...bi(e.snapshot.nodes)));let n=Si(e.annotations.androidSnapshot);n&&t.push(n);let r=et(e.snapshot.nodes);r&&t.push(r);let i=Ci(e);return i&&t.push(i),t.push(...Di(e.annotations.freshness,e.snapshot.backend)),Array.from(new Set(t))}function yi(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 bi(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 xi(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 Si(e){if(e?.backend===`uiautomator-dump`)return`Android snapshot helper unavailable; using stock UIAutomator dump, which can time out on busy React Native UIs.${e.fallbackReason?` Reason: ${e.fallbackReason}`:``}`}function Ci(e){let t=e.session?.snapshot;if(!e.annotations.freshness&&t&&wi(t,e.snapshot)&&Ti(t,e.capturedAt,e.runtimeNow)&&Oi(t.nodes.length,e.snapshot.nodes.length))return Ei}function wi(e,t){return e.presentationKey===void 0||t.presentationKey===void 0?!0:e.presentationKey===t.presentationKey}function Ti(e,t,n){return[t,n].some(t=>{let n=t-e.createdAt;return n>=0&&n<=2e3})}const Ei=`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 Di(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`?[Ei]:[]}function Oi(e,t){return e<12?!1:t<=Math.floor(e*.2)}const H={screenshot:oi,diffScreenshot:qr,snapshot:fi,diffSnapshot:pi};function ki(e){return{screenshot:t=>H.screenshot(e,t),diffScreenshot:t=>H.diffScreenshot(e,t),snapshot:t=>H.snapshot(e,t),diffSnapshot:t=>H.diffSnapshot(e,t)}}const Ai=async(e,t)=>await Pi(e,t,`press`),ji=async(e,t)=>await Pi(e,t,`click`),Mi=async(e,t)=>{if(!t.text)throw new n(`INVALID_ARGS`,`fill requires text`);let r=h(t),i=r.needsPreActionBaseline?null:await Li(e,t);if(i)return i;let a=await ae(e,t,{action:`fill`,requireInteractive:!0,promoteToHittableAncestor:!1,captureEvidenceBaseline:r.needsPreActionBaseline});if(!e.backend.fill)throw new n(`UNSUPPORTED_OPERATION`,`fill is not supported by this backend`);let o=Fi(a),s=x(await e.backend.fill(v(e,t),o,t.text,{delayMs:t.delayMs})),c=`node`in a?a.node?.type??``:``,l=c&&!Ce(c,e.backend.platform)?`fill target ${zi(a)} resolved to "${c}", attempting fill anyway.`:void 0;return await se(e,t,a,{...a,text:t.text,...l?{warning:l}:{},...s?{backendResult:s}:{}},r)},Ni=async(e,t)=>{let r=t.text;if(!r)throw new n(`INVALID_ARGS`,`type requires text`);let i=Bi(r);if(i)throw new n(`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 n(`UNSUPPORTED_OPERATION`,`type is not supported by this backend`);let a=C(t.delayMs??0,`delay-ms`,0,1e4),o=x(await e.backend.typeText(v(e,t),r,{delayMs:a}));return{kind:`text`,text:r,delayMs:a,...o?{backendResult:o}:{},...w(`Typed ${Array.from(r).length} chars`)}};async function Pi(e,t,r){let i=h(t),a=i.needsPreActionBaseline?null:await Ii(e,t,r);if(a)return a;let o=await ae(e,t,{action:r,requireInteractive:!0,promoteToHittableAncestor:!0,captureEvidenceBaseline:i.needsPreActionBaseline});if(!e.backend.tap)throw new n(`UNSUPPORTED_OPERATION`,`tap is not supported by this backend`);let s=Fi(o),c=x(await e.backend.tap(v(e,t),s,{button:t.button,count:t.count,intervalMs:t.intervalMs,holdMs:t.holdMs,jitterPx:t.jitterPx,doubleTap:t.doubleTap}));return await se(e,t,o,{...o,...c?{backendResult:c}:{}},i)}function Fi(e){if(!e.point)throw new n(`COMMAND_FAILED`,`Interaction target resolved without coordinates`);return e.point}async function Ii(e,t,n){if(n!==`click`||t.target.kind!==`ref`||!e.backend.tapTarget||Ri(t))return null;let r=await re(e,t,t.target,n),i=x(await e.backend.tapTarget(v(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},...r,...i?{backendResult:i}:{}}}async function Li(e,t){if(t.target.kind!==`ref`||!e.backend.fillTarget)return null;let n=await re(e,t,t.target,`fill`),r=x(await e.backend.fillTarget(v(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,...n,...r?{backendResult:r}:{}}}function Ri(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 Bi(e){return Ut(e)}function Vi(e){return{includeRects:Hi(e.predicate),interactiveOnly:!1}}function Hi(e){return e===`visible`||e===`hidden`}const Ui=1e4,Wi=async(e,t)=>{let r=t.locator??`any`;if(!t.query)throw new n(`INVALID_ARGS`,`find requires a value`);if(t.action===`wait`)return await $i(e,t,r);let{capture:i,match:a}=await ea(e,t,r);if(!a)throw new n(`COMMAND_FAILED`,`find did not match any element`);if(t.action===`exists`)return{kind:`found`,found:!0};let o=`@${a.ref}`;return t.action===`get_attrs`?{kind:`attrs`,ref:o,node:a}:{kind:`text`,ref:o,text:await g(e,i,a),node:a}},Gi=async(e,t)=>{if(t.target.kind===`ref`){let n=await ie(e,t.session),r=he(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`}),i=Re(r.node,e.backend.platform,{action:`get`}),a={kind:`ref`,ref:`@${r.ref}`};return t.property===`attrs`?{kind:`attrs`,target:a,node:r.node,selectorChain:i}:{kind:`text`,target:a,text:await g(e,n,r.node),node:r.node,selectorChain:i}}let n=await sa(e,t,t.session??`default`,{selector:t.target.selector,disambiguateAmbiguous:t.property===`text`}),r=Re(n.node,e.backend.platform,{action:`get`});if(t.property===`attrs`)return{kind:`attrs`,target:{kind:`selector`,selector:n.selector},node:n.node,selectorChain:r};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}},Ki=async(e,t)=>{let r=await Gi(e,{...t,property:`text`,target:t.target});if(r.kind!==`text`)throw new n(`COMMAND_FAILED`,`getText returned non-text result`);return r},qi=async(e,t)=>{let r=await Gi(e,{...t,property:`attrs`,target:t.target});if(r.kind!==`attrs`)throw new n(`COMMAND_FAILED`,`getAttrs returned non-attrs result`);return r},Ji=async(e,t)=>{if(!we(t.predicate))throw new n(`INVALID_ARGS`,Oe);if(t.predicate===`text`&&!t.expectedText)throw new n(`INVALID_ARGS`,`is text requires expected text value`);let r=f(t.selector),i=await _(e,t,{updateSession:!0,...Vi({predicate:t.predicate,selectorChain:r})});if(t.predicate===`exists`){let a=Le(i.snapshot.nodes,r,{platform:e.backend.platform});if(!a)throw new n(`COMMAND_FAILED`,Fe(r,[],{unique:!1}),{hint:Ie([])});return{predicate:t.predicate,pass:!0,selector:a.selector.raw,matches:a.matches,selectorChain:r.selectors.map(e=>e.raw)}}let a=Pe(i.snapshot.nodes,r,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:!1});if(!a)throw new n(`COMMAND_FAILED`,Fe(r,[],{unique:!0}),{command:`is`,reason:`selector_not_found`,predicate:t.predicate,selector:r.raw,hint:Ie([])});let o=Ee({predicate:t.predicate,node:a.node,nodes:i.snapshot.nodes,expectedText:t.expectedText,platform:e.backend.platform});if(!o.pass)throw new n(`COMMAND_FAILED`,`is ${t.predicate} failed for selector ${a.selector.raw}: ${o.details}`,{command:`is`,reason:`predicate_failed`,predicate:t.predicate,selector:a.selector.raw,predicateDetails:o.details});return{predicate:t.predicate,pass:!0,selector:a.selector.raw,...t.predicate===`text`?{text:o.actualText}:{},selectorChain:r.selectors.map(e=>e.raw)}},Yi=async(e,t)=>await Ji(e,{...t,predicate:`visible`,selector:t.target.selector}),Xi=async(e,t)=>await Ji(e,{...t,predicate:`hidden`,selector:t.target.selector}),Zi=async(e,t)=>{if(t.target.kind===`sleep`)return await S(e,t.target.durationMs),{kind:`sleep`,waitedMs:t.target.durationMs};if(t.target.kind===`ref`){let r=await ie(e,t.session),i=s(t.target.ref);if(!i)throw new n(`INVALID_ARGS`,`Invalid ref: ${t.target.ref}`);let a=c(r.snapshot.nodes,i),o=a?ke(a,r.snapshot.nodes):void 0;if(!o)throw new n(`COMMAND_FAILED`,`Ref ${t.target.ref} not found or has no label`);return await ia(e,t,o,t.target.timeoutMs)}if(t.target.kind===`selector`)return await ra(e,t,t.target.selector,t.target.timeoutMs);if(t.target.kind===`stable`)return await oa(e,t,t.target.quietMs,t.target.timeoutMs);if(!t.target.text)throw new n(`INVALID_ARGS`,`wait requires text`);return await ia(e,t,t.target.text,t.target.timeoutMs)},Qi=async(e,t)=>{let r=await Zi(e,{...t,target:{kind:`text`,text:t.text,timeoutMs:t.timeoutMs}});if(r.kind!==`text`)throw new n(`COMMAND_FAILED`,`waitForText returned non-text result`);return r};async function $i(e,t,r){let i=t.timeoutMs??Ui,a=b(e);for(;b(e)-a<i;){let{match:n}=await ea(e,t,r);if(n)return{kind:`found`,found:!0,waitedMs:b(e)-a};await S(e,300)}throw new n(`COMMAND_FAILED`,`find wait timed out`)}async function ea(e,t,n){let r=Me(n,t.query),i=await _(e,t,{updateSession:!0,scope:ta(e,n,t.query,r),...Vi({selectorChain:r})});if(je(i.snapshot.snapshotQuality))throw na(i.snapshot.snapshotQuality);return r?{capture:i,match:Pe(i.snapshot.nodes,r,{platform:e.backend.platform,requireRect:!1,requireUnique:!1})?.node}:{capture:i,match:Ne(i.snapshot.nodes,n,t.query,{requireRect:!1}).matches[0]}}function ta(e,t,n,r){if(!r&&e.backend.platform!==`web`)return p(t)?n:void 0}function na(e){return new n(`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 ra(e,t,r,i){let a=i??Ui,o=b(e),s=f(r),c=Vi({selectorChain:s});for(;b(e)-o<a;){let n=Le((await _(e,t,{updateSession:!0,...c})).snapshot.nodes,s,{platform:e.backend.platform});if(n)return{kind:`selector`,selector:n.selector.raw,waitedMs:b(e)-o};await S(e,300)}throw new n(`COMMAND_FAILED`,`wait timed out for selector: ${r}`)}async function ia(e,t,r,i){let a=i??Ui,o=b(e);for(;b(e)-o<a;){if(e.backend.findText?(await e.backend.findText(v(e,t),r)).found:await aa(e,t,r))return{kind:`text`,text:r,waitedMs:b(e)-o};await S(e,300)}throw new n(`COMMAND_FAILED`,`wait timed out for text: ${r}`)}async function aa(e,t,n){return!!De((await _(e,t,{updateSession:!0})).snapshot.nodes,n)}async function oa(e,t,r,i){let a=i??Ui,o=r??500,s=await ce(e,t,{quietMs:o,timeoutMs:a});if(!s.settled)throw new n(`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:ye}:{}}}async function sa(e,t,r,i){let a=f(i.selector),o=await _(e,{...t,session:r},{updateSession:!0,...Vi({selectorChain:a})}),s=Pe(o.snapshot.nodes,a,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:i.disambiguateAmbiguous});if(!s)throw new n(`COMMAND_FAILED`,Fe(a,[],{unique:!0}),{hint:Ie([])});return{capture:o,node:s.node,selector:s.selector.raw,ref:`@${s.node.ref}`}}const U={find:Wi,get:Gi,getText:Ki,getAttrs:qi,is:Ji,isVisible:Yi,isHidden:Xi,wait:Zi,waitForText:Qi},W={click:ji,press:Ai,fill:Mi,typeText:Ni,focus:ue,longPress:ve,swipe:be,scroll:de,pinch:xe};function ca(e){return{find:t=>U.find(e,t),get:t=>U.get(e,t),getText:(t,n={})=>U.getText(e,{...n,target:t}),getAttrs:(t,n={})=>U.getAttrs(e,{...n,target:t}),is:t=>U.is(e,t),isVisible:(t,n={})=>U.isVisible(e,{...n,target:t}),isHidden:(t,n={})=>U.isHidden(e,{...n,target:t}),wait:t=>U.wait(e,t),waitForText:(t,n={})=>U.waitForText(e,{...n,text:t})}}function la(e){return{click:(t,n={})=>W.click(e,{...n,target:t}),press:(t,n={})=>W.press(e,{...n,target:t}),fill:(t,n,r={})=>W.fill(e,{...r,target:t,text:n}),typeText:(t,n={})=>W.typeText(e,{...n,text:t}),focus:(t,n={})=>W.focus(e,{...n,target:t}),longPress:(t,n={})=>W.longPress(e,{...n,target:t}),swipe:t=>W.swipe(e,t),scroll:t=>W.scroll(e,t),pinch:t=>W.pinch(e,t)}}function G(e,t){if(e!==void 0)return K(e,t)}function K(e,t){let r=e?.trim();if(!r)throw new n(`INVALID_ARGS`,`${t} must be a non-empty string`);return r}const ua=async(e,t={})=>{if(!e.backend.listDevices)throw new n(`UNSUPPORTED_OPERATION`,`admin.devices is not supported by this backend`);return{kind:`adminDevices`,devices:await e.backend.listDevices(v(e,t),t.filter)}},da=async(e,t={})=>{if(!e.backend.bootDevice)throw new n(`UNSUPPORTED_OPERATION`,`admin.boot is not supported by this backend`);let r=xa(t.target),i=x(await e.backend.bootDevice(v(e,t),r));return{kind:`deviceBooted`,...r?{target:r}:{},...i?{backendResult:i}:{},...w(`Booted device`)}},fa=async(e,t={})=>{if(!e.backend.shutdownDevice)throw new n(`UNSUPPORTED_OPERATION`,`admin.shutdown is not supported by this backend`);let r=xa(t.target),i=x(await e.backend.shutdownDevice(v(e,t),r));return{kind:`deviceShutdown`,...r?{target:r}:{},...i?{backendResult:i}:{},...w(`Shutdown device`)}},pa=async(e,t)=>await ga(e,t,`install`),ma=async(e,t)=>await ga(e,t,`reinstall`),ha=async(e,t)=>await ga(e,t,`installFromSource`);async function ga(e,t,r){let i=r===`reinstall`?`reinstallApp`:`installApp`,a=e.backend[i];if(!a)throw new n(`UNSUPPORTED_OPERATION`,`admin.${r} is not supported by this backend`);let o=`app`in t&&t.app!==void 0?K(t.app,`app`):void 0;if(r!==`installFromSource`&&!o)throw new n(`INVALID_ARGS`,`admin.${r} requires app`);let s=v(e,t),c=await _a(e,s,t.source);try{let t=await a.call(e.backend,s,{...o?{app:o}:{},source:c.source});return Sa(r,o,c.source,t)}finally{await c.cleanup?.()}}async function _a(e,t,n){let r=await va(e,ya(n));try{return{source:ya(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 va(e,t){if(t.kind===`url`)return{source:t};let n=await z(e,t,{usage:`admin.install`,field:`source`});return{source:{kind:`path`,path:n.path},...n.cleanup?{cleanup:n.cleanup}:{}}}function ya(e){if(!e||typeof e!=`object`)throw new n(`INVALID_ARGS`,`install source is required`);if(e.kind===`path`)return{kind:`path`,path:K(e.path,`source.path`)};if(e.kind===`uploadedArtifact`)return{kind:`uploadedArtifact`,id:K(e.id,`source.id`)};if(e.kind===`url`){let t=K(e.url,`source.url`);return ba(t),{kind:`url`,url:t}}throw new n(`INVALID_ARGS`,`install source kind must be path, uploadedArtifact, or url`)}function ba(e){let t;try{t=new URL(e)}catch{throw new n(`INVALID_ARGS`,`Invalid install source URL: ${e}`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new n(`INVALID_ARGS`,`Install source URL must use http or https`)}function xa(e){if(!e)return;let t=G(e.id,`target.id`),n=G(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 Sa(e,t,n,r){let i=x(r),a=e===`reinstall`?`appReinstalled`:e===`installFromSource`?`appInstalledFromSource`:`appInstalled`,o=q(r,`appName`),s=q(r,`appId`),c=q(r,`bundleId`),l=q(r,`packageName`),u=q(r,`launchTarget`),d=q(r,`installablePath`),f=q(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}:{},...w(`${e===`reinstall`?`Reinstalled`:`Installed`}: ${o??u??t??Ca(n)}`)}}function q(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Ca(e){return e.kind===`path`?e.path:e.kind===`uploadedArtifact`?e.id:e.url}const wa=/^[A-Za-z0-9_.:-]{1,64}$/,Ta=async(e,t)=>{if(!e.backend.openApp)throw new n(`UNSUPPORTED_OPERATION`,`apps.open is not supported by this backend`);let r=ja(t),i=x(await e.backend.openApp(J(e,t),r,{launchArgs:t.launchArgs,relaunch:t.relaunch}));return{kind:`appOpened`,target:r,relaunch:t.relaunch===!0,...i?{backendResult:i}:{},...w(`Opened: ${Na(r)}`)}},Ea=async(e,t={})=>{if(!e.backend.closeApp)throw new n(`UNSUPPORTED_OPERATION`,`apps.close is not supported by this backend`);let r=G(t.app,`app`),i=x(await e.backend.closeApp(J(e,t),r));return{kind:`appClosed`,...r?{app:r}:{},...i?{backendResult:i}:{},...w(r?`Closed: ${r}`:`Closed app`)}},Da=async(e,t={})=>{if(!e.backend.listApps)throw new n(`UNSUPPORTED_OPERATION`,`apps.list is not supported by this backend`);return{kind:`appsList`,apps:await e.backend.listApps(J(e,t),ze(t.filter))}},Oa=async(e,t)=>{if(!e.backend.getAppState)throw new n(`UNSUPPORTED_OPERATION`,`apps.state is not supported by this backend`);let r=K(t.app,`app`);return{kind:`appState`,app:r,state:await e.backend.getAppState(J(e,t),r)}},ka=async(e,t)=>{if(!e.backend.pushFile)throw new n(`UNSUPPORTED_OPERATION`,`apps.push is not supported by this backend`);let r=K(t.app,`app`),i=await Pa(e,t.input);try{let n=x(await e.backend.pushFile(J(e,t),i.backendInput,r));return{kind:`appPushed`,app:r,inputKind:i.inputKind,...n?{backendResult:n}:{},...w(`Pushed to ${r}`)}}finally{await i.cleanup?.()}},Aa=async(e,t)=>{if(!e.backend.triggerAppEvent)throw new n(`UNSUPPORTED_OPERATION`,`apps.triggerEvent is not supported by this backend`);let r=Fa(t.name);Ia(t.payload,`apps.triggerEvent payload for "${r}"`);let i=x(await e.backend.triggerAppEvent(J(e,t),{name:r,...t.payload?{payload:t.payload}:{}}));return{kind:`appEventTriggered`,name:r,...t.payload?{payload:t.payload}:{},...i?{backendResult:i}:{},...w(`Triggered app event: ${r}`)}};function ja(e){let t=G(e.app,`app`),r=G(e.appId,`appId`),i=G(e.bundleId,`bundleId`),a=G(e.packageName,`packageName`),o=G(e.url,`url`),s=G(e.activity,`activity`),c={...t?{app:t}:{},...r?{appId:r}:{},...i?{bundleId:i}:{},...a?{packageName:a}:{},...o?{url:o}:{},...s?{activity:s}:{}};if(!Ma(c))throw new n(`INVALID_ARGS`,`apps.open requires app, appId, bundleId, packageName, url, or activity`);return c}function Ma(e){return!!(e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity)}function Na(e){return e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity??`app`}async function Pa(e,t){if(!t||typeof t!=`object`)throw new n(`INVALID_ARGS`,`apps.push requires an input`);if(t.kind===`json`)return La(t.payload,`apps.push JSON payload`,8192),{backendInput:{kind:`json`,payload:t.payload},inputKind:`json`};let r=await z(e,t,{usage:`apps.push`,field:`input`});return{backendInput:{kind:`file`,path:r.path},inputKind:`file`,...r.cleanup?{cleanup:r.cleanup}:{}}}function Fa(e){let t=K(e,`name`);if(!wa.test(t))throw new n(`INVALID_ARGS`,`Invalid apps.triggerEvent name: ${t}`,{hint:`Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash.`});return t}function Ia(e,t){e!==void 0&&La(e,t,8192)}function La(e,t,r){if(Ra(e,t),Buffer.byteLength(za(e,t),`utf8`)>r)throw new n(`INVALID_ARGS`,`${t} exceeds ${r} bytes`)}function Ra(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`${t} must be a JSON object`)}function za(e,t){try{let r=JSON.stringify(e);if(typeof r!=`string`)throw new n(`INVALID_ARGS`,`${t} must be JSON-serializable`);return r}catch{throw new n(`INVALID_ARGS`,`${t} must be JSON-serializable`)}}function J(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}const Y={open:Ta,close:Ea,list:Da,state:Oa,push:ka,triggerEvent:Aa},X={devices:ua,boot:da,shutdown:fa,install:pa,reinstall:ma,installFromSource:ha};function Ba(e){return{open:t=>Y.open(e,t),close:t=>Y.close(e,t),list:(t={})=>Y.list(e,{...t,filter:Be(t.filter)}),state:t=>Y.state(e,t),push:t=>Y.push(e,t),triggerEvent:t=>Y.triggerEvent(e,t)}}function Va(e){return{devices:t=>X.devices(e,t),boot:t=>X.boot(e,t),shutdown:t=>X.shutdown(e,t),install:t=>X.install(e,t),reinstall:t=>X.reinstall(e,t),installFromSource:t=>X.installFromSource(e,t)}}const Ha=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i,Ua=/\b[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g;function Wa(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(Ua,()=>(t=!0,`[REDACTED]`)),n=Ka(n,()=>{t=!0}),{value:n,redacted:t}}function Ga(e){try{let t=new URL(e),n=qa(t);return(t.username||t.password)&&(t.username=`REDACTED`,t.password=`REDACTED`,n=!0),{value:t.toString(),redacted:n}}catch{return}}function Ka(e,t){return/(https?:\/\/|token|secret|password|authorization|cookie|api[-_]?key)/i.test(e)?e.replaceAll(/https?:\/\/[^\s"'<>)]+/gi,e=>{let n=Ga(e);return n?(n.redacted&&t(),n.value):e}):e}function qa(e){let t=!1;for(let n of Array.from(e.searchParams.keys()))Ha.test(n)&&(e.searchParams.set(n,`[REDACTED]`),t=!0);return t}const Z=2048,Ja=4096,Ya=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i;function Xa(e){let t=e.redacted===!0;return{kind:`diagnosticsLogs`,entries:e.entries.map(e=>{let n=Q(e.message,Ja),r=ro(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 Za(e,t){let n=e.redacted===!0;return{kind:`diagnosticsNetwork`,entries:e.entries.map(e=>{let r=e.url?eo(e.url):void 0,i=t===`headers`||t===`all`?$a(e.requestHeaders):void 0,a=t===`headers`||t===`all`?$a(e.responseHeaders):void 0,o=t===`body`||t===`all`?to(e.requestBody):void 0,s=t===`body`||t===`all`?to(e.responseBody):void 0,c=ro(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 Qa(e){let t=e.redacted===!0;return{kind:`diagnosticsPerf`,metrics:e.metrics.map(e=>{let n=Q(e.message,Ja),r=ro(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 $a(e){if(!e)return{redacted:!1};let t=!1,n={};for(let[r,i]of Object.entries(e))if(Ya.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 eo(e){return Ga(e)??Q(e,Z)}function to(e){return e===void 0?{redacted:!1}:no(e)??Q(e,Z)}function no(e){try{let t=io(JSON.parse(e),Wa);return ao(JSON.stringify(t.value),Z,t.redacted)}catch{return}}function ro(e){return io(e,e=>Q(e,Z))}function io(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=io(e,t);return n||=r.redacted,r.value}),redacted:n}}let n=!1,r={};for(let[i,a]of Object.entries(e)){if(Ya.test(i)){r[i]=`[REDACTED]`,n=!0;continue}let e=io(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=Wa(e);return ao(n.value,t,n.redacted)}function ao(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,t={})=>{if(!e.backend.readLogs)throw new n(`UNSUPPORTED_OPERATION`,`diagnostics.logs is not supported by this backend`);return Xa(await e.backend.readLogs(await lo(e,t),uo(t)))},so=async(e,t={})=>{if(!e.backend.dumpNetwork)throw new n(`UNSUPPORTED_OPERATION`,`diagnostics.network is not supported by this backend`);let r=fo(t);return Za(await e.backend.dumpNetwork(await lo(e,t),r),r.include??`summary`)},co=async(e,t={})=>{if(!e.backend.measurePerf)throw new n(`UNSUPPORTED_OPERATION`,`diagnostics.perf is not supported by this backend`);return Qa(await e.backend.measurePerf(await lo(e,t),po(t)))};async function lo(e,t){let n=v(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 uo(e){return{...mo(e,100,500,`logs limit`),...e.levels===void 0?{}:{levels:_o(e.levels,`levels`)},...e.search===void 0?{}:{search:K(e.search,`search`)},...e.source===void 0?{}:{source:K(e.source,`source`)}}}function fo(e){return{...mo(e,25,200,`network limit`),include:go(e.include)}}function po(e){return{...ho(e),...e.sampleMs===void 0?{}:{sampleMs:C(e.sampleMs,`sampleMs`,100,6e4)},...e.metrics===void 0?{}:{metrics:_o(e.metrics,`metrics`,20)}}}function mo(e,t,n,r){return{...ho(e),...e.cursor===void 0?{}:{cursor:K(e.cursor,`cursor`)},limit:e.limit===void 0?t:C(e.limit,r,1,n)}}function ho(e){return{...e.since===void 0?{}:{since:K(e.since,`since`)},...e.until===void 0?{}:{until:K(e.until,`until`)}}}function go(e){if(e===void 0)return`summary`;if(e===`summary`||e===`headers`||e===`body`||e===`all`)return e;throw new n(`INVALID_ARGS`,`network include must be summary, headers, body, or all`)}function _o(e,t,r=50){if(!Array.isArray(e))throw new n(`INVALID_ARGS`,`${t} must be an array of strings`);if(e.length>r)throw new n(`INVALID_ARGS`,`${t} must contain at most ${r} entries`);return e.map((e,n)=>K(e,`${t}[${n}]`))}const vo={logs:oo,network:so,perf:co};function yo(e){return{logs:t=>vo.logs(e,t),network:t=>vo.network(e,t),perf:t=>vo.perf(e,t)}}const bo=async(e,t)=>{let r=Eo(t.action,`record`),i=r===`start`?e.backend.startRecording:e.backend.stopRecording;if(!i)throw new n(`UNSUPPORTED_OPERATION`,`record ${r} is not supported by this backend`);let a=t.out?await B(e,t.out,{field:`path`,ext:`.mp4`,artifactType:`screen-recording`}):void 0;try{let n=So(t,a?.path);return Do(r,await i.call(e.backend,v(e,t),n),await a?.publish())}catch(e){throw await a?.cleanup?.(),e}},xo=async(e,t)=>{let r=Eo(t.action,`trace`),i=r===`start`?e.backend.startTrace:e.backend.stopTrace;if(!i)throw new n(`UNSUPPORTED_OPERATION`,`trace ${r} is not supported by this backend`);let a=t.out?await B(e,t.out,{field:`outPath`,ext:`.trace`,artifactType:`trace-log`}):void 0;try{let n={...a?.path?{outPath:a.path}:{}};return Oo(r,await i.call(e.backend,v(e,t),n),await a?.publish())}catch(e){throw await a?.cleanup?.(),e}};function So(e,t){let n={};t&&(n.outPath=t);let r=Co(e.fps);r!==void 0&&(n.fps=r);let i=wo(e.maxSize);i!==void 0&&(n.maxSize=i);let a=To(e.quality);return a!==void 0&&(n.quality=a),e.hideTouches!==void 0&&(n.showTouches=e.hideTouches!==!0),n}function Co(e){return e===void 0?void 0:C(e,`fps`,1,60)}function wo(e){return e===void 0?void 0:C(e,`maxSize`,1,2**53-1)}function To(e){if(e===void 0)return;let t=fe(e);if(t===void 0)throw new n(`INVALID_ARGS`,`quality must be one of: medium, high (legacy numeric values 5-10 are accepted)`);return t}function Eo(e,t){if(e===`start`||e===`stop`)return e;throw new n(`INVALID_ARGS`,`${t} action must be start or stop`)}function Do(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}:{},...ko(e,t,n,{startKind:`recordingStarted`,stopKind:`recordingStopped`,startMessage:`Recording started`,stopMessage:`Recording stopped`})}}function Oo(e,t,n){return{...typeof t.outPath==`string`?{outPath:t.outPath}:{},...ko(e,t,n,{startKind:`traceStarted`,stopKind:`traceStopped`,startMessage:`Trace started`,stopMessage:`Trace stopped`})}}function ko(e,t,n,r){return{kind:e===`start`?r.startKind:r.stopKind,action:e,...n?{artifact:n}:{},backendResult:t,...w(e===`start`?r.startMessage:r.stopMessage)}}const Ao={record:bo,trace:xo};function jo(e){return{record:t=>Ao.record(e,t),trace:t=>Ao.trace(e,t)}}const Mo=async(e,t={})=>{if(!e.backend.pressBack)throw new n(`UNSUPPORTED_OPERATION`,`system.back is not supported by this backend`);let r=t.mode??`in-app`;if(r!==`in-app`&&r!==`system`)throw new n(`INVALID_ARGS`,`system.back mode must be in-app or system`);let i=x(await e.backend.pressBack(v(e,t),{mode:r}));return{kind:`systemBack`,mode:r,...i?{backendResult:i}:{},...w(`Back`)}},No=async(e,t={})=>{if(!e.backend.pressHome)throw new n(`UNSUPPORTED_OPERATION`,`system.home is not supported by this backend`);let r=x(await e.backend.pressHome(v(e,t)));return{kind:`systemHome`,...r?{backendResult:r}:{},...w(`Home`)}},Po=async(e,t)=>{if(!e.backend.pressTvRemote)throw new n(`UNSUPPORTED_OPERATION`,`system.tvRemote is not supported by this backend`);let r=_e(t.button),i=t.durationMs===void 0?void 0:C(t.durationMs,`durationMs`,0,1e4),a=x(await e.backend.pressTvRemote(v(e,t),{button:r,...i===void 0?{}:{durationMs:i}}));return{kind:`tvRemotePressed`,button:r,...i===void 0?{}:{durationMs:i},...a?{backendResult:a}:{},...w(`Pressed TV remote ${r}`)}},Fo=async(e,t)=>{if(!e.backend.rotate)throw new n(`UNSUPPORTED_OPERATION`,`system.rotate is not supported by this backend`);let r=Vo(t.orientation),i=x(await e.backend.rotate(v(e,t),r));return{kind:`systemRotated`,orientation:r,...i?{backendResult:i}:{},...w(`Rotated to ${r}`)}},Io=async(e,t={})=>{if(!e.backend.setKeyboard)throw new n(`UNSUPPORTED_OPERATION`,`system.keyboard is not supported by this backend`);let r=t.action??`status`;if(!Ht(r))throw new n(`INVALID_ARGS`,`system.keyboard action must be status, get, dismiss, enter, or return`);let i=await e.backend.setKeyboard(v(e,t),{action:r}),a=x(i),o=Yo(i)?i:{};return r===`enter`||r===`return`?Uo(o,a):r===`dismiss`?Wo(r,o,a):Go(r,o,a)},Lo=async(e,t)=>{if(t.action===`read`){if(!e.backend.getClipboard)throw new n(`UNSUPPORTED_OPERATION`,`system.clipboard read is not supported by this backend`);let r=await e.backend.getClipboard(v(e,t));return{kind:`clipboardText`,action:`read`,text:typeof r==`string`?r:r.text}}if(t.action!==`write`)throw new n(`INVALID_ARGS`,`system.clipboard action must be read or write`);if(!e.backend.setClipboard)throw new n(`UNSUPPORTED_OPERATION`,`system.clipboard write is not supported by this backend`);if(typeof t.text!=`string`)throw new n(`INVALID_ARGS`,`system.clipboard write requires text`);let r=x(await e.backend.setClipboard(v(e,t),t.text));return{kind:`clipboardUpdated`,action:`write`,textLength:Array.from(t.text).length,...r?{backendResult:r}:{},...w(`Clipboard updated`)}},Ro=async(e,t={})=>{if(!e.backend.openSettings)throw new n(`UNSUPPORTED_OPERATION`,`system.settings is not supported by this backend`);let r=G(t.target,`target`),i=x(await e.backend.openSettings(v(e,t),r));return{kind:`settingsOpened`,...r?{target:r}:{},...i?{backendResult:i}:{},...w(r?`Opened settings: ${r}`:`Opened settings`)}},zo=async(e,t={})=>{if(!e.backend.handleAlert)throw new n(`UNSUPPORTED_OPERATION`,`system.alert is not supported by this backend`);let r=t.action??`get`;if(r!==`get`&&r!==`accept`&&r!==`dismiss`&&r!==`wait`)throw new n(`INVALID_ARGS`,`system.alert action must be get, accept, dismiss, or wait`);let i=t.timeoutMs===void 0?void 0:C(t.timeoutMs,`timeoutMs`,0,12e4);return Ho(r,await e.backend.handleAlert(v(e,t),r,{timeoutMs:i}))},Bo=async(e,t={})=>{if(!e.backend.openAppSwitcher)throw new n(`UNSUPPORTED_OPERATION`,`system.appSwitcher is not supported by this backend`);let r=x(await e.backend.openAppSwitcher(v(e,t)));return{kind:`appSwitcherOpened`,...r?{backendResult:r}:{},...w(`Opened app switcher`)}};function Vo(e){switch(e){case`portrait`:case`portrait-upside-down`:case`landscape-left`:case`landscape-right`:return e;default:throw new n(`INVALID_ARGS`,`system.rotate orientation must be portrait, portrait-upside-down, landscape-left, or landscape-right`)}}function Ho(e,t){return e===`get`?Ko(t):e===`wait`?qo(t):Jo(e,t)}function Uo(e,t){return{kind:`keyboardEnterPressed`,action:`enter`,state:e,...t?{backendResult:t}:{},...w(`Keyboard enter pressed`)}}function Wo(e,t,n){return{kind:`keyboardDismissed`,action:e,state:t,...n?{backendResult:n}:{},...w(t.dismissed===!1?`Keyboard already hidden`:`Keyboard dismissed`)}}function Go(e,t,n){return{kind:`keyboardState`,action:e,state:t,...n?{backendResult:n}:{}}}function Ko(e){if(e.kind!==`alertStatus`)throw new n(`COMMAND_FAILED`,`system.alert get returned an invalid backend result`);return{kind:`alertStatus`,action:`get`,alert:e.alert}}function qo(e){if(e.kind!==`alertWait`)throw new n(`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},...w(e.alert?`Alert visible`:`Alert wait timed out`)}}function Jo(e,t){if(t.kind!==`alertHandled`)throw new n(`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}:{},...w(t.handled?`Alert ${e}ed`:`No alert handled`)}}function Yo(e){return!!(e&&typeof e==`object`)}const $={back:Mo,home:No,rotate:Fo,keyboard:Io,clipboard:Lo,settings:Ro,alert:zo,appSwitcher:Bo,tvRemote:Po};function Xo(e){return{back:t=>$.back(e,t),home:t=>$.home(e,t),rotate:t=>$.rotate(e,t),keyboard:t=>$.keyboard(e,t),clipboard:t=>$.clipboard(e,t),settings:t=>$.settings(e,t),alert:t=>$.alert(e,t),appSwitcher:t=>$.appSwitcher(e,t),tvRemote:t=>$.tvRemote(e,t)}}function Zo(e){return{capture:ki(e),selectors:ca(e),interactions:la(e),system:Xo(e),apps:Ba(e),admin:Va(e),recording:jo(e),observability:yo(e)}}var Qo=e({createAgentDevice:()=>$o,createMemorySessionStore:()=>es,localCommandPolicy:()=>rs,restrictedCommandPolicy:()=>is});function $o(e){let t={backend:e.backend,artifacts:e.artifacts,sessions:e.sessions??es(),policy:e.policy??is(),diagnostics:e.diagnostics,clock:e.clock,signal:e.signal};return{...t,...Zo(t)}}function es(e=[]){let t=new Map(e.map(e=>[e.name,ts(e)]));return{get:e=>ts(t.get(e)),set:e=>{t.set(e.name,ts(e))},delete:e=>{t.delete(e)},list:()=>Array.from(t.values(),e=>ts(e))}}function ts(e){if(e)return{...e,...e.snapshot?{snapshot:structuredClone(e.snapshot)}:{},...e.metadata?{metadata:ns(e.metadata)}:{}}}function ns(e){try{return structuredClone(e)}catch{return{...e}}}function rs(e={}){return{allowLocalInputPaths:!0,allowLocalOutputPaths:!0,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}function is(e={}){return{allowLocalInputPaths:!1,allowLocalOutputPaths:!1,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}export{j as a,an as c,nt as d,tt as f,rt as h,ii as i,Ut as l,at as m,rs as n,M as o,it as p,Qo as r,rn as s,$o as t,Ht as u};
3
+ `).toLowerCase(),n=D(e,_t),r=D(e,xt),i=D(e,ht,Ct),a=D(e,gt),o=ut(t),s=dt(t),c=ft(t,n,r);return{dismissNodes:n,minimizeNodes:r,collapsedNodes:i,redBox:pt(t,o,c),detected:mt({text:t,hasReactNativeStackFrame:o,hasOverlayControl:c,hasControllessRedBoxText:s,collapsedNodes:i,openDebuggerWarningNodes:a})}}function st(e){let t=Dt(e.dismissNodes);if(t)return jt(t,Mt(t));let n=Nt(e.collapsedNodes.filter(wt));return n?.rect?{action:`close-collapsed-banner`,point:Rt(n),rect:n.rect,ref:n.ref,label:Bt(n)}:null}function ct(e){return[e.label,e.value,e.identifier,e.type,e.role].filter(Boolean).join(` `)}function lt(e){return Je.test(e)}function ut(e){return Xe.some(t=>t.test(e))}function dt(e){return/\buncaught\b/.test(e)&&/unable to download asset/.test(e)}function ft(e,t,n){return t.length>0||n.length>0||/\b(reload js|copy stack)\b/.test(e)}function pt(e,t,n){return Ye.test(e)||dt(e)||t&&n}function mt(e){return e.collapsedNodes.length>0||e.openDebuggerWarningNodes.length>0||e.hasControllessRedBoxText||e.hasOverlayControl&&(lt(e.text)||e.hasReactNativeStackFrame)}function ht(e){let t=e?.trim().toLowerCase();return t?Qe.some(e=>t.includes(e))||Ze.some(e=>e.test(t)):!1}function gt(e){return e.includes(`open debugger to view warnings`)||/^!,\s+open debugger\b/.test(e)}function _t(e){return vt(e)||yt(e)||bt(e)}function vt(e){return/^dismiss(?:\s*\([^)]*\))?$/i.test(e)}function yt(e){return/^close(?:\s*\([^)]*\))?$/i.test(e)}function bt(e){return $e.has(e)}function xt(e){return/^minimi[sz]e(?:\b|\s|\()/i.test(e)}function St(e){return/^!,\s+/.test(e)}function Ct(e){return!e.rect||e.rect.height<=180}function wt(e){let t=Bt(e)?.trim().toLowerCase()??``;return(gt(t)||St(t))&&Et(e)}function Tt(e){return e?e.x<=1&&e.y<=1&&e.width>=300&&e.height>=600:!1}function Et(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 Dt(e){return Pt(e,At)}function Ot(e){let t=[e.type,e.role,e.subrole].join(` `).toLowerCase();return/\b(button|menuitem|link)\b/.test(t)}function kt(e){return e?e.width*e.height:1/0}function At(e){return[It(Ot(e)),It(e.hittable),-kt(e.rect)]}function jt(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:Bt(e)}}function Mt(e){let t=Bt(e)?.trim().toLowerCase();return t&&vt(t)?`dismiss`:`close`}function Nt(e){return Pt(e,Ft)}function Pt(e,t){let n=e.filter(e=>e.rect);return n.length===0?null:n.sort((e,n)=>Lt(t(n),t(e)))[0]??null}function Ft(e){return[It(e.hittable),e.rect?.width??0,e.rect?.y??0]}function It(e){return+(e===!0)}function Lt(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 Rt(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(zt(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 zt(e,t,n){return Math.min(n,Math.max(t,e))}function Bt(e){return e.label??e.value??e.identifier}const Vt=[`status`,`get`,`dismiss`,`enter`,`return`];function Ht(e){return Vt.includes(e)}function Ut(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 Wt(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=Te(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]}}function Gt(e,t){try{let n=Ke(e),r=E.extname(n)||`.js`;return[E.join(E.dirname(n),`${t}${r}`),E.join(E.dirname(n),`internal`,`${t}${r}`)].find(e=>Ge.existsSync(e))??null}catch{return null}}var O=class extends Error{};let k=null,Kt=!1,qt=!1,Jt=0;const A=new Map;function Yt(e){Kt=!0,!qt&&(qt=!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 Xt(e){let n=A.get(e.id);n&&(A.delete(e.id),$t(),e.ok?n.resolve(e.result):n.reject(new t(c(e.error.code),e.error.message,e.error.details)))}function Zt(e,t){k===e&&(Yt(t.message),k=null,e.terminate().catch(()=>{}),Qt(new O(`PNG worker failed: ${t.message}`)))}function Qt(e){let t=[...A.values()];A.clear();for(let n of t)n.reject(e)}function $t(){k&&(A.size>0?k.ref():k.unref())}function en(){if(Kt)return null;if(k)return k;let e=Gt(import.meta.url,`png-worker`);if(!e)return Yt(`worker entry module not found next to the current module`),null;try{let t=new qe(e,{execArgv:e.endsWith(`.ts`)?[`--experimental-strip-types`]:[]});return t.on(`message`,Xt),t.on(`error`,e=>{Zt(t,e)}),t.on(`exit`,e=>{Zt(t,Error(`PNG worker exited with code ${e}`))}),t.unref(),k=t,t}catch(e){return Yt(`failed to spawn worker: ${e instanceof Error?e.message:String(e)}`),null}}function tn(e){let t=en();if(!t)return Promise.reject(new O(`PNG worker is unavailable`));Jt+=1;let n=Jt;return new Promise((r,i)=>{A.set(n,{resolve:r,reject:i}),$t();try{t.postMessage({...e,id:n})}catch(e){A.delete(n),$t(),i(new O(`failed to post job to PNG worker: ${e instanceof Error?e.message:String(e)}`))}})}async function nn(e,t){try{return await tn(e)}catch(e){if(e instanceof O)return t();throw e}}function rn(){en()}async function an(){let e=k;k=null,Qt(new O(`PNG worker terminated`)),e&&await e.terminate()}async function j(e,t){let n=await nn({kind:`decode`,png:e,label:t},()=>{let n=Ue(e,t);return{kind:`decode`,width:n.width,height:n.height,data:n.data}});return new Ve({width:n.width,height:n.height,data:We(n.data)})}async function M(e){return We((await nn({kind:`encode`,width:e.width,height:e.height,data:e.data},()=>({kind:`encode`,png:Ve.sync.write(e)}))).png)}async function on(e){let{kind:t,...n}=await nn({kind:`diff-pixels`,...e},()=>({kind:`diff-pixels`,...He(e)}));return{...n,diffData:We(n.diffData)}}const sn=[0,187,255,255];function cn(e,t){for(let n of t)n.rect.width<4||n.rect.height<4||ln(e,n.rect)}function ln(e,t){let n=N(t.x,0,e.width-1),r=N(t.y,0,e.height-1),i=N(t.x+t.width-1,0,e.width-1),a=N(t.y+t.height-1,0,e.height-1);for(let t=0;t<2;t+=1){for(let o=n;o<=i;o+=1)un(e,o,r+t,sn),un(e,o,a-t,sn);for(let o=r;o<=a;o+=1)un(e,n+t,o,sn),un(e,i-t,o,sn)}}function un(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 N(e,t,n){return Math.min(Math.max(e,t),n)}const dn=[{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 fn(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(!hn(t,a,e))continue;let c=0,l=mn(o,a,0,e),u=i.create(e);for(;c<l;){let e=o[c];c+=1,i.visit(u,e),l=pn({mask:t,visited:a,queue:o,queueEnd:l,width:n,height:r,pixelIndex:e})}s.push(u)}return s}function pn(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 dn){let o=s+e.x,u=c+e.y;if(!gn(o,u,i,a))continue;let d=u*i+o;hn(t,n,d)&&(l=mn(r,n,l,d))}return l}function mn(e,t,n,r){return t[r]=1,e[n]=r,n+1}function hn(e,t,n){return e[n]===1&&t[n]!==1}function gn(e,t,n,r){return e>=0&&e<n&&t>=0&&t<r}const _n=.4,vn={icon:90,toggle:90,chevron:75,separator:45,visual:35,background:10},yn={leading:20,trailing:20,separator:10,unknown:0,background:-30};function bn(e){let t=Tn(Sn(xn(e.diffMask,e.width,e.height,e.ocr),e.width,e.height),10),n=In(e.ocr?.currentBlocksRaw??[]),r=In(e.ocr?.baselineBlocksRaw??[]);return t.filter(Bn).map(t=>En(t,e,n,r)).filter(t=>t.rect.y>=e.height*.08).filter(An).sort((e,t)=>t.score-e.score).slice(0,Math.max(0,e.maxDeltas??12)).map((e,t)=>Dn(e,t+1))}function xn(e,t,n,r){let i=new Uint8Array(e);if(!r)return i;for(let e of[...r.baselineBlocksRaw,...r.currentBlocksRaw])Hn(i,t,n,oe(e.rect,8));return i}function Sn(e,t,n){return fn({mask:e,width:t,height:n,hooks:{create:e=>Cn(e,t),visit:(e,n)=>wn(e,n,t)}})}function Cn(e,t){let n=e%t,r=Math.floor(e/t);return{minX:n,minY:r,maxX:n,maxY:r,differentPixels:0}}function wn(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 Tn(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=>Un(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 En(e,t,n,r){let i=Vn(e),a=Nn(i,t.regions),o=Pn(i,n,r),s=On(i,o?.block.rect,t.width),c=kn(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:zn(o.block.text)}:{},score:jn(l,e.differentPixels,t)}}function Dn(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 On(e,t,n){if(e.height<=3&&e.width>=n*.12)return`separator`;if(!t)return e.width>=n*_n?`background`:`unknown`;if(e.width>=n*_n)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 kn(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`:Mn(e,r)?`background`:`visual`}function An(e){return e.likelyKind!==`background`}function jn(e,t,n){let r=Mn(e.rect,n)?-35:0,i=e.regionIndex?20:0;return vn[e.likelyKind]+yn[e.slot]+i+r+Math.min(20,t/200)}function Mn(e,t){return e.width>=t.width*.25||e.height>=t.height*.06}function Nn(e,t){let n,r=0;for(let i of t){let t=Se(e,i.rect);t<=r||(r=t,n=i)}return n?.index}function Pn(e,t,n){let r=Fn(e,t);if(r)return Rn(e,r.blocks);let i=Fn(e,n);return i?Rn(e,i.blocks):void 0}function Fn(e,t){let n,r=0;for(let i of t){let t=Wn(e,i.rect);t<=r||(r=t,n=i)}return n}function In(e){let t=[];for(let n of[...e].sort((e,t)=>e.rect.y-t.rect.y)){let e=t.find(e=>Ln(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=le([e.rect,n.rect])}return t}function Ln(e,t){return Wn(e,t)>0?!0:Math.abs(b(e).y-b(t).y)<=Math.max(e.height,t.height)*.5}function Rn(e,t){let n,r=b(e);for(let e of t){let t=Math.sqrt(ee(r,b(e.rect)));n&&t>=n.distance||(n={block:e,distance:t})}return n}function zn(e){return e.trim().replace(/^[^\p{L}\p{N}]+/u,``).replace(/^\p{L}\s+/u,``)}function Bn(e){let t=Vn(e);return e.differentPixels>=24&&t.width>=3&&t.height>=3}function Vn(e){return{x:e.minX,y:e.minY,width:e.maxX-e.minX+1,height:e.maxY-e.minY+1}}function Hn(e,t,n,r){let i=te(Math.floor(r.x),0,t-1),a=te(Math.floor(r.y),0,n-1),o=te(Math.ceil(r.x+r.width),0,t),s=te(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 Un(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 Wn(e,t){return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}async function Gn(e){if(await d(`tesseract`))try{let[t,n]=await Promise.all([Jn(e.baselinePath),Jn(e.currentPath)]);if(t.exitCode!==0||n.exitCode!==0)return;let r=Kn(t.stdout,e.width,e.height),i=Kn(n.stdout,e.width,e.height),a=qn(r,i),o=tr(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 Kn(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=F(t,o,`level`),r=P(t,o,`text`).trim(),i=F(t,o,`conf`);if(n!==5||!ir(r)||i<0)continue;let a=F(t,o,`left`),c=F(t,o,`top`),l=F(t,o,`width`),u=F(t,o,`height`);l<=0||u<=0||s.push({key:[P(t,o,`page_num`),P(t,o,`block_num`),P(t,o,`par_num`),P(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=>Xn(e)).map(e=>Yn(e,t,n)).filter(e=>e!==null)}function qn(e,t){let n=new Set,r=[];for(let i of e){let e=Zn(i,ar(i.text),t,n);if(e===null)continue;n.add(e);let a=t[e],o=Qn(i,a);$n(o)&&r.push(o)}return r.sort((e,t)=>er(t)-er(e)).slice(0,12)}function Jn(e){return u(`tesseract`,[e,`stdout`,`-l`,`eng`,`tsv`],{allowFailure:!0,timeoutMs:1e4})}function Yn(e,t,n){if(e.length===0)return null;let r=[...e].sort((e,t)=>e.rect.x-t.rect.x),i=le(r.map(e=>e.rect)),a=Math.round(or(r.map(e=>e.confidence))*100)/100;return{text:r.map(e=>e.text).join(` `),confidence:a,rect:i,normalizedRect:m({x:I(i.x/t),y:I(i.y/n),width:I(i.width/t),height:I(i.height/n)})}}function Xn(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 Zn(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(ar(s.text)!==t)continue;let c=ee(b(e.normalizedRect),b(s.normalizedRect));c>=a||(i=o,a=c)}return i}function Qn(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=sr(t.rect.width/e.rect.width),i=sr(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 $n(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 er(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 tr(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-or(e.map(e=>e.delta.x)))<=32);e?e.push(n):t.push([n])}return t.filter(e=>e.length>=2).map(nr).filter(e=>e.yRange.max-e.yRange.min<=60).sort((e,t)=>rr(t)-rr(e)).slice(0,4)}function nr(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 rr(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 P(e,t,n){let r=t.get(n);return r===void 0?``:e[r]??``}function F(e,t,n){let r=Number(P(e,t,n));return Number.isFinite(r)?r:0}function ir(e){return/[\p{L}\p{N}]/u.test(e)}function ar(e){return e.trim().replace(/\s+/g,` `).toLowerCase()}function or(e){return e.reduce((e,t)=>e+t,0)/e.length}function I(e){return Math.round(e*100*100)/100}function sr(e){return Math.round(e*1e3)/1e3}function cr(e,t){return e.flatMap(e=>lr(e,t.baseline.width,t.baseline.height)?ur(e,t,gr(t.baseline.height)):[e])}function lr(e,t,n){let r=e.maxX-e.minX+1;return e.maxY-e.minY+1>=hr(n)&&r>=t*.35}function ur(e,t,n){let r=mr(e,pr(fr(dr(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])=>_r(e,n,r,t)).filter(e=>e!==null);return i.length>1?i:[e]}function dr(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 fr(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 pr(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 mr(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 hr(e){return Math.max(48,Math.round(e*.07))}function gr(e){return Math.max(24,Math.round(e*.03))}function _r(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??=vr(t,a),yr(i,e,t,a,r.baseline,r.current))}return i}function vr(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 yr(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 br=2.5;function xr(e){let t=Sr(e);return cr(t.length<=2e3?Tr(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,Math.max(0,e.maxRegions??8)).map((t,n)=>Or(t,n+1,{width:e.baseline.width,height:e.baseline.height,totalPixels:e.totalPixels,differentPixels:e.differentPixels}))}function Sr(e){let{diffMask:t,baseline:n,current:r}=e,{width:i,height:a}=n;return fn({mask:t,width:i,height:a,hooks:{create:e=>Cr(e,i),visit:(e,t)=>wr(e,t,i,n,r)}})}function Cr(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 wr(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 Tr(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=>Er(e,r,t));if(!e){n.push({...r});continue}Dr(e,r)}return n}function Er(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 Dr(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 Or(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=kr(e.baselineRed,e.baselineGreen,e.baselineBlue,e.differentPixels),o=kr(e.currentRed,e.currentGreen,e.currentBlue,e.differentPixels),s=r.width*r.height,c=R(e.differentPixels/s),l=Math.round(L(a)),u=Math.round(L(o)),d=Mr(r,n.width,n.height),f=Nr(s,n.totalPixels),p=jr(a,o),h=Ar(i,n.width,n.height);return{index:t,rect:r,normalizedRect:m({x:R(r.x/n.width),y:R(r.y/n.height),width:R(r.width/n.width),height:R(r.height/n.height)}),differentPixels:e.differentPixels,shareOfDiffPercentage:R(e.differentPixels/n.differentPixels),densityPercentage:c,shape:d,size:f,location:h,averageBaselineColorHex:Pr(a),averageCurrentColorHex:Pr(o),baselineLuminance:l,currentLuminance:u,dominantChange:p}}function kr(e,t,n,r){return{r:Math.round(e/r),g:Math.round(t/r),b:Math.round(n/r)}}function Ar(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 jr(e,t){let n=L(e),r=L(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 Mr(e,t,n){return e.width>=t*.55&&e.height>=n*.12?`large-area`:e.width>=e.height*br?`horizontal-band`:e.height>=e.width*br?`vertical-band`:`compact`}function Nr(e,t){let n=e/t;return n>=.04?`large`:n>=.01?`medium`:`small`}function L(e){return e.r*.2126+e.g*.7152+e.b*.0722}function Pr(e){return`#${Fr(e.r)}${Fr(e.g)}${Fr(e.b)}`}function Fr(e){return e.toString(16).padStart(2,`0`)}function R(e){return Math.round(e*100*100)/100}const Ir=255*Math.sqrt(3);async function Lr(e,t,n={}){await Rr(e,`Baseline image not found`),await Rr(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([j(i,`baseline screenshot`),j(a,`current screenshot`)]);zr(o.width,o.height,`baseline screenshot`,n.maxPixels),zr(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 Br(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*Ir,{diffData:d,diffMask:f,differentPixels:p}=await on({width:o.width,height:o.height,baselineData:o.data,currentData:s.data,maxColorDistance:u}),m=p>0?xr({diffMask:f,baseline:o,current:s,totalPixels:l,differentPixels:p,maxRegions:n.maxRegions}):[];if(p>0&&r){let e=new Ve({width:o.width,height:o.height,data:d});cn(e,m),await T.mkdir(E.dirname(r),{recursive:!0}),await T.writeFile(r,await M(e))}else await Br(n.outputPath);let h=p>0?await Gn({baselinePath:e,currentPath:t,width:o.width,height:o.height}):void 0,g=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,_=p>0&&h?bn({diffMask:f,width:o.width,height:o.height,regions:m,ocr:h}):[],ee=l>0?Math.round(p/l*100*100)/100:0;return{...p>0&&r?{diffPath:r}:{},...m.length>0?{regions:m}:{},...g?{ocr:g}:{},..._.length>0?{nonTextDeltas:_}:{},totalPixels:l,differentPixels:p,mismatchPercentage:ee,match:p===0}}async function Rr(e,n){try{await T.access(e)}catch{throw new t(`INVALID_ARGS`,`${n}: ${e}`)}}function zr(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 Br(e){if(e)try{await T.unlink(e)}catch(e){if(!Vr(e,`ENOENT`))throw e}}function Vr(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}function Hr(e,t){return e.map(e=>{let n=Ur(e,t);return n.length>0?{...e,currentOverlayMatches:n}:e})}function Ur(e,t){let n=Wr(e.rect);return t.map(t=>{let r=t.overlayRect,i=Se(e.rect,r);return i<=0?null:{ref:t.ref,...t.label?{label:t.label}:{},rect:r,overlayCoveragePercentage:Gr(i/Wr(r)),regionCoveragePercentage:Gr(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 Wr(e){return e.width*e.height}function Gr(e){return Math.round(e*100*100)/100}async function z(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 B(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 Kr(e,t){try{return await e.artifacts.createTempFile(t)}catch(e){throw s(e)}}const qr=async(e,n)=>{if(!n.baseline)throw new t(`INVALID_ARGS`,`diff screenshot requires a baseline image`);let r=Jr(n.threshold),i=n.current??{kind:`live`};if(n.overlayRefs&&!ti(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 z(e,n.baseline,{usage:`diff screenshot baseline`,field:`baseline`}),o,s,c,l=[];try{let t;ti(i)?(s=await Yr(e,n),t=s.path):(o=await z(e,i,{usage:`diff screenshot current`,field:`current`}),t=o.path),c=n.out?await B(e,n.out,{field:`diffPath`,ext:`.png`,artifactType:`screenshot-diff`}):void 0;let u=await Lr(a.path,t,{threshold:r,outputPath:c?.path,maxPixels:e.policy.maxImagePixels});ti(i)&&(u=await Xr(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 Jr(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 Yr(e,t){let n=await Kr(e,{prefix:`agent-device-diff-current`,ext:`.png`});try{await Zr(e,t,n.path,Qr(t))}catch(e){throw await n.cleanup(),e}return n}async function Xr(e,t,n,r,i){if(!t.overlayRefs)return r;if(r.match||r.dimensionMismatch)return n&&await ei(n),r;let a=await B(e,$r(t,n),{field:`currentOverlayPath`,ext:`.png`,artifactType:`screenshot`});try{let n=await Zr(e,t,a.path,{overlayRefs:!0,...Qr(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:Hr(r.regions,n.overlayRefs)}:{}}}catch(e){throw await a.cleanup?.(),e}}async function Zr(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 Qr(e){return{normalizeStatusBar:e.normalizeStatusBar??!0,...e.surface?{surface:e.surface}:{}}}function $r(e,t){if(e.currentOverlayOut)return e.currentOverlayOut;if(e.out?.kind===`path`)return{kind:`path`,path:V(t??e.out.path)};if(e.out?.kind===`downloadableArtifact`)return{kind:`downloadableArtifact`,...e.out.clientPath?{clientPath:V(e.out.clientPath)}:{},...e.out.fileName?{fileName:V(e.out.fileName)}:{}}}function V(e){let t=E.extname(e);return`${t?e.slice(0,-t.length):e}.current-overlay${t||`.png`}`}async function ei(e){try{await T.unlink(V(e))}catch(e){if(!ni(e,`ENOENT`))throw e}}function ti(e){return e.kind===`live`}function ni(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}async function ri(e,n){if(!Number.isInteger(n)||n<1)throw new t(`INVALID_ARGS`,`Screenshot max size must be a positive integer`);let r=await j(await T.readFile(e),`screenshot`),i=Math.max(r.width,r.height);if(i<=n)return;let a=n/i,o=ai(r,Math.max(1,Math.round(r.width*a)),Math.max(1,Math.round(r.height*a)));await T.writeFile(e,await M(o))}async function ii(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 j(await T.readFile(e),`screenshot`);i.width===n&&i.height===r||await T.writeFile(e,await M(ai(i,n,r)))}function ai(e,t,n){let r=new Ve({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 oi=async(e,n)=>{if(!e.backend.captureScreenshot)throw new t(`UNSUPPORTED_OPERATION`,`screenshot is not supported by this backend`);let r=await B(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 ri(r.path,n.maxSize),i=await r.publish()}catch(e){throw await r.cleanup?.(),e}return{path:r.path,...i?{artifacts:[i]}:{},...y(`Saved screenshot: ${r.path}`)}};function si(e,t){return e.presentationKey?e:{...e,presentationKey:i(t)}}function ci(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||!li(t,n,i)||!t.presentationKey||t.presentationKey!==n.presentationKey||!ui(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 li(e,t,n){return!(e.backend&&t.backend&&e.backend!==t.backend||n?.previousAppBundleId&&n.currentAppBundleId&&n.previousAppBundleId!==n.currentAppBundleId)}function ui(e,t){return e.truncated===t.truncated?JSON.stringify(di(e.nodes))===JSON.stringify(di(t.nodes)):!1}function di(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 fi=async(e,t)=>{let n=await mi(e,t),r=ci({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(gi(t.session,n)),{nodes:n.snapshot.nodes,truncated:n.snapshot.truncated??!1,visibility:Wt({nodes:n.snapshot.nodes,backend:n.snapshot.backend,snapshotRaw:t.raw}),...pe({...n.annotations,warnings:n.warnings}),...r?{unchanged:r}:{},...n.result.snapshotDiagnostics?{snapshotDiagnostics:n.result.snapshotDiagnostics}:{},..._i(n)}},pi=async(e,t)=>{let n=await mi(e,t),r=t.interactiveOnly===!0,i=n.session?.snapshot,a=gi(t.session,n);if(!i){let t=ne(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=me(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 mi(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=si(hi(a,e),n),s=ge(a),c=x(e);return{snapshot:o,result:a,session:i,annotations:s,warnings:vi({result:a,annotations:s,snapshot:o,options:n,session:i,capturedAt:o.createdAt??c,runtimeNow:c})}}function hi(e,t){return e.snapshot?e.snapshot:{nodes:e.nodes??[],truncated:e.truncated,backend:e.backend,createdAt:x(t)}}function gi(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 _i(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 vi(e){let t=[...e.annotations.warnings??[]];e.annotations.quality&&t.push(...Ae(e.annotations.quality,e.snapshot.nodes)),t.push(...xi(e)),e.annotations.quality||(t.push(...yi(e)),t.push(...bi(e.snapshot.nodes)));let n=Si(e.annotations.androidSnapshot);n&&t.push(n);let r=et(e.snapshot.nodes);r&&t.push(r);let i=Ci(e);return i&&t.push(i),t.push(...Di(e.annotations.freshness,e.snapshot.backend)),Array.from(new Set(t))}function yi(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 bi(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 xi(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 Si(e){if(e?.backend===`uiautomator-dump`)return`Android snapshot helper unavailable; using stock UIAutomator dump, which can time out on busy React Native UIs.${e.fallbackReason?` Reason: ${e.fallbackReason}`:``}`}function Ci(e){let t=e.session?.snapshot;if(!e.annotations.freshness&&t&&wi(t,e.snapshot)&&Ti(t,e.capturedAt,e.runtimeNow)&&Oi(t.nodes.length,e.snapshot.nodes.length))return Ei}function wi(e,t){return e.presentationKey===void 0||t.presentationKey===void 0?!0:e.presentationKey===t.presentationKey}function Ti(e,t,n){return[t,n].some(t=>{let n=t-e.createdAt;return n>=0&&n<=2e3})}const Ei=`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 Di(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`?[Ei]:[]}function Oi(e,t){return e<12?!1:t<=Math.floor(e*.2)}const H={screenshot:oi,diffScreenshot:qr,snapshot:fi,diffSnapshot:pi};function ki(e){return{screenshot:t=>H.screenshot(e,t),diffScreenshot:t=>H.diffScreenshot(e,t),snapshot:t=>H.snapshot(e,t),diffSnapshot:t=>H.diffSnapshot(e,t)}}const Ai=async(e,t)=>await Pi(e,t,`press`),ji=async(e,t)=>await Pi(e,t,`click`),Mi=async(e,n)=>{if(!n.text)throw new t(`INVALID_ARGS`,`fill requires text`);let r=h(n),i=r.needsPreActionBaseline?null:await Li(e,n);if(i)return i;let a=await ae(e,n,{action:`fill`,requireInteractive:!0,promoteToHittableAncestor:!1,captureEvidenceBaseline:r.needsPreActionBaseline});if(!e.backend.fill)throw new t(`UNSUPPORTED_OPERATION`,`fill is not supported by this backend`);let o=Fi(a),s=S(await e.backend.fill(v(e,n),o,n.text,{delayMs:n.delayMs})),c=`node`in a?a.node?.type??``:``,l=c&&!Ce(c,e.backend.platform)?`fill target ${zi(a)} resolved to "${c}", attempting fill anyway.`:void 0;return await se(e,n,a,{...a,text:n.text,...l?{warning:l}:{},...s?{backendResult:s}:{}},r)},Ni=async(e,n)=>{let r=n.text;if(!r)throw new t(`INVALID_ARGS`,`type requires text`);let i=Bi(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=w(n.delayMs??0,`delay-ms`,0,1e4),o=S(await e.backend.typeText(v(e,n),r,{delayMs:a}));return{kind:`text`,text:r,delayMs:a,...o?{backendResult:o}:{},...y(`Typed ${Array.from(r).length} chars`)}};async function Pi(e,n,r){let i=h(n),a=i.needsPreActionBaseline?null:await Ii(e,n,r);if(a)return a;let o=await ae(e,n,{action:r,requireInteractive:!0,promoteToHittableAncestor:!0,captureEvidenceBaseline:i.needsPreActionBaseline});if(!e.backend.tap)throw new t(`UNSUPPORTED_OPERATION`,`tap is not supported by this backend`);let s=Fi(o),c=S(await e.backend.tap(v(e,n),s,{button:n.button,count:n.count,intervalMs:n.intervalMs,holdMs:n.holdMs,jitterPx:n.jitterPx,doubleTap:n.doubleTap}));return await se(e,n,o,{...o,...c?{backendResult:c}:{}},i)}function Fi(e){if(!e.point)throw new t(`COMMAND_FAILED`,`Interaction target resolved without coordinates`);return e.point}async function Ii(e,t,n){if(n!==`click`||t.target.kind!==`ref`||!e.backend.tapTarget||Ri(t))return null;let r=await re(e,t,t.target,n),i=S(await e.backend.tapTarget(v(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},...r,...i?{backendResult:i}:{}}}async function Li(e,t){if(t.target.kind!==`ref`||!e.backend.fillTarget)return null;let n=await re(e,t,t.target,`fill`),r=S(await e.backend.fillTarget(v(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,...n,...r?{backendResult:r}:{}}}function Ri(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 Bi(e){return Ut(e)}function Vi(e){return{includeRects:Hi(e.predicate),interactiveOnly:!1}}function Hi(e){return e===`visible`||e===`hidden`}const Ui=1e4,Wi=async(e,n)=>{let r=n.locator??`any`;if(!n.query)throw new t(`INVALID_ARGS`,`find requires a value`);if(n.action===`wait`)return await $i(e,n,r);let{capture:i,match:a}=await ea(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 g(e,i,a),node:a}},Gi=async(e,t)=>{if(t.target.kind===`ref`){let n=await ie(e,t.session),r=he(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`}),i=Re(r.node,e.backend.platform,{action:`get`}),a={kind:`ref`,ref:`@${r.ref}`};return t.property===`attrs`?{kind:`attrs`,target:a,node:r.node,selectorChain:i}:{kind:`text`,target:a,text:await g(e,n,r.node),node:r.node,selectorChain:i}}let n=await sa(e,t,t.session??`default`,{selector:t.target.selector,disambiguateAmbiguous:t.property===`text`}),r=Re(n.node,e.backend.platform,{action:`get`});if(t.property===`attrs`)return{kind:`attrs`,target:{kind:`selector`,selector:n.selector},node:n.node,selectorChain:r};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}},Ki=async(e,n)=>{let r=await Gi(e,{...n,property:`text`,target:n.target});if(r.kind!==`text`)throw new t(`COMMAND_FAILED`,`getText returned non-text result`);return r},qi=async(e,n)=>{let r=await Gi(e,{...n,property:`attrs`,target:n.target});if(r.kind!==`attrs`)throw new t(`COMMAND_FAILED`,`getAttrs returned non-attrs result`);return r},Ji=async(e,n)=>{if(!we(n.predicate))throw new t(`INVALID_ARGS`,Oe);if(n.predicate===`text`&&!n.expectedText)throw new t(`INVALID_ARGS`,`is text requires expected text value`);let r=f(n.selector),i=await _(e,n,{updateSession:!0,...Vi({predicate:n.predicate,selectorChain:r})});if(n.predicate===`exists`){let a=Le(i.snapshot.nodes,r,{platform:e.backend.platform});if(!a)throw new t(`COMMAND_FAILED`,Fe(r,[],{unique:!1}),{hint:Ie([])});return{predicate:n.predicate,pass:!0,selector:a.selector.raw,matches:a.matches,selectorChain:r.selectors.map(e=>e.raw)}}let a=Pe(i.snapshot.nodes,r,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:!1});if(!a)throw new t(`COMMAND_FAILED`,Fe(r,[],{unique:!0}),{command:`is`,reason:`selector_not_found`,predicate:n.predicate,selector:r.raw,hint:Ie([])});let o=Ee({predicate:n.predicate,node:a.node,nodes:i.snapshot.nodes,expectedText:n.expectedText,platform:e.backend.platform});if(!o.pass)throw new t(`COMMAND_FAILED`,`is ${n.predicate} failed for selector ${a.selector.raw}: ${o.details}`,{command:`is`,reason:`predicate_failed`,predicate:n.predicate,selector:a.selector.raw,predicateDetails:o.details});return{predicate:n.predicate,pass:!0,selector:a.selector.raw,...n.predicate===`text`?{text:o.actualText}:{},selectorChain:r.selectors.map(e=>e.raw)}},Yi=async(e,t)=>await Ji(e,{...t,predicate:`visible`,selector:t.target.selector}),Xi=async(e,t)=>await Ji(e,{...t,predicate:`hidden`,selector:t.target.selector}),Zi=async(e,r)=>{if(r.target.kind===`sleep`)return await C(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?ke(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 ia(e,r,c,r.target.timeoutMs)}if(r.target.kind===`selector`)return await ra(e,r,r.target.selector,r.target.timeoutMs);if(r.target.kind===`stable`)return await oa(e,r,r.target.quietMs,r.target.timeoutMs);if(!r.target.text)throw new t(`INVALID_ARGS`,`wait requires text`);return await ia(e,r,r.target.text,r.target.timeoutMs)},Qi=async(e,n)=>{let r=await Zi(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 $i(e,n,r){let i=n.timeoutMs??Ui,a=x(e);for(;x(e)-a<i;){let{match:t}=await ea(e,n,r);if(t)return{kind:`found`,found:!0,waitedMs:x(e)-a};await C(e,300)}throw new t(`COMMAND_FAILED`,`find wait timed out`)}async function ea(e,t,n){let r=Me(n,t.query),i=await _(e,t,{updateSession:!0,scope:ta(e,n,t.query,r),...Vi({selectorChain:r})});if(je(i.snapshot.snapshotQuality))throw na(i.snapshot.snapshotQuality);return r?{capture:i,match:Pe(i.snapshot.nodes,r,{platform:e.backend.platform,requireRect:!1,requireUnique:!1})?.node}:{capture:i,match:Ne(i.snapshot.nodes,n,t.query,{requireRect:!1}).matches[0]}}function ta(e,t,n,r){if(!r&&e.backend.platform!==`web`)return p(t)?n:void 0}function na(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 ra(e,n,r,i){let a=i??Ui,o=x(e),s=f(r),c=Vi({selectorChain:s});for(;x(e)-o<a;){let t=Le((await _(e,n,{updateSession:!0,...c})).snapshot.nodes,s,{platform:e.backend.platform});if(t)return{kind:`selector`,selector:t.selector.raw,waitedMs:x(e)-o};await C(e,300)}throw new t(`COMMAND_FAILED`,`wait timed out for selector: ${r}`)}async function ia(e,n,r,i){let a=i??Ui,o=x(e);for(;x(e)-o<a;){if(e.backend.findText?(await e.backend.findText(v(e,n),r)).found:await aa(e,n,r))return{kind:`text`,text:r,waitedMs:x(e)-o};await C(e,300)}throw new t(`COMMAND_FAILED`,`wait timed out for text: ${r}`)}async function aa(e,t,n){return!!De((await _(e,t,{updateSession:!0})).snapshot.nodes,n)}async function oa(e,n,r,i){let a=i??Ui,o=r??500,s=await ce(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:ye}:{}}}async function sa(e,n,r,i){let a=f(i.selector),o=await _(e,{...n,session:r},{updateSession:!0,...Vi({selectorChain:a})}),s=Pe(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:Ie([])});return{capture:o,node:s.node,selector:s.selector.raw,ref:`@${s.node.ref}`}}const U={find:Wi,get:Gi,getText:Ki,getAttrs:qi,is:Ji,isVisible:Yi,isHidden:Xi,wait:Zi,waitForText:Qi},W={click:ji,press:Ai,fill:Mi,typeText:Ni,focus:ue,longPress:ve,swipe:be,scroll:de,pinch:xe};function ca(e){return{find:t=>U.find(e,t),get:t=>U.get(e,t),getText:(t,n={})=>U.getText(e,{...n,target:t}),getAttrs:(t,n={})=>U.getAttrs(e,{...n,target:t}),is:t=>U.is(e,t),isVisible:(t,n={})=>U.isVisible(e,{...n,target:t}),isHidden:(t,n={})=>U.isHidden(e,{...n,target:t}),wait:t=>U.wait(e,t),waitForText:(t,n={})=>U.waitForText(e,{...n,text:t})}}function la(e){return{click:(t,n={})=>W.click(e,{...n,target:t}),press:(t,n={})=>W.press(e,{...n,target:t}),fill:(t,n,r={})=>W.fill(e,{...r,target:t,text:n}),typeText:(t,n={})=>W.typeText(e,{...n,text:t}),focus:(t,n={})=>W.focus(e,{...n,target:t}),longPress:(t,n={})=>W.longPress(e,{...n,target:t}),swipe:t=>W.swipe(e,t),scroll:t=>W.scroll(e,t),pinch:t=>W.pinch(e,t)}}function G(e,t){if(e!==void 0)return K(e,t)}function K(e,n){let r=e?.trim();if(!r)throw new t(`INVALID_ARGS`,`${n} must be a non-empty string`);return r}const ua=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(v(e,n),n.filter)}},da=async(e,n={})=>{if(!e.backend.bootDevice)throw new t(`UNSUPPORTED_OPERATION`,`admin.boot is not supported by this backend`);let r=xa(n.target),i=S(await e.backend.bootDevice(v(e,n),r));return{kind:`deviceBooted`,...r?{target:r}:{},...i?{backendResult:i}:{},...y(`Booted device`)}},fa=async(e,n={})=>{if(!e.backend.shutdownDevice)throw new t(`UNSUPPORTED_OPERATION`,`admin.shutdown is not supported by this backend`);let r=xa(n.target),i=S(await e.backend.shutdownDevice(v(e,n),r));return{kind:`deviceShutdown`,...r?{target:r}:{},...i?{backendResult:i}:{},...y(`Shutdown device`)}},pa=async(e,t)=>await ga(e,t,`install`),ma=async(e,t)=>await ga(e,t,`reinstall`),ha=async(e,t)=>await ga(e,t,`installFromSource`);async function ga(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?K(n.app,`app`):void 0;if(r!==`installFromSource`&&!o)throw new t(`INVALID_ARGS`,`admin.${r} requires app`);let s=v(e,n),c=await _a(e,s,n.source);try{let t=await a.call(e.backend,s,{...o?{app:o}:{},source:c.source});return Sa(r,o,c.source,t)}finally{await c.cleanup?.()}}async function _a(e,t,n){let r=await va(e,ya(n));try{return{source:ya(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 va(e,t){if(t.kind===`url`)return{source:t};let n=await z(e,t,{usage:`admin.install`,field:`source`});return{source:{kind:`path`,path:n.path},...n.cleanup?{cleanup:n.cleanup}:{}}}function ya(e){if(!e||typeof e!=`object`)throw new t(`INVALID_ARGS`,`install source is required`);if(e.kind===`path`)return{kind:`path`,path:K(e.path,`source.path`)};if(e.kind===`uploadedArtifact`)return{kind:`uploadedArtifact`,id:K(e.id,`source.id`)};if(e.kind===`url`){let t=K(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 xa(e){if(!e)return;let t=G(e.id,`target.id`),n=G(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 Sa(e,t,n,r){let i=S(r),a=e===`reinstall`?`appReinstalled`:e===`installFromSource`?`appInstalledFromSource`:`appInstalled`,o=q(r,`appName`),s=q(r,`appId`),c=q(r,`bundleId`),l=q(r,`packageName`),u=q(r,`launchTarget`),d=q(r,`installablePath`),f=q(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}:{},...y(`${e===`reinstall`?`Reinstalled`:`Installed`}: ${o??u??t??Ca(n)}`)}}function q(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Ca(e){return e.kind===`path`?e.path:e.kind===`uploadedArtifact`?e.id:e.url}const wa=/^[A-Za-z0-9_.:-]{1,64}$/,Ta=async(e,n)=>{if(!e.backend.openApp)throw new t(`UNSUPPORTED_OPERATION`,`apps.open is not supported by this backend`);let r=ja(n),i=S(await e.backend.openApp(J(e,n),r,{launchArgs:n.launchArgs,relaunch:n.relaunch}));return{kind:`appOpened`,target:r,relaunch:n.relaunch===!0,...i?{backendResult:i}:{},...y(`Opened: ${Na(r)}`)}},Ea=async(e,n={})=>{if(!e.backend.closeApp)throw new t(`UNSUPPORTED_OPERATION`,`apps.close is not supported by this backend`);let r=G(n.app,`app`),i=S(await e.backend.closeApp(J(e,n),r));return{kind:`appClosed`,...r?{app:r}:{},...i?{backendResult:i}:{},...y(r?`Closed: ${r}`:`Closed app`)}},Da=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(J(e,n),ze(n.filter))}},Oa=async(e,n)=>{if(!e.backend.getAppState)throw new t(`UNSUPPORTED_OPERATION`,`apps.state is not supported by this backend`);let r=K(n.app,`app`);return{kind:`appState`,app:r,state:await e.backend.getAppState(J(e,n),r)}},ka=async(e,n)=>{if(!e.backend.pushFile)throw new t(`UNSUPPORTED_OPERATION`,`apps.push is not supported by this backend`);let r=K(n.app,`app`),i=await Pa(e,n.input);try{let t=S(await e.backend.pushFile(J(e,n),i.backendInput,r));return{kind:`appPushed`,app:r,inputKind:i.inputKind,...t?{backendResult:t}:{},...y(`Pushed to ${r}`)}}finally{await i.cleanup?.()}},Aa=async(e,n)=>{if(!e.backend.triggerAppEvent)throw new t(`UNSUPPORTED_OPERATION`,`apps.triggerEvent is not supported by this backend`);let r=Fa(n.name);Ia(n.payload,`apps.triggerEvent payload for "${r}"`);let i=S(await e.backend.triggerAppEvent(J(e,n),{name:r,...n.payload?{payload:n.payload}:{}}));return{kind:`appEventTriggered`,name:r,...n.payload?{payload:n.payload}:{},...i?{backendResult:i}:{},...y(`Triggered app event: ${r}`)}};function ja(e){let n=G(e.app,`app`),r=G(e.appId,`appId`),i=G(e.bundleId,`bundleId`),a=G(e.packageName,`packageName`),o=G(e.url,`url`),s=G(e.activity,`activity`),c={...n?{app:n}:{},...r?{appId:r}:{},...i?{bundleId:i}:{},...a?{packageName:a}:{},...o?{url:o}:{},...s?{activity:s}:{}};if(!Ma(c))throw new t(`INVALID_ARGS`,`apps.open requires app, appId, bundleId, packageName, url, or activity`);return c}function Ma(e){return!!(e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity)}function Na(e){return e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity??`app`}async function Pa(e,n){if(!n||typeof n!=`object`)throw new t(`INVALID_ARGS`,`apps.push requires an input`);if(n.kind===`json`)return La(n.payload,`apps.push JSON payload`,8192),{backendInput:{kind:`json`,payload:n.payload},inputKind:`json`};let r=await z(e,n,{usage:`apps.push`,field:`input`});return{backendInput:{kind:`file`,path:r.path},inputKind:`file`,...r.cleanup?{cleanup:r.cleanup}:{}}}function Fa(e){let n=K(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 Ia(e,t){e!==void 0&&La(e,t,8192)}function La(e,n,r){if(Ra(e,n),Buffer.byteLength(za(e,n),`utf8`)>r)throw new t(`INVALID_ARGS`,`${n} exceeds ${r} bytes`)}function Ra(e,n){if(!e||typeof e!=`object`||Array.isArray(e))throw new t(`INVALID_ARGS`,`${n} must be a JSON object`)}function za(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 J(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}const Y={open:Ta,close:Ea,list:Da,state:Oa,push:ka,triggerEvent:Aa},X={devices:ua,boot:da,shutdown:fa,install:pa,reinstall:ma,installFromSource:ha};function Ba(e){return{open:t=>Y.open(e,t),close:t=>Y.close(e,t),list:(t={})=>Y.list(e,{...t,filter:Be(t.filter)}),state:t=>Y.state(e,t),push:t=>Y.push(e,t),triggerEvent:t=>Y.triggerEvent(e,t)}}function Va(e){return{devices:t=>X.devices(e,t),boot:t=>X.boot(e,t),shutdown:t=>X.shutdown(e,t),install:t=>X.install(e,t),reinstall:t=>X.reinstall(e,t),installFromSource:t=>X.installFromSource(e,t)}}const Ha=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i,Ua=/\b[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g;function Wa(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(Ua,()=>(t=!0,`[REDACTED]`)),n=Ka(n,()=>{t=!0}),{value:n,redacted:t}}function Ga(e){try{let t=new URL(e),n=qa(t);return(t.username||t.password)&&(t.username=`REDACTED`,t.password=`REDACTED`,n=!0),{value:t.toString(),redacted:n}}catch{return}}function Ka(e,t){return/(https?:\/\/|token|secret|password|authorization|cookie|api[-_]?key)/i.test(e)?e.replaceAll(/https?:\/\/[^\s"'<>)]+/gi,e=>{let n=Ga(e);return n?(n.redacted&&t(),n.value):e}):e}function qa(e){let t=!1;for(let n of Array.from(e.searchParams.keys()))Ha.test(n)&&(e.searchParams.set(n,`[REDACTED]`),t=!0);return t}const Z=2048,Ja=4096,Ya=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i;function Xa(e){let t=e.redacted===!0;return{kind:`diagnosticsLogs`,entries:e.entries.map(e=>{let n=Q(e.message,Ja),r=ro(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 Za(e,t){let n=e.redacted===!0;return{kind:`diagnosticsNetwork`,entries:e.entries.map(e=>{let r=e.url?eo(e.url):void 0,i=t===`headers`||t===`all`?$a(e.requestHeaders):void 0,a=t===`headers`||t===`all`?$a(e.responseHeaders):void 0,o=t===`body`||t===`all`?to(e.requestBody):void 0,s=t===`body`||t===`all`?to(e.responseBody):void 0,c=ro(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 Qa(e){let t=e.redacted===!0;return{kind:`diagnosticsPerf`,metrics:e.metrics.map(e=>{let n=Q(e.message,Ja),r=ro(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 $a(e){if(!e)return{redacted:!1};let t=!1,n={};for(let[r,i]of Object.entries(e))if(Ya.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 eo(e){return Ga(e)??Q(e,Z)}function to(e){return e===void 0?{redacted:!1}:no(e)??Q(e,Z)}function no(e){try{let t=io(JSON.parse(e),Wa);return ao(JSON.stringify(t.value),Z,t.redacted)}catch{return}}function ro(e){return io(e,e=>Q(e,Z))}function io(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=io(e,t);return n||=r.redacted,r.value}),redacted:n}}let n=!1,r={};for(let[i,a]of Object.entries(e)){if(Ya.test(i)){r[i]=`[REDACTED]`,n=!0;continue}let e=io(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=Wa(e);return ao(n.value,t,n.redacted)}function ao(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 Xa(await e.backend.readLogs(await lo(e,n),uo(n)))},so=async(e,n={})=>{if(!e.backend.dumpNetwork)throw new t(`UNSUPPORTED_OPERATION`,`diagnostics.network is not supported by this backend`);let r=fo(n);return Za(await e.backend.dumpNetwork(await lo(e,n),r),r.include??`summary`)},co=async(e,n={})=>{if(!e.backend.measurePerf)throw new t(`UNSUPPORTED_OPERATION`,`diagnostics.perf is not supported by this backend`);return Qa(await e.backend.measurePerf(await lo(e,n),po(n)))};async function lo(e,t){let n=v(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 uo(e){return{...mo(e,100,500,`logs limit`),...e.levels===void 0?{}:{levels:_o(e.levels,`levels`)},...e.search===void 0?{}:{search:K(e.search,`search`)},...e.source===void 0?{}:{source:K(e.source,`source`)}}}function fo(e){return{...mo(e,25,200,`network limit`),include:go(e.include)}}function po(e){return{...ho(e),...e.sampleMs===void 0?{}:{sampleMs:w(e.sampleMs,`sampleMs`,100,6e4)},...e.metrics===void 0?{}:{metrics:_o(e.metrics,`metrics`,20)}}}function mo(e,t,n,r){return{...ho(e),...e.cursor===void 0?{}:{cursor:K(e.cursor,`cursor`)},limit:e.limit===void 0?t:w(e.limit,r,1,n)}}function ho(e){return{...e.since===void 0?{}:{since:K(e.since,`since`)},...e.until===void 0?{}:{until:K(e.until,`until`)}}}function go(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 _o(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)=>K(e,`${n}[${t}]`))}const vo={logs:oo,network:so,perf:co};function yo(e){return{logs:t=>vo.logs(e,t),network:t=>vo.network(e,t),perf:t=>vo.perf(e,t)}}const bo=async(e,n)=>{let r=Eo(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 B(e,n.out,{field:`path`,ext:`.mp4`,artifactType:`screen-recording`}):void 0;try{let t=So(n,a?.path);return Do(r,await i.call(e.backend,v(e,n),t),await a?.publish())}catch(e){throw await a?.cleanup?.(),e}},xo=async(e,n)=>{let r=Eo(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 B(e,n.out,{field:`outPath`,ext:`.trace`,artifactType:`trace-log`}):void 0;try{let t={...a?.path?{outPath:a.path}:{}};return Oo(r,await i.call(e.backend,v(e,n),t),await a?.publish())}catch(e){throw await a?.cleanup?.(),e}};function So(e,t){let n={};t&&(n.outPath=t);let r=Co(e.fps);r!==void 0&&(n.fps=r);let i=wo(e.maxSize);i!==void 0&&(n.maxSize=i);let a=To(e.quality);return a!==void 0&&(n.quality=a),e.hideTouches!==void 0&&(n.showTouches=e.hideTouches!==!0),n}function Co(e){return e===void 0?void 0:w(e,`fps`,1,60)}function wo(e){return e===void 0?void 0:w(e,`maxSize`,1,2**53-1)}function To(e){if(e===void 0)return;let n=fe(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 Eo(e,n){if(e===`start`||e===`stop`)return e;throw new t(`INVALID_ARGS`,`${n} action must be start or stop`)}function Do(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}:{},...ko(e,t,n,{startKind:`recordingStarted`,stopKind:`recordingStopped`,startMessage:`Recording started`,stopMessage:`Recording stopped`})}}function Oo(e,t,n){return{...typeof t.outPath==`string`?{outPath:t.outPath}:{},...ko(e,t,n,{startKind:`traceStarted`,stopKind:`traceStopped`,startMessage:`Trace started`,stopMessage:`Trace stopped`})}}function ko(e,t,n,r){return{kind:e===`start`?r.startKind:r.stopKind,action:e,...n?{artifact:n}:{},backendResult:t,...y(e===`start`?r.startMessage:r.stopMessage)}}const Ao={record:bo,trace:xo};function jo(e){return{record:t=>Ao.record(e,t),trace:t=>Ao.trace(e,t)}}const Mo=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=S(await e.backend.pressBack(v(e,n),{mode:r}));return{kind:`systemBack`,mode:r,...i?{backendResult:i}:{},...y(`Back`)}},No=async(e,n={})=>{if(!e.backend.pressHome)throw new t(`UNSUPPORTED_OPERATION`,`system.home is not supported by this backend`);let r=S(await e.backend.pressHome(v(e,n)));return{kind:`systemHome`,...r?{backendResult:r}:{},...y(`Home`)}},Po=async(e,n)=>{if(!e.backend.pressTvRemote)throw new t(`UNSUPPORTED_OPERATION`,`system.tvRemote is not supported by this backend`);let r=_e(n.button),i=n.durationMs===void 0?void 0:w(n.durationMs,`durationMs`,0,1e4),a=S(await e.backend.pressTvRemote(v(e,n),{button:r,...i===void 0?{}:{durationMs:i}}));return{kind:`tvRemotePressed`,button:r,...i===void 0?{}:{durationMs:i},...a?{backendResult:a}:{},...y(`Pressed TV remote ${r}`)}},Fo=async(e,n)=>{if(!e.backend.rotate)throw new t(`UNSUPPORTED_OPERATION`,`system.rotate is not supported by this backend`);let r=Vo(n.orientation),i=S(await e.backend.rotate(v(e,n),r));return{kind:`systemRotated`,orientation:r,...i?{backendResult:i}:{},...y(`Rotated to ${r}`)}},Io=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(!Ht(r))throw new t(`INVALID_ARGS`,`system.keyboard action must be status, get, dismiss, enter, or return`);let i=await e.backend.setKeyboard(v(e,n),{action:r}),a=S(i),o=Yo(i)?i:{};return r===`enter`||r===`return`?Uo(o,a):r===`dismiss`?Wo(r,o,a):Go(r,o,a)},Lo=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(v(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=S(await e.backend.setClipboard(v(e,n),n.text));return{kind:`clipboardUpdated`,action:`write`,textLength:Array.from(n.text).length,...r?{backendResult:r}:{},...y(`Clipboard updated`)}},Ro=async(e,n={})=>{if(!e.backend.openSettings)throw new t(`UNSUPPORTED_OPERATION`,`system.settings is not supported by this backend`);let r=G(n.target,`target`),i=S(await e.backend.openSettings(v(e,n),r));return{kind:`settingsOpened`,...r?{target:r}:{},...i?{backendResult:i}:{},...y(r?`Opened settings: ${r}`:`Opened settings`)}},zo=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:w(n.timeoutMs,`timeoutMs`,0,12e4);return Ho(r,await e.backend.handleAlert(v(e,n),r,{timeoutMs:i}))},Bo=async(e,n={})=>{if(!e.backend.openAppSwitcher)throw new t(`UNSUPPORTED_OPERATION`,`system.appSwitcher is not supported by this backend`);let r=S(await e.backend.openAppSwitcher(v(e,n)));return{kind:`appSwitcherOpened`,...r?{backendResult:r}:{},...y(`Opened app switcher`)}};function Vo(e){switch(e){case`portrait`:case`portrait-upside-down`:case`landscape-left`:case`landscape-right`:return e;default:throw new t(`INVALID_ARGS`,`system.rotate orientation must be portrait, portrait-upside-down, landscape-left, or landscape-right`)}}function Ho(e,t){return e===`get`?Ko(t):e===`wait`?qo(t):Jo(e,t)}function Uo(e,t){return{kind:`keyboardEnterPressed`,action:`enter`,state:e,...t?{backendResult:t}:{},...y(`Keyboard enter pressed`)}}function Wo(e,t,n){return{kind:`keyboardDismissed`,action:e,state:t,...n?{backendResult:n}:{},...y(t.dismissed===!1?`Keyboard already hidden`:`Keyboard dismissed`)}}function Go(e,t,n){return{kind:`keyboardState`,action:e,state:t,...n?{backendResult:n}:{}}}function Ko(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 qo(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},...y(e.alert?`Alert visible`:`Alert wait timed out`)}}function Jo(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}:{},...y(n.handled?`Alert ${e}ed`:`No alert handled`)}}function Yo(e){return!!(e&&typeof e==`object`)}const $={back:Mo,home:No,rotate:Fo,keyboard:Io,clipboard:Lo,settings:Ro,alert:zo,appSwitcher:Bo,tvRemote:Po};function Xo(e){return{back:t=>$.back(e,t),home:t=>$.home(e,t),rotate:t=>$.rotate(e,t),keyboard:t=>$.keyboard(e,t),clipboard:t=>$.clipboard(e,t),settings:t=>$.settings(e,t),alert:t=>$.alert(e,t),appSwitcher:t=>$.appSwitcher(e,t),tvRemote:t=>$.tvRemote(e,t)}}function Zo(e){return{capture:ki(e),selectors:ca(e),interactions:la(e),system:Xo(e),apps:Ba(e),admin:Va(e),recording:jo(e),observability:yo(e)}}var Qo=e({createAgentDevice:()=>$o,createMemorySessionStore:()=>es,localCommandPolicy:()=>rs,restrictedCommandPolicy:()=>is});function $o(e){let t={backend:e.backend,artifacts:e.artifacts,sessions:e.sessions??es(),policy:e.policy??is(),diagnostics:e.diagnostics,clock:e.clock,signal:e.signal};return{...t,...Zo(t)}}function es(e=[]){let t=new Map(e.map(e=>[e.name,ts(e)]));return{get:e=>ts(t.get(e)),set:e=>{t.set(e.name,ts(e))},delete:e=>{t.delete(e)},list:()=>Array.from(t.values(),e=>ts(e))}}function ts(e){if(e)return{...e,...e.snapshot?{snapshot:structuredClone(e.snapshot)}:{},...e.metadata?{metadata:ns(e.metadata)}:{}}}function ns(e){try{return structuredClone(e)}catch{return{...e}}}function rs(e={}){return{allowLocalInputPaths:!0,allowLocalOutputPaths:!0,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}function is(e={}){return{allowLocalInputPaths:!1,allowLocalOutputPaths:!1,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}export{j as a,an as c,nt as d,tt as f,rt as h,ii as i,Ut as l,at as m,rs as n,M as o,it as p,Qo as r,rn as s,$o as t,Ht as u};
@@ -1,4 +1,4 @@
1
- import{t as e}from"./rolldown-runtime.js";import{F as t,U as n}from"./sdk-contracts.js";import{AsyncLocalStorage as r}from"node:async_hooks";import i from"node:crypto";import a,{constants as o}from"node:fs";import s from"node:os";import c from"node:path";import{pipeline as l}from"node:stream/promises";import{Readable as u}from"node:stream";import{access as d,stat as f}from"node:fs/promises";import{spawn as p,spawnSync as m}from"node:child_process";const h=new r;function g(){return i.randomBytes(8).toString(`hex`)}function ee(){return`${Date.now().toString(36)}-${i.randomBytes(4).toString(`hex`)}`}async function te(e,t){let n={...e,diagnosticId:ee(),events:[],liveWrittenEventCount:0,phaseCounts:new Map};return await h.run(n,t)}function ne(e){let t=h.getStore();t&&Object.assign(t,e)}function re(){let e=h.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug,flushOnSuccess:e.flushOnSuccess}:{}}function ie(e){let t=h.getStore();if(!t)return 0;let n=0;for(let r of e)n+=t.phaseCounts.get(r)??0;return n}function _(e){let t=h.getStore();if(!t)return;let r={ts:new Date().toISOString(),level:e.level??`info`,phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?n(e.data):void 0};if(t.events.push(r),t.phaseCounts.set(e.phase,(t.phaseCounts.get(e.phase)??0)+1),!t.debug)return;let i=`${JSON.stringify(r)}\n`;try{t.logPath&&(v(t.logPath,i),t.liveWrittenEventCount=t.events.length),t.traceLogPath&&v(t.traceLogPath,i),!t.logPath&&!t.traceLogPath&&process.stderr.write(`[agent-device][diag] ${i}`)}catch{}}async function ae(e,t,n){let r=Date.now();try{let i=await t();return _({level:`info`,phase:e,durationMs:Date.now()-r,data:n}),i}catch(t){throw _({level:`error`,phase:e,durationMs:Date.now()-r,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function oe(e={}){let t=h.getStore();if(!t||!e.force&&!t.debug&&!t.flushOnSuccess||t.events.length===0)return null;try{if(t.logPath){let e=t.events.slice(t.liveWrittenEventCount);if(e.length>0){let r=e.map(e=>JSON.stringify(n(e)));v(t.logPath,`${r.join(`
2
- `)}\n`)}let r=t.logPath;return t.events=[],t.liveWrittenEventCount=0,r}let e=se(t.session??`default`),r=new Date().toISOString().slice(0,10),i=c.join(s.homedir(),`.agent-device`,`logs`,e,r);a.mkdirSync(i,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,`-`),l=c.join(i,`${o}-${t.diagnosticId}.ndjson`),u=t.events.map(e=>JSON.stringify(n(e)));return a.writeFileSync(l,`${u.join(`
3
- `)}\n`),t.events=[],l}catch{return null}}function se(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function v(e,t){a.mkdirSync(c.dirname(e),{recursive:!0}),a.appendFileSync(e,t,`utf8`)}const ce=new Set([`1`,`true`,`yes`,`on`]),le=new Set([`0`,`false`,`no`,`off`]);function ue(e){return`AGENT_DEVICE_${e.replace(/([A-Z])/g,`_$1`).replace(/[^A-Za-z0-9_]/g,`_`).toUpperCase()}`}function de(e,n,r,i){if(e.multiple)return(Array.isArray(n)?n:[n]).map(t=>de({...e,multiple:!1},t,r,i));if(e.type===`boolean`)return fe(n,r,i);if(e.type===`booleanOrString`){if(typeof n==`boolean`)return n;if(typeof n==`string`&&y(n)!==void 0)return y(n);if(typeof n==`string`&&n.trim().length>0)return n;throw new t(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected boolean or non-empty string.`)}if(e.type===`string`){if(typeof n==`string`&&n.trim().length>0)return n;throw new t(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected non-empty string.`)}if(e.type===`enum`){if(e.setValue!==void 0)return pe(e,n,r,i);if(typeof n!=`string`||!e.enumValues?.includes(n))throw new t(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected one of: ${e.enumValues?.join(`, `)}.`);return n}let a=typeof n==`number`?n:typeof n==`string`?Number(n):NaN;if(!Number.isFinite(a)||!Number.isInteger(a))throw new t(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected integer.`);if(typeof e.min==`number`&&a<e.min)throw new t(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Must be >= ${e.min}.`);if(typeof e.max==`number`&&a>e.max)throw new t(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Must be <= ${e.max}.`);return a}function fe(e,n,r){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=y(e);if(t!==void 0)return t}throw new t(`INVALID_ARGS`,`Invalid value for "${r}" in ${n}. Expected boolean.`)}function y(e){let t=e.trim().toLowerCase();if(ce.has(t))return!0;if(le.has(t))return!1}function pe(e,n,r,i){let a=e.setValue;if(n===a)return a;if(typeof n==`string`){let e=n.trim();if(e===``||e===`true`||e===`1`)return a;if(e===`false`||e===`0`)return}if(n===!0)return a;if(n!==!1)throw new t(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected boolean-like value for enum flag.`)}const me=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,he=[`.com`,`.exe`,`.bat`,`.cmd`],b=new r;async function ge(e,t){return e?await b.run(e,t):await t()}async function x(e){return await b.run(void 0,e)}async function _e(e,t,n={}){let r=b.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}async function ve(e,t,n={}){let r=b.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}function S(e){let t=typeof e.stdout==`string`?e.stdout:String(e.stdout??``),n=typeof e.stderr==`string`?e.stderr:String(e.stderr??``),r=typeof e.exitCode==`number`?e.exitCode:1;return t===e.stdout&&n===e.stderr&&r===e.exitCode?e:{...e,stdout:t,stderr:n,exitCode:r}}function C(e,t,n={}){let r=O(e),i=E();return new Promise((a,o)=>{let s=p(r,t,{cwd:n.cwd,env:n.env,stdio:[`pipe`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});n.onSpawn?.(s);let c=``,l=n.binaryStdout?[]:void 0,u=``,d=!1,f=B(n.timeoutMs),m=f?setTimeout(()=>{d=!0,H(s,n.detached)},f):null,h=V(s,n);n.binaryStdout||s.stdout.setEncoding(`utf8`),s.stderr.setEncoding(`utf8`),je(s,n.stdin).catch(i=>{h.didAbort||d||Me(i)||(o(Ee(r,e,t,i)),H(s,n.detached))}),s.stdout.on(`data`,e=>{if(n.binaryStdout){l?.push(Buffer.isBuffer(e)?e:Buffer.from(e));return}let t=String(e);c+=t,n.onStdoutChunk?.(t)}),s.stderr.on(`data`,e=>{let t=String(e);u+=t,n.onStderrChunk?.(t)}),s.on(`error`,n=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t),o(P(h,r,e,t,n))}),s.on(`close`,s=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t);let p=s??1;if(!h.didAbort&&d&&f){o(De(r,e,t,f,p,c,u));return}let g=F(h,r,e,t,p,n.allowFailure,c,u);if(g){o(g);return}a({stdout:c,stderr:u,exitCode:p,stdoutBuffer:l?Buffer.concat(l):void 0})})})}async function ye(e){let t=L(e);if(!t)return!1;if(c.isAbsolute(t))return R(t);let n=process.env.PATH;if(!n)return!1;let r=ke();for(let e of n.split(c.delimiter)){let n=e.trim();if(n){for(let e of Ae(t,r))if(await R(c.join(n,e)))return!0}}return!1}async function be(e,n){let r=I(e,n,`executable`);if(r){if(!await R(r))throw new t(`TOOL_MISSING`,`${n} points to a missing or non-executable file: ${r}`,{envName:n,path:r});return r}}async function xe(e,n){let r=I(e,n,`file`);if(r){if(!await z(r))throw new t(`TOOL_MISSING`,`${n} points to a missing or non-file path: ${r}`,{envName:n,path:r});return r}}function Se(e,n,r={}){let i=O(e),a=m(i,n,{cwd:r.cwd,env:r.env,stdio:[`pipe`,`pipe`,`pipe`],encoding:r.binaryStdout?void 0:`utf8`,input:r.stdin,timeout:B(r.timeoutMs),windowsHide:!0,shell:!1,...r.maxBuffer===void 0?{}:{maxBuffer:r.maxBuffer}});if(a.error){let o=a.error.code;throw o===`ETIMEDOUT`?new t(`COMMAND_FAILED`,`${i} timed out after ${B(r.timeoutMs)}ms`,{cmd:e,args:n,timeoutMs:B(r.timeoutMs)},a.error):o===`ENOENT`?k(i,e,a.error):A(i,e,n,a.error)}let o=r.binaryStdout?Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(a.stdout??``):void 0,s=r.binaryStdout?``:typeof a.stdout==`string`?a.stdout:(a.stdout??``).toString(),c=typeof a.stderr==`string`?a.stderr:(a.stderr??``).toString(),l=a.status??1;if(l!==0&&!r.allowFailure)throw M(i,e,n,l,s,c);return{stdout:s,stderr:c,exitCode:l,stdoutBuffer:o}}function Ce(e,t,n={}){return w(e,t,n).pid}function w(e,t,n={}){let r=p(O(e),t,{cwd:n.cwd,env:n.env,stdio:n.stdio??`ignore`,detached:!0,windowsHide:!0,shell:!1}),i=r.pid??0,a=new Promise(e=>{r.once(`error`,t=>{e({pid:i,error:t.message})}),r.once(`exit`,(t,n)=>{e({pid:i,...typeof t==`number`?{exitCode:t}:{},...n?{signal:n}:{}})})});return r.unref(),{pid:i,exited:a}}function T(e,t,n={}){let r=O(e),i=E(),a=p(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??[`ignore`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});i.emitBackgroundSpawn(e,t);let o=``,s=``,c=n.captureOutput??!0,l=V(a,n);return c&&(a.stdout?.setEncoding(`utf8`),a.stderr?.setEncoding(`utf8`),a.stdout?.on(`data`,e=>{o+=e}),a.stderr?.on(`data`,e=>{s+=e})),{child:a,wait:new Promise((c,u)=>{a.on(`error`,n=>{l.dispose(),i.emitBackgroundCompletion(e,t,`error`),u(P(l,r,e,t,n))}),a.on(`close`,a=>{l.dispose(),i.emitBackgroundCompletion(e,t,`exit`);let d=a??1,f=F(l,r,e,t,d,n.allowFailure,o,s);if(f){u(f);return}c({stdout:o,stderr:s,exitCode:d})})})}}function E(){let e=re(),t=e.debug===!0,n=y(process.env.AGENT_DEVICE_EXEC_TRACE??``)===!0;if(!t&&!n)return we();n&&e.flushOnSuccess!==!0&&ne({flushOnSuccess:!0});let r=Date.now(),i=!1;return{emitForegroundCompletion:(e,t)=>{i||(i=!0,D({cmd:e,args:t,startedAtMs:r}))},emitBackgroundSpawn:(e,t)=>{D({cmd:e,args:t,data:{event:`spawn`}})},emitBackgroundCompletion:(e,t,n)=>{i||(i=!0,D({cmd:e,args:t,startedAtMs:r,data:{event:n}}))}}}function we(){return{emitForegroundCompletion:()=>{},emitBackgroundSpawn:()=>{},emitBackgroundCompletion:()=>{}}}function D(e){let t=e.args.slice(0,6);_({level:`debug`,phase:`exec_command`,durationMs:e.startedAtMs===void 0?void 0:Math.max(0,Date.now()-e.startedAtMs),data:{command:e.cmd,argsPrefix:t,...e.args.length>t.length?{omittedArgCount:e.args.length-t.length}:{},...e.data??{}}})}function O(e){let n=L(e);if(!n)throw new t(`INVALID_ARGS`,`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e,hint:`Use a bare command name from PATH or an absolute executable path.`});return n}function Te(e,t,n,r){return r.code===`ENOENT`?k(e,t,r):A(e,t,n,r)}function k(e,n,r){return new t(`TOOL_MISSING`,`${e} not found in PATH`,{cmd:n},r)}function A(e,n,r,i){return new t(`COMMAND_FAILED`,`Failed to run ${e}`,{cmd:n,args:r},i)}function Ee(e,n,r,i){return new t(`COMMAND_FAILED`,`Failed to write stdin for ${e}`,{cmd:n,args:r},i instanceof Error?i:void 0)}function j(e,n,r){return new t(`COMMAND_FAILED`,`request canceled`,{cmd:n,args:r,executable:e,reason:`request_canceled`})}function De(e,n,r,i,a,o,s){return new t(`COMMAND_FAILED`,`${e} timed out after ${i}ms`,{cmd:n,args:r,stdout:o,stderr:s,exitCode:a,timeoutMs:i})}function M(e,n,r,i,a,o){return new t(`COMMAND_FAILED`,`${e} exited with code ${i}`,N({stdout:a,stderr:o,exitCode:i},{cmd:n,args:r}))}function Oe(e,n,r){if(e.exitCode===0)return e;throw new t(`COMMAND_FAILED`,n,N(e,typeof r==`function`?r(e):r))}function N(e,t){return{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,processExitError:!0,...t}}function P(e,t,n,r,i){return e.didAbort?j(t,n,r):Te(t,n,r,i)}function F(e,t,n,r,i,a,o,s){return e.didAbort?j(t,n,r):i!==0&&!a?M(t,n,r,i,o,s):null}function I(e,n,r){let i=e?.trim();if(i){if(!c.isAbsolute(i)||i.includes(`\0`))throw new t(`INVALID_ARGS`,`${n} must be an absolute ${r} path, not ${JSON.stringify(e)}`,{envName:n,path:e});return i}}function L(e){let t=e.trim();return!t||t.includes(`\0`)?null:c.isAbsolute(t)?t:t.includes(`/`)||t.includes(`\\`)?null:me.test(t)?t:null}function ke(){if(process.platform!==`win32`)return[``];let e=process.env.PATHEXT;if(!e)return he;let t=e.split(`;`).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:he}function Ae(e,t){if(process.platform!==`win32`)return[e];let n=e.toLowerCase();return t.some(e=>n.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}async function R(e){try{return await z(e)?(await d(e,process.platform===`win32`?o.F_OK:o.X_OK),!0):!1}catch{return!1}}async function z(e){try{return(await f(e)).isFile()}catch{return!1}}function B(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function V(e,t){let n=!1,r=()=>{n=!0,H(e,t.detached)};return t.signal?.aborted?r():t.signal?.addEventListener(`abort`,r,{once:!0}),{get didAbort(){return n},dispose:()=>{t.signal?.removeEventListener(`abort`,r)}}}function H(e,t){if(t&&e.pid&&process.platform!==`win32`)try{process.kill(-e.pid,`SIGKILL`);return}catch{}e.kill(`SIGKILL`)}async function je(e,t){if(e.stdin){if(t===void 0){e.stdin?.end();return}await l(u.from([t]),e.stdin)}}function Me(e){return e instanceof Error&&`code`in e&&e.code===`EPIPE`}var Ne=e({androidAdbResultError:()=>K,attachAdbFailureHint:()=>G,classifyAdbFailure:()=>W,createAndroidPortReverseManager:()=>We,createDeviceAdbExecutor:()=>Y,createLocalAndroidAdbProvider:()=>Ve,installAndroidAdbPackage:()=>Ke,pullAndroidAdbFile:()=>Ge,resolveAndroidAdbExecutor:()=>He,resolveAndroidAdbProvider:()=>X,resolveAndroidTextInjector:()=>Ue,resolveAndroidTouchInjector:()=>Z,withAndroidAdbProvider:()=>Je});const U=new r,Pe=[{reason:`device_unauthorized`,pattern:/device unauthorized|device still authorizing/,hint:`USB debugging is not authorized — accept the authorization prompt on the device screen (re-plug the cable if none appears), then retry.`},{reason:`device_offline`,pattern:/device offline/,hint:`The device is connected but offline — wait for it to finish booting or run adb reconnect, then retry.`,retriable:!0},{reason:`multiple_devices`,pattern:/more than one (?:device\/emulator|device and emulator)/,hint:`Multiple Android devices are connected — pass --serial <serial> (see adb devices) to select one.`},{reason:`no_devices`,pattern:/no devices\/emulators found|no devices found/,hint:`No Android devices detected — boot an emulator or connect a device and verify it appears in adb devices.`},{reason:`device_not_found`,pattern:/device (?:'[^']*' )?not found/,hint:`The device disconnected or is restarting — verify it is listed in adb devices, then retry.`,retriable:!0},{reason:`server_version_mismatch`,pattern:/adb server version \(\d+\) doesn't match this client/,hint:`Multiple adb installs conflict — adb restarts its server automatically, so retry; align PATH to a single adb to stop recurrences.`,retriable:!0},{reason:`connection_dropped`,pattern:/transport error|connection reset|broken pipe|protocol fault/,hint:`The adb connection dropped — retry; if it persists, run adb kill-server and reconnect the device.`,retriable:!0},{reason:`install_insufficient_storage`,pattern:/install_failed_insufficient_storage/,hint:`The device is out of storage — free up space or uninstall unused apps, then retry the install.`,matchStdout:!0},{reason:`install_update_incompatible`,pattern:/install_failed_update_incompatible/,hint:`The installed app has an incompatible signature — uninstall the existing app first, then retry the install.`,matchStdout:!0},{reason:`install_version_downgrade`,pattern:/install_failed_version_downgrade/,hint:`The APK is older than the installed app — uninstall the app first (or install with downgrade allowed), then retry.`,matchStdout:!0},{reason:`install_failed`,pattern:/install_failed_\w+|install_parse_failed_\w+/,hint:`The Android package installer rejected the APK — see the INSTALL_FAILED code in the error output for the exact cause.`,matchStdout:!0}],Fe={reason:`timeout`,hint:`adb timed out — the adb server may be wedged. Run adb kill-server && adb start-server, check adb devices, then retry.`};function W(e,t=``){let n=e.toLowerCase(),r=t.toLowerCase();for(let{pattern:e,matchStdout:t,...i}of Pe)if(e.test(n)||t&&e.test(r))return i}function G(e){if(!(e instanceof t)||e.code!==`COMMAND_FAILED`)return e;let n=Ie(e);return n&&(e.details={...e.details,adbFailure:n.reason,...typeof e.details?.hint==`string`?{}:{hint:n.hint},...n.retriable!==void 0&&e.details?.retriable===void 0?{retriable:n.retriable}:{}}),e}function Ie(e){return typeof e.details?.timeoutMs==`number`?Fe:W(typeof e.details?.stderr==`string`?e.details.stderr:``,typeof e.details?.stdout==`string`?e.details.stdout:``)}function K(e,n,r){return G(new t(`COMMAND_FAILED`,e,n.exitCode===0?{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,...r}:N(n,r)))}function q(e){return async(...t)=>{try{return await e(...t)}catch(e){throw G(e)}}}const Le=new WeakSet;function Re(e){if(Le.has(e))return e;let t={...e,exec:q(J(e.exec)),...e.pull?{pull:q(J(e.pull))}:{},...e.install?{install:q(J(e.install))}:{},...e.installBundle?{installBundle:q(e.installBundle)}:{}};return Le.add(t),t}function J(e){return async(...t)=>S(await e(...t))}function Y(e){return ze(e.id)}function ze(e){return q(async(t,n)=>await x(async()=>await _e(`adb`,[`-s`,e,...t],{...n,detached:process.platform!==`win32`})))}function Be(e){return(t,n)=>{let r=T(`adb`,[`-s`,e,...t],{...n,allowFailure:!0,captureOutput:!1});return r.wait.catch(()=>{}),r.child}}function Ve(e){let t=Y(e);return{exec:t,spawn:Be(e.id),reverse:Ze(t),pull:async(e,n,r)=>await t([`pull`,e,n],r),install:async(e,n)=>{let{installArgs:r,execOptions:i}=$(n);return await t([`install`,...r,e],i)}}}function He(e,t){let n=U.getStore();return t||(n?.serial===e.id?n.provider.exec:Y(e))}function X(e,t){if(t)return Q(t);let n=U.getStore();return n?.serial===e.id?Q(n.provider):Ve(e)}function Ue(e){let t=U.getStore();return t?.serial===e.id?t.provider.text:void 0}function Z(e){let t=U.getStore();return t?.serial===e.id?t.provider.touch:void 0}function We(e){let n=Q(e),r=n.reverse??Ze(n.exec),i=new Map;return{async ensure(e,n){let a=i.get(e.local);if(a&&a.ownerId!==e.ownerId)throw new t(`COMMAND_FAILED`,`Android port reverse ${e.local} is already owned by ${a.ownerId??`another session`}`,{current:a,requested:e});a?.remote!==e.remote&&(await r.ensure(e,n),i.set(e.local,{...e}))},async remove(e,t){if(!i.has(e)){await r.remove(e,t);return}await r.remove(e,t),i.delete(e)},async removeAllOwned(e,t){let n=[...i.values()].filter(t=>t.ownerId===e).map(e=>e.local);if(n.length===0){await r.removeAllOwned(e,t);return}for(let e of n)await r.remove(e,t),i.delete(e)},async list(e){return r.list?await r.list(e):[...i.values()]}}}function Q(e){return Re(typeof e==`function`?{exec:e}:e)}async function Ge(e,n,r){let{device:i,provider:a,...o}=r??{},s=qe(i,a),c=s?.pull;if(c)return await x(async()=>await c(e,n,o));let l=s?.exec;if(!l)throw new t(`COMMAND_FAILED`,`Android adb pull requires an adb provider`);return await x(async()=>await l([`pull`,e,n],o))}async function Ke(e,n){let{device:r,provider:i,...a}=n??{},o=qe(r,i),s=o?.install;if(s)return await x(async()=>await s(e,a));let c=o?.exec;if(!c)throw new t(`COMMAND_FAILED`,`Android adb install requires an adb provider`);let{installArgs:l,execOptions:u}=$(a);return await x(async()=>await c([`install`,...l,e],u))}function qe(e,t){if(t)return Q(t);if(e)return X(e);let n=U.getStore();if(n)return Q(n.provider)}async function Je(e,t,n){if(!e)return await n();let r={provider:Q(e),serial:t.serial},i=Ye(r);return await U.run(r,async()=>await ge(i,n))}function Ye(e){return(t,n,r)=>{if(t!==`adb`)return;let i=Xe(n,e.serial);if(i)return x(async()=>await e.provider.exec(i,r))}}function Xe(e,t){if(!(e[0]!==`-s`||!e[1])&&e[1]===t)return e.slice(2)}function Ze(e){let t=new Map;return{async ensure(n,r){if(await e([`reverse`,n.local,n.remote],{allowFailure:!1,signal:r?.signal,timeoutMs:r?.timeoutMs}),n.ownerId){let e=t.get(n.ownerId)??new Set;e.add(n.local),t.set(n.ownerId,e)}},async remove(n,r){let i=await e([`reverse`,`--remove`,n],{allowFailure:!0,signal:r?.signal,timeoutMs:r?.timeoutMs});if(i.exitCode!==0&&!$e(i.stdout,i.stderr))throw K(`Failed to remove Android port reverse ${n}`,i,{local:n});for(let e of t.values())e.delete(n)},async removeAllOwned(e,n){let r=[...t.get(e)??[]];for(let e of r)await this.remove(e,n);t.delete(e)},async list(n){let r=await e([`reverse`,`--list`],{allowFailure:!0,signal:n?.signal,timeoutMs:n?.timeoutMs});return r.exitCode===0?Qe(r.stdout,t):[]}}}function Qe(e,t){let n=new Map;for(let[e,r]of t)for(let t of r)n.set(t,e);return e.split(`
1
+ import{t as e}from"./rolldown-runtime.js";import{T as t,_ as n}from"./sdk-contracts.js";import{AsyncLocalStorage as r}from"node:async_hooks";import i from"node:crypto";import a,{constants as o}from"node:fs";import s from"node:os";import c from"node:path";import{pipeline as l}from"node:stream/promises";import{Readable as u}from"node:stream";import{access as d,stat as f}from"node:fs/promises";import{spawn as p,spawnSync as m}from"node:child_process";const h=new r;function g(){return i.randomBytes(8).toString(`hex`)}function ee(){return`${Date.now().toString(36)}-${i.randomBytes(4).toString(`hex`)}`}async function te(e,t){let n={...e,diagnosticId:ee(),events:[],liveWrittenEventCount:0,phaseCounts:new Map};return await h.run(n,t)}function ne(e){let t=h.getStore();t&&Object.assign(t,e)}function re(){let e=h.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug,flushOnSuccess:e.flushOnSuccess}:{}}function ie(e){let t=h.getStore();if(!t)return 0;let n=0;for(let r of e)n+=t.phaseCounts.get(r)??0;return n}function _(e){let n=h.getStore();if(!n)return;let r={ts:new Date().toISOString(),level:e.level??`info`,phase:e.phase,session:n.session,requestId:n.requestId,command:n.command,durationMs:e.durationMs,data:e.data?t(e.data):void 0};if(n.events.push(r),n.phaseCounts.set(e.phase,(n.phaseCounts.get(e.phase)??0)+1),!n.debug)return;let i=`${JSON.stringify(r)}\n`;try{n.logPath&&(v(n.logPath,i),n.liveWrittenEventCount=n.events.length),n.traceLogPath&&v(n.traceLogPath,i),!n.logPath&&!n.traceLogPath&&process.stderr.write(`[agent-device][diag] ${i}`)}catch{}}async function ae(e,t,n){let r=Date.now();try{let i=await t();return _({level:`info`,phase:e,durationMs:Date.now()-r,data:n}),i}catch(t){throw _({level:`error`,phase:e,durationMs:Date.now()-r,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function oe(e={}){let n=h.getStore();if(!n||!e.force&&!n.debug&&!n.flushOnSuccess||n.events.length===0)return null;try{if(n.logPath){let e=n.events.slice(n.liveWrittenEventCount);if(e.length>0){let r=e.map(e=>JSON.stringify(t(e)));v(n.logPath,`${r.join(`
2
+ `)}\n`)}let r=n.logPath;return n.events=[],n.liveWrittenEventCount=0,r}let e=se(n.session??`default`),r=new Date().toISOString().slice(0,10),i=c.join(s.homedir(),`.agent-device`,`logs`,e,r);a.mkdirSync(i,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,`-`),l=c.join(i,`${o}-${n.diagnosticId}.ndjson`),u=n.events.map(e=>JSON.stringify(t(e)));return a.writeFileSync(l,`${u.join(`
3
+ `)}\n`),n.events=[],l}catch{return null}}function se(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function v(e,t){a.mkdirSync(c.dirname(e),{recursive:!0}),a.appendFileSync(e,t,`utf8`)}const ce=new Set([`1`,`true`,`yes`,`on`]),le=new Set([`0`,`false`,`no`,`off`]);function ue(e){return`AGENT_DEVICE_${e.replace(/([A-Z])/g,`_$1`).replace(/[^A-Za-z0-9_]/g,`_`).toUpperCase()}`}function de(e,t,r,i){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>de({...e,multiple:!1},t,r,i));if(e.type===`boolean`)return fe(t,r,i);if(e.type===`booleanOrString`){if(typeof t==`boolean`)return t;if(typeof t==`string`&&y(t)!==void 0)return y(t);if(typeof t==`string`&&t.trim().length>0)return t;throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected boolean or non-empty string.`)}if(e.type===`string`){if(typeof t==`string`&&t.trim().length>0)return t;throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected non-empty string.`)}if(e.type===`enum`){if(e.setValue!==void 0)return pe(e,t,r,i);if(typeof t!=`string`||!e.enumValues?.includes(t))throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected one of: ${e.enumValues?.join(`, `)}.`);return t}let a=typeof t==`number`?t:typeof t==`string`?Number(t):NaN;if(!Number.isFinite(a)||!Number.isInteger(a))throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected integer.`);if(typeof e.min==`number`&&a<e.min)throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Must be >= ${e.min}.`);if(typeof e.max==`number`&&a>e.max)throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Must be <= ${e.max}.`);return a}function fe(e,t,r){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=y(e);if(t!==void 0)return t}throw new n(`INVALID_ARGS`,`Invalid value for "${r}" in ${t}. Expected boolean.`)}function y(e){let t=e.trim().toLowerCase();if(ce.has(t))return!0;if(le.has(t))return!1}function pe(e,t,r,i){let a=e.setValue;if(t===a)return a;if(typeof t==`string`){let e=t.trim();if(e===``||e===`true`||e===`1`)return a;if(e===`false`||e===`0`)return}if(t===!0)return a;if(t!==!1)throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected boolean-like value for enum flag.`)}const me=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,he=[`.com`,`.exe`,`.bat`,`.cmd`],b=new r;async function ge(e,t){return e?await b.run(e,t):await t()}async function x(e){return await b.run(void 0,e)}async function _e(e,t,n={}){let r=b.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}async function ve(e,t,n={}){let r=b.getStore()?.(e,t,n);return r?S(await r):await C(e,t,n)}function S(e){let t=typeof e.stdout==`string`?e.stdout:String(e.stdout??``),n=typeof e.stderr==`string`?e.stderr:String(e.stderr??``),r=typeof e.exitCode==`number`?e.exitCode:1;return t===e.stdout&&n===e.stderr&&r===e.exitCode?e:{...e,stdout:t,stderr:n,exitCode:r}}function C(e,t,n={}){let r=O(e),i=E();return new Promise((a,o)=>{let s=p(r,t,{cwd:n.cwd,env:n.env,stdio:[`pipe`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});n.onSpawn?.(s);let c=``,l=n.binaryStdout?[]:void 0,u=``,d=!1,f=B(n.timeoutMs),m=f?setTimeout(()=>{d=!0,H(s,n.detached)},f):null,h=V(s,n);n.binaryStdout||s.stdout.setEncoding(`utf8`),s.stderr.setEncoding(`utf8`),je(s,n.stdin).catch(i=>{h.didAbort||d||Me(i)||(o(Ee(r,e,t,i)),H(s,n.detached))}),s.stdout.on(`data`,e=>{if(n.binaryStdout){l?.push(Buffer.isBuffer(e)?e:Buffer.from(e));return}let t=String(e);c+=t,n.onStdoutChunk?.(t)}),s.stderr.on(`data`,e=>{let t=String(e);u+=t,n.onStderrChunk?.(t)}),s.on(`error`,n=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t),o(P(h,r,e,t,n))}),s.on(`close`,s=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t);let p=s??1;if(!h.didAbort&&d&&f){o(De(r,e,t,f,p,c,u));return}let g=F(h,r,e,t,p,n.allowFailure,c,u);if(g){o(g);return}a({stdout:c,stderr:u,exitCode:p,stdoutBuffer:l?Buffer.concat(l):void 0})})})}async function ye(e){let t=L(e);if(!t)return!1;if(c.isAbsolute(t))return R(t);let n=process.env.PATH;if(!n)return!1;let r=ke();for(let e of n.split(c.delimiter)){let n=e.trim();if(n){for(let e of Ae(t,r))if(await R(c.join(n,e)))return!0}}return!1}async function be(e,t){let r=I(e,t,`executable`);if(r){if(!await R(r))throw new n(`TOOL_MISSING`,`${t} points to a missing or non-executable file: ${r}`,{envName:t,path:r});return r}}async function xe(e,t){let r=I(e,t,`file`);if(r){if(!await z(r))throw new n(`TOOL_MISSING`,`${t} points to a missing or non-file path: ${r}`,{envName:t,path:r});return r}}function Se(e,t,r={}){let i=O(e),a=m(i,t,{cwd:r.cwd,env:r.env,stdio:[`pipe`,`pipe`,`pipe`],encoding:r.binaryStdout?void 0:`utf8`,input:r.stdin,timeout:B(r.timeoutMs),windowsHide:!0,shell:!1,...r.maxBuffer===void 0?{}:{maxBuffer:r.maxBuffer}});if(a.error){let o=a.error.code;throw o===`ETIMEDOUT`?new n(`COMMAND_FAILED`,`${i} timed out after ${B(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:B(r.timeoutMs)},a.error):o===`ENOENT`?k(i,e,a.error):A(i,e,t,a.error)}let o=r.binaryStdout?Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(a.stdout??``):void 0,s=r.binaryStdout?``:typeof a.stdout==`string`?a.stdout:(a.stdout??``).toString(),c=typeof a.stderr==`string`?a.stderr:(a.stderr??``).toString(),l=a.status??1;if(l!==0&&!r.allowFailure)throw M(i,e,t,l,s,c);return{stdout:s,stderr:c,exitCode:l,stdoutBuffer:o}}function Ce(e,t,n={}){return w(e,t,n).pid}function w(e,t,n={}){let r=p(O(e),t,{cwd:n.cwd,env:n.env,stdio:n.stdio??`ignore`,detached:!0,windowsHide:!0,shell:!1}),i=r.pid??0,a=new Promise(e=>{r.once(`error`,t=>{e({pid:i,error:t.message})}),r.once(`exit`,(t,n)=>{e({pid:i,...typeof t==`number`?{exitCode:t}:{},...n?{signal:n}:{}})})});return r.unref(),{pid:i,exited:a}}function T(e,t,n={}){let r=O(e),i=E(),a=p(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??[`ignore`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});i.emitBackgroundSpawn(e,t);let o=``,s=``,c=n.captureOutput??!0,l=V(a,n);return c&&(a.stdout?.setEncoding(`utf8`),a.stderr?.setEncoding(`utf8`),a.stdout?.on(`data`,e=>{o+=e}),a.stderr?.on(`data`,e=>{s+=e})),{child:a,wait:new Promise((c,u)=>{a.on(`error`,n=>{l.dispose(),i.emitBackgroundCompletion(e,t,`error`),u(P(l,r,e,t,n))}),a.on(`close`,a=>{l.dispose(),i.emitBackgroundCompletion(e,t,`exit`);let d=a??1,f=F(l,r,e,t,d,n.allowFailure,o,s);if(f){u(f);return}c({stdout:o,stderr:s,exitCode:d})})})}}function E(){let e=re(),t=e.debug===!0,n=y(process.env.AGENT_DEVICE_EXEC_TRACE??``)===!0;if(!t&&!n)return we();n&&e.flushOnSuccess!==!0&&ne({flushOnSuccess:!0});let r=Date.now(),i=!1;return{emitForegroundCompletion:(e,t)=>{i||(i=!0,D({cmd:e,args:t,startedAtMs:r}))},emitBackgroundSpawn:(e,t)=>{D({cmd:e,args:t,data:{event:`spawn`}})},emitBackgroundCompletion:(e,t,n)=>{i||(i=!0,D({cmd:e,args:t,startedAtMs:r,data:{event:n}}))}}}function we(){return{emitForegroundCompletion:()=>{},emitBackgroundSpawn:()=>{},emitBackgroundCompletion:()=>{}}}function D(e){let t=e.args.slice(0,6);_({level:`debug`,phase:`exec_command`,durationMs:e.startedAtMs===void 0?void 0:Math.max(0,Date.now()-e.startedAtMs),data:{command:e.cmd,argsPrefix:t,...e.args.length>t.length?{omittedArgCount:e.args.length-t.length}:{},...e.data??{}}})}function O(e){let t=L(e);if(!t)throw new n(`INVALID_ARGS`,`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e,hint:`Use a bare command name from PATH or an absolute executable path.`});return t}function Te(e,t,n,r){return r.code===`ENOENT`?k(e,t,r):A(e,t,n,r)}function k(e,t,r){return new n(`TOOL_MISSING`,`${e} not found in PATH`,{cmd:t},r)}function A(e,t,r,i){return new n(`COMMAND_FAILED`,`Failed to run ${e}`,{cmd:t,args:r},i)}function Ee(e,t,r,i){return new n(`COMMAND_FAILED`,`Failed to write stdin for ${e}`,{cmd:t,args:r},i instanceof Error?i:void 0)}function j(e,t,r){return new n(`COMMAND_FAILED`,`request canceled`,{cmd:t,args:r,executable:e,reason:`request_canceled`})}function De(e,t,r,i,a,o,s){return new n(`COMMAND_FAILED`,`${e} timed out after ${i}ms`,{cmd:t,args:r,stdout:o,stderr:s,exitCode:a,timeoutMs:i})}function M(e,t,r,i,a,o){return new n(`COMMAND_FAILED`,`${e} exited with code ${i}`,N({stdout:a,stderr:o,exitCode:i},{cmd:t,args:r}))}function Oe(e,t,r){if(e.exitCode===0)return e;throw new n(`COMMAND_FAILED`,t,N(e,typeof r==`function`?r(e):r))}function N(e,t){return{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,processExitError:!0,...t}}function P(e,t,n,r,i){return e.didAbort?j(t,n,r):Te(t,n,r,i)}function F(e,t,n,r,i,a,o,s){return e.didAbort?j(t,n,r):i!==0&&!a?M(t,n,r,i,o,s):null}function I(e,t,r){let i=e?.trim();if(i){if(!c.isAbsolute(i)||i.includes(`\0`))throw new n(`INVALID_ARGS`,`${t} must be an absolute ${r} path, not ${JSON.stringify(e)}`,{envName:t,path:e});return i}}function L(e){let t=e.trim();return!t||t.includes(`\0`)?null:c.isAbsolute(t)?t:t.includes(`/`)||t.includes(`\\`)?null:me.test(t)?t:null}function ke(){if(process.platform!==`win32`)return[``];let e=process.env.PATHEXT;if(!e)return he;let t=e.split(`;`).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:he}function Ae(e,t){if(process.platform!==`win32`)return[e];let n=e.toLowerCase();return t.some(e=>n.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}async function R(e){try{return await z(e)?(await d(e,process.platform===`win32`?o.F_OK:o.X_OK),!0):!1}catch{return!1}}async function z(e){try{return(await f(e)).isFile()}catch{return!1}}function B(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function V(e,t){let n=!1,r=()=>{n=!0,H(e,t.detached)};return t.signal?.aborted?r():t.signal?.addEventListener(`abort`,r,{once:!0}),{get didAbort(){return n},dispose:()=>{t.signal?.removeEventListener(`abort`,r)}}}function H(e,t){if(t&&e.pid&&process.platform!==`win32`)try{process.kill(-e.pid,`SIGKILL`);return}catch{}e.kill(`SIGKILL`)}async function je(e,t){if(e.stdin){if(t===void 0){e.stdin?.end();return}await l(u.from([t]),e.stdin)}}function Me(e){return e instanceof Error&&`code`in e&&e.code===`EPIPE`}var Ne=e({androidAdbResultError:()=>K,attachAdbFailureHint:()=>G,classifyAdbFailure:()=>W,createAndroidPortReverseManager:()=>We,createDeviceAdbExecutor:()=>Y,createLocalAndroidAdbProvider:()=>Ve,installAndroidAdbPackage:()=>Ke,pullAndroidAdbFile:()=>Ge,resolveAndroidAdbExecutor:()=>He,resolveAndroidAdbProvider:()=>X,resolveAndroidTextInjector:()=>Ue,resolveAndroidTouchInjector:()=>Z,withAndroidAdbProvider:()=>Je});const U=new r,Pe=[{reason:`device_unauthorized`,pattern:/device unauthorized|device still authorizing/,hint:`USB debugging is not authorized — accept the authorization prompt on the device screen (re-plug the cable if none appears), then retry.`},{reason:`device_offline`,pattern:/device offline/,hint:`The device is connected but offline — wait for it to finish booting or run adb reconnect, then retry.`,retriable:!0},{reason:`multiple_devices`,pattern:/more than one (?:device\/emulator|device and emulator)/,hint:`Multiple Android devices are connected — pass --serial <serial> (see adb devices) to select one.`},{reason:`no_devices`,pattern:/no devices\/emulators found|no devices found/,hint:`No Android devices detected — boot an emulator or connect a device and verify it appears in adb devices.`},{reason:`device_not_found`,pattern:/device (?:'[^']*' )?not found/,hint:`The device disconnected or is restarting — verify it is listed in adb devices, then retry.`,retriable:!0},{reason:`server_version_mismatch`,pattern:/adb server version \(\d+\) doesn't match this client/,hint:`Multiple adb installs conflict — adb restarts its server automatically, so retry; align PATH to a single adb to stop recurrences.`,retriable:!0},{reason:`connection_dropped`,pattern:/transport error|connection reset|broken pipe|protocol fault/,hint:`The adb connection dropped — retry; if it persists, run adb kill-server and reconnect the device.`,retriable:!0},{reason:`install_insufficient_storage`,pattern:/install_failed_insufficient_storage/,hint:`The device is out of storage — free up space or uninstall unused apps, then retry the install.`,matchStdout:!0},{reason:`install_update_incompatible`,pattern:/install_failed_update_incompatible/,hint:`The installed app has an incompatible signature — uninstall the existing app first, then retry the install.`,matchStdout:!0},{reason:`install_version_downgrade`,pattern:/install_failed_version_downgrade/,hint:`The APK is older than the installed app — uninstall the app first (or install with downgrade allowed), then retry.`,matchStdout:!0},{reason:`install_failed`,pattern:/install_failed_\w+|install_parse_failed_\w+/,hint:`The Android package installer rejected the APK — see the INSTALL_FAILED code in the error output for the exact cause.`,matchStdout:!0}],Fe={reason:`timeout`,hint:`adb timed out — the adb server may be wedged. Run adb kill-server && adb start-server, check adb devices, then retry.`};function W(e,t=``){let n=e.toLowerCase(),r=t.toLowerCase();for(let{pattern:e,matchStdout:t,...i}of Pe)if(e.test(n)||t&&e.test(r))return i}function G(e){if(!(e instanceof n)||e.code!==`COMMAND_FAILED`)return e;let t=Ie(e);return t&&(e.details={...e.details,adbFailure:t.reason,...typeof e.details?.hint==`string`?{}:{hint:t.hint},...t.retriable!==void 0&&e.details?.retriable===void 0?{retriable:t.retriable}:{}}),e}function Ie(e){return typeof e.details?.timeoutMs==`number`?Fe:W(typeof e.details?.stderr==`string`?e.details.stderr:``,typeof e.details?.stdout==`string`?e.details.stdout:``)}function K(e,t,r){return G(new n(`COMMAND_FAILED`,e,t.exitCode===0?{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode,...r}:N(t,r)))}function q(e){return async(...t)=>{try{return await e(...t)}catch(e){throw G(e)}}}const Le=new WeakSet;function Re(e){if(Le.has(e))return e;let t={...e,exec:q(J(e.exec)),...e.pull?{pull:q(J(e.pull))}:{},...e.install?{install:q(J(e.install))}:{},...e.installBundle?{installBundle:q(e.installBundle)}:{}};return Le.add(t),t}function J(e){return async(...t)=>S(await e(...t))}function Y(e){return ze(e.id)}function ze(e){return q(async(t,n)=>await x(async()=>await _e(`adb`,[`-s`,e,...t],{...n,detached:process.platform!==`win32`})))}function Be(e){return(t,n)=>{let r=T(`adb`,[`-s`,e,...t],{...n,allowFailure:!0,captureOutput:!1});return r.wait.catch(()=>{}),r.child}}function Ve(e){let t=Y(e);return{exec:t,spawn:Be(e.id),reverse:Ze(t),pull:async(e,n,r)=>await t([`pull`,e,n],r),install:async(e,n)=>{let{installArgs:r,execOptions:i}=$(n);return await t([`install`,...r,e],i)}}}function He(e,t){let n=U.getStore();return t||(n?.serial===e.id?n.provider.exec:Y(e))}function X(e,t){if(t)return Q(t);let n=U.getStore();return n?.serial===e.id?Q(n.provider):Ve(e)}function Ue(e){let t=U.getStore();return t?.serial===e.id?t.provider.text:void 0}function Z(e){let t=U.getStore();return t?.serial===e.id?t.provider.touch:void 0}function We(e){let t=Q(e),r=t.reverse??Ze(t.exec),i=new Map;return{async ensure(e,t){let a=i.get(e.local);if(a&&a.ownerId!==e.ownerId)throw new n(`COMMAND_FAILED`,`Android port reverse ${e.local} is already owned by ${a.ownerId??`another session`}`,{current:a,requested:e});a?.remote!==e.remote&&(await r.ensure(e,t),i.set(e.local,{...e}))},async remove(e,t){if(!i.has(e)){await r.remove(e,t);return}await r.remove(e,t),i.delete(e)},async removeAllOwned(e,t){let n=[...i.values()].filter(t=>t.ownerId===e).map(e=>e.local);if(n.length===0){await r.removeAllOwned(e,t);return}for(let e of n)await r.remove(e,t),i.delete(e)},async list(e){return r.list?await r.list(e):[...i.values()]}}}function Q(e){return Re(typeof e==`function`?{exec:e}:e)}async function Ge(e,t,r){let{device:i,provider:a,...o}=r??{},s=qe(i,a),c=s?.pull;if(c)return await x(async()=>await c(e,t,o));let l=s?.exec;if(!l)throw new n(`COMMAND_FAILED`,`Android adb pull requires an adb provider`);return await x(async()=>await l([`pull`,e,t],o))}async function Ke(e,t){let{device:r,provider:i,...a}=t??{},o=qe(r,i),s=o?.install;if(s)return await x(async()=>await s(e,a));let c=o?.exec;if(!c)throw new n(`COMMAND_FAILED`,`Android adb install requires an adb provider`);let{installArgs:l,execOptions:u}=$(a);return await x(async()=>await c([`install`,...l,e],u))}function qe(e,t){if(t)return Q(t);if(e)return X(e);let n=U.getStore();if(n)return Q(n.provider)}async function Je(e,t,n){if(!e)return await n();let r={provider:Q(e),serial:t.serial},i=Ye(r);return await U.run(r,async()=>await ge(i,n))}function Ye(e){return(t,n,r)=>{if(t!==`adb`)return;let i=Xe(n,e.serial);if(i)return x(async()=>await e.provider.exec(i,r))}}function Xe(e,t){if(!(e[0]!==`-s`||!e[1])&&e[1]===t)return e.slice(2)}function Ze(e){let t=new Map;return{async ensure(n,r){if(await e([`reverse`,n.local,n.remote],{allowFailure:!1,signal:r?.signal,timeoutMs:r?.timeoutMs}),n.ownerId){let e=t.get(n.ownerId)??new Set;e.add(n.local),t.set(n.ownerId,e)}},async remove(n,r){let i=await e([`reverse`,`--remove`,n],{allowFailure:!0,signal:r?.signal,timeoutMs:r?.timeoutMs});if(i.exitCode!==0&&!$e(i.stdout,i.stderr))throw K(`Failed to remove Android port reverse ${n}`,i,{local:n});for(let e of t.values())e.delete(n)},async removeAllOwned(e,n){let r=[...t.get(e)??[]];for(let e of r)await this.remove(e,n);t.delete(e)},async list(n){let r=await e([`reverse`,`--list`],{allowFailure:!0,signal:n?.signal,timeoutMs:n?.timeoutMs});return r.exitCode===0?Qe(r.stdout,t):[]}}}function Qe(e,t){let n=new Map;for(let[e,r]of t)for(let t of r)n.set(t,e);return e.split(`
4
4
  `).map(e=>e.trim().split(/\s+/)).filter(e=>e.length>=3).map(([,e,t])=>{let r=e;return{local:r,remote:t,ownerId:n.get(r)}})}function $e(e,t){let n=`${e}\n${t}`.toLowerCase();return n.includes(`listener`)&&n.includes(`not found`)}function $(e){let{replace:t,allowTestPackages:n,allowDowngrade:r,grantPermissions:i,...a}=e??{},o=[];return t&&o.push(`-r`),n&&o.push(`-t`),r&&o.push(`-d`),i&&o.push(`-g`),{installArgs:o,execOptions:a}}export{g as A,Se as C,y as D,ue as E,ae as F,te as I,oe as M,re as N,de as O,ne as P,ve as S,x as T,xe as _,We as a,Ce as b,He as c,Z as d,S as f,be as g,Oe as h,W as i,_ as j,ie as k,X as l,R as m,K as n,Ke as o,N as p,G as r,Ge as s,Ne as t,Ue as u,_e as v,ye as w,w as x,T as y};
@@ -1 +1 @@
1
- import{F as e}from"./sdk-contracts.js";const t=`user-installed`;function n(e){return e??`user-installed`}function r(t){if(t===void 0)throw new e(`INVALID_ARGS`,`appsFilter must be resolved before executing the apps command`);return t}export{r as n,n as r,t};
1
+ import{_ as e}from"./sdk-contracts.js";const t=`user-installed`;function n(e){return e??`user-installed`}function r(t){if(t===void 0)throw new e(`INVALID_ARGS`,`appsFilter must be resolved before executing the apps command`);return t}export{r as n,n as r,t};
@@ -1,2 +1,2 @@
1
- import{F as e,I as t,a as n,i as r}from"./sdk-contracts.js";import{a as i,i as a,n as o,t as s}from"./sdk-batch.js";function c(t,n,r,i){let a=r(t[n]);if(a===void 0)throw new e(`COMMAND_FAILED`,i,{response:t});return a}function l(e,t,n){return n(e[t])}function u(e,t,n){let r=e[t];return r===null?null:n(r)}function d(e,t){return c(e,t,x,`Daemon response is missing "${t}".`)}function f(e,t){return l(e,t,x)}function p(e,t){return u(e,t,x)}function m(e,t){return c(e,t,S,`Daemon response is missing numeric "${t}".`)}function h(e,t){return c(e,t,C,`Daemon response has invalid "${t}".`)}function g(e,t){return c(e,t,w,`Daemon response has invalid "${t}".`)}function _(e,t){return l(e,t,T)??`mobile`}function v(e){if(!D(e))return;let t=b(e,`x`),n=b(e,`y`),r=b(e,`width`),i=b(e,`height`);if(!(t===void 0||n===void 0||r===void 0||i===void 0))return{x:t,y:n,width:r,height:i}}function y(e){if(!D(e))return;let t=b(e,`x`),n=b(e,`y`);if(!(t===void 0||n===void 0))return{x:t,y:n}}function b(e,t){let n=e[t];return typeof n==`number`?n:void 0}function x(e){return typeof e==`string`&&e.length>0?e:void 0}function S(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function C(e){return e===`apple`?`ios`:e===`ios`||e===`macos`||e===`android`||e===`linux`||e===`web`?e:void 0}function w(e){return e===`simulator`||e===`emulator`||e===`device`?e:void 0}function T(e){return e===`tv`||e===`mobile`||e===`desktop`?e:void 0}function E(t){if(!D(t))throw new e(`COMMAND_FAILED`,`Daemon returned an unexpected response shape.`,{value:t});return t}function D(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function O(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function k(e){return e.split(`
2
- `).map(e=>e.trim()).filter(e=>e.length>0)}function A(e){return Number.isInteger(e)&&e>=1&&e<=1e3}function j(t,n){if(t>n)throw new e(`INVALID_ARGS`,`batch has ${t} steps; max allowed is ${n}.`)}function M(t,n){if(!D(t))throw new e(`INVALID_ARGS`,`Invalid batch step ${n}.`);return t}function N(t,n){let r=t.input;if(!D(r))throw new e(`INVALID_ARGS`,`Batch step ${n} input must be an object.`);return r}function P(t,n){if(t!==void 0)try{return r.parse(t)}catch(t){throw new e(`INVALID_ARGS`,`Batch step ${n} runtime is invalid: ${t instanceof Error?t.message:String(t)}`)}}const F=new Set(s);async function I(e,n,r){let i=U(e.flags),a=i?.batchOnError??`stop`;if(a!==`stop`)return W(`INVALID_ARGS`,`Unsupported batch on-error mode: ${a}.`);let o=i?.batchMaxSteps??100;if(!A(o))return W(`INVALID_ARGS`,`Invalid batch max-steps: ${String(i?.batchMaxSteps)}`);try{let t=L(i?.batchSteps,o),a=Date.now(),s=[];for(let[i,a]of t.entries()){let o=await H(e,n,a,r,i+1,i===t.length-1);if(!o.ok)return{ok:!1,error:{code:o.error.code,message:`Batch failed at step ${o.step} (${a.command}): ${o.error.message}`,hint:o.error.hint,diagnosticId:o.error.diagnosticId,logPath:o.error.logPath,details:{...o.error.details??{},step:o.step,command:a.command,positionals:a.positionals,executed:i,total:t.length,partialResults:s}}};s.push(o.result)}return{ok:!0,data:{total:t.length,executed:t.length,totalDurationMs:Date.now()-a,results:s}}}catch(e){let n=t(e);return W(n.code,n.message,n.details)}}function L(t,n){if(!Array.isArray(t)||t.length===0)throw new e(`INVALID_ARGS`,`batch requires a non-empty batchSteps array.`);j(t.length,n);let r=[];for(let n=0;n<t.length;n+=1){let o=t[n];if(!D(o))throw new e(`INVALID_ARGS`,`Invalid batch step at index ${n}.`);let s=Object.keys(o).filter(e=>!F.has(e));if(s.length>0){let t=s.map(e=>`"${e}"`).join(`, `);throw new e(`INVALID_ARGS`,`Batch step ${n+1} has unknown field(s): ${t}. Allowed fields: command, positionals, flags, runtime.`)}let c=i(o.command);if(!c)throw new e(`INVALID_ARGS`,`Batch step ${n+1} requires command.`);if(a(c,n+1),o.positionals!==void 0&&!Array.isArray(o.positionals))throw new e(`INVALID_ARGS`,`Batch step ${n+1} positionals must be an array.`);let l=o.positionals??[];if(l.some(e=>typeof e!=`string`))throw new e(`INVALID_ARGS`,`Batch step ${n+1} positionals must contain only strings.`);if(o.flags!==void 0&&!D(o.flags))throw new e(`INVALID_ARGS`,`Batch step ${n+1} flags must be an object.`);r.push({command:c,positionals:l,flags:o.flags??{},runtime:P(o.runtime,n+1)})}return r}function R(e,t){let{batchSteps:n,batchOnError:r,batchMaxSteps:i,...a}=t??{};return z(U(e),a)}function z(e,t){let n=U(e)??{},r=t;for(let e of o)r[e]===void 0&&n[e]!==void 0&&(r[e]=n[e]);return t}function B(e,t){return n(e)?t?e:`digest`:e}function V(e,t){let n=e?.responseLevel,r=B(n,t);return r===n?e:{...e,responseLevel:r}}async function H(e,t,n,r,i,a){let o=Date.now(),s=R(e.flags,n.flags);s.session===void 0&&(s.session=t);let c=await r({token:e.token,session:t,command:n.command,positionals:n.positionals,flags:s,runtime:n.runtime===void 0?e.runtime:n.runtime,meta:V(e.meta,a)}),l=Date.now()-o;return c.ok?{ok:!0,step:i,result:{step:i,command:n.command,ok:!0,data:c.data??{},durationMs:l}}:{ok:!1,step:i,error:c.error}}function U(e){return e}function W(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{details:n}:{}}}}export{h as _,P as a,O as b,E as c,v as d,_ as f,m as g,g as h,A as i,D as l,f as m,I as n,N as o,p,j as r,M as s,z as t,y as u,d as v,k as y};
1
+ import{_ as e,a as t,i as n,v as r}from"./sdk-contracts.js";import{a as i,i as a,n as o,t as s}from"./sdk-batch.js";function c(t,n,r,i){let a=r(t[n]);if(a===void 0)throw new e(`COMMAND_FAILED`,i,{response:t});return a}function l(e,t,n){return n(e[t])}function u(e,t,n){let r=e[t];return r===null?null:n(r)}function d(e,t){return c(e,t,x,`Daemon response is missing "${t}".`)}function f(e,t){return l(e,t,x)}function p(e,t){return u(e,t,x)}function m(e,t){return c(e,t,S,`Daemon response is missing numeric "${t}".`)}function h(e,t){return c(e,t,C,`Daemon response has invalid "${t}".`)}function g(e,t){return c(e,t,w,`Daemon response has invalid "${t}".`)}function _(e,t){return l(e,t,T)??`mobile`}function v(e){if(!D(e))return;let t=b(e,`x`),n=b(e,`y`),r=b(e,`width`),i=b(e,`height`);if(!(t===void 0||n===void 0||r===void 0||i===void 0))return{x:t,y:n,width:r,height:i}}function y(e){if(!D(e))return;let t=b(e,`x`),n=b(e,`y`);if(!(t===void 0||n===void 0))return{x:t,y:n}}function b(e,t){let n=e[t];return typeof n==`number`?n:void 0}function x(e){return typeof e==`string`&&e.length>0?e:void 0}function S(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function C(e){return e===`apple`?`ios`:e===`ios`||e===`macos`||e===`android`||e===`linux`||e===`web`?e:void 0}function w(e){return e===`simulator`||e===`emulator`||e===`device`?e:void 0}function T(e){return e===`tv`||e===`mobile`||e===`desktop`?e:void 0}function E(t){if(!D(t))throw new e(`COMMAND_FAILED`,`Daemon returned an unexpected response shape.`,{value:t});return t}function D(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function O(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function k(e){return e.split(`
2
+ `).map(e=>e.trim()).filter(e=>e.length>0)}function A(e){return Number.isInteger(e)&&e>=1&&e<=1e3}function j(t,n){if(t>n)throw new e(`INVALID_ARGS`,`batch has ${t} steps; max allowed is ${n}.`)}function M(t,n){if(!D(t))throw new e(`INVALID_ARGS`,`Invalid batch step ${n}.`);return t}function N(t,n){let r=t.input;if(!D(r))throw new e(`INVALID_ARGS`,`Batch step ${n} input must be an object.`);return r}function P(t,r){if(t!==void 0)try{return n.parse(t)}catch(t){throw new e(`INVALID_ARGS`,`Batch step ${r} runtime is invalid: ${t instanceof Error?t.message:String(t)}`)}}const F=new Set(s);async function I(e,t,n){let i=U(e.flags),a=i?.batchOnError??`stop`;if(a!==`stop`)return W(`INVALID_ARGS`,`Unsupported batch on-error mode: ${a}.`);let o=i?.batchMaxSteps??100;if(!A(o))return W(`INVALID_ARGS`,`Invalid batch max-steps: ${String(i?.batchMaxSteps)}`);try{let r=L(i?.batchSteps,o),a=Date.now(),s=[];for(let[i,a]of r.entries()){let o=await H(e,t,a,n,i+1,i===r.length-1);if(!o.ok)return{ok:!1,error:{code:o.error.code,message:`Batch failed at step ${o.step} (${a.command}): ${o.error.message}`,hint:o.error.hint,diagnosticId:o.error.diagnosticId,logPath:o.error.logPath,details:{...o.error.details??{},step:o.step,command:a.command,positionals:a.positionals,executed:i,total:r.length,partialResults:s}}};s.push(o.result)}return{ok:!0,data:{total:r.length,executed:r.length,totalDurationMs:Date.now()-a,results:s}}}catch(e){let t=r(e);return W(t.code,t.message,t.details)}}function L(t,n){if(!Array.isArray(t)||t.length===0)throw new e(`INVALID_ARGS`,`batch requires a non-empty batchSteps array.`);j(t.length,n);let r=[];for(let n=0;n<t.length;n+=1){let o=t[n];if(!D(o))throw new e(`INVALID_ARGS`,`Invalid batch step at index ${n}.`);let s=Object.keys(o).filter(e=>!F.has(e));if(s.length>0){let t=s.map(e=>`"${e}"`).join(`, `);throw new e(`INVALID_ARGS`,`Batch step ${n+1} has unknown field(s): ${t}. Allowed fields: command, positionals, flags, runtime.`)}let c=i(o.command);if(!c)throw new e(`INVALID_ARGS`,`Batch step ${n+1} requires command.`);if(a(c,n+1),o.positionals!==void 0&&!Array.isArray(o.positionals))throw new e(`INVALID_ARGS`,`Batch step ${n+1} positionals must be an array.`);let l=o.positionals??[];if(l.some(e=>typeof e!=`string`))throw new e(`INVALID_ARGS`,`Batch step ${n+1} positionals must contain only strings.`);if(o.flags!==void 0&&!D(o.flags))throw new e(`INVALID_ARGS`,`Batch step ${n+1} flags must be an object.`);r.push({command:c,positionals:l,flags:o.flags??{},runtime:P(o.runtime,n+1)})}return r}function R(e,t){let{batchSteps:n,batchOnError:r,batchMaxSteps:i,...a}=t??{};return z(U(e),a)}function z(e,t){let n=U(e)??{},r=t;for(let e of o)r[e]===void 0&&n[e]!==void 0&&(r[e]=n[e]);return t}function B(e,n){return t(e)?n?e:`digest`:e}function V(e,t){let n=e?.responseLevel,r=B(n,t);return r===n?e:{...e,responseLevel:r}}async function H(e,t,n,r,i,a){let o=Date.now(),s=R(e.flags,n.flags);s.session===void 0&&(s.session=t);let c=await r({token:e.token,session:t,command:n.command,positionals:n.positionals,flags:s,runtime:n.runtime===void 0?e.runtime:n.runtime,meta:V(e.meta,a)}),l=Date.now()-o;return c.ok?{ok:!0,step:i,result:{step:i,command:n.command,ok:!0,data:c.data??{},durationMs:l}}:{ok:!1,step:i,error:c.error}}function U(e){return e}function W(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{details:n}:{}}}}export{h as _,P as a,O as b,E as c,v as d,_ as f,m as g,g as h,A as i,D as l,f as m,I as n,N as o,p,j as r,M as s,z as t,y as u,d as v,k as y};