agent-device 0.17.0 → 0.17.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.0.apk → agent-device-android-multitouch-helper-0.17.2.apk} +0 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.2.apk.sha256 +1 -0
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.0.manifest.json → agent-device-android-multitouch-helper-0.17.2.manifest.json} +4 -4
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.0.apk → agent-device-android-snapshot-helper-0.17.2.apk} +0 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.2.apk.sha256 +1 -0
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.0.manifest.json → agent-device-android-snapshot-helper-0.17.2.manifest.json} +6 -6
- package/dist/src/123.js +1 -0
- package/dist/src/1352.js +1 -1
- package/dist/src/1534.js +1 -0
- package/dist/src/1620.js +1 -0
- package/dist/src/1644.js +2 -0
- package/dist/src/2284.js +1 -0
- package/dist/src/2403.js +3 -0
- package/dist/src/2415.js +28 -29
- package/dist/src/2474.js +1 -0
- package/dist/src/2672.js +1 -0
- package/dist/src/3393.js +1 -0
- package/dist/src/4778.js +1 -1
- package/dist/src/5898.js +1 -0
- package/dist/src/7556.js +1 -1
- package/dist/src/7847.js +1 -1
- package/dist/src/8173.js +27 -0
- package/dist/src/8407.js +1 -0
- package/dist/src/8699.js +1 -1
- package/dist/src/8806.js +3 -3
- package/dist/src/9010.js +1 -0
- package/dist/src/9238.js +3 -3
- package/dist/src/9471.js +1 -1
- package/dist/src/9542.js +3 -3
- package/dist/src/9616.js +1 -0
- package/dist/src/9673.js +1 -0
- package/dist/src/9974.js +1 -0
- package/dist/src/android-adb.d.ts +12 -6
- package/dist/src/android-adb.js +1 -1
- package/dist/src/android-snapshot-helper.d.ts +15 -7
- package/dist/src/android.js +1 -1
- package/dist/src/apple.js +1 -1
- package/dist/src/apps.js +2 -2
- package/dist/src/args.js +2 -2
- package/dist/src/batch.d.ts +16 -4
- package/dist/src/cli.js +18 -42
- package/dist/src/command-surface.js +1 -1
- package/dist/src/contracts.d.ts +28 -4
- package/dist/src/contracts.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.d.ts +3 -1
- package/dist/src/generic.js +13 -11
- package/dist/src/index.d.ts +142 -73
- package/dist/src/index.js +1 -1
- package/dist/src/input-actions.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/internal/png-worker.d.ts +26 -0
- package/dist/src/internal/png-worker.js +1 -0
- package/dist/src/metro.d.ts +3 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-trace-recording.js +26 -0
- package/dist/src/record-trace.js +1 -26
- package/dist/src/remote-config.d.ts +33 -7
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.d.ts +3 -3
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +2 -2
- package/dist/src/session.js +10 -11
- package/dist/src/snapshot.js +1 -1
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +6 -2
- package/package.json +7 -4
- package/server.json +2 -2
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.0.apk.sha256 +0 -1
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.0.apk.sha256 +0 -1
- package/dist/src/1998.js +0 -1
- package/dist/src/2805.js +0 -1
- package/dist/src/4057.js +0 -1
- package/dist/src/5792.js +0 -1
- package/dist/src/6085.js +0 -1
- package/dist/src/6232.js +0 -1
- package/dist/src/8020.js +0 -1
- package/dist/src/8502.js +0 -1
- package/dist/src/940.js +0 -1
- package/dist/src/9404.js +0 -1
- package/dist/src/9533.js +0 -1
- package/dist/src/command-metadata.js +0 -1
- /package/dist/src/{1393.js → 3675.js} +0 -0
- /package/dist/src/{5310.js → 695.js} +0 -0
package/dist/src/snapshot.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__webpack_require__ as e}from"./rslib-runtime.js";import{promises as t}from"node:fs";import a from"node:os";import n from"node:path";import{centerOfRect as s}from"./
|
|
1
|
+
import{__webpack_require__ as e}from"./rslib-runtime.js";import{promises as t}from"node:fs";import a from"node:os";import n from"node:path";import{centerOfRect as s}from"./1644.js";import{normalizeError as o,AppError as r}from"./9152.js";import{withDiagnosticTimer as i,emitDiagnostic as l}from"./7599.js";import{pressAndroid as d,backAndroid as p}from"./input-actions.js";import{createDaemonRuntimeSessionStore as u,captureSnapshot as c,dispatchCommand as f,resolveSnapshotScope as m,runMacOsAlertAction as h,errorResponse as w,runIosRunnerCommand as g,isCommandSupportedOnDevice as y,snapshotAndroid as _,annotateScreenshotWithRefs as v,context_contextFromFlags as S}from"./2415.js";import{successText as b}from"./1534.js";import{sleep as I}from"./4829.js";import{buildSnapshotSession as A,dispatchWaitViaRuntime as R,createDaemonRuntimePolicy as C,recordIfSession as N,resolveSessionDevice as M,withSessionlessRunnerCleanup as P}from"./selector-runtime.js";import{parseTimeout as k}from"./2284.js";import{SETTINGS_INVALID_ARGS_MESSAGE as D,isMacOsSettingSupported as E,getUnsupportedMacOsSettingMessage as K}from"./1352.js";import{createAgentDevice as O}from"./123.js";var U={};e.r(U),e.d(U,{handleSnapshotCommands:()=>em});let x=new Set(["com.android.permissioncontroller","com.google.android.permissioncontroller","com.google.android.packageinstaller","com.android.packageinstaller"]),L=new Set(["android","com.android.systemui"]),B=/^android:id\/(?:alertTitle|message|button[123]|parentPanel|buttonPanel|contentPanel)$/i,H=/^android:id\/button[123]$/i,$=/(?:^|:)id\/permission_/i,q=/\b(?:is(?:n't| not) responding|keeps stopping|has stopped|close app|app info)\b/i,T=/^(?:ok|allow|allow all|while using the app|only this time|yes|continue|save|confirm|turn on|open settings)$/i,F=/^(?:cancel|deny|don.t allow|don’t allow|not now|no|dismiss|close|close app|later|skip)$/i;function j(e,t){let a=t[0];if(!a)return;let n=z(e,a.index);for(let a of t.slice(1)){let t=new Set(z(e,a.index));for(let e=n.length-1;e>=0;e-=1)t.has(n[e])||n.splice(e,1)}return n[n.length-1]}function z(e,t){let a=new Map(e.map(e=>[e.index,e])),n=[],s=a.get(t);for(;s;)n.push(s.index),s=void 0===s.parentIndex?void 0:a.get(s.parentIndex);return n.reverse()}function G(e,t){let a=new Map;for(let t of e){if(void 0===t.parentIndex)continue;let e=a.get(t.parentIndex)??[];e.push(t),a.set(t.parentIndex,e)}let n=new Set([t]),s=[t];for(let e of s)for(let t of a.get(e)??[])n.has(t.index)||(n.add(t.index),s.push(t.index));return e.filter(e=>n.has(e.index))}function V(e){let t=e.type??"",a=e.identifier??"";return!!(e.hittable||/\bbutton\b/i.test(t)||H.test(a)||/(?:^|:)id\/permission_(?:allow|deny)/i.test(a))}function W(e){if(!e)return"";let t=[e.label,e.value].filter(e=>"string"==typeof e&&e.trim().length>0);return t[0]?.trim()??""}async function J(e,t,a={}){if("wait"===t)return await Q(e,a.timeoutMs??1e4);if("get"===t){var n;let t=await Z(e);return{kind:"alertStatus",platform:"android",action:"get",alert:n=t?.alert??null,...n?b("Alert visible"):b("No alert visible")}}return await X(e,t)}async function Q(e,t){let a=Date.now(),n=await Y(e,t);if(!n)throw new r("COMMAND_FAILED","alert wait timed out");return{kind:"alertWait",platform:"android",action:"wait",alert:n.alert,waitedMs:Date.now()-a,...b("Alert visible")}}async function X(e,t){var a;let n,s,o=await Y(e,2e3);if(!o)throw new r("COMMAND_FAILED","alert not found",{hint:"If a sheet is visible in snapshot but alert reports no alert, it is likely app-owned UI. Use snapshot -i and press the visible label/ref."});let i=(a=o.buttons,n="accept"===t?"accept":"dismiss",(s=a.find(e=>e.role===n))||("dismiss"===t?a.find(e=>"neutral"===e.role)??null:1===a.length?a[0]??null:null));if(i)return await d(e,i.x,i.y),ee(t,o.alert,i.label);if("dismiss"===t)return await p(e),ee(t,o.alert,"Back");throw new r("COMMAND_FAILED","alert accept found an alert but no accept button",{alert:o.alert,hint:"Inspect alert get --json for visible buttons, then use press by visible label/ref if needed."})}async function Y(e,t){let a=Date.now();for(;Date.now()-a<t;){let t=await Z(e);if(t)return t;await I(300)}return null}async function Z(e){return function(e){var t,a,n,o;let r,i=function(e){let t=e.filter(e=>{var t;let a;return a=(t=e).bundleId??"",x.has(a)||$.test(t.identifier??"")});if(t.length)return{nodes:t,source:"permission"};let a=function(e){let t=e.filter(e=>{var t;let a;return a=(t=e).bundleId??"",L.has(a)&&q.test(W(t))});if(0===t.length)return[];let a=j(e,t);return void 0===a?t:G(e,a).filter(e=>e.bundleId&&L.has(e.bundleId))}(e);return a.length?{nodes:a,source:"system-dialog"}:{nodes:function(e){var t;let a,n,s=e.filter(e=>{var t;return t=e.type??"",/(?:^|[.$])[^.]*Dialog$/i.test(t)}),o=e.filter(e=>B.test(e.identifier??"")),r=s.length?[...s,...o]:(a=(t=o).some(e=>H.test(e.identifier??"")),n=t.some(e=>!H.test(e.identifier??"")),a&&n?t:[]);if(0===r.length)return[];let i=j(e,r);return void 0===i?r:G(e,i)}(e),source:"native-dialog"}}(e),l=i.nodes;if(0===l.length)return null;let d=function(e){let t=new Set,a=[];for(let n of e){let e=W(n);if(!e||!n.rect||!V(n))continue;let o=e.trim().toLowerCase();if(!o||t.has(o))continue;t.add(o);let r=s(n.rect);a.push({label:e,x:r.x,y:r.y,role:function(e,t){var a;let n=(a=e.identifier??"",/(?:^|:)id\/button1$/i.test(a)?"accept":/(?:^|:)id\/button2$/i.test(a)?"dismiss":/(?:^|:)id\/button3$/i.test(a)?"neutral":/(?:^|:)id\/permission_allow/i.test(a)?"accept":/(?:^|:)id\/permission_deny/i.test(a)?"dismiss":null);return n||(T.test(t.trim())?"accept":F.test(t.trim())?"dismiss":"neutral")}(n,e)})}return a}(l),p=l.filter(e=>W(e)&&!V(e)),u=W((t=p).find(e=>/(?:^|:)id\/(?:alertTitle|permission_message)$/i.test(e.identifier??"")))||W(t[0]),c=(a=p,n=u,(r=a.map(e=>W(e)).filter(e=>e&&e!==n)).length?[...new Set(r)].join("\n"):void 0),f=(o=l,o.find(e=>e.bundleId)?.bundleId);return{alert:{...u?{title:u}:{},...c?{message:c}:{},buttons:d.map(e=>e.label),platform:"android",source:i.source,...f?{packageName:f}:{}},buttons:d}}((await i("snapshot_capture",async()=>await _(e,{helperWaitForIdleTimeoutMs:0,includeHiddenContentHints:!1}),{backend:"android",purpose:"alert"})).nodes)}function ee(e,t,a){return{kind:"alertHandled",platform:"android",action:e,handled:!0,alert:t,button:a,...b(`Alert ${e}ed`)}}async function et(e){var t;let{req:a,logPath:n,session:s,device:o}=e,r="accept"===(t=a.positionals?.[0])||"dismiss"===t||"wait"===t?t:"get",i=s?"frontmost-app"===s.surface?{surface:"frontmost-app"}:{bundleId:s.appBundleId,surface:s.surface}:{};if(!y("alert",o))return w("UNSUPPORTED_OPERATION","alert is not supported on this device");if("android"===o.platform){let t=k(a.positionals?.[1])??1e4;return eo(e,await J(o,r,{timeoutMs:t}))}if("macos"===o.platform){let t=async e=>await h(e,i);return await ea(e,r,t)}let l={verbose:a.flags?.verbose,logPath:n,traceLogPath:s?.trace?.outPath,requestId:a.meta?.requestId},d=async e=>await g(o,{command:"alert",action:e,appBundleId:s?.appBundleId},l);return await ea(e,r,d)}async function ea(e,t,a){if("wait"===t)return await en(e,a);let n="accept"===t||"dismiss"===t?t:"get";return"accept"===n||"dismiss"===n?await es(e,n,a):eo(e,await a("get"))}async function en(e,t){let a=k(e.req.positionals?.[1])??1e4,n=Date.now();for(;Date.now()-n<a;){try{return eo(e,await t("get"))}catch{}await I(300)}return w("COMMAND_FAILED","alert wait timed out")}async function es(e,t,a){var n,s;let o,i,l=Date.now();for(;Date.now()-l<2e3;){try{return eo(e,await a(t))}catch(t){i=t;let e=String(t?.message??"").toLowerCase();if(!e.includes("alert not found")&&!e.includes("no alert"))break}await I(300)}throw(n=i)instanceof r&&(s=n,(o=String(s?.message??"").toLowerCase()).includes("alert not found")||o.includes("no alert"))?new r(n.code,n.message,{...n.details??{},hint:"If the permission sheet is visible in snapshot or screenshot but alert reports no alert, take a scoped snapshot around the visible button label and use press @ref."}):n}function eo(e,t){return N(e.sessionStore,e.session,e.req,t),{ok:!0,data:t}}async function er(e){let{req:t,logPath:a,sessionStore:n,session:s,device:o,parsed:r}=e,{setting:i,state:l,appBundleId:d,permissionTarget:p,latitude:u,longitude:c}=r;if(!y("settings",o))return w("UNSUPPORTED_OPERATION","settings is not supported on this device");if("macos"===o.platform&&!E(i))return w("INVALID_ARGS",K(i));let m=d??s?.appBundleId;if("clear-app-state"===i&&!m)return w("INVALID_ARGS","settings clear-app-state requires an app id when no app is bound to the session");let h="clear-app-state"===i?[i,l,m??""]:"permission"===i?[i,l,p??"",t.positionals?.[3]??"",m??""]:"location"===i&&"set"===l?[i,l,u??"",c??"",m??""]:[i,l,m??""],g=await f(o,"settings",h,t.flags?.out,{...S(a,t.flags,m,s?.trace?.outPath)});return N(n,s,t,g??{setting:i,state:l}),{ok:!0,data:g??{setting:i,state:l}}}async function ei(e){var t,a;let n;if("snapshot"!==e.command||"android"!==e.device.platform)return;let s=o(e.error);if("COMMAND_FAILED"===(t=s).code&&(a=t,n=`${a.message}
|
|
2
2
|
${a.hint??""}`,/Android UI hierarchy dump timed out/i.test(n)||/Stock UIAutomator fallback was skipped/i.test(n)||/Android accessibility snapshots can be blocked/i.test(n)||function(e){if(!e||"object"!=typeof e)return!1;let t=String(e.errorType??""),a=String(e.message??"");return/TimeoutException/i.test(t)||/timed out/i.test(a)}(t.details?.helper)||function(e){var t;if(!e)return!1;let a=e?.timeoutMs,n=e?.cmd,s=Array.isArray(t=e?.args)?t.map(String):"string"==typeof t?t.split(/\s+/):[];return"number"==typeof a&&"adb"===n&&s.includes("uiautomator")&&s.includes("dump")}(t.details)))return{ok:!1,error:{...s,details:{...s.details??{},androidSnapshotTimeoutScreenshot:await el(e)}}}}async function el(e){try{var s,r,i;let o=await t.mkdtemp(n.join(a.tmpdir(),"agent-device-android-snapshot-timeout-")),d=n.join(o,"snapshot-timeout-overlay-refs.png"),p=(s=await f(e.device,"screenshot",[d],void 0,{...S(e.logPath,{screenshotNoStabilize:!0},e.session?.appBundleId,e.session?.trace?.outPath),surface:e.session?.surface}),r=d,(i=s,"object"==typeof i&&null!==i&&"path"in i&&"string"==typeof i.path)?s.path:r);await t.access(p);let u=await ed(p,e.session);return l({level:"warn",phase:"android_snapshot_timeout_screenshot_captured",data:{path:p,overlayRefCount:"overlayRefCount"in u?u.overlayRefCount:void 0,overlayRefsAnnotated:"overlayRefsAnnotated"in u?u.overlayRefsAnnotated:void 0}}),u}catch(t){let e=o(t);return l({level:"warn",phase:"android_snapshot_timeout_screenshot_failed",data:{error:e.message}}),{captureFailed:!0,error:e.message}}}async function ed(e,t){if(!t?.snapshot)return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:"unavailable",overlayRefCount:0};try{let a=await v({screenshotPath:e,snapshot:t.snapshot});return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:a.length>0,overlayRefCount:a.length,overlayRefSource:"session-snapshot",overlayRefs:a}}catch(a){let t=o(a);return l({level:"warn",phase:"android_snapshot_timeout_screenshot_overlay_failed",data:{path:e,error:t.message}}),{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:"session-snapshot",overlayRefCount:0,overlayAnnotationError:t.message}}}async function ep(e){return await ec({...e,command:"snapshot",unsupportedMessage:"snapshot is not supported on this device",execute:async({runtime:e,sessionName:t,req:a,snapshotScope:n})=>{let s=await e.capture.snapshot({session:t,interactiveOnly:a.flags?.snapshotInteractiveOnly,compact:a.flags?.snapshotCompact,depth:a.flags?.snapshotDepth,scope:n,raw:a.flags?.snapshotRaw,forceFull:a.flags?.snapshotForceFull});return{data:s,record:{kind:"snapshot",nodes:s.nodes.length,truncated:s.truncated}}}})}async function eu(e){return await ec({...e,command:"diff",unsupportedMessage:"diff is not supported on this device",execute:async({runtime:e,sessionName:t,req:a,snapshotScope:n})=>{let s=await e.capture.diffSnapshot({session:t,interactiveOnly:a.flags?.snapshotInteractiveOnly,compact:a.flags?.snapshotCompact,depth:a.flags?.snapshotDepth,scope:n,raw:a.flags?.snapshotRaw});return{data:s,record:{kind:"diff",mode:"snapshot",baselineInitialized:s.baselineInitialized,summary:s.summary}}}})}async function ec(e){var t,a;let{req:n,sessionName:s,logPath:o,sessionStore:i}=e,{session:l,device:d}=await M(i,s,n.flags);if(!y(e.command,d))return w("UNSUPPORTED_OPERATION",e.unsupportedMessage);let p=m(n.flags?.snapshotScope,l);if(!p.ok)return p;let f=(t=e.command,a=l,"ios"!==d.platform||a?.appBundleId?null:w("SESSION_NOT_FOUND",`iOS ${t} requires an active app session on the target device. Run open first (for example: open --session ${a?.name??"sim"} --platform ios --device "<name>" <app>).`));return f||await P(l,d,async()=>{var t,a;let f,m,h=function(e){let{req:t,sessionName:a,logPath:n,sessionStore:s,session:o,device:i,snapshotScope:l}=e;return O({backend:function(e){let{req:t,logPath:a,session:n,device:s,snapshotScope:o}=e;return{platform:s.platform,captureSnapshot:async(e,r)=>{let i=await c({device:s,session:n,flags:t.flags,outPath:r?.outPath??t.flags?.out,logPath:a,snapshotScope:o});return{snapshot:i.snapshot,analysis:i.analysis,androidSnapshot:i.androidSnapshot,freshness:i.freshness,appName:n?.appBundleId?n.appName??n.appBundleId:void 0,appBundleId:n?.appBundleId}}}}({req:t,logPath:n,session:o,device:i,snapshotScope:l}),...C("snapshot"),sessions:u({sessionName:a,getSession:()=>s.get(a),recordOptions:{includeSnapshot:!0},setRecord:e=>{var n;let o=function(e){if(!e.snapshot)throw new r("UNKNOWN","snapshot runtime did not produce session state");return e}(e),l=s.get(a);s.set(a,function(e){var t,a;let{current:n,sessionName:s,device:o,record:r,refScopedSnapshot:i}=e,l=(t=n,a=r,i&&a.snapshot?.nodes.length===0&&t?.snapshot!==void 0),d=l?n.snapshot:r.snapshot,p=A({session:n,sessionName:s,device:o,snapshot:d,appBundleId:r.appBundleId});return p.snapshotScopeSource=function(e){let{current:t,keepCurrentSnapshot:a,refScopedSnapshot:n}=e;if(n)return a?t?.snapshotScopeSource:t?.snapshotScopeSource??t?.snapshot}({current:n,keepCurrentSnapshot:l,refScopedSnapshot:i}),r.appName&&(p.appName=r.appName),p}({current:l,sessionName:a,device:i,record:o,refScopedSnapshot:(n=t,n.flags?.snapshotScope?.trim().startsWith("@")===!0)}))}})})}({req:n,sessionName:s,logPath:o,sessionStore:i,session:l,device:d,snapshotScope:p.scope});try{m=await e.execute({runtime:h,sessionName:s,req:n,snapshotScope:p.scope})}catch(a){let t=await ei({error:a,command:e.command,logPath:o,session:l,device:d});if(!t)throw a;return t}return(f=(t={req:n,sessionName:s,sessionStore:i,result:m.record}).sessionStore.get(t.sessionName))&&t.sessionStore.recordAction(f,{command:t.req.command,positionals:t.req.positionals??[],flags:t.req.flags??{},result:"snapshot"===(a=t.result).kind?{nodes:a.nodes,truncated:a.truncated}:{mode:a.mode,baselineInitialized:a.baselineInitialized,summary:a.summary}}),{ok:!0,data:m.data}})}let ef={snapshot:async({req:e,sessionName:t,logPath:a,sessionStore:n})=>await ep({req:e,sessionName:t,logPath:a,sessionStore:n}),diff:async({req:e,sessionName:t,logPath:a,sessionStore:n})=>e.positionals?.[0]!=="snapshot"?w("INVALID_ARGS","diff currently supports only: diff snapshot"):await eu({req:e,sessionName:t,logPath:a,sessionStore:n}),wait:async({req:e,sessionName:t,logPath:a,sessionStore:n})=>await R({req:e,sessionName:t,logPath:a,sessionStore:n}),alert:async({req:e,sessionName:t,logPath:a,sessionStore:n})=>{let{session:s,device:o}=await M(n,t,e.flags);return await P(s,o,async()=>await et({req:e,logPath:a,sessionStore:n,session:s,device:o}))},settings:async({req:e,sessionName:t,logPath:a,sessionStore:n})=>{let s,o,r,i=(s=e.positionals?.[0]?.toLowerCase(),o=e.positionals?.[1]?.toLowerCase(),r=e.positionals?.[2]?.toLowerCase(),"clear-app-state"===s?{ok:!0,parsed:{setting:s,state:"clear",appBundleId:"clear"===o?e.positionals?.[2]:e.positionals?.[1]}}:s&&o&&("permission"!==s||r)&&("location"!==s||"set"!==o||e.positionals?.[2]&&e.positionals?.[3])?{ok:!0,parsed:{setting:s,state:o,permissionTarget:r,latitude:e.positionals?.[2],longitude:e.positionals?.[3]}}:w("INVALID_ARGS",D));if(!i.ok)return i;let{session:l,device:d}=await M(n,t,e.flags);return await P(l,d,async()=>await er({req:e,logPath:a,sessionStore:n,session:l,device:d,parsed:i.parsed}))}};async function em(e){let t=ef[e.req.command];return t?await t(e):null}export{U as snapshot_namespaceObject};
|
package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift
CHANGED
|
@@ -17,6 +17,10 @@ extension RunnerTests {
|
|
|
17
17
|
min(max((durationMs / 5.0) / 1000.0, 0.016), 0.120)
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
+
private func coordinateDragHoldDuration() -> TimeInterval {
|
|
21
|
+
0.050
|
|
22
|
+
}
|
|
23
|
+
|
|
20
24
|
func unsupportedResponse(for outcome: RunnerInteractionOutcome) -> Response? {
|
|
21
25
|
switch outcome {
|
|
22
26
|
case .performed:
|
|
@@ -657,7 +661,7 @@ extension RunnerTests {
|
|
|
657
661
|
}
|
|
658
662
|
let holdDuration = command.synthesized == true
|
|
659
663
|
? synthesizedSwipeFallbackHoldDuration(durationMs: command.durationMs ?? 250)
|
|
660
|
-
:
|
|
664
|
+
: coordinateDragHoldDuration()
|
|
661
665
|
let (timing, outcome) = performGesture(activeApp) {
|
|
662
666
|
dragAt(
|
|
663
667
|
app: activeApp,
|
|
@@ -715,7 +719,7 @@ extension RunnerTests {
|
|
|
715
719
|
}
|
|
716
720
|
let holdDuration = command.synthesized == true
|
|
717
721
|
? synthesizedSwipeFallbackHoldDuration(durationMs: command.durationMs ?? 250)
|
|
718
|
-
:
|
|
722
|
+
: coordinateDragHoldDuration()
|
|
719
723
|
let (timing, outcome) = performGesture(activeApp) {
|
|
720
724
|
performDragSeries(
|
|
721
725
|
count: count,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-device",
|
|
3
|
-
"version": "0.17.
|
|
3
|
+
"version": "0.17.2",
|
|
4
4
|
"description": "Agent-native CLI for AI mobile testing and app automation across iOS, Android, tvOS, Android TV, macOS, and Linux.",
|
|
5
5
|
"mcpName": "io.github.callstackincubator/agent-device",
|
|
6
6
|
"license": "MIT",
|
|
@@ -75,7 +75,8 @@
|
|
|
75
75
|
},
|
|
76
76
|
"scripts": {
|
|
77
77
|
"build": "rslib build",
|
|
78
|
-
"clean:daemon": "
|
|
78
|
+
"clean:daemon": "node --experimental-strip-types scripts/clean-daemon.ts",
|
|
79
|
+
"daemon:state-dir": "node --experimental-strip-types scripts/print-daemon-state-dir.ts",
|
|
79
80
|
"clean:xcuitest": "node scripts/clean-xcuitest-derived.mjs",
|
|
80
81
|
"clean:xcuitest:ios": "node scripts/clean-xcuitest-derived.mjs ios",
|
|
81
82
|
"clean:xcuitest:macos": "node scripts/clean-xcuitest-derived.mjs macos",
|
|
@@ -103,7 +104,9 @@
|
|
|
103
104
|
"perf:android": "node --experimental-strip-types scripts/perf/run.ts --platform android",
|
|
104
105
|
"lint": "oxlint . --deny-warnings",
|
|
105
106
|
"format": "oxfmt --write src test skills package.json tsconfig.json tsconfig.lib.json rslib.config.ts vitest.config.ts .github/actions/setup-node-pnpm/action.yml .oxlintrc.json .oxfmtrc.json '!test/skillgym/.skillgym-results/**'",
|
|
106
|
-
"
|
|
107
|
+
"format:check": "oxfmt --check src test skills package.json tsconfig.json tsconfig.lib.json rslib.config.ts vitest.config.ts .github/actions/setup-node-pnpm/action.yml .oxlintrc.json .oxfmtrc.json '!test/skillgym/.skillgym-results/**'",
|
|
108
|
+
"fallow": "fallow audit --base origin/main",
|
|
109
|
+
"fallow:all": "fallow --summary",
|
|
107
110
|
"fallow:baseline": "(fallow dead-code --save-baseline fallow-baselines/dead-code.json --summary || true) && (fallow health --save-baseline fallow-baselines/health.json --summary || true)",
|
|
108
111
|
"check:fallow": "fallow audit",
|
|
109
112
|
"check:quick": "pnpm lint && pnpm typecheck",
|
|
@@ -212,7 +215,7 @@
|
|
|
212
215
|
"@rslib/core": "0.20.1",
|
|
213
216
|
"@types/node": "^22.0.0",
|
|
214
217
|
"@vitest/coverage-v8": "4.1.2",
|
|
215
|
-
"fallow": "^2.
|
|
218
|
+
"fallow": "^2.91.0",
|
|
216
219
|
"oxfmt": "^0.42.0",
|
|
217
220
|
"oxlint": "^1.57.0",
|
|
218
221
|
"skillgym": "^0.8.0",
|
package/server.json
CHANGED
|
@@ -7,12 +7,12 @@
|
|
|
7
7
|
"url": "https://github.com/callstackincubator/agent-device",
|
|
8
8
|
"source": "github"
|
|
9
9
|
},
|
|
10
|
-
"version": "0.17.
|
|
10
|
+
"version": "0.17.2",
|
|
11
11
|
"packages": [
|
|
12
12
|
{
|
|
13
13
|
"registryType": "npm",
|
|
14
14
|
"identifier": "agent-device",
|
|
15
|
-
"version": "0.17.
|
|
15
|
+
"version": "0.17.2",
|
|
16
16
|
"transport": {
|
|
17
17
|
"type": "stdio"
|
|
18
18
|
}
|
package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.0.apk.sha256
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
5d44d6844bd050d159d1f2f8fadd6200166ac5b5c67ebdce7d9f57f880690555 agent-device-android-multitouch-helper-0.17.0.apk
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
8ec1a43c2b6a9003452763c8f8601444720bcb1efcc3cd24f3afd61157d0e29b agent-device-android-snapshot-helper-0.17.0.apk
|
package/dist/src/1998.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{AppError as t}from"./9152.js";function e(t){return t?{message:t}:{}}function r(t,e){return e?{...t,message:e}:t}function n(t){return"string"==typeof t?.message&&t.message.length>0?t.message:null}function i(e,r){if(void 0===e||""===e.trim())throw new t("INVALID_ARGS",`settings location set requires ${r}`);return o(Number(e),r)}function a(t){return{latitude:o(t?.latitude,"latitude"),longitude:o(t?.longitude,"longitude")}}function o(e,r){let n="latitude"===r?-90:-180,i="latitude"===r?90:180;if("number"!=typeof e||!Number.isFinite(e)||e<n||e>i)throw new t("INVALID_ARGS",`${r} must be a number from ${n} to ${i}`);return e}function s(e){if(void 0===e)throw new t("INVALID_ARGS","rotate requires an orientation argument. Use portrait|portrait-upside-down|landscape-left|landscape-right.");switch(e?.trim().toLowerCase()){case"portrait":return"portrait";case"portrait-upside-down":case"upside-down":return"portrait-upside-down";case"landscape-left":case"left":return"landscape-left";case"landscape-right":case"right":return"landscape-right";default:throw new t("INVALID_ARGS",`Invalid rotation: ${e}. Use portrait|portrait-upside-down|landscape-left|landscape-right.`)}}export{s as parseDeviceRotation,n as readCommandMessage,i as readLocationCoordinate,a as requireLocationCoordinates,e as successText,r as withSuccessText};
|
package/dist/src/2805.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
let e={devices:"List available devices.",boot:"Boot or prepare a selected device without using CLI positional arguments.",apps:"List installed apps.",session:"List active sessions.",open:"Open an app, deep link, URL, or platform surface.",prepare:"Prepare platform helper infrastructure.",close:"Close an app or end the active session.",install:"Install an app binary.",reinstall:"Reinstall an app binary.","install-from-source":"Install an app from a structured source.",push:"Deliver a push payload.","trigger-app-event":"Trigger an app-defined event.",snapshot:"Capture an accessibility snapshot.",screenshot:"Capture a screenshot.",diff:"Diff accessibility snapshots.",wait:"Wait for duration, text, ref, or selector.",alert:"Inspect or handle platform alerts.",appstate:"Show foreground app or activity.",back:"Navigate back.",home:"Go to the home screen.",rotate:"Rotate device orientation.","app-switcher":"Open the app switcher.",keyboard:"Inspect or dismiss the keyboard.",clipboard:"Read or write clipboard text.","react-native":"Run supported React Native app automation helpers.",replay:"Replay a recorded session.",test:"Run one or more replay scripts.",perf:"Show session performance metrics and frame health.",logs:"Manage session app logs.",network:"Show recent HTTP traffic.",record:"Start or stop screen recording.",trace:"Start or stop trace capture.",settings:"Change OS settings and app permissions.",metro:"Prepare Metro runtime or reload React Native apps.",click:"Click or tap a semantic UI target by ref, selector, or point.",press:"Press a semantic UI target by ref, selector, or point.",fill:"Fill text into a semantic UI target by ref, selector, or point.",longpress:"Long press by ref, selector, or point.",swipe:"Swipe between two points.",focus:"Focus input at coordinates.",type:"Type text in the focused field.",scroll:"Scroll in a direction or to an edge.",get:"Get element text or attributes.",is:"Assert UI state.",find:"Find an element and optionally act on it.",gesture:"Run a structured gesture.",batch:"Run multiple structured command steps in one daemon request."};function t(t){let r=e[t];if(!r)throw Error(`Missing command description for ${t}`);return r}function r(){return Object.entries(e).map(([e,t])=>({name:e,description:t}))}export{r as listCommandDescriptionMetadata,t as requireCommandDescription};
|
package/dist/src/4057.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function t(t){return t.map((t,n)=>({...t,ref:`e${n+1}`}))}function n(t){let n=t.trim();return n.startsWith("@")?n.slice(1)||null:n.startsWith("e")?n:null}function e(t,n){return t.find(t=>t.ref===n)??null}function r(t){return JSON.stringify({interactiveOnly:t?.interactiveOnly===!0,compact:t?.compact===!0,depth:"number"==typeof t?.depth?t.depth:null,scope:t?.scope?.trim()||null,raw:t?.raw===!0})}function o(t){if(t)return{compact:t.snapshotCompact,depth:t.snapshotDepth,interactiveOnly:t.snapshotInteractiveOnly,raw:t.snapshotRaw,scope:t.snapshotScope}}function a(t){return{x:Math.round(t.x+t.width/2),y:Math.round(t.y+t.height/2)}}export{t as attachRefs,r as buildSnapshotPresentationKey,a as centerOfRect,e as findNodeByRef,n as normalizeRef,o as snapshotPresentationOptionsFromFlags};
|
package/dist/src/5792.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
let e={alert:"alert",appState:"appstate",appSwitcher:"app-switcher",apps:"apps",back:"back",batch:"batch",boot:"boot",click:"click",close:"close",clipboard:"clipboard",devices:"devices",diff:"diff",fill:"fill",find:"find",focus:"focus",gesture:"gesture",get:"get",home:"home",install:"install",installFromSource:"install-from-source",is:"is",keyboard:"keyboard",logs:"logs",longPress:"longpress",network:"network",open:"open",perf:"perf",prepare:"prepare",press:"press",push:"push",record:"record",reactNative:"react-native",reinstall:"reinstall",replay:"replay",rotate:"rotate",scroll:"scroll",screenshot:"screenshot",settings:"settings",snapshot:"snapshot",swipe:"swipe",test:"test",trace:"trace",triggerAppEvent:"trigger-app-event",type:"type",wait:"wait"},t={installSource:"install_source",leaseAllocate:"lease_allocate",leaseHeartbeat:"lease_heartbeat",leaseRelease:"lease_release",releaseMaterializedPaths:"release_materialized_paths",runtime:"runtime",sessionList:"session_list"},s={auth:"auth",connect:"connect",connection:"connection",disconnect:"disconnect",mcp:"mcp",metro:"metro",reactDevtools:"react-devtools",session:"session"},a="gesture requires one of: pan, fling, swipe, pinch, rotate, transform",r=[e.devices,e.boot,e.apps,e.open,e.close,e.install,e.reinstall,e.installFromSource,e.push,e.triggerAppEvent,e.snapshot,e.screenshot,e.diff,e.wait,e.alert,e.settings,e.click,e.press,e.longPress,e.swipe,e.focus,e.type,e.fill,e.scroll,e.get,e.gesture,e.is,e.find,e.perf,e.logs,e.network,e.record,e.trace,e.test,e.appState,e.back,e.home,e.rotate,e.appSwitcher,e.keyboard,e.clipboard,e.reactNative],o=n(s.auth,s.connect,s.connection,s.disconnect,s.mcp,s.reactDevtools,e.prepare);function n(...e){return new Set(e)}function c(){return[...Object.values(e),...Object.values(s)].sort()}function i(t){return Object.values(e).includes(t)||t===s.metro||t===s.session}function l(){return c().filter(e=>!o.has(e))}n(s.auth,s.connect,s.connection,s.disconnect,s.mcp,s.metro,s.reactDevtools,s.session,e.appState,e.prepare,e.batch,e.devices,e.gesture,e.replay,e.test,e.trace);export{r as BATCH_COMMAND_NAMES,a as GESTURE_SUBCOMMAND_ERROR,t as INTERNAL_COMMANDS,e as PUBLIC_COMMANDS,i as isClientBackedCliCommandName,c as listCliCommandNames,l as listMcpExposedCommandNames};
|
package/dist/src/6085.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{splitSelectorFromArgs as t,tryParseSelectorChain as e}from"./940.js";import{AppError as r}from"./9152.js";import{compactRecord as i}from"./9404.js";import{PUBLIC_COMMANDS as n}from"./5792.js";import{readLocationCoordinate as o}from"./1998.js";import{screenshotOptionsFromFlags as s,screenshotFlagsFromOptions as a}from"./5310.js";function l(t,e){return r=>u(t,e?e(r):[],r)}function u(t,e,r){return{command:t,positionals:e,options:function(t){var e;let r="mobile"===(e=t.deviceTarget??t.target)||"tv"===e||"desktop"===e?e:void 0;if(void 0===r&&void 0===t.target)return t;let{target:i,...n}=t;return void 0===r?n:{...n,target:r}}(r)}}function c(t){return i({session:t.session,platform:t.platform,deviceTarget:t.target,device:t.device,udid:t.udid,serial:t.serial,iosSimulatorDeviceSet:t.iosSimulatorDeviceSet,androidDeviceAllowlist:t.androidDeviceAllowlist})}function f(t){return{platform:t.platform,target:t.target,device:t.device,udid:t.udid,serial:t.serial,iosSimulatorDeviceSet:t.iosSimulatorDeviceSet,androidDeviceAllowlist:t.androidDeviceAllowlist}}function d(t){return i({depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw})}function p(t){return{depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw}}function m(t){return i({count:t.count,intervalMs:t.intervalMs,holdMs:t.holdMs,jitterPx:t.jitterPx,doubleTap:t.doubleTap})}function h(t){return"ref"in t&&void 0!==t.ref?i({kind:"ref",ref:t.ref,label:t.label}):"selector"in t&&void 0!==t.selector?{kind:"selector",selector:t.selector}:{kind:"point",x:t.x,y:t.y}}function g(t){let e=S(t);if("string"==typeof e.ref)return[e.ref,...A(e.label)];if("string"==typeof e.selector)return[e.selector];if("point"===e.kind||void 0!==e.x||void 0!==e.y)return[String(v(e.x,"x")),String(v(e.y,"y"))];throw new r("INVALID_ARGS","interaction requires @ref, selector, or point target")}function w(t){let e=S(t);if("string"==typeof e.ref)return[e.ref,...A(e.label)];if("string"==typeof e.selector)return[e.selector];throw new r("INVALID_ARGS","element command requires @ref or selector target")}function S(t){if(!t||"object"!=typeof t||Array.isArray(t))throw new r("INVALID_ARGS","Expected target object.");let e=t.target;return e&&"object"==typeof e&&!Array.isArray(e)?e:t}function v(t,e){if("number"!=typeof t||!Number.isFinite(t))throw new r("INVALID_ARGS",`point target requires numeric ${e}.`);return t}function A(t){return"string"==typeof t&&t.length>0?[t]:[]}function _(t){if(t[0]?.startsWith("@"))return{ref:t[0],label:D(t.slice(1))};let e=t.join(" ").trim();if(!e)throw new r("INVALID_ARGS","get requires @ref or selector expression");return{selector:e}}function I(t){if("text"===t||"attrs"===t)return t;throw new r("INVALID_ARGS","get only supports text or attrs")}function N(e,i={}){let n=t(e,i);if(!n)throw new r("INVALID_ARGS","is requires a selector expression");return n}function x(t,e){try{let e=JSON.parse(t);if(e&&"object"==typeof e&&!Array.isArray(e))return e}catch{}throw new r("INVALID_ARGS",`${e} must be a JSON object`)}function D(t){return t.join(" ").trim()||void 0}function R(...t){return new Set(t)}function b(t){return new Set(t)}function y(t,e){return void 0!==t&&e.has(t)}function M(t){return void 0!==t&&""!==t.trim()&&Number.isFinite(Number(t))}function G(t){return void 0===t?void 0:Number(t)}function L(t){return void 0===t?[]:[t]}function F(t){return void 0===t?[]:[String(t)]}function V(t,e){if(void 0===t||""===t)throw new r("INVALID_ARGS",e);return t}function C(t,e){if("string"!=typeof t||0===t.length)throw new r("INVALID_ARGS",e);return t}function k(t){if(!t)return null;let e=Number(t);return Number.isFinite(e)?e:null}let j={snapshot:(t,e)=>({...c(e),interactiveOnly:e.snapshotInteractiveOnly,compact:e.snapshotCompact,depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw,forceFull:e.snapshotForceFull,timeoutMs:e.timeoutMs}),screenshot:(t,e)=>({...c(e),path:t[0]??e.out,...s(e)}),diff:(t,e)=>{if("snapshot"!==t[0])throw new r("INVALID_ARGS","Only diff snapshot is available through this parser.");return{...c(e),kind:"snapshot",out:e.out,interactiveOnly:e.snapshotInteractiveOnly,compact:e.snapshotCompact,depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}},wait:(t,e)=>(function(t,e){let i=E(t);if(!i)throw new r("INVALID_ARGS","wait requires <ms>, text <text>, @ref, or <selector> [timeoutMs].");let n={...f(e),...p(e)};if("sleep"===i.kind)return{...n,durationMs:i.durationMs};if("text"===i.kind){if(!i.text)throw new r("INVALID_ARGS","wait requires text.");return{...n,text:i.text,...K(i.timeoutMs)}}return"ref"===i.kind?{...n,ref:i.rawRef,...K(i.timeoutMs)}:{...n,selector:i.selectorExpression,...K(i.timeoutMs)}})(t,e),alert:(t,e)=>({...c(e),...function(t){if(t.length>2)throw new r("INVALID_ARGS","alert accepts at most action and timeout arguments.");return i({action:function(t){let e=t?.toLowerCase();if(void 0===e||"get"===e||"accept"===e||"dismiss"===e||"wait"===e)return e;throw new r("INVALID_ARGS","alert action must be get, accept, dismiss, or wait.")}(t[0]),timeoutMs:function(t,e){if(void 0===t)return;let i=Number(t);if(Number.isFinite(i))return i;throw new r("INVALID_ARGS",`${e} must be a finite number.`)}(t[1],"alert timeout")})}(t)}),settings:(t,e)=>(function(t,e){let i=f(e),n=t[0],s=t[1];if(y(n,P)&&y(s,T))return{...i,setting:n,state:s};if("location"===n&&"set"===s)return{...i,setting:n,state:s,latitude:o(t[2],"latitude"),longitude:o(t[3],"longitude")};if("appearance"===n&&y(s,O)||y(n,H)&&y(s,U)||"fingerprint"===n&&y(s,W))return{...i,setting:n,state:s};if("permission"===n&&y(s,$))return{...i,setting:n,state:s,permission:function(t){if(y(t,J))return t;throw new r("INVALID_ARGS","settings permission requires a permission target.")}(t[2]),mode:function(t){if(void 0===t||"full"===t||"limited"===t)return t;throw new r("INVALID_ARGS","settings permission mode must be full or limited.")}(t[3])};if("clear-app-state"===n){let e="clear"===s?t[2]:s;return{...i,setting:n,state:"clear",app:e}}throw new r("INVALID_ARGS","Invalid settings arguments.")})(t,e)},q={snapshot:l(n.snapshot),screenshot:t=>u(n.screenshot,L(t.path),{...t,...a(t)}),diff:l(n.diff,t=>[C(t.kind,"diff requires kind")]),wait:l(n.wait,t=>(function(t){if(1!==[void 0!==t.durationMs?"durationMs":void 0,void 0!==t.text?"text":void 0,void 0!==t.ref?"ref":void 0,void 0!==t.selector?"selector":void 0].filter(Boolean).length)throw new r("INVALID_ARGS","wait command requires exactly one of durationMs, text, ref, or selector.");if(void 0!==t.durationMs)return[String(t.durationMs)];let i=F(t.timeoutMs);if(void 0!==t.text)return["text",t.text,...i];if(void 0!==t.ref)return[t.ref,...i];let n=t.selector;if(!e(n))throw new r("INVALID_ARGS",`Invalid wait selector: ${n}`);return[n,...i]})(t)),alert:l(n.alert,t=>{var e;return[(e=t).action??"get",...F(e.timeoutMs)]}),settings:l(n.settings,t=>{var e;return"clear-app-state"===(e=t).setting?[e.setting,...L(e.app)]:"location"===e.setting&&"set"===e.state?[e.setting,e.state,String(e.latitude),String(e.longitude)]:"permission"===e.setting?[e.setting,e.state,e.permission,...L(e.mode)]:[e.setting,e.state]})};function E(r){let i=r[0];if(void 0===i)return null;let n=k(i);if(null!==n)return{kind:"sleep",durationMs:n};let o=k(r[r.length-1]);if("text"===i)return{kind:"text",text:(null!==o?r.slice(1,-1).join(" "):r.slice(1).join(" ")).trim(),timeoutMs:o};if(i.startsWith("@"))return{kind:"ref",rawRef:i,timeoutMs:o};let s=t(null!==o?r.slice(0,-1):r.slice());return s&&0===s.rest.length&&e(s.selectorExpression)?{kind:"selector",selectorExpression:s.selectorExpression,timeoutMs:o}:{kind:"text",text:(null!==o?r.slice(0,-1).join(" "):r.join(" ")).trim(),timeoutMs:o}}function K(t){return null===t?{}:{timeoutMs:t}}let P=R("wifi","airplane","location","animations"),T=R("on","off"),O=R("light","dark","toggle"),H=R("faceid","touchid"),U=R("match","nonmatch","enroll","unenroll"),W=R("match","nonmatch"),$=R("grant","deny","reset"),J=R("camera","microphone","photos","contacts","contacts-limited","notifications","calendar","location","location-always","media-library","motion","reminders","siri","accessibility","screen-recording","input-monitoring");export{j as captureCliReaders,q as captureDaemonWriters,b as commandNameSet,c as commonInputFromFlags,l as direct,w as elementTargetPositionals,g as interactionTargetPositionals,M as isFiniteNumberString,G as optionalCliNumber,F as optionalNumber,L as optionalString,D as optionalTrimmedText,k as parseTimeout,E as parseWaitPositionals,_ as readElementTargetFromPositionals,I as readGetFormat,x as readJsonObject,m as repeatedInputFromFlags,u as request,C as requiredDaemonString,V as requiredString,f as selectionOptionsFromFlags,d as selectorSnapshotInputFromFlags,p as selectorSnapshotOptionsFromFlags,N as splitRequiredSelector,h as targetInputFromClientTarget};
|
package/dist/src/6232.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{withSuccessText as e,successText as a}from"./1998.js";function n(e){let a=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:a,appBundleId:e.bundleId,package:e.packageName}}function t(e,a,n){return{deviceId:a,deviceName:n,..."android"===e?{serial:a}:"ios"===e?{udid:a}:{}}}function i(e,a={}){let n=a.includeAndroidSerial??!0;return{platform:e.platform,target:e.target,device:e.name,id:e.id,..."ios"===e.platform?{device_udid:e.ios?.udid??e.id,ios_simulator_device_set:e.ios?.simulatorSetPath??null}:{},..."android"===e.platform&&n?{serial:e.android?.serial??e.id}:{}}}function r(e){return{name:e.name,...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...i(e.device,{includeAndroidSerial:!1}),createdAt:e.createdAt}}function d(e){return{platform:e.platform,id:e.id,name:e.name,kind:e.kind,target:e.target,..."boolean"==typeof e.booted?{booted:e.booted}:{}}}function s(e){return e.bundleId??e.package??e.app}function p(a){return e({app:a.app,appPath:a.appPath,platform:a.platform,...a.appId?{appId:a.appId}:{},...a.bundleId?{bundleId:a.bundleId}:{},...a.package?{package:a.package}:{}},`Installed: ${s(a)}`)}function o(e){return e.appName??e.bundleId??e.packageName??e.launchTarget}function l(a){return e({launchTarget:a.launchTarget,...a.appName?{appName:a.appName}:{},...a.appId?{appId:a.appId}:{},...a.bundleId?{bundleId:a.bundleId}:{},...a.packageName?{package:a.packageName}:{},...a.installablePath?{installablePath:a.installablePath}:{},...a.archivePath?{archivePath:a.archivePath}:{},...a.materializationId?{materializationId:a.materializationId}:{},...a.materializationExpiresAt?{materializationExpiresAt:a.materializationExpiresAt}:{}},`Installed: ${o(a)}`)}function u(a){let n=a.appName??a.appBundleId??a.session;return e({session:a.session,...a.sessionStateDir?{sessionStateDir:a.sessionStateDir}:{},...a.runnerLogPath?{runnerLogPath:a.runnerLogPath}:{},...a.requestLogPath?{requestLogPath:a.requestLogPath}:{},...a.appName?{appName:a.appName}:{},...a.appBundleId?{appBundleId:a.appBundleId}:{},...a.startup?{startup:a.startup}:{},...a.runtime?{runtime:a.runtime}:{},...a.device?i(a.device):{}},n?`Opened: ${n}`:"Opened")}function c(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...a(e.session?`Closed: ${e.session}`:"Closed")}}function m(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...e.androidSnapshot?{androidSnapshot:e.androidSnapshot}:{},...e.warnings&&e.warnings.length>0?{warnings:e.warnings}:{},...e.unchanged?{unchanged:e.unchanged}:{}}}export{n as buildAppIdentifiers,t as buildDeviceIdentifiers,s as resolveDeployResultTarget,o as resolveInstallFromSourceResultTarget,c as serializeCloseResult,p as serializeDeployResult,d as serializeDevice,l as serializeInstallFromSourceResult,u as serializeOpenResult,r as serializeSessionListEntry,m as serializeSnapshotResult};
|
package/dist/src/8020.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
let e=["metrics","frames"],r=["sample"],E="perf area must be metrics or frames",s="perf action must be sample";function t(r){return e.includes(r)}function A(e){return r.includes(e)}export{s as PERF_ACTION_ERROR_MESSAGE,r as PERF_ACTION_VALUES,E as PERF_AREA_ERROR_MESSAGE,e as PERF_AREA_VALUES,A as isPerfAction,t as isPerfArea};
|
package/dist/src/8502.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{PUBLIC_COMMANDS as t}from"./5792.js";import{splitSelectorFromArgs as r}from"./940.js";import{AppError as e}from"./9152.js";import{optionalTrimmedText as i,readElementTargetFromPositionals as o,optionalCliNumber as n,repeatedInputFromFlags as s,optionalNumber as l,targetInputFromClientTarget as u,requiredDaemonString as a,request as c,interactionTargetPositionals as g,direct as m,isFiniteNumberString as f,commonInputFromFlags as d,selectorSnapshotInputFromFlags as p,readGetFormat as _,elementTargetPositionals as x}from"./6085.js";let M={click:(t,r)=>({...d(r),...p(r),...s(r),target:u(b(t)),button:r.clickButton}),press:(t,r)=>({...d(r),...p(r),...s(r),target:u(b(t))}),longpress:(t,r)=>{let e,i={...b((e=function(t){if(f(t[0])&&f(t[1]))return{target:t.slice(0,2),...void 0!==t[2]?{durationMs:Number(t[2])}:{}};let r=t.at(-1);return t.length>1&&f(r)?{target:t.slice(0,-1),durationMs:Number(r)}:{target:t}}(t)).target),...void 0!==e.durationMs?{durationMs:e.durationMs}:{}};return{...d(r),...p(r),target:u(i),durationMs:i.durationMs}},swipe:(t,r)=>({...d(r),from:{x:Number(t[0]),y:Number(t[1])},to:{x:Number(t[2]),y:Number(t[3])},durationMs:n(t[4]),count:r.count,pauseMs:r.pauseMs,pattern:r.pattern}),focus:(t,r)=>({...d(r),x:Number(t[0]),y:Number(t[1])}),type:(t,r)=>({...d(r),text:t.join(" "),delayMs:r.delayMs}),fill:(t,r)=>{let e=S(t);return{...d(r),...p(r),target:u(e.target),text:e.text,delayMs:r.delayMs}},scroll:(t,r)=>({...d(r),direction:function(t){if("up"===t||"down"===t||"left"===t||"right"===t||"top"===t||"bottom"===t)return t;throw new e("INVALID_ARGS",`Unknown direction: ${String(t)}`)}(t[0]),amount:n(t[1]),pixels:r.pixels}),get:(t,r)=>({...d(r),...p(r),format:_(t[0]),target:u(o(t.slice(1)))})},N={click:r=>c(t.click,g(r),{...r,clickButton:r.button}),press:m(t.press,t=>g(t)),longpress:m(t.longPress,t=>{var r;return[...g(r=t),...l(r.durationMs)]}),swipe:m(t.swipe,function(t){return[String(t.from?.x),String(t.from?.y),String(t.to?.x),String(t.to?.y),...l(t.durationMs)]}),focus:m(t.focus,t=>[String(t.x),String(t.y)]),type:m(t.type,t=>[t.text]),fill:m(t.fill,t=>{var r;return[...g(r=t),r.text]}),scroll:m(t.scroll,t=>[a(t.direction,"scroll requires direction"),...l(t.amount)]),get:m(t.get,t=>[a(t.format,"get requires format"),...x(t)])};function b(t){if(t[0]?.startsWith("@")){let r=i(t.slice(1));return{ref:t[0],...void 0===r?{}:{label:r}}}let e=r(t);return e?{selector:e.selectorExpression}:{x:Number(t[0]),y:Number(t[1])}}function S(t){let e=t[0];if(e?.startsWith("@")){let r=t.length>=3?t.slice(2).join(" "):t.slice(1).join(" ");return{kind:"ref",target:{ref:e,label:t.length>=3?i(t.slice(1,2)):void 0},text:r}}let o=r(t,{preferTrailingValue:!0});return o?{kind:"selector",target:{selector:o.selectorExpression},text:o.rest.join(" ")}:{kind:"point",target:{x:Number(t[0]),y:Number(t[1])},text:t.slice(2).join(" ")}}export{M as interactionCliReaders,N as interactionDaemonWriters,S as readFillTargetFromPositionals,b as readInteractionTargetFromPositionals};
|
package/dist/src/940.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{AppError as e}from"./9152.js";import{normalizeText as t}from"./7556.js";let n=new Set(["id","role","text","label","value","appname","windowtitle"]),r=new Set(["visible","hidden","editable","selected","enabled","hittable"]),l=new Set([...n,...r]),i=new Map([['"','"'],["'","'"],["\\","\\"],["/","/"],["b","\b"],["f","\f"],["n","\n"],["r","\r"],["t"," "]]);function u(t){let n=t.trim();if(!n)throw new e("INVALID_ARGS","Selector expression cannot be empty");let r=function(t){let n=[],r="",l=null;for(let i=0;i<t.length;i+=1){let u=t[i];if(('"'===u||"'"===u)&&!p(t,i)){l=d(l,u),r+=u;continue}if(!l&&"|"===u&&"|"===t[i+1]){let l=r.trim();if(!l)throw new e("INVALID_ARGS",`Invalid selector fallback expression: ${t}`);n.push(l),r="",i+=1;continue}r+=u}let i=r.trim();if(!i)throw new e("INVALID_ARGS",`Invalid selector fallback expression: ${t}`);return n.push(i),n}(n);if(0===r.length)throw new e("INVALID_ARGS","Selector expression cannot be empty");return{raw:n,selectors:r.map(t=>(function(t){let n=t.trim();if(!n)throw new e("INVALID_ARGS","Selector segment cannot be empty");let r=function(t){let n=[],r="",l=null;for(let e=0;e<t.length;e+=1){let i=t.charAt(e);if(('"'===i||"'"===i)&&!p(t,e)){l=d(l,i),r+=i;continue}if(!l&&/\s/.test(i)){r.trim()&&n.push(r.trim()),r="";continue}r+=i}if(l)throw new e("INVALID_ARGS",`Unclosed quote in selector: ${t}`);return r.trim()&&n.push(r.trim()),n}(n);if(0===r.length)throw new e("INVALID_ARGS",`Invalid selector segment: ${t}`);return{raw:n,terms:r.map(f)}})(t))}}function o(e){try{return u(e)}catch{return null}}function a(e){let t=e.trim();if(!t)return!1;if("||"===t)return!0;let n=t.indexOf("=");if(-1!==n){let e=t.slice(0,n).trim().toLowerCase();return l.has(e)}return l.has(t.toLowerCase())}function c(e,t={}){if(0===e.length)return null;let n=t.preferTrailingValue??!1,r=0,l=[];for(;r<e.length;){let t=e[r];if(void 0===t||!a(t))break;r+=1;let n=e.slice(0,r).join(" ").trim();n&&o(n)&&l.push(r)}if(0===l.length)return null;let i=l.at(-1);if(void 0===i)return null;let u=i;if(n)for(let t=l.length-1;t>=0;t-=1){let n=l[t];if(void 0!==n&&n<e.length){u=n;break}}let s=e.slice(0,u).join(" ").trim();return s?{selectorExpression:s,rest:e.slice(u)}:null}function s(e){let t=e[0]??"",n=c(e.slice(1),{preferTrailingValue:"text"===t});return{predicate:t,split:n}}function f(t){let n=t.trim();if(!n)throw new e("INVALID_ARGS","Empty selector term");let i=n.indexOf("=");if(-1===i){let l=n.toLowerCase();if(!r.has(l))throw new e("INVALID_ARGS",`Invalid selector term "${t}", expected key=value`);return{key:l,value:!0}}let u=n.slice(0,i).trim().toLowerCase(),o=n.slice(i+1).trim();if(!l.has(u))throw new e("INVALID_ARGS",`Unknown selector key: ${u}`);if(!o)throw new e("INVALID_ARGS",`Missing selector value for key: ${u}`);if(r.has(u)){let t,n="true"===(t=h(o).toLowerCase())||"false"!==t&&null;if(null===n)throw new e("INVALID_ARGS",`Invalid boolean value for ${u}: ${o}`);return{key:u,value:n}}return{key:u,value:h(o)}}function d(e,t){return e?e===t?null:e:t}function h(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?function(e){let t="",n=0;for(;n<e.length;){var r;let l=e.charAt(n);if("\\"!==l){t+=l,n+=1;continue}let u=e.charAt(n+1);if(!u){t+=l,n+=1;continue}let o=(r=u,i.get(r)??null);if(null!==o){t+=o,n+=2;continue}if("u"===u){let r=e.slice(n+2,n+6);if(/^[0-9a-fA-F]{4}$/.test(r)){t+=String.fromCharCode(Number.parseInt(r,16)),n+=6;continue}}t+=l,n+=1}return t}(t.slice(1,-1)):t}function p(e,t){let n=0;for(let r=t-1;r>=0&&"\\"===e[r];r-=1)n+=1;return n%2==1}function m(e){var t;let n=x(e.label),r=x(e.value),l=x(e.identifier),i=(t=l)&&!/^[\w.]+:id\/[\w.-]+$/i.test(t)&&!/^_?NS:\d+$/i.test(t)?l:"";return v(e.type??"")?r||n||i:n||r||i}function b(e){let t=e.replace(/\s+/g," ").trim();return t.length<=48?t:`${t.slice(0,45)}...`}function w(e,t){var n;let r=m(e),l=function(e,t){if("text-view"===t||"text-field"===t||"search"===t)return!0;let n=g(e.type??""),r=`${e.role??""} ${e.subrole??""}`.toLowerCase();return n.includes("textview")||n.includes("textarea")||n.includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("edittext")||r.includes("text area")||r.includes("text field")}(e,t);return{text:r,isLargeSurface:l,shouldSummarize:l&&!!(n=r)&&(n.length>80||/[\r\n]/.test(n))}}function x(e){return"string"==typeof e?e.trim():""}function g(e){let t=e.trim().replace(/XCUIElementType/gi,"").replace(/^AX/,"").toLowerCase(),n=Math.max(t.lastIndexOf("."),t.lastIndexOf("/"));return -1!==n&&(t=t.slice(n+1)),t}function v(e){let t=g(e);return t.includes("textfield")||t.includes("securetextfield")||t.includes("searchfield")||t.includes("edittext")||t.includes("textview")||t.includes("textarea")}function S(e,t){let n=t.toLowerCase();return e.find(e=>{let t=(e.label??"").toLowerCase(),r=(e.value??"").toLowerCase(),l=(e.identifier??"").toLowerCase();return t.includes(n)||r.includes(n)||l.includes(n)})??null}function I(e,t){let n=[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0);return n&&A(n)?n:function(e,t){if(!e.rect)return;let n=e.rect.y+e.rect.height/2,r=null;for(let e of t){if(!e.rect)continue;let t=[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0);if(!t||!A(t))continue;let l=Math.abs(e.rect.y+e.rect.height/2-n);(!r||l<r.distance)&&(r={label:t,distance:l})}return r?.label}(e,t)??(n&&A(n)?n:void 0)}function A(e){let t=e.trim();return!(!t||/^(true|false)$/i.test(t)||/^\d+$/.test(t))}function $(e){let t=[],n=[];for(let r of e){let e=r.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let l=g(r.type??""),i=[r.label,r.value,r.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0),u=!!i&&A(i);if(("group"===l||"ioscontentgroup"===l)&&!u){t.push(e);continue}let o=Math.max(0,e-t.length);n.push({...r,depth:o})}return n}function y(e,t){let n=g(e);return!n||("android"===t?n.includes("edittext")||n.includes("autocompletetextview"):n.includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("textview")||n.includes("textarea")||"search"===n)}function N(e,t){return t.hittable?t:R(e,t,e=>!0===e.hittable)}function L(e){return new Map(e.map(e=>[e.index,e]))}function C(e,t,n,r){let l=t,i=new Set;for(;"number"==typeof l.parentIndex&&!i.has(l.index)&&(i.add(l.index),l=n.get(l.parentIndex)??e[l.parentIndex]);){let e=r(l);if(null!==e)return e}return null}function _(e,t,n,r){return!!C(e,t,r,e=>e===n||e.index===n.index?e:null)}function R(e,t,n){let r=L(e);return C(e,t,r,e=>n(e)?e:null)}function V(e){return[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0)[0]??""}function T(e){return m(e)}function D(e){return!0===e.hittable||!!e.rect&&e.rect.width>0&&e.rect.height>0}function G(e,t){return y(e.type??"",t)&&!1!==e.enabled}function k(e,t,n){return t.terms.every(t=>(function(e,t,n){switch(t.key){case"id":return M(e.identifier,String(t.value));case"role":return M(g(e.type??""),String(t.value));case"label":return M(e.label,String(t.value));case"value":return M(e.value,String(t.value));case"text":return M(V(e),String(t.value));case"appname":return M(e.appName,String(t.value));case"windowtitle":return M(e.windowTitle,String(t.value));case"visible":return D(e)===!!t.value;case"hidden":return!D(e)==!!t.value;case"editable":return G(e,n)===!!t.value;case"selected":return!0===e.selected==!!t.value;case"enabled":return!1!==e.enabled==!!t.value;case"hittable":return!0===e.hittable==!!t.value;default:return!1}})(e,t,n))}function M(e,n){return t(e??"")===t(n)}function q(e,t,n){let r=n.requireRect??!1,l=n.requireUnique??!0,i=[];for(let[u,o]of t.selectors.entries()){let t=function(e,t,n,r){let l=0,i=null,u=null,o=!1;for(let a of e){if(r&&!a.rect||!k(a,t,n))continue;if(l+=1,i??=a,!u){u=a;continue}let e=function(e,t){let n=e.depth??0,r=t.depth??0;if(n!==r)return n>r?1:-1;let l=U(e),i=U(t);return l!==i?l<i?1:-1:0}(a,u);e>0?(u=a,o=!1):0===e&&(o=!0)}return{count:l,firstNode:i,disambiguated:o?null:u}}(e,o,n.platform,r);if(i.push({selector:o.raw,matches:t.count}),0!==t.count&&t.firstNode){if(l&&1!==t.count){if(!n.disambiguateAmbiguous||!t.disambiguated)continue;return{node:t.disambiguated,selector:o,selectorIndex:u,matches:t.count,diagnostics:i}}return{node:t.firstNode,selector:o,selectorIndex:u,matches:t.count,diagnostics:i}}}return null}function F(e,t,n){let r=n.requireRect??!1,l=[];for(let[i,u]of t.selectors.entries()){let t=function(e,t,n,r){let l=0;for(let i of e)(!r||i.rect)&&k(i,t,n)&&(l+=1);return l}(e,u,n.platform,r);if(l.push({selector:u.raw,matches:t}),t>0)return{selectorIndex:i,selector:u,matches:t,diagnostics:l}}return null}function O(e,t,n){if(0===t.length)return`Selector did not match: ${e.raw}`;let r=t.map(e=>`${e.selector} -> ${e.matches}`).join(", ");return n.unique??!0?`Selector did not resolve uniquely (${r})`:`Selector did not match (${r})`}function U(e){return e.rect?e.rect.width*e.rect.height:1/0}function E(e,t,n={}){let r=[],l=g(e.type??""),i=P(e.identifier),u=P(e.label),o=P(e.value),a=P(V(e)),c="fill"===n.action;i&&r.push(`id=${K(i)}`),l&&u&&r.push(c?`role=${K(l)} label=${K(u)} editable=true`:`role=${K(l)} label=${K(u)}`),u&&r.push(c?`label=${K(u)} editable=true`:`label=${K(u)}`),o&&r.push(c?`value=${K(o)} editable=true`:`value=${K(o)}`),a&&a!==u&&a!==o&&r.push(c?`text=${K(a)} editable=true`:`text=${K(a)}`),l&&c&&!r.some(e=>e.includes("editable=true"))&&r.push(`role=${K(l)} editable=true`);let s=Array.from(new Set(r));return 0===s.length&&l&&s.push(c?`role=${K(l)} editable=true`:`role=${K(l)}`),0===s.length&&D(e)&&s.push("visible=true"),s}function K(e){return JSON.stringify(e)}function P(e){if(!e)return null;let t=e.trim();return t||null}export{E as buildSelectorChainForNode,L as buildSnapshotNodeByIndex,b as buildTextPreview,w as describeTextSurface,T as extractNodeReadText,V as extractNodeText,m as extractReadableText,R as findNearestAncestor,N as findNearestHittableAncestor,S as findNodeByLabel,F as findSelectorChainMatch,C as findSnapshotAncestor,O as formatSelectorFailure,_ as isDescendantOfSnapshotNode,y as isFillableType,G as isNodeEditable,D as isNodeVisible,a as isSelectorToken,k as matchesSelector,g as normalizeType,u as parseSelectorChain,v as prefersValueForReadableText,$ as pruneGroupNodes,I as resolveRefLabel,q as resolveSelectorChain,s as splitIsSelectorArgs,c as splitSelectorFromArgs,x as trimText,o as tryParseSelectorChain};
|
package/dist/src/9404.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
let e=["ios","android","macos","linux","apple"],t=["mobile","tv","desktop"],r=["ref","selector","point"];function i(e){return{type:"string",...e?{description:e}:{}}}function n(e){return{type:"integer",...e?{description:e}:{}}}function o(e){return{type:"boolean",...e?{description:e}:{}}}function s(e){return{type:"object",additionalProperties:!0,...e?{description:e}:{}}}function a(e){return{...e,required:!0}}function d(e){return z(i(e),k)}function c(e){return z({type:"number",...e?{description:e}:{}},$)}function l(e,t={}){var r,i;return z((r=e,i=t,{...n(r),...void 0===i.min?{}:{minimum:i.min},...void 0===i.max?{}:{maximum:i.max}}),(e,r)=>F(e,r,t))}function u(e){return z(o(e),D)}function p(e,t){return z({type:"string",enum:e,...t?{description:t}:{}},(t,r)=>U(t,r,e))}function f(e){return z(s(e),H)}function m(e){return z({type:"array",items:{type:"string"},...e?{description:e}:{}},K)}function b(e){return z(e,(e,t)=>e[t])}function g(e,t){return z(e,t)}function y(){return z({oneOf:[...W(),{type:"object",properties:{kind:{type:"string",const:"point"},x:{type:"number"},y:{type:"number"}},required:["kind","x","y"],additionalProperties:!1}],description:"UI target. This is separate from deviceTarget, which selects the device form."},(e,t)=>void 0===e[t]?void 0:function(e,t){let i=G(e,t),n=q(i,"kind",r);switch(n){case"ref":return{kind:n,ref:T(i,"ref"),label:k(i,"label")};case"selector":return{kind:n,selector:T(i,"selector")};case"point":return{kind:n,x:O(i,"x"),y:O(i,"y")}}}(e,t))}function h(){return z({oneOf:W(),description:"UI element target by snapshot ref or selector expression."},(e,t)=>{let r,i;return void 0===e[t]?void 0:"ref"===(i=q(r=G(e,t),"kind",["ref","selector"]))?{kind:i,ref:T(r,"ref"),label:k(r,"label")}:{kind:i,selector:T(r,"selector")}})}function v(e){return z({type:"object",description:e,properties:{x:{type:"number"},y:{type:"number"}},required:["x","y"],additionalProperties:!1},(e,t)=>void 0===e[t]?void 0:I(e,t))}function w(){return{depth:l("Snapshot traversal depth.",{min:0}),scope:d("Snapshot scope selector used before resolution."),raw:u("Use raw snapshot data during selector resolution.")}}function x(){return{count:l("Number of press/click repetitions.",{min:1}),intervalMs:l("Delay between repeated press/click actions.",{min:0}),holdMs:l("Hold duration for each action.",{min:0}),jitterPx:l("Randomization radius in pixels.",{min:0}),doubleTap:u("Request a double-tap action.")}}function E(r){return function(r,i=[]){return{type:"object",properties:{session:{type:"string",description:"Agent-device session name."},platform:{type:"string",enum:e,description:"Platform selector used to resolve a device."},deviceTarget:{type:"string",enum:t,description:"Device target form. Maps to the CLI --target flag."},target:{type:"string",enum:t,description:"Alias for deviceTarget on commands without a UI target field. Interaction commands reserve target for the UI element."},device:{type:"string",description:"Device name selector."},udid:{type:"string",description:"iOS device UDID selector."},serial:{type:"string",description:"Android serial selector."},iosSimulatorDeviceSet:{type:"string",description:"iOS simulator device-set path used for device resolution."},androidDeviceAllowlist:{type:"string",description:"Android serial allowlist used for device resolution."},daemonBaseUrl:{type:"string",description:"Remote daemon base URL."},daemonAuthToken:{type:"string",description:"Remote daemon auth token."},tenant:{type:"string",description:"Remote tenant identifier."},runId:{type:"string",description:"Lease run identifier."},leaseId:{type:"string",description:"Existing lease identifier."},cwd:{type:"string",description:"Working directory for command execution."},debug:{type:"boolean",description:"Enable debug diagnostics."},...r},...i.length>0?{required:i}:{},additionalProperties:!1}}(Object.fromEntries(Object.entries(r).map(([e,t])=>[e,t.schema])),Object.entries(r).flatMap(([e,t])=>t.required?[e]:[]))}function j(e,t){let r=A(e),i=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{let i=t.read(r,e);if(t.required&&void 0===i)throw Error(`Expected ${e} to be set.`);return void 0===i?[]:[[e,i]]})),n=S(r,{readTargetAlias:!Object.hasOwn(t,"target")});return L({...n,...P(n),...i})}function A(e){if(null==e)return{};if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Expected object arguments.");return e}function S(r,i={}){return{session:k(r,"session"),platform:U(r,"platform",e),deviceTarget:function(e,r){let i=U(e,"deviceTarget",t);if(!1===r.readTargetAlias||void 0===e.target)return i;let n=U(e,"target",t);if(void 0!==i&&n!==i)throw Error("Expected target alias to match deviceTarget when both are set.");return i??n}(r,i),device:k(r,"device"),udid:k(r,"udid"),serial:k(r,"serial"),iosSimulatorDeviceSet:k(r,"iosSimulatorDeviceSet"),androidDeviceAllowlist:k(r,"androidDeviceAllowlist"),daemonBaseUrl:k(r,"daemonBaseUrl"),daemonAuthToken:k(r,"daemonAuthToken"),tenant:k(r,"tenant"),runId:k(r,"runId"),leaseId:k(r,"leaseId"),cwd:k(r,"cwd"),debug:D(r,"debug")}}function I(e,t){let r=G(e,t);return{x:O(r,"x"),y:O(r,"y")}}function T(e,t){let r=e[t];if("string"!=typeof r||0===r.length)throw Error(`Expected ${t} to be a non-empty string.`);return r}function k(e,t){let r=e[t];if(void 0!==r){if("string"!=typeof r||0===r.length)throw Error(`Expected ${t} to be a non-empty string.`);return r}}function O(e,t){let r=e[t];if("number"!=typeof r||!Number.isFinite(r))throw Error(`Expected ${t} to be a finite number.`);return r}function $(e,t){let r=e[t];if(void 0!==r){if("number"!=typeof r||!Number.isFinite(r))throw Error(`Expected ${t} to be a finite number.`);return r}}function F(e,t,r={}){let i=e[t];if(void 0!==i){if(!Number.isInteger(i))throw Error(`Expected ${t} to be an integer.`);if(void 0!==r.min&&i<r.min)throw Error(`Expected ${t} to be at least ${r.min}.`);if(void 0!==r.max&&i>r.max)throw Error(`Expected ${t} to be at most ${r.max}.`);return i}}function D(e,t){let r=e[t];if(void 0!==r){if("boolean"!=typeof r)throw Error(`Expected ${t} to be a boolean.`);return r}}function q(e,t,r){let i=e[t];if("string"!=typeof i||!r.includes(i))throw Error(`Expected ${t} to be one of: ${r.join(", ")}.`);return i}function U(e,t,r){let i=e[t];if(void 0!==i){if("string"!=typeof i||!r.includes(i))throw Error(`Expected ${t} to be one of: ${r.join(", ")}.`);return i}}function P(e){return L({session:e.session,platform:e.platform,target:e.deviceTarget,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist,daemonBaseUrl:e.daemonBaseUrl,daemonAuthToken:e.daemonAuthToken,tenant:e.tenant,runId:e.runId,leaseId:e.leaseId,cwd:e.cwd,debug:e.debug})}function M(e){switch(e.kind){case"ref":return{ref:e.ref,label:e.label};case"selector":return{selector:e.selector};case"point":return{x:e.x,y:e.y}}}function R(e){switch(e.kind){case"ref":return{ref:e.ref,label:e.label};case"selector":return{selector:e.selector}}}function B(e){return{count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap}}function C(e){return{depth:e.depth,scope:e.scope,raw:e.raw}}function N(e,t,r){let i=new Set(t),n=Object.keys(e).filter(e=>!i.has(e));if(n.length>0)throw Error(`${r} has unknown field(s): ${n.join(", ")}.`)}function L(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}function z(e,t){return{schema:e,required:!1,read:t}}function H(e,t){let r=e[t];if(void 0!==r){if(!r||"object"!=typeof r||Array.isArray(r))throw Error(`Expected ${t} to be an object.`);return r}}function K(e,t){let r=e[t];if(void 0!==r){if(!Array.isArray(r)||r.some(e=>"string"!=typeof e))throw Error(`Expected ${t} to be an array of strings.`);return r}}function W(){return[{type:"object",properties:{kind:{type:"string",const:"ref"},ref:{type:"string",description:"Snapshot element ref such as @e12."},label:{type:"string",description:"Optional human label for the ref."}},required:["kind","ref"],additionalProperties:!1},{type:"object",properties:{kind:{type:"string",const:"selector"},selector:{type:"string",description:"Agent-device selector expression."}},required:["kind","selector"],additionalProperties:!1}]}function G(e,t){let r=e[t];if(!r||"object"!=typeof r||Array.isArray(r))throw Error(`Expected ${t} to be an object.`);return r}export{N as assertAllowedKeys,u as booleanField,o as booleanSchema,P as commonToClientOptions,L as compactRecord,g as customField,h as elementTargetField,p as enumField,E as fieldsInputSchema,l as integerField,n as integerSchema,y as interactionTargetField,b as jsonSchemaField,f as looseObjectField,s as looseObjectSchema,c as numberField,U as optionalEnum,F as optionalInteger,v as pointField,S as readCommonInput,j as readFieldInput,A as readInputRecord,I as readPoint,x as repeatedFields,q as requiredEnum,a as requiredField,O as requiredNumber,w as selectorSnapshotFields,m as stringArrayField,d as stringField,i as stringSchema,R as toClientElementTarget,M as toClientInteractionTarget,B as toRepeatedOptions,C as toSelectorSnapshotOptions};
|
package/dist/src/9533.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{promises as e}from"node:fs";import{deflateSync as t,inflateSync as n}from"node:zlib";import r from"node:path";import{asAppError as i,AppError as a}from"./9152.js";import{normalizeRef as o,centerOfRect as s,buildSnapshotPresentationKey as l,findNodeByRef as d}from"./4057.js";import{expandRect as c,intersectArea as u,isScrollableNodeLike as h,unionRects as p,rectCenter as f,clamp as w,squaredDistance as m}from"./4778.js";import{trimText as b,extractNodeText as g,findSnapshotAncestor as y,parseSelectorChain as x,isNodeVisible as v,buildSnapshotNodeByIndex as k,isNodeEditable as I,buildTextPreview as A,findNearestHittableAncestor as N,buildSelectorChainForNode as M,findSelectorChainMatch as R,resolveSelectorChain as P,findNodeByLabel as S,resolveRefLabel as O,describeTextSurface as E,extractReadableText as D,formatSelectorFailure as _,normalizeType as T,isFillableType as $}from"./940.js";import{successText as C}from"./1998.js";import{whichCmd as L,runCmd as U}from"./9818.js";import{findBestMatchesByLocator as B}from"./7556.js";import"./7847.js";import{resolveAppsFilter as G,assertResolvedAppsFilter as F}from"./1393.js";let q=["status","get","dismiss","enter","return"];function X(e){return q.includes(e)}function Y(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 V(e){let t=e.direction,n="up"===t||"down"===t?e.referenceHeight:e.referenceWidth,r=function(e){if(void 0===e)return .6;if(!Number.isFinite(e)||e<=0)throw new a("INVALID_ARGS","scroll amount must be a positive number");return e}(e.amount),i=void 0!==e.pixels?function(e){if(!Number.isFinite(e)||e<=0)throw new a("INVALID_ARGS","scroll pixels must be a positive integer");return Math.max(1,Math.round(e))}(e.pixels):Math.round(n*r),o=Math.max(1,Math.round(.05*n)),s=Math.max(1,Math.min(i,Math.max(1,n-2*o))),l=Math.round(s/2),d=Math.round(e.referenceWidth/2),c=Math.round(e.referenceHeight/2),u=(n,r,i,a)=>({direction:t,x1:n,y1:r,x2:i,y2:a,referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:s});switch(t){case"up":return u(d,c-l,d,c+l);case"down":return u(d,c+l,d,c-l);case"left":return u(d-l,c,d+l,c);case"right":return u(d+l,c,d-l,c)}}function H(e){return{...V({...e,direction:function(e){switch(e){case"up":return"down";case"down":return"up";case"left":return"right";case"right":return"left"}}(e.direction)}),direction:e.direction}}function K(e,t,n={}){let r=n.marginPx??8,[i,a,o]="left"===e?[85,15,50]:"right"===e?[15,85,50]:"left-edge"===e?[99,15,50]:[1,85,50],s=W(t,i,o,{marginPx:r}),l=W(t,a,o,{marginPx:r});return{preset:e,x1:s.x,y1:s.y,x2:l.x,y2:l.y,referenceWidth:t.referenceWidth,referenceHeight:t.referenceHeight}}function z(e){switch(e){case"left":case"right":case"left-edge":case"right-edge":return e;default:throw new a("INVALID_ARGS","gesture swipe requires left, right, left-edge, or right-edge")}}function j(e){let t=function(e){let t=e.filter(e=>(function(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("application")||t.includes("window")})(e.type)&&Q(e.rect)).map(e=>e.rect).sort((e,t)=>(t?.width??0)*(t?.height??0)-(e?.width??0)*(e?.height??0))[0];if(t)return t;let n=e.map(e=>e.rect).filter(Q);if(0===n.length)return;let r=Math.max(...n.map(e=>e.x+e.width)),i=Math.max(...n.map(e=>e.y+e.height));if(!(r<=0)&&!(i<=0))return{x:0,y:0,width:r,height:i}}(e);if(t)return{referenceWidth:t.width,referenceHeight:t.height}}function W(e,t,n,r={}){let i={x:Math.round(e.referenceWidth*t/100),y:Math.round(e.referenceHeight*n/100)};return void 0===r.marginPx?i:J(i,e,r.marginPx)}function J(e,t,n){return{x:ee(e.x,n,t.referenceWidth),y:ee(e.y,n,t.referenceHeight)}}function Z(e){switch(e){case"up":case"down":case"left":case"right":return e;default:throw new a("INVALID_ARGS",`Unknown direction: ${e}`)}}function Q(e){return!!e&&e.width>0&&e.height>0}function ee(e,t,n){let r=Math.max(t,n-t);return et(e,t,r)}function et(e,t,n){return Math.min(Math.round(n),Math.max(Math.round(t),Math.round(e)))}function en(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function er(e){let t=null,n=-1;for(let r of e){let e=r.width*r.height;e>n&&(t=r,n=e)}return t}function ei(e,t,n,r){return Math.max(e,n)<=Math.min(t,r)}function ea(e){let t=e.trim().toLowerCase();return!!t&&/^(vertical|horizontal)\s+scroll\s+bar(?:,?\s*\d+\s+pages?)?$/.test(t)}function eo(e,t){if(!(e?.trim().toLowerCase()??"").includes("vertical scroll bar"))return null;let n=function(e){if(!e)return null;let t=/^(\d{1,3})%$/.exec(e.trim());if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?Math.max(0,Math.min(100,n)):null}(t);return null===n?null:n<=1?{above:!1,below:!0}:n>=99?{above:!0,below:!1}:{above:!0,below:!0}}function es(e){let t=new Map;for(let[n,r]of e.entries())t.set(r.index,n);let n=[],r=[];for(let[i,a]of e.entries()){let e=Math.max(0,a.depth??0);for(;r.length>0&&e<=r[r.length-1].depth;)r.pop();let o="number"==typeof a.parentIndex?t.get(a.parentIndex):void 0,s="number"==typeof o&&o<i?o:r[r.length-1]?.index;n.push({...a,index:i,depth:e,parentIndex:s}),r.push({depth:e,index:i})}return n}function el(e){return new Map(e.map(e=>[e.index,e]))}function ed(e){return e.label?.trim()||e.value?.trim()||e.identifier?.trim()||""}function ec(e){if(0===e.length)return{nodes:e,hiddenCount:0,summaryLines:[]};let{byIndex:t,visibleNodeIndexes:n,offscreenNodes:r,hintedContainers:i}=eh(e),a=0===n.size?e:e.filter(e=>n.has(e.index));return{nodes:a.map(e=>(function(e,t){let n=t.get(e.index);if(!n||0===n.size)return e;let r=!!(!0===e.hiddenContentAbove||n.has("above"))||void 0,i=!!(!0===e.hiddenContentBelow||n.has("below"))||void 0;return{...e,hiddenContentAbove:r,hiddenContentBelow:i}})(e,i.directionsByContainer)),hiddenCount:0===n.size?0:e.length-a.length,summaryLines:function(e,t,n){let r=new Map;for(let i of e){let e=function(e,t,n){if(!e.rect)return null;let r=ef(e,t,n);return r?ew(e.rect,r):null}(i,t,n);if(!e)continue;let a=r.get(e)??[];a.push(i),r.set(e,a)}return["above","below"].flatMap(e=>{let t=r.get(e);if(!t||0===t.length)return[];let n=(function(e){let t=new Set,n=[];for(let r of e){let e=ed(r);!e||t.has(e)||(t.add(e),n.push(e))}return n})(t).slice(0,3).map(e=>`"${e}"`),i=1===t.length?"interactive item":"interactive items",a=n.length>0?`: ${n.join(", ")}`:"";return[`[off-screen ${e}] ${t.length} ${i}${a}`]})}(r.filter(e=>!i.coveredNodeIndexes.has(e.index)&&function(e){if(!0===e.hittable)return!0;let t=(e.type??"").toLowerCase();return t.includes("button")||t.includes("link")||t.includes("textfield")||t.includes("edittext")||t.includes("searchfield")||t.includes("checkbox")||t.includes("radio")||t.includes("switch")||t.includes("menuitem")||!!ed(e)}(e)),e,t)}}function eu(e){if(0===e.length)return new Map;let{hintedContainers:t}=eh(e);var n=t.directionsByContainer;let r=new Map;for(let[e,t]of n){let n={};t.has("above")&&(n.hiddenContentAbove=!0),t.has("below")&&(n.hiddenContentBelow=!0),(n.hiddenContentAbove||n.hiddenContentBelow)&&r.set(e,n)}return r}function eh(e){let t=el(e),n=new Set,r=[];for(let i of e){if(ep(i,e,t)){!function(e,t,n){let r=e,i=new Set;for(;r&&!i.has(r.index);)i.add(r.index),t.add(r.index),r="number"==typeof r.parentIndex?n.get(r.parentIndex):void 0}(i,n,t);continue}r.push(i)}let i=function(e,t,n,r){let i=new Map,a=new Map,o=new Set;for(let e of t){if(!e.rect)continue;let t=em(e,n,r);if(!t?.rect)continue;let s=ew(e.rect,t.rect);if(!s)continue;let l=i.get(t.index)??new Set;l.add(s),i.set(t.index,l);let d=a.get(t.index)??new Set;d.add(s),a.set(t.index,d),o.add(e.index)}return function(e,t,n,r,i){for(let a of e){let e=function(e){let t=eo(e.label,e.value);if(!t)return null;let n=new Set;return t.above&&n.add("above"),t.below&&n.add("below"),n.size>0?n:null}(a);if(!e||0===e.size)continue;let o=em(a,t,n);if(!o)continue;let s=r.get(o.index)??new Set,l=i.get(o.index);for(let t of e)(!l||!(l.size>0)||l.has(t))&&s.add(t);r.set(o.index,s)}}(e,n,r,i,a),{directionsByContainer:i,coveredNodeIndexes:o}}(e,r,n,t);return{byIndex:t,visibleNodeIndexes:n,offscreenNodes:r,hintedContainers:i}}function ep(e,t,n=el(t)){var r;if(!e.rect)return!0;let i=ef(e,t,n);return!i||(r=e.rect,ei(r.x,r.x+r.width,i.x,i.x+i.width)&&ei(r.y,r.y+r.height,i.y,i.y+i.height))}function ef(e,t,n=el(t)){var r,i;let a=(r=e,i=n,eb(r,i,e=>!!e.rect)?.rect??null);return a||function(e,t){let n=s(t),r=e.filter(e=>{var t;return!!(t=e.rect)&&Number.isFinite(t.x)&&Number.isFinite(t.y)&&Number.isFinite(t.width)&&Number.isFinite(t.height)}),i=r.filter(e=>{let t=(e.type??"").toLowerCase();return t.includes("application")||t.includes("window")}),a=er(i.map(e=>e.rect).filter(e=>en(e,n.x,n.y)));if(a)return a;let o=er(i.map(e=>e.rect));if(o)return o;let l=er(r.map(e=>e.rect).filter(e=>en(e,n.x,n.y)));return l||null}(t,e.rect??{x:0,y:0,width:0,height:0})}function ew(e,t){return e.y+e.height<=t.y?"above":e.y>=t.y+t.height?"below":null}function em(e,t,n){return eb(e,n,e=>t.has(e.index))}function eb(e,t,n){let r="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(i.add(r.index),n(r)&&h(r))return r;r="number"==typeof r.parentIndex?t.get(r.parentIndex):void 0}return null}async function eg(e){let{edge:t,target:n={},scope:r,captureNodes:i}=e;try{let e=await i(r),a=function(e,t,n={}){var r,i,a;let o,s=(e??[]).map((e,t)=>({...e,ref:"ref"in e&&e.ref?e.ref:`e${t+1}`}));if(0===s.length)return{canScroll:!1,emptySnapshot:!0,signature:""};let l=eu(s),d=function(e,t,n,r){let i=new Map(e.map(e=>[e.index,e])),a=e.filter(e=>h(e)&&eM(e.rect));if(0===a.length)return null;let o=function(e,t){if(void 0===e)return null;let n=t.get(e);for(;n;){if(h(n)&&eM(n.rect))return n;n=void 0===n.parentIndex?void 0:t.get(n.parentIndex)}return null}(r.nodeIndex,i);if(o)return o;let s=r.point;if(s){let e=a.filter(e=>{var t,n;return e.rect&&(t=e.rect,(n=s).x>=t.x&&n.x<=t.x+t.width&&n.y>=t.y&&n.y<=t.y+t.height)}).sort(eI);if(e.length>0)return e.find(e=>ev(e,t.get(e.index),n))??e[0]??null}let l=a.filter(e=>ev(e,t.get(e.index),n)).sort(eA);return l.length>0?l[0]??null:a.filter(t=>ep(t,e)).sort(eA)[0]??a.sort(eA)[0]??null}(s,l,t,n),c=(d?(r=s,i=d.index,o=new Map(r.map(e=>[e.index,e])),r.filter(e=>e.index===i||function(e,t,n){let r=void 0===e.parentIndex?void 0:n.get(e.parentIndex);for(;r;){if(r.index===t)return!0;r=void 0===r.parentIndex?void 0:n.get(r.parentIndex)}return!1}(e,i,o))):s).map(e=>{let t=e.rect?["x","y","width","height"].map(t=>{var n;return n=e.rect?.[t],"number"==typeof n&&Number.isFinite(n)?n.toFixed(1):""}).join(","):"";return[String(e.index??""),String(e.parentIndex??""),String(e.type??""),String(e.label??""),String(e.value??""),t].join("|")}).join("\n");return d?{canScroll:ev(d,l.get(d.index),t),emptySnapshot:!1,signature:c,scope:[(a=d).identifier,a.label,a.value].map(e=>"string"==typeof e?e.trim():"").find(ek)}:{canScroll:!1,emptySnapshot:!1,signature:c}}(e,t,n);if(r&&a.emptySnapshot)return await eg({edge:t,target:n,captureNodes:i});return a}catch(e){var o,s,l;throw o=t,s=r,l=e,s?new a("COMMAND_FAILED",`Failed to verify scroll ${o} state for scoped container`,{scope:s,hint:`scroll ${o} could not verify the scoped scroll container. Run snapshot -i -c for the current screen and retry with a visible scroll target.`},l):new a("COMMAND_FAILED",`Failed to verify scroll ${o} state`,{hint:`scroll ${o} needs a snapshot showing hidden content ${"bottom"===o?"below":"above"} before it will move.`},l)}}async function ey(e){let t,{edge:n,captureState:r,scroll:i}=e,o=await r();o.scope&&(o=await r(o.scope));let s=0;for(;o.canScroll;){if(s>=40)throw new a("COMMAND_FAILED",`scroll ${n} reached the safety limit before the snapshot showed the edge`,{hint:"The scoped scroll container still reports hidden content. Use a smaller manual scroll + snapshot loop to inspect the current state."});t=await i(),s+=1,o=await r(o.scope)}return{passes:s,result:t}}function ex(e,t,n,r,i){return t&&0===n?`Already at ${t}; no hidden content ${"bottom"===t?"below":"above"} detected`:t?`Scrolled to ${t} with ${n} ${e} passes`:void 0!==i?`Scrolled ${e} by ${i}px`:void 0!==r?`Scrolled ${e} by ${r}`:`Scrolled ${e}`}function ev(e,t,n){return"bottom"===n?!0===e.hiddenContentBelow||t?.hiddenContentBelow===!0:!0===e.hiddenContentAbove||t?.hiddenContentAbove===!0}function ek(e){return e.length>0&&e.length<=80&&!/^(true|false)$/i.test(e)&&!/^\d+$/.test(e)&&!/^\d+%$/.test(e)}function eI(e,t){return eN(e.rect)-eN(t.rect)}function eA(e,t){return eN(t.rect)-eN(e.rect)}function eN(e){return e?e.width*e.height:0}function eM(e){return!!(e&&e.width>0&&e.height>0)}function eR(e,t,n,r){if(!Number.isFinite(e)||!Number.isInteger(e)||e<n||e>r)throw new a("INVALID_ARGS",`${t} must be an integer between ${n} and ${r}`);return e}let eP=["x","y","width","height"];function eS(e){let t=eO(e);if(!t)return null;let n=s(t);return Number.isFinite(n.x)&&Number.isFinite(n.y)?n:null}function eO(e){if(!e)return null;let t=Number(e.x),n=Number(e.y),r=Number(e.width),i=Number(e.height);return Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(i)&&!(r<0)&&!(i<0)?{x:t,y:n,width:r,height:i}:null}function eE(e,t){return!!e&&!!t&&eP.every(n=>.5>=Math.abs(e[n]-t[n]))}function eD(e){return{x:e_(e.x,e.width),y:e_(e.y,e.height)}}function e_(e,t){if(t<=1)return Math.floor(e);let n=Math.ceil(e);return Math.round(Math.min(Math.floor(e+t-1),Math.max(n,e+t/2)))}let eT=["tabbar","toolbar","navigationbar","bottomnavigation","bottomnavigationview","sheet","dialog","alert","popover","menu"],e$=["button","link","menuitem","tabitem","textfield","searchfield","edittext","checkbox","radio","switch","cell"];function eC(e){if(e.length<2)return e;let t=[...e],n={nodes:t,byIndex:new Map(t.map(e=>[e.index,e]))},r=!1;for(let[e,i]of t.entries()){if(!function(e){return!!eF(e.rect)&&(!!(!0===e.hittable||eU(e,e$))||!!(e.label?.trim()||e.value?.trim()||e.identifier?.trim()))}(i)||!function e(t,n,r){let i=eF(r.rect);if(!i)return null;let a=s(i);for(let o=n+1;o<t.nodes.length;o+=1){let n=t.nodes[o];if(n&&function(t,n,r,i,a){if(!t.nodes[n])return!1;let o=function(t,n,r,i){var a,o,s,l;let d=t.nodes[n];if(!d||!(!(!eF((a=d).rect)||function(e){let t=eB(e);return t.includes("application")||t.includes("window")}(a))&&eU(a,eT))||eG(o=r,s=d,l=t.byIndex)||eG(s,o,l))return null;let c=eF(d.rect);return!c||eE(i,c)||e(t,n,d)?null:c}(t,n,r,i);return!!(o&&en(o,a.x,a.y))}(t,o,r,i,a))return n}return null}(n,e,i))continue;r=!0;let a={...i,hittable:!1,interactionBlocked:"covered",presentationHints:Array.from(new Set([...i.presentationHints??[],"covered"]))};t[e]=a,n.byIndex.set(a.index,a)}return r?t:e}function eL(e){return void 0!==e.interactionBlocked}function eU(e,t){let n=eB(e);return t.some(e=>n.includes(e))}function eB(e){return[e.type,e.role,e.subrole].map(e=>T(e??"")).join(" ")}function eG(e,t,n){let r="number"==typeof t.parentIndex?n.get(t.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(r.index===e.index)return!0;i.add(r.index),r="number"==typeof r.parentIndex?n.get(r.parentIndex):void 0}return!1}function eF(e){let t=eO(e);return t&&t.width>0&&t.height>0?t:null}let eq=/\b(logbox|redbox|reload js|copy stack|component stack|call stack|runtime error|open debugger to view warnings)\b/,eX=/\b(redbox|runtime error|reload js|copy stack|component stack|call stack)\b/,eY=[/\b[\w.$<>/-]+\.(?:tsx?|jsx?):\d+(?::\d+)?\b/,/\b[\w.$<>/-]+\.(?:tsx?|jsx?)\s+\(\d+:\d+\)/],eV=[/^!,\s+/,/^(warn|warning|error):\s+/,/\b(?:possible\s+)?unhandled (?:promise )?rejection\b/],eH=["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"],eK=new Set(["x","\xd7","✕","✖","⨯"]);function ez(e){return ej(e)}function ej(e){var t,n,r,i,a,o,l,d,c,u;let h,p,f,w,m,b,g,y,x=(h=(t=e).map(eQ).join("\n").toLowerCase(),p=e7(t,e5),f=e7(t,e8),w=e7(t,e1,e3),m=e7(t,e2),b=(n=h,eY.some(e=>e.test(n))),g=e0(h),y=(r=h,i=p,a=f,i.length>0||a.length>0||/\b(reload js|copy stack)\b/.test(r)),{dismissNodes:p,minimizeNodes:f,collapsedNodes:w,redBox:(o=h,l=b,d=y,eX.test(o)||e0(o)||l&&d),detected:(c={text:h,hasReactNativeStackFrame:b,hasOverlayControl:y,hasControllessRedBoxText:g,collapsedNodes:w,openDebuggerWarningNodes:m}).collapsedNodes.length>0||c.openDebuggerWarningNodes.length>0||c.hasControllessRedBoxText||c.hasOverlayControl&&(u=c.text,eq.test(u)||c.hasReactNativeStackFrame)}),v=x.detected?function(e){let t=tt(e.dismissNodes,te);if(t){let e;var n,r=t,i=(n=t,(e=tr(n)?.trim().toLowerCase())&&e4(e)?"dismiss":"close");if(!r.rect)throw Error("React Native overlay target node must have rect");return{action:i,point:s(r.rect),rect:r.rect,ref:r.ref,label:tr(r)}}let a=tt(e.collapsedNodes.filter(e6),tn);return a?.rect?{action:"close-collapsed-banner",point:function(e){var t,n;if(!e.rect)throw Error("Collapsed React Native warning node must have rect");let r=Math.min(e.rect.height,52),i=Math.min(36,Math.max(18,.45*r));return{x:Math.round((t=e.rect.x+e.rect.width-i,n=e.rect.x+1,Math.min(e.rect.x+e.rect.width-1,Math.max(n,t)))),y:Math.round(e.rect.y+r/2)}}(a),rect:a.rect,ref:a.ref,label:tr(a)}:null}(x):null;return{detected:x.detected,redBox:x.redBox,dismissNodes:x.dismissNodes,minimizeNodes:x.minimizeNodes,collapsedNodes:x.collapsedNodes,primaryAction:v}}function eW(e){return[...e.dismissNodes,...e.minimizeNodes,...e.collapsedNodes]}function eJ(e){var t;return e1(e.label?.trim())&&!!(t=e.rect)&&t.x<=1&&t.y<=1&&t.width>=300&&t.height>=600}function eZ(e,t){let n=e.label?.trim();return!!n&&!!eJ(e)&&t.some(e=>e.label?.trim()===n&&e9(e))}function eQ(e){return[e.label,e.value,e.identifier,e.type,e.role].filter(Boolean).join(" ")}function e0(e){return/\buncaught\b/.test(e)&&/unable to download asset/.test(e)}function e1(e){let t=e?.trim().toLowerCase();return!!t&&(eH.some(e=>t.includes(e))||eV.some(e=>e.test(t)))}function e2(e){return e.includes("open debugger to view warnings")||/^!,\s+open debugger\b/.test(e)}function e5(e){var t,n;return e4(e)||(t=e,/^close(?:\s*\([^)]*\))?$/i.test(t))||(n=e,eK.has(n))}function e4(e){return/^dismiss(?:\s*\([^)]*\))?$/i.test(e)}function e8(e){return/^minimi[sz]e(?:\b|\s|\()/i.test(e)}function e3(e){return!e.rect||e.rect.height<=180}function e6(e){let t=tr(e)?.trim().toLowerCase()??"";return(e2(t)||/^!,\s+/.test(t))&&e9(e)}function e9(e){return!!e.rect&&e.rect.width>=120&&e.rect.height>=36&&e.rect.height<=180}function e7(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 te(e){var t;let n;return[+(!0===(n=[e.type,e.role,e.subrole].join(" ").toLowerCase(),/\b(button|menuitem|link)\b/.test(n))),+(!0===e.hittable),-((t=e.rect)?t.width*t.height:1/0)]}function tt(e,t){let n=e.filter(e=>e.rect);return 0===n.length?null:n.sort((e,n)=>(function(e,t){for(let n=0;n<e.length;n+=1){let r=e[n]-t[n];if(0!==r)return r}return 0})(t(n),t(e)))[0]??null}function tn(e){return[+(!0===e.hittable),e.rect?.width??0,e.rect?.y??0]}function tr(e){return e.label??e.value??e.identifier}let ti=Buffer.from([137,80,78,71,13,10,26,10]),ta=new Map([[0,1],[2,3],[3,1],[4,2],[6,4]]),to=new Map([[0,new Set([1,2,4,8,16])],[2,new Set([8,16])],[3,new Set([1,2,4,8])],[4,new Set([8,16])],[6,new Set([8,16])]]),ts=[{x:0,y:0,dx:8,dy:8},{x:4,y:0,dx:8,dy:8},{x:0,y:4,dx:4,dy:8},{x:2,y:0,dx:4,dy:4},{x:0,y:2,dx:2,dy:4},{x:1,y:0,dx:2,dy:2},{x:0,y:1,dx:1,dy:2}];class tl{width;height;data;static sync={read:td,write:tc};constructor(e){this.width=ty(e.width,"width"),this.height=ty(e.height,"height");let t=this.width*this.height*4;if(this.data=e.data?Buffer.from(e.data):Buffer.alloc(t),this.data.length!==t)throw Error(`PNG data length must be ${t} bytes`)}}function td(e){var t;let{metadata:r,idatChunks:i}=function(e){let t,n=[];for(let r of function*(e){if(!e.subarray(0,ti.length).equals(ti))throw Error("Invalid PNG signature");let t=ti.length;for(;t<e.length;){if(t+12>e.length)throw Error("Truncated PNG chunk");let n=e.readUInt32BE(t),r=e.toString("ascii",t+4,t+8),i=t+8,a=i+n;if(a+4>e.length)throw Error(`Truncated PNG ${r} chunk`);let o=e.subarray(i,a),s=e.readUInt32BE(a);if(tg(e.subarray(t+4,a))!==s)throw Error(`Invalid PNG ${r} chunk CRC`);t=a+4,yield{type:r,data:o}}}(e))if("IHDR"===r.type?t=function(e){var t;if(13!==e.length)throw Error("Invalid PNG IHDR length");let n=e.readUInt32BE(0),r=e.readUInt32BE(4),i=e[8],a=e[9],o=e[10],s=e[11],l=e[12];if(t=a,!ta.has(t))throw Error(`Unsupported PNG color type ${a}`);let d=to.get(a);if(!d?.has(i))throw Error(`Unsupported PNG color type ${a} with bit depth ${i}`);if(0!==o)throw Error(`Unsupported PNG compression method ${o}`);if(0!==s)throw Error(`Unsupported PNG filter method ${s}`);if(0!==l&&1!==l)throw Error(`Unsupported PNG interlace method ${l}`);return{width:ty(n,"width"),height:ty(r,"height"),bitDepth:i,colorType:a,interlace:l}}(r.data):"IDAT"===r.type?n.push(Buffer.from(r.data)):t=function(e,t){if("PLTE"===e.type){if(!t)throw Error("PNG PLTE appeared before IHDR");t.palette=Buffer.from(e.data)}else if("tRNS"===e.type){if(!t)throw Error("PNG tRNS appeared before IHDR");t.transparency=Buffer.from(e.data)}return t}(r,t),"IEND"===r.type)break;return{metadata:t,idatChunks:n}}(e);if(!r)throw Error("PNG is missing IHDR");if(0===i.length)throw Error("PNG is missing IDAT");let a=function(e,t){let r=function(e){if(0===e.interlace)return function(e,t){return(tw(e)+1)*t}(e,e.height);let t=0;for(let n of ts){let r=th(e.width,n.x,n.dx),i=th(e.height,n.y,n.dy);0!==r&&0!==i&&(t+=function(e,t){return(tw(e)+1)*t}({...e,width:r,height:i},i))}return t}(t);try{let t=n(Buffer.concat(e),{maxOutputLength:r});if(t.length!==r)throw Error("PNG pixel data is truncated");return t}catch(e){var i;if((i=e)instanceof Error&&"code"in i&&"ERR_BUFFER_TOO_LARGE"===i.code)throw Error(`PNG pixel data exceeds expected length ${r}`);throw e}}(i,r);return new tl({width:r.width,height:r.height,data:1===r.interlace?function(e,t){let n=Buffer.alloc(t.width*t.height*4),r=0;for(let i of ts){let a=th(t.width,i.x,i.dx),o=th(t.height,i.y,i.dy);if(0===a||0===o)continue;let s={...t,width:a,height:o,interlace:0},l=tu({inflated:e,offset:r,scanlineLength:tw(s),height:o,bytesPerPixel:tm(s)});r=l.offset;let d=tw(s);for(let e=0;e<o;e+=1){let r=l.raw.subarray(e*d,(e+1)*d);for(let o=0;o<a;o+=1){let a=i.x+o*i.dx,l=((i.y+e*i.dy)*t.width+a)*4,[d,c,u,h]=tp(r,o,s);n[l]=d,n[l+1]=c,n[l+2]=u,n[l+3]=h}}}return n}(a,r):function(e,t){let n=Buffer.alloc(t.width*t.height*4),r=tw(t);for(let i=0;i<t.height;i+=1){let a=e.subarray(i*r,(i+1)*r);for(let e=0;e<t.width;e+=1){let r=(i*t.width+e)*4,[o,s,l,d]=tp(a,e,t);n[r]=o,n[r+1]=s,n[r+2]=l,n[r+3]=d}}return n}(tu({inflated:a,offset:0,scanlineLength:tw(t=r),height:t.height,bytesPerPixel:tm(t)}).raw,r)})}function tc(e){let n=4*e.width,r=Buffer.alloc((n+1)*e.height);for(let t=0;t<e.height;t+=1){let i=t*(n+1);r[i]=0,e.data.copy(r,i+1,t*n,(t+1)*n)}let i=Buffer.alloc(13);return i.writeUInt32BE(e.width,0),i.writeUInt32BE(e.height,4),i[8]=8,i[9]=6,i[10]=0,i[11]=0,i[12]=0,Buffer.concat([ti,tb("IHDR",i),tb("IDAT",t(r)),tb("IEND",Buffer.alloc(0))])}function tu(e){let{inflated:t,offset:n,scanlineLength:r,height:i,bytesPerPixel:a}=e,o=n+(r+1)*i;if(t.length<o)throw Error("PNG pixel data is truncated");let s=Buffer.alloc(r*i);for(let e=0;e<i;e+=1){let i=n+e*(r+1),o=e*r,l=t[i];for(let n=0;n<r;n+=1){let d=t[i+1+n],c=n>=a?s[o+n-a]:0,u=e>0?s[o+n-r]:0,h=e>0&&n>=a?s[o+n-r-a]:0;s[o+n]=function(e,t,n,r,i){if(0===e)return t;if(1===e)return t+n&255;if(2===e)return t+r&255;if(3===e)return t+Math.floor((n+r)/2)&255;if(4===e)return t+function(e,t,n){let r=e+t-n,i=Math.abs(r-e),a=Math.abs(r-t),o=Math.abs(r-n);return i<=a&&i<=o?e:a<=o?t:n}(n,r,i)&255;throw Error(`Unsupported PNG filter type ${e}`)}(l,d,c,u,h)}}return{raw:s,offset:o}}function th(e,t,n){return e<=t?0:Math.floor((e-t+n-1)/n)}function tp(e,t,n){if(3===n.colorType){var r,i,a,o,s,l,d,c=e,u=t,h=n;if(!h.palette)throw Error("Indexed PNG is missing PLTE");let p=tf(c,u,h.bitDepth),f=3*p;if(f+2>=h.palette.length)throw Error("Indexed PNG palette is invalid");return[h.palette[f],h.palette[f+1],h.palette[f+2],h.transparency?.[p]??255]}if(n.bitDepth<8){let i,a;return[a=Math.round((i=tf(e,t,(r=n).bitDepth))/((1<<r.bitDepth)-1)*255),a,a,255*!(r.transparency&&r.transparency.length>=2&&i===r.transparency.readUInt16BE(0))]}let p=16===n.bitDepth?2:1,f=t*ta.get(n.colorType)*p,w=t=>16===n.bitDepth?e.readUInt16BE(f+2*t):e[f+t*p],m=e=>{var t;return t=w(e),16===n.bitDepth?Math.round(t/65535*255):t};if(0===n.colorType){let e=m(0);return[e,e,e,255*(i=w(0),!(a=n).transparency||!!(a.transparency.length<2)||i!==a.transparency.readUInt16BE(0))]}if(2===n.colorType){return[m(0),m(1),m(2),255*(o=w(0),s=w(1),l=w(2),!(d=n).transparency||!!(d.transparency.length<6)||o!==d.transparency.readUInt16BE(0)||s!==d.transparency.readUInt16BE(2)||l!==d.transparency.readUInt16BE(4))]}if(4===n.colorType){let e=m(0);return[e,e,e,m(1)]}return[m(0),m(1),m(2),m(3)]}function tf(e,t,n){let r=t*n;return e[Math.floor(r/8)]>>8-n-r%8&(1<<n)-1}function tw(e){let t=ta.get(e.colorType);return Math.ceil(e.width*t*e.bitDepth/8)}function tm(e){return Math.max(1,Math.ceil(ta.get(e.colorType)*e.bitDepth/8))}function tb(e,t){let n=Buffer.from(e,"ascii"),r=Buffer.alloc(8+t.length+4);return r.writeUInt32BE(t.length,0),n.copy(r,4),t.copy(r,8),r.writeUInt32BE(tg(Buffer.concat([n,t])),8+t.length),r}function tg(e){let t=0xffffffff;for(let n of e){t^=n;for(let e=0;e<8;e+=1)t=1&t?0xedb88320^t>>>1:t>>>1}return(0xffffffff^t)>>>0}function ty(e,t){if(!Number.isInteger(e)||e<1)throw Error(`PNG ${t} must be positive`);return e}function tx(e,t){try{return tl.sync.read(e)}catch(e){throw new a("COMMAND_FAILED",`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}async function tv(t,n){if(!Number.isInteger(n)||n<1)throw new a("INVALID_ARGS","Screenshot max size must be a positive integer");let r=tx(await e.readFile(t),"screenshot"),i=Math.max(r.width,r.height);if(i<=n)return;let o=n/i,s=Math.max(1,Math.round(r.width*o)),l=Math.max(1,Math.round(r.height*o)),d=function(e,t,n){let r=new tl({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,l=(n+1)*e.width/t,d=0,c=0,u=0,h=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(l);r+=1){let i=n*(Math.min(r+1,l)-Math.max(r,s)),a=(t*e.width+r)*4;d+=(e.data[a]??0)*i,c+=(e.data[a+1]??0)*i,u+=(e.data[a+2]??0)*i,h+=(e.data[a+3]??0)*i,p+=i}}let f=(i*r.width+n)*4;r.data[f]=Math.round(d/p),r.data[f+1]=Math.round(c/p),r.data[f+2]=Math.round(u/p),r.data[f+3]=Math.round(h/p)}}return r}(r,s,l);await e.writeFile(t,tl.sync.write(d))}async function tk(e,t,n){if("path"===t.kind&&!e.policy.allowLocalInputPaths)throw new a("INVALID_ARGS",`Local ${n.field??"input"} paths are not allowed by command policy`);try{return await e.artifacts.resolveInput(t,n)}catch(e){throw i(e)}}async function tI(e,t,n){if(t?.kind==="path"&&!e.policy.allowLocalOutputPaths)throw new a("INVALID_ARGS","Local output paths are not allowed by command policy");try{return await e.artifacts.reserveOutput(t,{...n,visibility:n.visibility??"client-visible",requestedClientPath:t?.kind==="downloadableArtifact"?t.clientPath??n.requestedClientPath:n.requestedClientPath})}catch(e){throw i(e)}}async function tA(e,t){try{return await e.artifacts.createTempFile(t)}catch(e){throw i(e)}}let tN=async(e,t)=>{let n;if(!e.backend.captureScreenshot)throw new a("UNSUPPORTED_OPERATION","screenshot is not supported by this backend");let r=await tI(e,t.out,{field:"path",ext:".png"});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,stabilize:t.stabilize,surface:t.surface}),void 0!==t.maxSize&&await tv(r.path,t.maxSize),n=await r.publish()}catch(e){throw await r.cleanup?.(),e}return{path:r.path,...n?{artifacts:[n]}:{},...C(`Saved screenshot: ${r.path}`)}},tM=[0,187,255,255];function tR(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 tP(e,t,n){return Math.min(Math.max(e,t),n)}let tS=[{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 tO(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){var l,d;if(!tE(t,a,e))continue;let c=0,u=(l=o,a[d=e]=1,l[0]=d,1),h=i.create(e);for(;c<u;){let e=o[c];c+=1,i.visit(h,e),u=function(e){let{mask:t,visited:n,queue:r,width:i,height:a,pixelIndex:o}=e,s=o%i,l=Math.floor(o/i),d=e.queueEnd;for(let e of tS){var c,u,h,p;let o=s+e.x,f=l+e.y;if(c=o,u=f,h=i,p=a,!(c>=0)||!(c<h)||!(u>=0)||!(u<p))continue;let w=f*i+o;tE(t,n,w)&&(d=function(e,t,n,r){return t[r]=1,e[n]=r,n+1}(r,n,d,w))}return d}({mask:t,visited:a,queue:o,queueEnd:u,width:n,height:r,pixelIndex:e})}s.push(h)}return s}function tE(e,t,n){return 1===e[n]&&1!==t[n]}let tD={icon:90,toggle:90,chevron:75,separator:45,visual:35,background:10},t_={leading:20,trailing:20,separator:10,unknown:0,background:-30};function tT(e){return"background"!==e.likelyKind}function t$(e,t){return e.width>=.25*t.width||e.height>=.06*t.height}function tC(e,t){let n,r=0;for(let i of t){let t=tF(e,i.rect);t<=r||(r=t,n=i)}return n}function tL(e){let t=[];for(let n of[...e].sort((e,t)=>e.rect.y-t.rect.y)){let e=t.find(e=>{var t,r;return t=e.rect,tF(t,r=n.rect)>0||Math.abs(f(t).y-f(r).y)<=.5*Math.max(t.height,r.height)});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=p([e.rect,n.rect])}return t}function tU(e,t){let n,r=f(e);for(let e of t){let t=Math.sqrt(m(r,f(e.rect)));n&&t>=n.distance||(n={block:e,distance:t})}return n}function tB(e){let t=tG(e);return e.differentPixels>=24&&t.width>=3&&t.height>=3}function tG(e){return{x:e.minX,y:e.minY,width:e.maxX-e.minX+1,height:e.maxY-e.minY+1}}function tF(e,t){return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}async function tq(e){if(await L("tesseract"))try{let[t,n]=await Promise.all([tY(e.baselinePath),tY(e.currentPath)]);if(0!==t.exitCode||0!==n.exitCode)return;let r=tX(t.stdout,e.width,e.height),i=tX(n.stdout,e.width,e.height),a=function(e,t){let n=new Set,r=[];for(let a of e){var i;let e=tW(a.text),o=function(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(tW(s.text)!==t)continue;let l=m(f(e.normalizedRect),f(s.normalizedRect));l>=a||(i=o,a=l)}return i}(a,e,t,n);if(null===o)continue;n.add(o);let s=function(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=tQ(t.rect.width/e.rect.width),i=tQ(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(100*Math.min(e.confidence,t.confidence))/100,possibleTextMetricMismatch:a}}(a,t[o]);i=s,(Math.abs(i.delta.x)>=2||Math.abs(i.delta.y)>=2||Math.abs(i.delta.width)>=2||Math.abs(i.delta.height)>=2||i.possibleTextMetricMismatch)&&r.push(s)}return r.sort((e,t)=>tV(t)-tV(e)).slice(0,12)}(r,i),o=function(e){let t=[];for(let n of[...e].sort((e,t)=>e.currentRect.y-t.currentRect.y)){let e=t.find(e=>32>=Math.abs(n.delta.x-tJ(e.map(e=>e.delta.x))));e?e.push(n):t.push([n])}return t.filter(e=>e.length>=2).map(tH).filter(e=>e.yRange.max-e.yRange.min<=60).sort((e,t)=>tK(t)-tK(e)).slice(0,4)}(a);if(0===r.length&&0===i.length)return;return{provider:"tesseract",baselineBlocks:r.length,currentBlocks:i.length,baselineBlocksRaw:r,currentBlocksRaw:i,matches:a,...o.length>0?{movementClusters:o}:{}}}catch{return}}function tX(e,t,n){let[r,...i]=e.split(/\r?\n/);if(!r)return[];let a=new Map(r.split(" ").map((e,t)=>[e,t])),o=[];for(let e of i){var s;if(!e.trim())continue;let t=e.split(" "),n=tj(t,a,"level"),r=tz(t,a,"text").trim(),i=tj(t,a,"conf");if(5!==n||(s=r,!/[\p{L}\p{N}]/u.test(s))||i<0)continue;let l=tj(t,a,"left"),d=tj(t,a,"top"),c=tj(t,a,"width"),u=tj(t,a,"height");c<=0||u<=0||o.push({key:[tz(t,a,"page_num"),tz(t,a,"block_num"),tz(t,a,"par_num"),tz(t,a,"line_num")].join(":"),text:r,confidence:i,rect:{x:l,y:d,width:c,height:u}})}let l=new Map;for(let e of o){let t=l.get(e.key);t?t.push(e):l.set(e.key,[e])}return Array.from(l.values()).flatMap(e=>(function(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}if(e.rect.x-(t.rect.x+t.rect.width)>Math.max(48,2.5*Math.max(t.rect.height,e.rect.height))){n.push(r),r=[e];continue}r.push(e)}return r.length>0&&n.push(r),n})(e)).map(e=>(function(e,t,n){if(0===e.length)return null;let r=[...e].sort((e,t)=>e.rect.x-t.rect.x),i=p(r.map(e=>e.rect)),a=Math.round(100*tJ(r.map(e=>e.confidence)))/100;return{text:r.map(e=>e.text).join(" "),confidence:a,rect:i,normalizedRect:{x:tZ(i.x/t),y:tZ(i.y/n),width:tZ(i.width/t),height:tZ(i.height/n)}}})(e,t,n)).filter(e=>null!==e)}function tY(e){return U("tesseract",[e,"stdout","-l","eng","tsv"],{allowFailure:!0,timeoutMs:1e4})}function tV(e){return Math.abs(e.delta.x)+Math.abs(e.delta.y)+Math.abs(e.delta.width)+Math.abs(e.delta.height)+25*!!e.possibleTextMetricMismatch}function tH(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 tK(e){return 2*Math.abs((e.xRange.min+e.xRange.max)/2)+Math.abs((e.yRange.min+e.yRange.max)/2)}function tz(e,t,n){let r=t.get(n);return void 0===r?"":e[r]??""}function tj(e,t,n){let r=Number(tz(e,t,n));return Number.isFinite(r)?r:0}function tW(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function tJ(e){return e.reduce((e,t)=>e+t,0)/e.length}function tZ(e){return Math.round(100*e*100)/100}function tQ(e){return Math.round(1e3*e)/1e3}function t0(e,t,n,r){return{r:Math.round(e/r),g:Math.round(t/r),b:Math.round(n/r)}}function t1(e){return .2126*e.r+.7152*e.g+.0722*e.b}function t2(e){return`#${t5(e.r)}${t5(e.g)}${t5(e.b)}`}function t5(e){return e.toString(16).padStart(2,"0")}function t4(e){return Math.round(100*e*100)/100}let t8=255*Math.sqrt(3);async function t3(t,n,i={}){var a,o,s,l,d;let h,p,f,m;await t6(t,"Baseline image not found"),await t6(n,"Current screenshot not found");let b=i.outputPath,[g,y]=await Promise.all([e.readFile(t),e.readFile(n)]),x=tx(g,"baseline screenshot"),v=tx(y,"current screenshot");t9(x.width,x.height,"baseline screenshot",i.maxPixels),t9(v.width,v.height,"current screenshot",i.maxPixels);let k=i.threshold??.1;if(x.width!==v.width||x.height!==v.height){let e=x.width*x.height;return await t7(i.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:x.width,height:x.height},actual:{width:v.width,height:v.height}}}}let I=x.width*x.height,A=k*t8,N=new tl({width:x.width,height:x.height}),M=new Uint8Array(I),R=0;for(let e=0,t=0;e<x.data.length;e+=4,t+=1){if(Math.sqrt((x.data[e]-v.data[e])**2+(x.data[e+1]-v.data[e+1])**2+(x.data[e+2]-v.data[e+2])**2)>A){R+=1,M[t]=1;let n=ne(v,e);N.data[e]=nt(n,220,.78),N.data[e+1]=nt(n,0,.78),N.data[e+2]=nt(n,0,.78),N.data[e+3]=255;continue}let n=ne(v,e);N.data[e]=n,N.data[e+1]=n,N.data[e+2]=n,N.data[e+3]=255}let P=R>0?(o=(h=function(e){let{diffMask:t,baseline:n,current:r}=e,{width:i,height:a}=n;return tO({mask:t,width:i,height:a,hooks:{create:e=>{var t,n;let r,a;return r=(t=e)%(n=i),{minX:r,minY:a=Math.floor(t/n),maxX:r,maxY:a,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0}},visit:(e,t)=>{var a,o,s,l,d;let c,u,h;return a=e,o=t,s=i,l=n,d=r,c=o%s,u=Math.floor(o/s),h=4*o,void(a.minX=Math.min(a.minX,c),a.minY=Math.min(a.minY,u),a.maxX=Math.max(a.maxX,c),a.maxY=Math.max(a.maxY,u),a.differentPixels+=1,a.baselineRed+=l.data[h],a.baselineGreen+=l.data[h+1],a.baselineBlue+=l.data[h+2],a.currentRed+=d.data[h],a.currentGreen+=d.data[h+1],a.currentBlue+=d.data[h+2])}}})}(a={diffMask:M,baseline:x,current:v,totalPixels:I,differentPixels:R,maxRegions:i.maxRegions})).length<=2e3?function(e){let t=[];for(let i of e.sort((e,t)=>{let n=e.minY-t.minY;return 0!==n?n:e.minX-t.minX})){var n,r;let e=t.find(e=>{var t,n,r;return t=e,n=i,r=12,t.minX-r<=n.maxX&&n.minX-r<=t.maxX&&t.minY-r<=n.maxY&&n.minY-r<=t.maxY});if(!e){t.push({...i});continue}n=e,r=i,n.minX=Math.min(n.minX,r.minX),n.minY=Math.min(n.minY,r.minY),n.maxX=Math.max(n.maxX,r.maxX),n.maxY=Math.max(n.maxY,r.maxY),n.differentPixels+=r.differentPixels,n.baselineRed+=r.baselineRed,n.baselineGreen+=r.baselineGreen,n.baselineBlue+=r.baselineBlue,n.currentRed+=r.currentRed,n.currentGreen+=r.currentGreen,n.currentBlue+=r.currentBlue}return t}(h):h,o.flatMap(e=>{var t,n,r;let i;return(t=e,n=a.baseline.width,r=a.baseline.height,i=t.maxX-t.minX+1,t.maxY-t.minY+1>=Math.max(48,Math.round(.07*r))&&i>=.35*n)?function(e,t,n){var r;let i=function(e,t){let n=[],r=null;for(let i=0;i<e.length;i+=1){if(e[i]<=t){r??=i;continue}null!==r&&(i-r>=6&&n.push([r,i-1]),r=null)}return null!==r&&e.length-r>=6&&n.push([r,e.length-1]),n}((r=function(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)1===t[i*n+r]&&(a+=1);r.push(a)}return r}(e,t.diffMask,t.baseline.width)).map((e,t)=>{let n=0,i=0,a=Math.max(0,t-3),o=Math.min(r.length-1,t+3);for(let e=a;e<=o;e+=1)n+=r[e],i+=1;return Math.round(n/i)}),Math.max(1,Math.round((e.maxX-e.minX+1)*.08))),a=function(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}(e,i,n);if(a.length<=1)return[e];let o=a.map(([n,r])=>(function(e,t,n,r){let i=null;for(let s=t;s<=n;s+=1)for(let t=e.minX;t<=e.maxX;t+=1){var a,o;let e=s*r.baseline.width+t;1===r.diffMask[e]&&function(e,t,n,r,i,a){let o=4*t;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]}(i??={minX:a=t,minY:o=s,maxX:a,maxY:o,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0},e,t,s,r.baseline,r.current)}return i})(e,n,r,t)).filter(e=>null!==e);return o.length>1?o:[e]}(e,a,Math.max(24,Math.round(.03*a.baseline.height))):[e]})).sort((e,t)=>{let n=t.differentPixels-e.differentPixels;if(0!==n)return n;let r=e.minY-t.minY;return 0!==r?r:e.minX-t.minX}).slice(0,Math.max(0,a.maxRegions??8)).map((e,t)=>{var n,r,i,o,s,l,d,c,u,h,p;let f,w,m,b,g,y,x,v,k,I,A,N,M,R,P,S,O;return n=e,r=t+1,i={width:a.baseline.width,height:a.baseline.height,totalPixels:a.totalPixels,differentPixels:a.differentPixels},y={x:n.minX,y:n.minY,width:n.maxX-n.minX+1,height:n.maxY-n.minY+1},x={x:Math.round(n.minX+y.width/2),y:Math.round(n.minY+y.height/2)},v=t0(n.baselineRed,n.baselineGreen,n.baselineBlue,n.differentPixels),k=t0(n.currentRed,n.currentGreen,n.currentBlue,n.differentPixels),I=y.width*y.height,A=t4(n.differentPixels/I),N=Math.round(t1(v)),M=Math.round(t1(k)),R=(o=y,s=i.width,l=i.height,o.width>=.55*s&&o.height>=.12*l?"large-area":o.width>=2.5*o.height?"horizontal-band":o.height>=2.5*o.width?"vertical-band":"compact"),P=(f=I/i.totalPixels)>=.04?"large":f>=.01?"medium":"small",S=(d=v,c=k,w=t1(d),Math.abs(m=t1(c)-w)>=12?m>0?"brighter":"darker":Math.max(Math.abs(c.r-d.r),Math.abs(c.g-d.g),Math.abs(c.b-d.b))>=12?"color-shift":"mixed"),O=(u=x,h=i.width,p=i.height,b=u.x<h/3?"left":u.x>2*h/3?"right":"center",g=u.y<p/3?"top":u.y>2*p/3?"bottom":"middle","center"===b&&"middle"===g?"center":`${g}-${b}`),{index:r,rect:y,normalizedRect:{x:t4(y.x/i.width),y:t4(y.y/i.height),width:t4(y.width/i.width),height:t4(y.height/i.height)},differentPixels:n.differentPixels,shareOfDiffPercentage:t4(n.differentPixels/i.differentPixels),densityPercentage:A,shape:R,size:P,location:O,averageBaselineColorHex:t2(v),averageCurrentColorHex:t2(k),baselineLuminance:N,currentLuminance:M,dominantChange:S}}):[];if(R>0&&b){for(let e of P)e.rect.width<4||e.rect.height<4||function(e,t){let n=tP(t.x,0,e.width-1),r=tP(t.y,0,e.height-1),i=tP(t.x+t.width-1,0,e.width-1),a=tP(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)tR(e,o,r+t,tM),tR(e,o,a-t,tM);for(let o=r;o<=a;o+=1)tR(e,n+t,o,tM),tR(e,i-t,o,tM)}}(N,e.rect);await e.mkdir(r.dirname(b),{recursive:!0}),await e.writeFile(b,tl.sync.write(N))}else await t7(i.outputPath);let S=R>0?await tq({baselinePath:t,currentPath:n,width:x.width,height:x.height}):void 0,O=S&&(S.matches.length>0||(S.movementClusters?.length??0)>0)?{provider:S.provider,baselineBlocks:S.baselineBlocks,currentBlocks:S.currentBlocks,matches:S.matches,...S.movementClusters?{movementClusters:S.movementClusters}:{}}:void 0,E=R>0&&S?(p=function(e){let t=[];for(let n of e.sort((e,t)=>e.minY-t.minY||e.minX-t.minX)){let e=t.find(e=>{var t,r,i;return t=e,r=n,i=10,t.minX-i<=r.maxX&&r.minX-i<=t.maxX&&t.minY-i<=r.maxY&&r.minY-i<=t.maxY});if(!e){t.push({...n});continue}e.minX=Math.min(e.minX,n.minX),e.minY=Math.min(e.minY,n.minY),e.maxX=Math.max(e.maxX,n.maxX),e.maxY=Math.max(e.maxY,n.maxY),e.differentPixels+=n.differentPixels}return t}((l=function(e,t,n,r){let i=new Uint8Array(e);if(!r)return i;for(let e of[...r.baselineBlocksRaw,...r.currentBlocksRaw])!function(e,t,n,r){let i=w(Math.floor(r.x),0,t-1),a=w(Math.floor(r.y),0,n-1),o=w(Math.ceil(r.x+r.width),0,t),s=w(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}(i,t,n,c(e.rect,8));return i}((s={diffMask:M,width:x.width,height:x.height,regions:P,ocr:S}).diffMask,s.width,s.height,s.ocr),d=s.width,tO({mask:l,width:d,height:s.height,hooks:{create:e=>{var t,n;let r,i;return r=(t=e)%(n=d),{minX:r,minY:i=Math.floor(t/n),maxX:r,maxY:i,differentPixels:0}},visit:(e,t)=>{var n,r,i;let a,o;return n=e,a=(r=t)%(i=d),o=Math.floor(r/i),void(n.minX=Math.min(n.minX,a),n.minY=Math.min(n.minY,o),n.maxX=Math.max(n.maxX,a),n.maxY=Math.max(n.maxY,o),n.differentPixels+=1)}}}))),f=tL(s.ocr?.currentBlocksRaw??[]),m=tL(s.ocr?.baselineBlocksRaw??[]),p.filter(tB).map(e=>{var t,n,r,i,a,o,l,d,c,h,p;let w,b,g,y,x,v,k,I,A,N;return t=e,n=s,r=f,i=m,y=function(e,t){let n,r=0;for(let i of t){let t=u(e,i.rect);t<=r||(r=t,n=i)}return n?.index}(g=tG(t),n.regions),x=function(e,t,n){let r=tC(e,t);if(r)return tU(e,r.blocks);let i=tC(e,n);return i?tU(e,i.blocks):void 0}(g,r,i),v=function(e,t,n){if(e.height<=3&&e.width>=.12*n)return"separator";if(!t)return e.width>=.4*n?"background":"unknown";if(e.width>=.4*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>=.35*n?"background":"unknown"}(g,x?.block.rect,n.width),k=(a=g,o=v,l=t.differentPixels,d=n,w=a.width/a.height,b=l/(a.width*a.height),"separator"===o?"separator":"background"===o?"background":"trailing"===o&&w>=1.5&&w<=3.8&&b>=.35?"toggle":"trailing"===o&&a.width<=.06*d.width&&a.height<=.04*d.height?"chevron":"leading"===o&&w>=.55&&w<=1.8?"icon":t$(a,d)?"background":"visual"),I={...y?{regionIndex:y}:{},slot:v,likelyKind:k,rect:g},{...y?{regionIndex:y}:{},slot:v,likelyKind:k,rect:g,...x?{nearestText:x.block.text.trim().replace(/^[^\p{L}\p{N}]+/u,"").replace(/^\p{L}\s+/u,"")}:{},score:(c=I,h=t.differentPixels,p=n,A=t$(c.rect,p)?-35:0,N=20*!!c.regionIndex,tD[c.likelyKind]+t_[c.slot]+N+A+Math.min(20,h/200))}}).filter(e=>e.rect.y>=.08*s.height).filter(tT).sort((e,t)=>t.score-e.score).slice(0,Math.max(0,s.maxDeltas??12)).map((e,t)=>{var n;return n=e,{index:t+1,...n.regionIndex?{regionIndex:n.regionIndex}:{},slot:n.slot,likelyKind:n.likelyKind,rect:n.rect,...n.nearestText?{nearestText:n.nearestText}:{}}})):[],D=I>0?Math.round(R/I*1e4)/100:0;return{...R>0&&b?{diffPath:b}:{},...P.length>0?{regions:P}:{},...O?{ocr:O}:{},...E.length>0?{nonTextDeltas:E}:{},totalPixels:I,differentPixels:R,mismatchPercentage:D,match:0===R}}async function t6(t,n){try{await e.access(t)}catch{throw new a("INVALID_ARGS",`${n}: ${t}`)}}function t9(e,t,n,r){if(null==r||r<=0)return;let i=e*t;if(!(i<=r))throw new a("INVALID_ARGS",`${n} is ${i} pixels, which exceeds the configured maxImagePixels limit of ${r}`)}async function t7(t){if(t)try{await e.unlink(t)}catch(e){var n;if(!("object"==typeof(n=e)&&null!==n&&"code"in n&&"ENOENT"===n.code))throw e}}function ne(e,t){return nt(Math.round(.299*e.data[t]+.587*e.data[t+1]+.114*e.data[t+2]),255,.72)}function nt(e,t,n){return Math.round(e*(1-n)+t*n)}function nn(e){return e.width*e.height}function nr(e){return Math.round(100*e*100)/100}async function ni(e,t){let n=await tA(e,{prefix:"agent-device-diff-current",ext:".png"});try{await no(e,t,n.path,ns(t))}catch(e){throw await n.cleanup(),e}return n}async function na(e,t,n,r,i){var a,o,s,l;if(!t.overlayRefs)return r;if(r.match||r.dimensionMismatch)return n&&await nd(n),r;let d=(a=t,o=n,a.currentOverlayOut?a.currentOverlayOut:a.out?.kind==="path"?{kind:"path",path:nl(o??a.out.path)}:a.out?.kind==="downloadableArtifact"?{kind:"downloadableArtifact",...a.out.clientPath?{clientPath:nl(a.out.clientPath)}:{},...a.out.fileName?{fileName:nl(a.out.fileName)}:{}}:void 0),c=await tI(e,d,{field:"currentOverlayPath",ext:".png"});try{let n=await no(e,t,c.path,{overlayRefs:!0,...ns(t)}),a=await c.publish();return a&&i.push(a),{...r,currentOverlayPath:n.path??c.path,...n.overlayRefs?{currentOverlayRefCount:n.overlayRefs.length}:{},...r.regions&&n.overlayRefs?{regions:(s=r.regions,l=n.overlayRefs,s.map(e=>{var t,n;let r,i=(t=e,n=l,r=nn(t.rect),n.map(e=>{let n=e.overlayRect,i=u(t.rect,n);return i<=0?null:{ref:e.ref,...e.label?{label:e.label}:{},rect:n,overlayCoveragePercentage:nr(i/nn(n)),regionCoveragePercentage:nr(i/r)}}).filter(e=>null!==e).sort((e,t)=>{let n=t.regionCoveragePercentage-e.regionCoveragePercentage;return 0!==n?n:t.overlayCoveragePercentage-e.overlayCoveragePercentage}).slice(0,3).map(e=>({ref:e.ref,...e.label?{label:e.label}:{},rect:e.rect,regionCoveragePercentage:e.regionCoveragePercentage})));return i.length>0?{...e,currentOverlayMatches:i}:e}))}:{}}}catch(e){throw await c.cleanup?.(),e}}async function no(e,t,n,r={}){if(!e.backend.captureScreenshot)throw new a("UNSUPPORTED_OPERATION","screenshot is not supported by this backend");return await e.backend.captureScreenshot({session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata},n,r)??{}}function ns(e){return e.surface?{surface:e.surface}:{}}function nl(e){let t=r.extname(e),n=t?e.slice(0,-t.length):e;return`${n}.current-overlay${t||".png"}`}async function nd(t){try{await e.unlink(nl(t))}catch(e){var n;if(!("object"==typeof(n=e)&&null!==n&&"code"in n&&"ENOENT"===n.code))throw e}}function nc(e){return"live"===e.kind}let nu={application:"application",navigationbar:"navigation-bar",tabbar:"tab-bar",button:"button",imagebutton:"button",link:"link",cell:"cell",statictext:"text",checkedtextview:"text",textfield:"text-field",edittext:"text-field",textarea:"text-view",switch:"switch",slider:"slider",image:"image",imageview:"image",webview:"webview",framelayout:"group",linearlayout:"group",relativelayout:"group",constraintlayout:"group",viewgroup:"group",view:"group",listview:"list",recyclerview:"list",collectionview:"collection",searchfield:"search",segmentedcontrol:"segmented-control",group:"group",window:"window",checkbox:"checkbox",radio:"radio",menuitem:"menu-item",toolbar:"toolbar",scrollarea:"scroll-area",scrollview:"scroll-area",nestedscrollview:"scroll-area",table:"table"};function nh(e,t={}){let n=[],r=[];for(let i of e){let e=i.depth??0,a=i.label?.trim()||i.value?.trim()||i.identifier?.trim()||"",o=nw(i.type??"Element");if("group"===o&&!a)continue;for(;n.length>0&&e<=n[n.length-1];)n.pop();let s=n.length;n.push(e),r.push({node:i,depth:s,type:o,text:np(i,s,!1,o,t)})}return r}function np(e,t,n,r,i={}){var a,o,s,l,d,c,u,h;let p,f=r??nw(e.type??"Element"),w=E(e,f),m=(a=e,o=f,s=i,l=w,s.summarizeTextSurfaces&&l.shouldSummarize&&function(e,t,n){let r=b(e.label);if(r&&r!==n)return r;let i=b(e.identifier);if(i&&!nb(i)&&i!==n)return i;switch(t){case"text":case"text-view":return"Text view";case"text-field":return"Text field";case"search":return"Search field";default:return""}}(a,o,l.text)||nf(a,o)),g=" ".repeat(t),y=e.ref?`@${e.ref}`:"",x=(d=e,c=f,u=i,h=w,p=[],!1===d.enabled&&p.push("disabled"),p.push(...d.presentationHints??[]),u.summarizeTextSurfaces&&(!0===d.selected&&p.push("selected"),!0===d.focused&&p.push("focused"),nm(c)&&p.push("editable"),function(e,t){if("scroll-area"===t)return!0;let n=(e.type??"").toLowerCase(),r=`${e.role??""} ${e.subrole??""}`.toLowerCase();return n.includes("scroll")||r.includes("scroll")}(d,c)&&p.push("scrollable"),h.shouldSummarize&&(p.push(`preview:"${A(h.text).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`),p.push("truncated"))),ng(p)).map(e=>` [${e}]`).join(""),v=m?` "${m}"`:"";return n?`${g}${y} [${f}]${x}`.trimEnd():`${g}${y} [${f}]${v}${x}`.trimEnd()}function nf(e,t){var n,r;let i=e.label?.trim();if(i&&(n=t,r=i,("scroll-area"===n||"list"===n||"collection"===n||"table"===n)&&ea(r)))return"";let a=e.value?.trim();if(nm(t)){if(a)return a;if(i)return i}else if(i)return i;if(a)return a;let o=e.identifier?.trim();return!o||nb(o)&&("group"===t||"image"===t||"list"===t||"collection"===t)?"":o}function nw(e){var t;let n=e.replace(/XCUIElementType/gi,"").toLowerCase(),r=e.includes(".")&&(e.startsWith("android.")||e.startsWith("androidx.")||e.startsWith("com."));return(n.includes(".")&&(n=n.replace(/^android\.widget\./,"").replace(/^android\.view\./,"").replace(/^android\.webkit\./,"").replace(/^androidx\./,"").replace(/^com\.google\.android\./,"").replace(/^com\.android\./,""),r&&n.includes(".")&&(n=n.slice(n.lastIndexOf(".")+1))),"textview"===n)?r?"text":"text-view":(t=n,(Object.prototype.hasOwnProperty.call(nu,t)?nu[t]:void 0)||n||"element")}function nm(e){return"text-field"===e||"text-view"===e||"search"===e}function nb(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function ng(e){return[...new Set(e)]}function ny(e,t){let n=nw(e.type??"Element"),r=nf(e,n),i=!1===e.enabled?"disabled":"enabled",a=!0===e.selected?"selected":"unselected",o=!0===e.hittable?"hittable":"not-hittable";return[String(t??e.depth??0),n,r,i,a,o].join("|")}function nx(e,t){return t.flatten?e.map(e=>({text:np(e,0,!1),comparable:ny(e,0)})):nh(e).map(e=>({text:e.text,comparable:ny(e.node,e.depth)}))}function nv(e,t){return e.get(t)??0}function nk(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}))}function nI(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}function nA(e){return e.clock?.now()??Date.now()}async function nN(e,t){e.clock?await e.clock.sleep(t):await new Promise(e=>setTimeout(e,t))}async function nM(e,t){var n,r,i,o,s,d;let c,u,h,p;if(!e.backend.captureSnapshot)throw new a("UNSUPPORTED_OPERATION","snapshot is not supported by this backend");let f=t.session??"default",w=await e.sessions.get(f),m=await e.backend.captureSnapshot({session:f,requestId:t.requestId,appId:w?.appId,appBundleId:w?.appBundleId,signal:t.signal??e.signal,metadata:t.metadata},{interactiveOnly:t.interactiveOnly,compact:t.compact,depth:t.depth,scope:t.scope,raw:t.raw}),b=(r=m,i=e,n=r.snapshot?r.snapshot:{nodes:r.nodes??[],truncated:r.truncated,backend:r.backend,createdAt:nA(i)},n.presentationKey?n:{...n,presentationKey:l(t)}),g=nA(e);return{snapshot:b,result:m,session:w,warnings:((c=[...(o={result:m,snapshot:b,options:t,session:w,capturedAt:b.createdAt??g,runtimeNow:g}).result.warnings??[]]).push(...function(e){let t=e.result.analysis;if("android"!==e.snapshot.backend||!0!==e.options.interactiveOnly||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"number"==typeof e.options.depth&&"number"==typeof t.maxDepth&&t.maxDepth>=e.options.depth+2&&n.push(`Interactive output is empty at depth ${e.options.depth}; retry without -d.`),n}(o)),c.push(...function(e){if("xctest"!==e.snapshot.backend||!0!==e.options.interactiveOnly||!0!==e.options.compact||1!==e.snapshot.nodes.length)return[];let t=e.snapshot.nodes[0];return t?.type!=="Application"?[]:["iOS compact interactive snapshot exposed only the application root. XCTest typed 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."]}(o)),(u=function(e){if(e?.backend!=="uiautomator-dump")return;let t=e.fallbackReason?` Reason: ${e.fallbackReason}`:"";return`Android snapshot helper unavailable; using stock UIAutomator dump, which can time out on busy React Native UIs.${t}`}(o.result.androidSnapshot))&&c.push(u),(h=function(e){if(ej(e).detected)return"Hint: React Native warning/error overlay detected. It overlays part of the app and should be handled before interacting.\nRun: agent-device react-native dismiss-overlay\nThe command verifies the overlay is gone. Run agent-device snapshot -i -c afterward only when you need fresh refs for the next action."}(o.snapshot.nodes))&&c.push(h),(p=function(e){var t,n,r,i,a,o;let s=e.session?.snapshot;if(!e.result.freshness&&s&&(t=s,n=e.snapshot,void 0===t.presentationKey||void 0===n.presentationKey||t.presentationKey===n.presentationKey)&&(r=s,i=e.capturedAt,[i,e.runtimeNow].some(e=>{let t=e-r.createdAt;return t>=0&&t<=2e3}))&&(a=s.nodes.length,o=e.snapshot.nodes.length,!(a<12)&&o<=Math.floor(.2*a)))return nP}(o))&&c.push(p),c.push(...(s=o.result.freshness,d=o.snapshot.backend,s?.staleAfterRetries&&"android"===d?"stuck-route"===s.reason?[`Recent ${s.action} was followed by a nearly identical snapshot after ${s.retryCount} automatic retr${1===s.retryCount?"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.`]:"sharp-drop"===s.reason?[nP]:[]:[])),Array.from(new Set(c)))}}function nR(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}}let nP="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 nS(e){return["visible","hidden","exists","editable","selected","text"].includes(e)}function nO(e){let{predicate:t,node:n,nodes:r,expectedText:i,platform:a}=e,o=g(n),s=I(n,a),l=!0===n.selected,d="text"===t?v(n):function(e,t,n){var r,i,a;let o;if("android"===n&&!1===e.visibleToUser)return!1;if(nE(e.rect))return function(e,t){return ep(e,t)}(e,t);if(e.rect)return!1;if("android"!==n&&!0===e.hittable)return!0;let s=(r=e,i=t,a=n,o=k(i),y(i,r,o,e=>!function(e,t){if("android"===t&&!1===e.visibleToUser)return!1;let n=T(e.type??"");return!(n.includes("application")||n.includes("window")||n.includes("scrollview")||n.includes("tableview")||n.includes("collectionview"))&&"table"!==n&&"list"!==n&&"listview"!==n&&("android"===t?!0===e.hittable&&nE(e.rect):!0===e.hittable||nE(e.rect))}(e,a)?null:e));return!!s&&(nE(s.rect)?function(e,t){return ep(e,t)}(s,t):"android"!==n&&!0===s.hittable)}(n,r,a),c=!1;switch(t){case"visible":c=d;break;case"hidden":c=!d;break;case"editable":c=s;break;case"selected":c=l;break;case"text":c=o===(i??"")}let u="text"===t?`expected="${i??""}" actual="${o}"`:`actual=${JSON.stringify({visible:d,editable:s,selected:l})}`;return{pass:c,actualText:o,details:u}}function nE(e){return!!(e&&Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.width)&&Number.isFinite(e.height)&&e.width>0&&e.height>0)}async function nD(e,t){let n=t??"default",r=await e.sessions.get(n);if(!r)throw new a("SESSION_NOT_FOUND","No active session. Run open first.");if(!r.snapshot)throw new a("INVALID_ARGS","No snapshot in session. Run snapshot first.");return{sessionName:n,session:r,snapshot:r.snapshot}}async function n_(e,t,n={updateSession:!0}){let r=e.backend.captureSnapshot;if(!r)throw new a("UNSUPPORTED_OPERATION","snapshot is not supported by this backend");let i=t.session??"default",o=await e.sessions.get(i),s=await r(nI(e,t),{interactiveOnly:!1,compact:!1,depth:t.depth,scope:n.scope??t.scope,raw:t.raw}),l=s.snapshot??{nodes:s.nodes??[],truncated:s.truncated,backend:s.backend,createdAt:nA(e)};return n.updateSession&&o&&await e.sessions.set({...o,snapshot:l}),{sessionName:i,session:o,snapshot:l}}async function nT(e,t,n){if(e.backend.readText){let r=await e.backend.readText(nI(e,{session:t.sessionName}),n);if(r.text.trim())return r.text}return D(n)}let n$=async(e,t)=>{if("ref"===t.target.kind){let n=await nD(e,t.session),r=function(e,t,n){let r=o(t);if(!r)throw new a("INVALID_ARGS",n.invalidRefMessage);let i=d(e,r)??(n.fallbackLabel.length>0?S(e,n.fallbackLabel):null);if(!i)throw new a("COMMAND_FAILED",n.notFoundMessage);return{ref:r,node:i}}(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=M(r.node,e.backend.platform,{action:"get"}),s={kind:"ref",ref:`@${r.ref}`};return"attrs"===t.property?{kind:"attrs",target:s,node:r.node,selectorChain:i}:{kind:"text",target:s,text:await nT(e,n,r.node),node:r.node,selectorChain:i}}let n=await nz(e,t,t.session??"default",{selector:t.target.selector,disambiguateAmbiguous:"text"===t.property}),r=M(n.node,e.backend.platform,{action:"get"});if("attrs"===t.property)return{kind:"attrs",target:{kind:"selector",selector:n.selector},node:n.node,selectorChain:r};let i=await nT(e,n.capture,n.node);return{kind:"text",target:{kind:"selector",selector:n.selector},text:i,node:n.node,selectorChain:r}},nC=async(e,t)=>{let n=await n$(e,{...t,property:"text",target:t.target});if("text"!==n.kind)throw new a("COMMAND_FAILED","getText returned non-text result");return n},nL=async(e,t)=>{let n=await n$(e,{...t,property:"attrs",target:t.target});if("attrs"!==n.kind)throw new a("COMMAND_FAILED","getAttrs returned non-attrs result");return n},nU=async(e,t)=>{if(!nS(t.predicate))throw new a("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text");if("text"===t.predicate&&!t.expectedText)throw new a("INVALID_ARGS","is text requires expected text value");let n=await n_(e,t,{updateSession:!0}),r=x(t.selector);if("exists"===t.predicate){let i=R(n.snapshot.nodes,r,{platform:e.backend.platform});if(!i)throw new a("COMMAND_FAILED",_(r,[],{unique:!1}));return{predicate:t.predicate,pass:!0,selector:i.selector.raw,matches:i.matches,selectorChain:r.selectors.map(e=>e.raw)}}let i=P(n.snapshot.nodes,r,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:!1});if(!i)throw new a("COMMAND_FAILED",_(r,[],{unique:!0}),{command:"is",reason:"selector_not_found",predicate:t.predicate,selector:r.raw});let o=nO({predicate:t.predicate,node:i.node,nodes:n.snapshot.nodes,expectedText:t.expectedText,platform:e.backend.platform});if(!o.pass)throw new a("COMMAND_FAILED",`is ${t.predicate} failed for selector ${i.selector.raw}: ${o.details}`,{command:"is",reason:"predicate_failed",predicate:t.predicate,selector:i.selector.raw,predicateDetails:o.details});return{predicate:t.predicate,pass:!0,selector:i.selector.raw,..."text"===t.predicate?{text:o.actualText}:{},selectorChain:r.selectors.map(e=>e.raw)}},nB=async(e,t)=>await nU(e,{...t,predicate:"visible",selector:t.target.selector}),nG=async(e,t)=>await nU(e,{...t,predicate:"hidden",selector:t.target.selector}),nF=async(e,t)=>{if("sleep"===t.target.kind)return await nN(e,t.target.durationMs),{kind:"sleep",waitedMs:t.target.durationMs};if("ref"===t.target.kind){let n=await nD(e,t.session),r=o(t.target.ref);if(!r)throw new a("INVALID_ARGS",`Invalid ref: ${t.target.ref}`);let i=d(n.snapshot.nodes,r),s=i?O(i,n.snapshot.nodes):void 0;if(!s)throw new a("COMMAND_FAILED",`Ref ${t.target.ref} not found or has no label`);return await nH(e,t,s,t.target.timeoutMs)}if("selector"===t.target.kind)return await nV(e,t,t.target.selector,t.target.timeoutMs);if(!t.target.text)throw new a("INVALID_ARGS","wait requires text");return await nH(e,t,t.target.text,t.target.timeoutMs)},nq=async(e,t)=>{let n=await nF(e,{...t,target:{kind:"text",text:t.text,timeoutMs:t.timeoutMs}});if("text"!==n.kind)throw new a("COMMAND_FAILED","waitForText returned non-text result");return n};async function nX(e,t,n){let r=t.timeoutMs??1e4,i=nA(e);for(;nA(e)-i<r;){let{match:r}=await nY(e,t,n);if(r)return{kind:"found",found:!0,waitedMs:nA(e)-i};await nN(e,300)}throw new a("COMMAND_FAILED","find wait timed out")}async function nY(e,t,n){let r=await n_(e,t,{updateSession:!0,scope:"text"===n||"label"===n||"any"===n?t.query:void 0}),i=B(r.snapshot.nodes,n,t.query,{requireRect:!1}).matches[0];return{capture:r,match:i}}async function nV(e,t,n,r){let i=r??1e4,o=nA(e),s=x(n);for(;nA(e)-o<i;){let n=R((await n_(e,t,{updateSession:!0})).snapshot.nodes,s,{platform:e.backend.platform});if(n)return{kind:"selector",selector:n.selector.raw,waitedMs:nA(e)-o};await nN(e,300)}throw new a("COMMAND_FAILED",`wait timed out for selector: ${n}`)}async function nH(e,t,n,r){let i=r??1e4,o=nA(e);for(;nA(e)-o<i;){if(e.backend.findText?(await e.backend.findText(nI(e,t),n)).found:await nK(e,t,n))return{kind:"text",text:n,waitedMs:nA(e)-o};await nN(e,300)}throw new a("COMMAND_FAILED",`wait timed out for text: ${n}`)}async function nK(e,t,n){return!!S((await n_(e,t,{updateSession:!0})).snapshot.nodes,n)}async function nz(e,t,n,r){let i=await n_(e,{...t,session:n},{updateSession:!0}),o=x(r.selector),s=P(i.snapshot.nodes,o,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:r.disambiguateAmbiguous});if(!s)throw new a("COMMAND_FAILED",_(o,[],{unique:!0}));return{capture:i,node:s.node,selector:s.selector.raw,ref:`@${s.node.ref}`}}let nj=["button","link","menuitem","tabitem","textfield","searchfield","securetextfield","checkbox","radio","switch","cell"];function nW(e,t){return nJ(e,t).node}function nJ(e,t){var n;if(eL(t))return{node:t,reason:"covered"};let r=function(e,t){let n=eO(t.rect);if(!n)return null;let r=t,i=new Set;for(;!i.has(r.ref);){i.add(r.ref);let t=e.filter(e=>{if(e.parentIndex!==r.index||!e.hittable||eL(e))return!1;let t=eO(e.rect);return!!t&&eE(t,n)});if(1!==t.length)break;r=t[0]}return r===t?null:r}(e,t);if(r?.rect&&eS(r.rect))return{node:r,reason:"same-rect-descendant"};if([(n=t).type,n.role,n.subrole].map(e=>T(e??"")).some(nZ)&&t.rect&&eS(t.rect))return{node:t,reason:"semantic-target"};let i=N(e,t);return i?.rect&&!eL(i)&&eS(i.rect)?!function(e,t,n){var r,i;let a,o,l,d=eO(e.rect),c=eO(t.rect);if(!d||!c)return!1;let h=function(e,t){let n=s(t),r=e.filter(e=>{let t=(e.type??"").toLowerCase();return t.includes("application")||t.includes("window")}).map(e=>eO(e.rect)).filter(e=>null!==e);if(0===r.length)return null;let i=r.filter(e=>en(e,n.x,n.y));return er(i.length>0?i:r)}(n,d);return!!h&&(a=u(r=c,i=h),o=r.width*r.height,l=i.width*i.height,!(a<=0)&&!(o<=0)&&!(l<=0)&&!!(a/l>=.9)&&!!(a/o>=.8))&&!eE(d,c)}(t,i,e)?{node:i,reason:"hittable-ancestor"}:{node:t,reason:"overly-broad-ancestor"}:{node:t,reason:"original"}}function nZ(e){return"tab"===e||nj.some(t=>e.includes(t))}async function nQ(e,t,n){var r;return(await n6(e,t,n.action),"point"===t.target.kind)?{kind:"point",point:{x:(r=t.target).x,y:r.y}}:"ref"===t.target.kind?await n0(e,t,t.target,n):await n1(e,t,t.target,n)}async function n0(e,t,n,r){let i=await n7(e,t,n),s=i.resolved,l=r.promoteToHittableAncestor?n5(i.snapshot.nodes,s.node,{action:r.action,label:`Ref ${n.ref}`}):s.node;return n4(l,`Ref ${n.ref}`,r.action),function(e,t,n,r){let i=e.rect?ef(e,t):null;if(!(!e.rect||!i||ep(e,t)))throw new a("COMMAND_FAILED",`Ref ${n} is off-screen and not safe to ${r}`,{reason:"offscreen_ref",ref:o(n),rect:e.rect,viewport:i,hint:`Use scroll with the direction from the off-screen summary, take a fresh snapshot, then retry ${r} with the new ref or a selector.`})}(l,i.snapshot.nodes,n.ref,r.action),{kind:"ref",point:rt(l,`Ref ${n.ref} not found or has invalid bounds`),target:{kind:"ref",ref:`@${s.ref}`},node:l,selectorChain:M(l,e.backend.platform,{action:"fill"===r.action?"fill":"click"}),refLabel:O(l,i.snapshot.nodes)}}async function n1(e,t,n,r){let i=x(n.selector),o=await n3(e,t,r.requireInteractive),s=P(n2(o.snapshot.nodes),i,{platform:e.backend.platform,requireRect:!0,requireUnique:!0,disambiguateAmbiguous:!0});if(s&&s.node.rect||!r.requireInteractive||(s=P(n2((o=await n3(e,t,!1)).snapshot.nodes),i,{platform:e.backend.platform,requireRect:!0,requireUnique:!0,disambiguateAmbiguous:!0})),!s||!s.node.rect){let t=P(o.snapshot.nodes,i,{platform:e.backend.platform,requireRect:!0,requireUnique:!1});if(t?.node&&eL(t.node))throw n8({label:`Selector ${t.selector.raw}`,node:t.node,action:r.action,selector:t.selector.raw});throw new a("COMMAND_FAILED",_(i,s?.diagnostics??[],{unique:!0}))}let l=r.promoteToHittableAncestor?n5(o.snapshot.nodes,s.node,{action:r.action,label:`Selector ${s.selector.raw}`}):s.node;return n4(l,`Selector ${s.selector.raw}`,r.action),{kind:"selector",point:rt(l,`Selector ${s.selector.raw} resolved to invalid bounds`),target:{kind:"selector",selector:s.selector.raw},node:l,selectorChain:M(l,e.backend.platform,{action:"fill"===r.action?"fill":"click"}),refLabel:O(l,o.snapshot.nodes)}}function n2(e){return e.filter(e=>!eL(e))}function n5(e,t,n){let r=nJ(e,t);if("covered"===r.reason)throw n8({label:n.label,node:t,action:n.action});return r.node}function n4(e,t,n){if(eL(e))throw n8({label:t,node:e,action:n})}function n8(e){return new a("COMMAND_FAILED",`${e.label} is covered by another visible element and cannot ${function(e){switch(e){case"fill":return"be filled";case"focus":return"be focused";case"longPress":return"be long-pressed";default:return"be tapped"}}(e.action)} safely`,{hint:"Use a different visible target, scroll it clear of the overlay, or inspect with snapshot/screenshot before retrying.",...e.selector?{selector:e.selector}:{},ref:`@${e.node.ref}`,interactionBlocked:e.node.interactionBlocked})}async function n3(e,t,n){if(!e.backend.captureSnapshot)throw new a("UNSUPPORTED_OPERATION","snapshot is not supported by this backend");let r=t.session??"default",i=await e.sessions.get(r);if(!i)throw new a("SESSION_NOT_FOUND","No active session. Run open first.");let o=await e.backend.captureSnapshot(nI(e,t),{interactiveOnly:n,compact:n}),s=o.snapshot??{nodes:o.nodes??[],truncated:o.truncated,backend:o.backend,createdAt:nA(e)};return await e.sessions.set({...i,snapshot:s}),{snapshot:s}}async function n6(e,t,n){if("macos"!==e.backend.platform)return;let r=await n9(e,t);if(("desktop"===r||"menubar"===r)&&("menubar"!==r||"click"!==n&&"press"!==n))throw new a("UNSUPPORTED_OPERATION",`${n} is not supported on macOS ${r} sessions yet. Open an app session to act, or use the ${r} surface to inspect.`)}async function n9(e,t){let n=await e.sessions.get(t.session??"default");return n?.metadata?.surface}async function n7(e,t,n){let r=t.session??"default",i=await e.sessions.get(r);if(!i)throw new a("SESSION_NOT_FOUND","No active session. Run open first.");if(!i.snapshot)throw new a("INVALID_ARGS","No snapshot in session. Run snapshot first.");let o=n.fallbackLabel??"",s=re(i.snapshot.nodes,n.ref,{fallbackLabel:o});if(s)return{snapshot:i.snapshot,resolved:s};let l=await n3(e,t,!0),d=re(l.snapshot.nodes,n.ref,{fallbackLabel:o});if(!d)throw new a("COMMAND_FAILED",`Ref ${n.ref} not found or has no bounds`);return{...l,resolved:d}}function re(e,t,n){let r=o(t);if(!r)throw new a("INVALID_ARGS",`Invalid ref: ${t}`);let i=d(e,r);if(rn(i))return{ref:r,node:i};let s=n.fallbackLabel.length>0?S(e,n.fallbackLabel):null;return rn(s)?{ref:r,node:s}:null}function rt(e,t){let n=eS(e.rect);if(!n)throw new a("COMMAND_FAILED",t);return n}function rn(e){return!!e&&null!==eS(e.rect)}async function rr(e,t,n){let r;if(t.from||t.to||t.direction||void 0!==t.distance)throw new a("INVALID_ARGS","gesture swipe preset cannot be combined with from, to, direction, or distance");let i=z(t.preset);await n6(e,t,"swipe");let o=K(i,{referenceWidth:(r=rc((await n3(e,t,!1)).snapshot.nodes)).width,referenceHeight:r.height},{platform:e.backend.platform}),s=void 0===t.durationMs?void 0:eR(t.durationMs,"durationMs",16,1e4),l={x:o.x1,y:o.y1},d={x:o.x2,y:o.y2},c=rh(await n(nI(e,t),l,d,{durationMs:s}));return{kind:"swipe",from:l,to:d,preset:i,...void 0!==s?{durationMs:s}:{},fromTarget:{kind:"viewport"},...c?{backendResult:c}:{},...C(`Swiped ${i}`)}}async function ri(e,t){let n=t.target??{kind:"viewport"};return"viewport"===n.kind?(await n6(e,t,"scroll"),{kind:"viewport"}):await nQ(e,{...t,target:n},{action:"scroll",requireInteractive:!1,promoteToHittableAncestor:!1})}async function ra(e,t){if(t.from){var n;if("x"in(n=t.from)&&"y"in n)return await n6(e,t,"swipe"),{point:rl(t.from,"from")};let r=await nQ(e,{...t,target:t.from},{action:"swipe",requireInteractive:!1,promoteToHittableAncestor:!1});return{point:r.point,target:r}}if(!t.direction)throw new a("INVALID_ARGS","swipe requires from+to or a direction");return await n6(e,t,"swipe"),{point:s(rc((await n3(e,t,!1)).snapshot.nodes)),target:{kind:"viewport"}}}async function ro(e,t,n,r,i){if(!e.backend.captureSnapshot)throw new a("UNSUPPORTED_OPERATION",`scroll ${n} requires snapshot support to verify hidden content before scrolling`);let{captureSnapshot:o}=e.backend;return await eg({edge:n,target:r,scope:i,captureNodes:async n=>{let r=await o(nI(e,t),{compact:!0,scope:n});return r.snapshot?.nodes??r.nodes??[]}})}function rs(e,t){switch(e){case"up":case"down":case"left":case"right":return e;default:throw new a("INVALID_ARGS",`${t} must be up, down, left, or right`)}}function rl(e,t){let n=Number(e.x),r=Number(e.y);if(!Number.isFinite(n)||!Number.isFinite(r))throw new a("INVALID_ARGS",`${t} point requires finite x and y`);return{x:n,y:r}}function rd(e,t){if(!Number.isFinite(e)||e<=0)throw new a("INVALID_ARGS",`${t} must be a positive number`);return e}function rc(e){let t=e.filter(t=>ep(t,e)).map(e=>e.rect).filter(ru),n=t.length>0?t:e.map(e=>e.rect).filter(ru);if(0===n.length)throw new a("COMMAND_FAILED","Cannot infer viewport for directional swipe");let r=Math.min(...n.map(e=>e.x)),i=Math.min(...n.map(e=>e.y));return{x:r,y:i,width:Math.max(...n.map(e=>e.x+e.width))-r,height:Math.max(...n.map(e=>e.y+e.height))-i}}function ru(e){return!!(e&&e.width>0&&e.height>0)}function rh(e){return e&&"object"==typeof e?e:void 0}async function rp(e,t,n){let r=await nQ(e,t,{action:n,requireInteractive:!0,promoteToHittableAncestor:!0});if(!e.backend.tap)throw new a("UNSUPPORTED_OPERATION","tap is not supported by this backend");let i=rf(await e.backend.tap(nI(e,t),r.point,{button:t.button,count:t.count,intervalMs:t.intervalMs,holdMs:t.holdMs,jitterPx:t.jitterPx,doubleTap:t.doubleTap}));return{...r,...i?{backendResult:i}:{}}}function rf(e){return e&&"object"==typeof e?e:void 0}function rw(e,t){if(void 0!==e)return rm(e,t)}function rm(e,t){let n=e?.trim();if(!n)throw new a("INVALID_ARGS",`${t} must be a non-empty string`);return n}function rb(e){return e&&"object"==typeof e?e:void 0}let rg=/^[A-Za-z0-9_.:-]{1,64}$/;async function ry(e,t){if(!t||"object"!=typeof t)throw new a("INVALID_ARGS","apps.push requires an input");if("json"===t.kind)return rx(t.payload,"apps.push JSON payload",8192),{backendInput:{kind:"json",payload:t.payload},inputKind:"json"};let n=await tk(e,t,{usage:"apps.push",field:"input"});return{backendInput:{kind:"file",path:n.path},inputKind:"file",...n.cleanup?{cleanup:n.cleanup}:{}}}function rx(e,t,n){if(function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new a("INVALID_ARGS",`${t} must be a JSON object`)}(e,t),Buffer.byteLength(function(e,t){try{let n=JSON.stringify(e);if("string"!=typeof n)throw new a("INVALID_ARGS",`${t} must be JSON-serializable`);return n}catch{throw new a("INVALID_ARGS",`${t} must be JSON-serializable`)}}(e,t),"utf8")>n)throw new a("INVALID_ARGS",`${t} exceeds ${n} bytes`)}function rv(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}function rk(e){return e&&"object"==typeof e?e:void 0}async function rI(e,t,n){let r="reinstall"===n?"reinstallApp":"installApp",i=e.backend[r];if(!i)throw new a("UNSUPPORTED_OPERATION",`admin.${n} is not supported by this backend`);let o="app"in t&&void 0!==t.app?rm(t.app,"app"):void 0;if("installFromSource"!==n&&!o)throw new a("INVALID_ARGS",`admin.${n} requires app`);let s=nI(e,t),l=await rA(e,s,t.source);try{var d,c,u,h,p;let t,r,a,f,w,m,b,g,y=await i.call(e.backend,s,{...o?{app:o}:{},source:l.source});return d=n,c=o,u=l.source,h=y,t=rP(h),r=rR(h,"appName"),a=rR(h,"appId"),f=rR(h,"bundleId"),w=rR(h,"packageName"),m=rR(h,"launchTarget"),b=rR(h,"installablePath"),g=rR(h,"archivePath"),{kind:"reinstall"===d?"appReinstalled":"installFromSource"===d?"appInstalledFromSource":"appInstalled",...c?{app:c}:{},source:u,...a?{appId:a}:{},...r?{appName:r}:{},...f?{bundleId:f}:{},...w?{packageName:w}:{},...m?{launchTarget:m}:{},...b?{installablePath:b}:{},...g?{archivePath:g}:{},...t?{backendResult:t}:{},...C(`${"reinstall"===d?"Reinstalled":"Installed"}: ${r??m??c??(p=u,"path"===p.kind?p.path:"uploadedArtifact"===p.kind?p.id:p.url)}`)}}finally{await l.cleanup?.()}}async function rA(e,t,n){let r=rM(n),i=await rN(e,r);try{let n=e.backend.resolveInstallSource?await e.backend.resolveInstallSource(t,i.source):i.source;return{source:rM(n),...i.cleanup?{cleanup:i.cleanup}:{}}}catch(e){if(i.cleanup)try{await i.cleanup()}catch{}throw e}}async function rN(e,t){if("url"===t.kind)return{source:t};let n=await tk(e,t,{usage:"admin.install",field:"source"});return{source:{kind:"path",path:n.path},...n.cleanup?{cleanup:n.cleanup}:{}}}function rM(e){if(!e||"object"!=typeof e)throw new a("INVALID_ARGS","install source is required");if("path"===e.kind)return{kind:"path",path:rm(e.path,"source.path")};if("uploadedArtifact"===e.kind)return{kind:"uploadedArtifact",id:rm(e.id,"source.id")};if("url"===e.kind){let t=rm(e.url,"source.url");return function(e){let t;try{t=new URL(e)}catch{throw new a("INVALID_ARGS",`Invalid install source URL: ${e}`)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new a("INVALID_ARGS","Install source URL must use http or https")}(t),{kind:"url",url:t}}throw new a("INVALID_ARGS","install source kind must be path, uploadedArtifact, or url")}function rR(e,t){let n=e[t];return"string"==typeof n&&n.length>0?n:void 0}function rP(e){return e&&"object"==typeof e?e:void 0}function rS(e,t){if("start"===e||"stop"===e)return e;throw new a("INVALID_ARGS",`${t} action must be start or stop`)}function rO(e,t,n,r){return{kind:"start"===e?r.startKind:r.stopKind,action:e,...n?{artifact:n}:{},backendResult:t,...C("start"===e?r.startMessage:r.stopMessage)}}let rE=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i,rD=/\b[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g;function r_(e){var t,n;let r=!1,i=e;return{value:(t=i=(i=(i=(i=(i=i.replaceAll(/(authorization|token|secret|password|passwd|api[-_]?key)=([^&\s]+)/gi,(e,t)=>(r=!0,`${String(t)}=[REDACTED]`))).replaceAll(/("(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)"\s*:\s*")([^"]*)(")/gi,(e,t,n,i)=>(r=!0,`${String(t)}[REDACTED]${String(i)}`))).replaceAll(/\b(Bearer\s+)([^\s",;]+)/gi,(e,t)=>(r=!0,`${String(t)}[REDACTED]`))).replaceAll(/((?:authorization|cookie|token|secret|password|passwd|api[-_]?key)\s*[:=]\s*)([^\s,;&]+)/gi,(e,t)=>(r=!0,`${String(t)}[REDACTED]`))).replaceAll(rD,()=>(r=!0,"[REDACTED]")),n=()=>{r=!0},i=/(https?:\/\/|token|secret|password|authorization|cookie|api[-_]?key)/i.test(t)?t.replaceAll(/https?:\/\/[^\s"'<>)]+/gi,e=>{let t=rT(e);return t?(t.redacted&&n(),t.value):e}):t),redacted:r}}function rT(e){try{let t=new URL(e),n=function(e){let t=!1;for(let n of Array.from(e.searchParams.keys()))rE.test(n)&&(e.searchParams.set(n,"[REDACTED]"),t=!0);return t}(t);return(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED",n=!0),{value:t.toString(),redacted:n}}catch{return}}let r$=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i;function rC(e){if(!e)return{redacted:!1};let t=!1,n={};for(let[r,i]of Object.entries(e))if(r$.test(r))n[r]="[REDACTED]",t=!0;else{let e=rG(i,2048);n[r]=e.value??"",t||=e.redacted}return{value:n,redacted:t}}function rL(e){return void 0===e?{redacted:!1}:function(e){try{let t=JSON.parse(e),n=rB(t,r_);return rF(JSON.stringify(n.value),2048,n.redacted)}catch{return}}(e)??rG(e,2048)}function rU(e){return rB(e,e=>rG(e,2048))}function rB(e,t){if(void 0===e)return{redacted:!1};if("string"==typeof e)return t(e);if(!e||"object"!=typeof e)return{value:e,redacted:!1};if(Array.isArray(e)){let n=!1;return{value:e.map(e=>{let r=rB(e,t);return n||=r.redacted,r.value}),redacted:n}}let n=!1,r={};for(let[i,a]of Object.entries(e)){if(r$.test(i)){r[i]="[REDACTED]",n=!0;continue}let e=rB(a,t);r[i]=e.value,n||=e.redacted}return{value:r,redacted:n}}function rG(e,t){if(void 0===e)return{redacted:!1};let n=r_(e);return rF(n.value,t,n.redacted)}function rF(e,t,n){if(void 0===e)return{redacted:n};let r=e;return r.length>t&&(r=`${r.slice(0,t)}...[truncated]`,n=!0),{value:r,redacted:n}}async function rq(e,t){let n=nI(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 rX(e,t,n,r){return{...rY(e),...void 0!==e.cursor?{cursor:rm(e.cursor,"cursor")}:{},limit:void 0===e.limit?t:eR(e.limit,r,1,n)}}function rY(e){return{...void 0!==e.since?{since:rm(e.since,"since")}:{},...void 0!==e.until?{until:rm(e.until,"until")}:{}}}function rV(e,t,n=50){if(!Array.isArray(e))throw new a("INVALID_ARGS",`${t} must be an array of strings`);if(e.length>n)throw new a("INVALID_ARGS",`${t} must contain at most ${n} entries`);return e.map((e,n)=>rm(e,`${t}[${n}]`))}let rH=tN,rK=async(e,t)=>{let n,r,i;if(!t.baseline)throw new a("INVALID_ARGS","diff screenshot requires a baseline image");let o=function(e){if(null==e||""===e)return .1;let t=Number(e);if(Number.isNaN(t)||t<0||t>1)throw new a("INVALID_ARGS","--threshold must be a number between 0 and 1");return t}(t.threshold),s=t.current??{kind:"live"};if(t.overlayRefs&&!nc(s))throw new a("INVALID_ARGS","diff screenshot <current.png> cannot use --overlay-refs because saved-image comparisons have no live accessibility refs");let l=await tk(e,t.baseline,{usage:"diff screenshot baseline",field:"baseline"}),d=[];try{let a;a=nc(s)?(r=await ni(e,t)).path:(n=await tk(e,s,{usage:"diff screenshot current",field:"current"})).path,i=t.out?await tI(e,t.out,{field:"diffPath",ext:".png"}):void 0;let c=await t3(l.path,a,{threshold:o,outputPath:i?.path,maxPixels:e.policy.maxImagePixels});nc(s)&&(c=await na(e,t,i?.path,c,d));let u=c.diffPath?await i?.publish():void 0;return u&&d.push(u),c.diffPath||await i?.cleanup?.(),{...c,...d.length>0?{artifacts:d}:{}}}catch(e){throw await i?.cleanup?.(),e}finally{await l.cleanup?.(),await n?.cleanup?.(),await r?.cleanup?.()}},rz=async(e,t)=>{var n;let r,i,a=await nM(e,t),o=function(e){var t,n,r,i,a;let{previous:o,current:s,options:l,identity:d}=e;if(!0===l.forceFull||!0===l.raw||!o||!1===o.comparisonSafe||!1===s.comparisonSafe||(t=o,n=s,r=d,t.backend&&n.backend&&t.backend!==n.backend||r?.previousAppBundleId&&r.currentAppBundleId&&r.previousAppBundleId!==r.currentAppBundleId)||!o.presentationKey||o.presentationKey!==s.presentationKey||(i=o,a=s,i.truncated!==a.truncated||JSON.stringify(nk(i.nodes))!==JSON.stringify(nk(a.nodes))))return;let c=l.scope?.trim();return{ageMs:Math.max(0,s.createdAt-o.createdAt),nodeCount:s.nodes.length,...!0===l.interactiveOnly?{interactiveOnly:!0}:{},...c?{scope:c}:{}}}({previous:a.session?.snapshot,current:a.snapshot,options:t,identity:{previousAppBundleId:a.session?.appBundleId,currentAppBundleId:a.result.appBundleId??a.session?.appBundleId}});return await e.sessions.set(nR(t.session,a)),{nodes:a.snapshot.nodes,truncated:a.snapshot.truncated??!1,visibility:function(e){var t;let{nodes:n,backend:r,snapshotRaw:i}=e;if(i||"macos-helper"===(t=r)||"linux-atspi"===t)return{partial:!1,visibleNodeCount:n.length,totalNodeCount:n.length,reasons:[]};let a=ec(n),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:n.length,reasons:[...o]}}({nodes:a.snapshot.nodes,backend:a.snapshot.backend,snapshotRaw:t.raw}),...a.result.androidSnapshot?{androidSnapshot:a.result.androidSnapshot}:{},...a.warnings.length>0?{warnings:a.warnings}:{},...o?{unchanged:o}:{},...(r=(n=a).result.appName??n.session?.appName,i=n.result.appBundleId??n.session?.appBundleId,{...r||i?{appName:r??i}:{},...i?{appBundleId:i}:{}})}},rj=async(e,t)=>{let n=await nM(e,t),r=!0===t.interactiveOnly,i=n.session?.snapshot,a=nR(t.session,n);if(!i){let t=function(e,t={}){return nx(e,t).length}(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=function(e,t,n={}){let r=function(e,t){let n=e.length,r=t.length,i=n+r,a=new Map,o=[];a.set(1,0);for(let s=0;s<=i;s+=1){o.push(new Map(a));for(let i=-s;i<=s;i+=2){let l=i===-s||i!==s&&nv(a,i-1)<nv(a,i+1)?nv(a,i+1):nv(a,i-1)+1,d=l-i;for(;l<n&&d<r&&e[l].comparable===t[d].comparable;)l+=1,d+=1;if(a.set(i,l),l>=n&&d>=r)return function(e,t,n,r,i){let a=[],o=r,s=i;for(let r=e.length-1;r>=0;r-=1){let i=e[r],l=o-s,d=l===-r||l!==r&&nv(i,l-1)<nv(i,l+1)?l+1:l-1,c=nv(i,d),u=c-d;for(;o>c&&s>u;)a.push({kind:"unchanged",text:n[s-1].text}),o-=1,s-=1;if(0===r)break;o===c?(a.push({kind:"added",text:n[u].text}),s=u):(a.push({kind:"removed",text:t[c].text}),o=c)}return a.reverse(),a}(o,e,t,n,r)}}return[]}(nx(e,n),nx(t,n)),i={additions:0,removals:0,unchanged:0};for(let e of r)"added"===e.kind&&(i.additions+=1),"removed"===e.kind&&(i.removals+=1),"unchanged"===e.kind&&(i.unchanged+=1);return{summary:i,lines:r}}(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}:{}}},rW=async(e,t)=>{let n=t.locator??"any";if(!t.query)throw new a("INVALID_ARGS","find requires a value");if("wait"===t.action)return await nX(e,t,n);let{capture:r,match:i}=await nY(e,t,n);if(!i)throw new a("COMMAND_FAILED","find did not match any element");if("exists"===t.action)return{kind:"found",found:!0};let o=`@${i.ref}`;return"get_attrs"===t.action?{kind:"attrs",ref:o,node:i}:{kind:"text",ref:o,text:await nT(e,r,i),node:i}},rJ=n$,rZ=nC,rQ=nL,r0=nU,r1=nB,r2=nG,r5=nF,r4=nq,r8=async(e,t)=>await rp(e,t,"click"),r3=async(e,t)=>await rp(e,t,"press"),r6=async(e,t)=>{var n;if(!t.text)throw new a("INVALID_ARGS","fill requires text");let r=await nQ(e,t,{action:"fill",requireInteractive:!0,promoteToHittableAncestor:!1});if(!e.backend.fill)throw new a("UNSUPPORTED_OPERATION","fill is not supported by this backend");let i=rf(await e.backend.fill(nI(e,t),r.point,t.text,{delayMs:t.delayMs})),o="node"in r?r.node.type??"":"",s=o&&!$(o,e.backend.platform)?`fill target ${n=r,n.target?.kind==="ref"?n.target.ref:n.target?.kind==="selector"?n.target.selector:"point"} resolved to "${o}", attempting fill anyway.`:void 0;return{...r,text:t.text,...s?{warning:s}:{},...i?{backendResult:i}:{}}},r9=async(e,t)=>{let n=t.text;if(!n)throw new a("INVALID_ARGS","type requires text");let r=Y(n);if(r)throw new a("INVALID_ARGS",`type does not accept a target ref like "${r}"`,{hint:`Use fill ${r} "text" to target that field, or press ${r} then type "text" to append.`});if(!e.backend.typeText)throw new a("UNSUPPORTED_OPERATION","type is not supported by this backend");let i=eR(t.delayMs??0,"delay-ms",0,1e4),o=rf(await e.backend.typeText(nI(e,t),n,{delayMs:i}));return{kind:"text",text:n,delayMs:i,...o?{backendResult:o}:{},...C(`Typed ${Array.from(n).length} chars`)}},r7=async(e,t)=>{let n=await nQ(e,t,{action:"focus",requireInteractive:!0,promoteToHittableAncestor:!1});if(!e.backend.focus)throw new a("UNSUPPORTED_OPERATION","focus is not supported by this backend");let r=rh(await e.backend.focus(nI(e,t),n.point));return{...n,...r?{backendResult:r}:{},...C(`Focused (${n.point.x}, ${n.point.y})`)}},ie=async(e,t)=>{let n=await nQ(e,t,{action:"longPress",requireInteractive:!0,promoteToHittableAncestor:!0});if(!e.backend.longPress)throw new a("UNSUPPORTED_OPERATION","longPress is not supported by this backend");let r=void 0===t.durationMs?void 0:eR(t.durationMs,"durationMs",0,12e4),i=rh(await e.backend.longPress(nI(e,t),n.point,{durationMs:r}));return{...n,...void 0!==r?{durationMs:r}:{},...i?{backendResult:i}:{},...C(`Long pressed (${n.point.x}, ${n.point.y})`)}},it=async(e,t)=>{if(!e.backend.swipe)throw new a("UNSUPPORTED_OPERATION","swipe is not supported by this backend");if(t.preset)return await rr(e,t,e.backend.swipe);let n=await ra(e,t),r=function(e,t){if(t.to)return{point:rl(t.to,"to")};let n=rs(t.direction,"swipe direction"),r=rd(t.distance??200,"swipe distance");switch(n){case"up":return{point:{x:e.x,y:e.y-r},direction:n,distance:r};case"down":return{point:{x:e.x,y:e.y+r},direction:n,distance:r};case"left":return{point:{x:e.x-r,y:e.y},direction:n,distance:r};case"right":return{point:{x:e.x+r,y:e.y},direction:n,distance:r}}}(n.point,t),i=void 0===t.durationMs?void 0:eR(t.durationMs,"durationMs",16,1e4),o=rh(await e.backend.swipe(nI(e,t),n.point,r.point,{durationMs:i}));return{kind:"swipe",from:n.point,to:r.point,...r.direction?{direction:r.direction}:{},...void 0!==r.distance?{distance:r.distance}:{},...void 0!==i?{durationMs:i}:{},...n.target?{fromTarget:n.target}:{},...o?{backendResult:o}:{},...C("Swiped")}},ir=async(e,t)=>{var n,r,i,o;let s;if(!e.backend.scroll)throw new a("UNSUPPORTED_OPERATION","scroll is not supported by this backend");let l="bottom"===(n=t.direction)?{direction:"down",edge:"bottom"}:"top"===n?{direction:"up",edge:"top"}:{direction:rs(n,"scroll direction")},d=(r=t.amount,i="scroll amount",void 0===r?void 0:rd(r,i)),c=function(e,t){if(void 0!==e){if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw new a("INVALID_ARGS",`${t} must be a positive integer`);return e}}(t.pixels,"scroll pixels");if(void 0!==d&&void 0!==c)throw new a("INVALID_ARGS","scroll accepts either amount or pixels, not both");let u=await ri(e,t),h="viewport"===u.kind?{kind:"viewport"}:{kind:"point",point:u.point},p=e.backend.scroll,f=async()=>await p(nI(e,t),h,{direction:l.direction,...void 0!==d?{amount:d}:{},...void 0!==c?{pixels:c}:{}}),w=0;if(l.edge){let n=l.edge,r="viewport"===(o=u).kind?{}:{point:o.point,nodeIndex:"node"in o?o.node.index:void 0},i=await ey({edge:n,captureState:async i=>await ro(e,t,n,r,i),scroll:f});s=i.result,w=i.passes}else s=await f(),w=1;let m=rh(s);return{...u,direction:l.direction,...l.edge?{edge:l.edge,passes:w}:{},...void 0!==d?{amount:d}:{},...void 0!==c?{pixels:c}:{},...m?{backendResult:m}:{},...C(ex(l.direction,l.edge,w,d,c))}},ii=async(e,t)=>{if(!e.backend.pinch)throw new a("UNSUPPORTED_OPERATION","pinch is not supported by this backend");await n6(e,t,"pinch");let n=rd(t.scale,"pinch scale"),r=t.center?await nQ(e,{...t,target:t.center},{action:"pinch",requireInteractive:!1,promoteToHittableAncestor:!1}):void 0,i=rh(await e.backend.pinch(nI(e,t),{scale:n,...r?{center:r.point}:{}}));return{kind:"pinch",scale:n,...r?{center:r.point,centerTarget:r}:{},...i?{backendResult:i}:{},...C(`Pinched to scale ${n}`)}},ia=async(e,t={})=>{if(!e.backend.pressBack)throw new a("UNSUPPORTED_OPERATION","system.back is not supported by this backend");let n=t.mode??"in-app";if("in-app"!==n&&"system"!==n)throw new a("INVALID_ARGS","system.back mode must be in-app or system");let r=rb(await e.backend.pressBack(nI(e,t),{mode:n}));return{kind:"systemBack",mode:n,...r?{backendResult:r}:{},...C("Back")}},io=async(e,t={})=>{if(!e.backend.pressHome)throw new a("UNSUPPORTED_OPERATION","system.home is not supported by this backend");let n=rb(await e.backend.pressHome(nI(e,t)));return{kind:"systemHome",...n?{backendResult:n}:{},...C("Home")}},is=async(e,t)=>{if(!e.backend.rotate)throw new a("UNSUPPORTED_OPERATION","system.rotate is not supported by this backend");let n=function(e){switch(e){case"portrait":case"portrait-upside-down":case"landscape-left":case"landscape-right":return e;default:throw new a("INVALID_ARGS","system.rotate orientation must be portrait, portrait-upside-down, landscape-left, or landscape-right")}}(t.orientation),r=rb(await e.backend.rotate(nI(e,t),n));return{kind:"systemRotated",orientation:n,...r?{backendResult:r}:{},...C(`Rotated to ${n}`)}},il=async(e,t={})=>{var n,r,i,o,s,l,d;if(!e.backend.setKeyboard)throw new a("UNSUPPORTED_OPERATION","system.keyboard is not supported by this backend");let c=t.action??"status";if(!X(c))throw new a("INVALID_ARGS","system.keyboard action must be status, get, dismiss, enter, or return");let u=await e.backend.setKeyboard(nI(e,t),{action:c}),h=rb(u),p=(n=u)&&"object"==typeof n?u:{};return"enter"===c||"return"===c?{kind:"keyboardEnterPressed",action:"enter",state:p,...(r=h)?{backendResult:r}:{},...C("Keyboard enter pressed")}:"dismiss"===c?(i=c,{kind:"keyboardDismissed",action:i,state:o=p,...(s=h)?{backendResult:s}:{},...C(!1===o.dismissed?"Keyboard already hidden":"Keyboard dismissed")}):(l=c,{kind:"keyboardState",action:l,state:p,...(d=h)?{backendResult:d}:{}})},id=async(e,t)=>{if("read"===t.action){if(!e.backend.getClipboard)throw new a("UNSUPPORTED_OPERATION","system.clipboard read is not supported by this backend");let n=await e.backend.getClipboard(nI(e,t));return{kind:"clipboardText",action:"read",text:"string"==typeof n?n:n.text}}if("write"!==t.action)throw new a("INVALID_ARGS","system.clipboard action must be read or write");if(!e.backend.setClipboard)throw new a("UNSUPPORTED_OPERATION","system.clipboard write is not supported by this backend");if("string"!=typeof t.text)throw new a("INVALID_ARGS","system.clipboard write requires text");let n=rb(await e.backend.setClipboard(nI(e,t),t.text));return{kind:"clipboardUpdated",action:"write",textLength:Array.from(t.text).length,...n?{backendResult:n}:{},...C("Clipboard updated")}},ic=async(e,t={})=>{if(!e.backend.openSettings)throw new a("UNSUPPORTED_OPERATION","system.settings is not supported by this backend");let n=rw(t.target,"target"),r=rb(await e.backend.openSettings(nI(e,t),n));return{kind:"settingsOpened",...n?{target:n}:{},...r?{backendResult:r}:{},...C(n?`Opened settings: ${n}`:"Opened settings")}},iu=async(e,t={})=>{var n,r;if(!e.backend.handleAlert)throw new a("UNSUPPORTED_OPERATION","system.alert is not supported by this backend");let i=t.action??"get";if("get"!==i&&"accept"!==i&&"dismiss"!==i&&"wait"!==i)throw new a("INVALID_ARGS","system.alert action must be get, accept, dismiss, or wait");let o=void 0===t.timeoutMs?void 0:eR(t.timeoutMs,"timeoutMs",0,12e4),s=await e.backend.handleAlert(nI(e,t),i,{timeoutMs:o});return n=i,r=s,"get"===n?function(e){if("alertStatus"!==e.kind)throw new a("COMMAND_FAILED","system.alert get returned an invalid backend result");return{kind:"alertStatus",action:"get",alert:e.alert}}(r):"wait"===n?function(e){if("alertWait"!==e.kind)throw new a("COMMAND_FAILED","system.alert wait returned an invalid backend result");return{kind:"alertWait",action:"wait",alert:e.alert,...void 0!==e.waitedMs?{waitedMs:e.waitedMs}:{},...void 0!==e.timedOut?{timedOut:e.timedOut}:{},...C(e.alert?"Alert visible":"Alert wait timed out")}}(r):function(e,t){if("alertHandled"!==t.kind)throw new a("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}:{},...C(t.handled?`Alert ${e}ed`:"No alert handled")}}(n,r)},ih=async(e,t={})=>{if(!e.backend.openAppSwitcher)throw new a("UNSUPPORTED_OPERATION","system.appSwitcher is not supported by this backend");let n=rb(await e.backend.openAppSwitcher(nI(e,t)));return{kind:"appSwitcherOpened",...n?{backendResult:n}:{},...C("Opened app switcher")}},ip=async(e,t)=>{var n;if(!e.backend.openApp)throw new a("UNSUPPORTED_OPERATION","apps.open is not supported by this backend");let r=function(e){var t;let n=rw(e.app,"app"),r=rw(e.appId,"appId"),i=rw(e.bundleId,"bundleId"),o=rw(e.packageName,"packageName"),s=rw(e.url,"url"),l=rw(e.activity,"activity"),d={...n?{app:n}:{},...r?{appId:r}:{},...i?{bundleId:i}:{},...o?{packageName:o}:{},...s?{url:s}:{},...l?{activity:l}:{}};if(!((t=d).app??t.appId??t.bundleId??t.packageName??t.url??t.activity))throw new a("INVALID_ARGS","apps.open requires app, appId, bundleId, packageName, url, or activity");return d}(t),i=rk(await e.backend.openApp(rv(e,t),r,{launchArgs:t.launchArgs,relaunch:t.relaunch}));return{kind:"appOpened",target:r,relaunch:!0===t.relaunch,...i?{backendResult:i}:{},...C(`Opened: ${(n=r).app??n.appId??n.bundleId??n.packageName??n.url??n.activity??"app"}`)}},iw=async(e,t={})=>{if(!e.backend.closeApp)throw new a("UNSUPPORTED_OPERATION","apps.close is not supported by this backend");let n=rw(t.app,"app"),r=rk(await e.backend.closeApp(rv(e,t),n));return{kind:"appClosed",...n?{app:n}:{},...r?{backendResult:r}:{},...C(n?`Closed: ${n}`:"Closed app")}},im=async(e,t={})=>{if(!e.backend.listApps)throw new a("UNSUPPORTED_OPERATION","apps.list is not supported by this backend");return{kind:"appsList",apps:await e.backend.listApps(rv(e,t),F(t.filter))}},ib=async(e,t)=>{if(!e.backend.getAppState)throw new a("UNSUPPORTED_OPERATION","apps.state is not supported by this backend");let n=rm(t.app,"app"),r=await e.backend.getAppState(rv(e,t),n);return{kind:"appState",app:n,state:r}},ig=async(e,t)=>{if(!e.backend.pushFile)throw new a("UNSUPPORTED_OPERATION","apps.push is not supported by this backend");let n=rm(t.app,"app"),r=await ry(e,t.input);try{let i=await e.backend.pushFile(rv(e,t),r.backendInput,n),a=rk(i);return{kind:"appPushed",app:n,inputKind:r.inputKind,...a?{backendResult:a}:{},...C(`Pushed to ${n}`)}}finally{await r.cleanup?.()}},iy=async(e,t)=>{var n,r;if(!e.backend.triggerAppEvent)throw new a("UNSUPPORTED_OPERATION","apps.triggerEvent is not supported by this backend");let i=function(e){let t=rm(e,"name");if(!rg.test(t))throw new a("INVALID_ARGS",`Invalid apps.triggerEvent name: ${t}`,{hint:"Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash."});return t}(t.name);n=t.payload,r=`apps.triggerEvent payload for "${i}"`,void 0!==n&&rx(n,r,8192);let o=rk(await e.backend.triggerAppEvent(rv(e,t),{name:i,...t.payload?{payload:t.payload}:{}}));return{kind:"appEventTriggered",name:i,...t.payload?{payload:t.payload}:{},...o?{backendResult:o}:{},...C(`Triggered app event: ${i}`)}},ix=async(e,t={})=>{if(!e.backend.listDevices)throw new a("UNSUPPORTED_OPERATION","admin.devices is not supported by this backend");return{kind:"adminDevices",devices:await e.backend.listDevices(nI(e,t),t.filter)}},iv=async(e,t={})=>{if(!e.backend.bootDevice)throw new a("UNSUPPORTED_OPERATION","admin.boot is not supported by this backend");let n=function(e){if(!e)return;let t=rw(e.id,"target.id"),n=rw(e.name,"target.name"),r={...t?{id:t}:{},...n?{name:n}:{},...e.platform?{platform:e.platform}:{},...e.target?{target:e.target}:{},...void 0!==e.headless?{headless:e.headless}:{}};return Object.keys(r).length>0?r:void 0}(t.target),r=rP(await e.backend.bootDevice(nI(e,t),n));return{kind:"deviceBooted",...n?{target:n}:{},...r?{backendResult:r}:{},...C("Booted device")}},ik=async(e,t)=>await rI(e,t,"install"),iI=async(e,t)=>await rI(e,t,"reinstall"),iA=async(e,t)=>await rI(e,t,"installFromSource"),iN=async(e,t)=>{let n=rS(t.action,"record"),r="start"===n?e.backend.startRecording:e.backend.stopRecording;if(!r)throw new a("UNSUPPORTED_OPERATION",`record ${n} is not supported by this backend`);let i=t.out?await tI(e,t.out,{field:"path",ext:".mp4"}):void 0;try{var o,s,l,d,c;let a,u,h=(o=t,s=i?.path,a=void 0===o.fps?void 0:eR(o.fps,"fps",1,60),u=void 0===o.quality?void 0:eR(o.quality,"quality",5,10),{...s?{outPath:s}:{},...void 0!==a?{fps:a}:{},...void 0!==u?{quality:u}:{},...void 0!==o.hideTouches?{showTouches:!0!==o.hideTouches}:{}}),p=await r.call(e.backend,nI(e,t),h),f=await i?.publish();return l=n,d=p,c=f,{..."string"==typeof d.path?{path:d.path}:{},..."string"==typeof d.telemetryPath?{telemetryPath:d.telemetryPath}:{},..."string"==typeof d.warning?{warning:d.warning}:{},...rO(l,d,c,{startKind:"recordingStarted",stopKind:"recordingStopped",startMessage:"Recording started",stopMessage:"Recording stopped"})}}catch(e){throw await i?.cleanup?.(),e}},iM=async(e,t)=>{let n=rS(t.action,"trace"),r="start"===n?e.backend.startTrace:e.backend.stopTrace;if(!r)throw new a("UNSUPPORTED_OPERATION",`trace ${n} is not supported by this backend`);let i=t.out?await tI(e,t.out,{field:"outPath",ext:".trace"}):void 0;try{var o,s,l;let a={...i?.path?{outPath:i.path}:{}},d=await r.call(e.backend,nI(e,t),a),c=await i?.publish();return o=n,s=d,l=c,{..."string"==typeof s.outPath?{outPath:s.outPath}:{},...rO(o,s,l,{startKind:"traceStarted",stopKind:"traceStopped",startMessage:"Trace started",stopMessage:"Trace stopped"})}}catch(e){throw await i?.cleanup?.(),e}},iR=async(e,t={})=>{var n,r;let i;if(!e.backend.readLogs)throw new a("UNSUPPORTED_OPERATION","diagnostics.logs is not supported by this backend");return i=!0===(n=await e.backend.readLogs(await rq(e,t),{...rX(r=t,100,500,"logs limit"),...void 0!==r.levels?{levels:rV(r.levels,"levels")}:{},...void 0!==r.search?{search:rm(r.search,"search")}:{},...void 0!==r.source?{source:rm(r.source,"source")}:{}})).redacted,{kind:"diagnosticsLogs",entries:n.entries.map(e=>{let t=rG(e.message,4096),n=rU(e.metadata);return i||=t.redacted||n.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.level?{level:e.level}:{},message:t.value??"",...e.source?{source:e.source}:{},...n.value?{metadata:n.value}:{}}}),...n.nextCursor?{nextCursor:n.nextCursor}:{},...n.timeWindow?{timeWindow:n.timeWindow}:{},...n.backend?{backend:n.backend}:{},redacted:i,...n.notes?{notes:n.notes}:{}}},iP=async(e,t={})=>{var n,r,i;let o;if(!e.backend.dumpNetwork)throw new a("UNSUPPORTED_OPERATION","diagnostics.network is not supported by this backend");let s={...rX(i=t,25,200,"network limit"),include:function(e){if(void 0===e)return"summary";if("summary"===e||"headers"===e||"body"===e||"all"===e)return e;throw new a("INVALID_ARGS","network include must be summary, headers, body, or all")}(i.include)};return n=await e.backend.dumpNetwork(await rq(e,t),s),r=s.include??"summary",o=!0===n.redacted,{kind:"diagnosticsNetwork",entries:n.entries.map(e=>{var t;let n=e.url?rT(t=e.url)??rG(t,2048):void 0,i="headers"===r||"all"===r?rC(e.requestHeaders):void 0,a="headers"===r||"all"===r?rC(e.responseHeaders):void 0,s="body"===r||"all"===r?rL(e.requestBody):void 0,l="body"===r||"all"===r?rL(e.responseBody):void 0,d=rU(e.metadata);return o||=(n?.redacted??!1)||(i?.redacted??!1)||(a?.redacted??!1)||(s?.redacted??!1)||(l?.redacted??!1)||d.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.method?{method:e.method}:{},...n?{url:n.value}:{},...void 0!==e.status?{status:e.status}:{},...void 0!==e.durationMs?{durationMs:e.durationMs}:{},...i?.value?{requestHeaders:i.value}:{},...a?.value?{responseHeaders:a.value}:{},...s?.value!==void 0?{requestBody:s.value}:{},...l?.value!==void 0?{responseBody:l.value}:{},...d.value?{metadata:d.value}:{}}}),...n.nextCursor?{nextCursor:n.nextCursor}:{},...n.timeWindow?{timeWindow:n.timeWindow}:{},...n.backend?{backend:n.backend}:{},redacted:o,...n.notes?{notes:n.notes}:{}}},iS=async(e,t={})=>{var n,r;let i;if(!e.backend.measurePerf)throw new a("UNSUPPORTED_OPERATION","diagnostics.perf is not supported by this backend");return i=!0===(n=await e.backend.measurePerf(await rq(e,t),{...rY(r=t),...void 0!==r.sampleMs?{sampleMs:eR(r.sampleMs,"sampleMs",100,6e4)}:{},...void 0!==r.metrics?{metrics:rV(r.metrics,"metrics",20)}:{}})).redacted,{kind:"diagnosticsPerf",metrics:n.metrics.map(e=>{let t=rG(e.message,4096),n=rU(e.metadata);return i||=t.redacted||n.redacted,{name:e.name,...void 0!==e.value?{value:e.value}:{},...e.unit?{unit:e.unit}:{},...e.status?{status:e.status}:{},...void 0!==t.value?{message:t.value}:{},...n.value?{metadata:n.value}:{}}}),...n.startedAt?{startedAt:n.startedAt}:{},...n.endedAt?{endedAt:n.endedAt}:{},...n.backend?{backend:n.backend}:{},redacted:i,...n.notes?{notes:n.notes}:{}}};function iO(e){let t={backend:e.backend,artifacts:e.artifacts,sessions:e.sessions??function(e=[]){let t=new Map(e.map(e=>[e.name,iE(e)]));return{get:e=>iE(t.get(e)),set:e=>{t.set(e.name,iE(e))},delete:e=>{t.delete(e)},list:()=>Array.from(t.values(),e=>iE(e))}}(),policy:e.policy??function(e={}){return{allowLocalInputPaths:!1,allowLocalOutputPaths:!1,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}(),diagnostics:e.diagnostics,clock:e.clock,signal:e.signal};return{...t,capture:{screenshot:e=>rH(t,e),diffScreenshot:e=>rK(t,e),snapshot:e=>rz(t,e),diffSnapshot:e=>rj(t,e)},selectors:{find:e=>rW(t,e),get:e=>rJ(t,e),getText:(e,n={})=>rZ(t,{...n,target:e}),getAttrs:(e,n={})=>rQ(t,{...n,target:e}),is:e=>r0(t,e),isVisible:(e,n={})=>r1(t,{...n,target:e}),isHidden:(e,n={})=>r2(t,{...n,target:e}),wait:e=>r5(t,e),waitForText:(e,n={})=>r4(t,{...n,text:e})},interactions:{click:(e,n={})=>r8(t,{...n,target:e}),press:(e,n={})=>r3(t,{...n,target:e}),fill:(e,n,r={})=>r6(t,{...r,target:e,text:n}),typeText:(e,n={})=>r9(t,{...n,text:e}),focus:(e,n={})=>r7(t,{...n,target:e}),longPress:(e,n={})=>ie(t,{...n,target:e}),swipe:e=>it(t,e),scroll:e=>ir(t,e),pinch:e=>ii(t,e)},system:{back:e=>ia(t,e),home:e=>io(t,e),rotate:e=>is(t,e),keyboard:e=>il(t,e),clipboard:e=>id(t,e),settings:e=>ic(t,e),alert:e=>iu(t,e),appSwitcher:e=>ih(t,e)},apps:{open:e=>ip(t,e),close:e=>iw(t,e),list:(e={})=>im(t,{...e,filter:G(e.filter)}),state:e=>ib(t,e),push:e=>ig(t,e),triggerEvent:e=>iy(t,e)},admin:{devices:e=>ix(t,e),boot:e=>iv(t,e),install:e=>ik(t,e),reinstall:e=>iI(t,e),installFromSource:e=>iA(t,e)},recording:{record:e=>iN(t,e),trace:e=>iM(t,e)},observability:{logs:e=>iR(t,e),network:e=>iP(t,e),perf:e=>iS(t,e)}}}function iE(e){if(e)return{...e,...e.snapshot?{snapshot:structuredClone(e.snapshot)}:{},...e.metadata?{metadata:function(e){try{return structuredClone(e)}catch{return{...e}}}(e.metadata)}:{}}}function iD(e={}){return{allowLocalInputPaths:!0,allowLocalOutputPaths:!0,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}export{tl as PNG,ej as analyzeReactNativeOverlay,eC as annotateCoveredSnapshotNodes,eE as areRectsApproximatelyEqual,ec as buildMobileSnapshotPresentation,V as buildScrollGesturePlan,nh as buildSnapshotDisplayLines,H as buildSwipeGesturePlan,K as buildSwipePresetGesturePlan,eg as captureScrollEdgeState,J as clampGesturePoint,et as clampToRange,iO as createAgentDevice,tx as decodePng,eu as deriveMobileSnapshotHiddenContentHints,ez as detectReactNativeOverlay,ed as displayNodeLabel,nO as evaluateIsPredicate,Y as findMistargetedTypeRefToken,ex as formatScrollEdgeMessage,np as formatSnapshotLine,j as inferGestureReferenceFrame,eo as inferVerticalScrollIndicatorDirections,X as isKeyboardAction,eJ as isReactNativeCollapsedWarningWrapperCandidate,eZ as isReactNativeCollapsedWarningWrapperWithVisibleBanner,eL as isSnapshotNodeInteractionBlocked,nS as isSupportedPredicate,ea as isSystemScrollIndicatorLabel,iD as localCommandPolicy,es as normalizeSnapshotTree,Z as parseScrollDirection,z as parseSwipePreset,W as pointFromPercent,eD as pointInsideRect,eW as readReactNativeOverlayActionNodes,eR as requireIntInRange,nW as resolveActionableTouchNode,nJ as resolveActionableTouchResolution,eS as resolveRectCenter,ey as runScrollEdgePasses};
|