agent-device 0.20.6 → 0.20.7
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 +3 -3
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.6.apk → agent-device-android-ime-helper-0.20.7.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.7.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.6.manifest.json → agent-device-android-ime-helper-0.20.7.manifest.json} +4 -4
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.6.apk → agent-device-android-snapshot-helper-0.20.7.apk} +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.7.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.6.manifest.json → agent-device-android-snapshot-helper-0.20.7.manifest.json} +6 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +20 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +67 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +339 -4
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSelectorMatchPolicy.swift +78 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +31 -2
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +29 -7
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CoordinateTextEntryTests.swift +4 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +36 -28
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +7 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SelectorMatchPolicyTests.swift +4 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +2 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +100 -12
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +4 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +57 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +1 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +18 -3
- package/dist/src/agent-browser-tool.js +1 -1
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/android-adb.js +1 -1
- package/dist/src/android.js +1 -1
- package/dist/src/app-helpers.js +1 -1
- package/dist/src/app-lifecycle.js +7 -7
- package/dist/src/app-lifecycle2.js +2 -0
- package/dist/src/app-log-files.js +1 -0
- package/dist/src/app-log-reconnect.js +1 -0
- package/dist/src/app-log-runtime.js +4 -0
- package/dist/src/app-resolution.js +2 -1
- package/dist/src/apps.js +5 -5
- package/dist/src/audio-probe.js +1 -1
- package/dist/src/auth-session.js +1 -0
- package/dist/src/auth.js +2 -0
- package/dist/src/boot-diagnostics.js +2 -2
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-grammar.js +1 -0
- package/dist/src/cli-help.js +199 -259
- package/dist/src/cli-output.js +1 -0
- package/dist/src/cli-runner.js +1 -2
- package/dist/src/cli.js +6 -16
- package/dist/src/client-metro.js +1 -1
- package/dist/src/cloud-artifacts.d.ts +2 -137
- package/dist/src/command-schema.js +3 -3
- package/dist/src/connection-runtime.js +1 -0
- package/dist/src/connection.js +5 -0
- package/dist/src/context.js +1 -1
- package/dist/src/daemon-shutdown-report.js +1 -0
- package/dist/src/daemon.js +2 -0
- package/dist/src/debug-symbols.js +3 -3
- package/dist/src/device-claim-inspection.js +1 -0
- package/dist/src/device-input-state.js +2 -2
- package/dist/src/device.js +1 -1
- package/dist/src/device2.js +2 -0
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/generic-settle.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/harmonyos.js +1 -0
- package/dist/src/helper.js +1 -1
- package/dist/src/host-process.js +2 -2
- package/dist/src/ime-lifecycle.js +7 -7
- package/dist/src/index.d.ts +43 -12
- package/dist/src/input-actions.js +4 -4
- package/dist/src/input-actions2.js +1 -1
- package/dist/src/input-actions3.js +1 -0
- package/dist/src/install-artifact.js +1 -5
- package/dist/src/install-artifact2.js +1 -1
- package/dist/src/install-source2.js +1 -1
- package/dist/src/interaction-runtime.js +1 -1
- package/dist/src/interaction-snapshot.js +1 -1
- package/dist/src/interaction-touch-reference-frame.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interactor.js +2 -2
- package/dist/src/interactor2.js +1 -1
- package/dist/src/internal/bin.js +2 -2
- package/dist/src/internal/daemon.js +8 -15
- package/dist/src/inventory.js +5 -0
- package/dist/src/inventory2.js +1 -0
- package/dist/src/inventory3.js +2 -0
- package/dist/src/inventory4.js +1 -0
- package/dist/src/inventory5.js +1 -0
- package/dist/src/inventory6.js +1 -0
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun-runtime-dependencies.js +1 -0
- package/dist/src/limrun.d.ts +10 -125
- package/dist/src/limrun.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/logcat.js +1 -1
- package/dist/src/manifest.js +1 -1
- package/dist/src/owner-identity.js +1 -0
- package/dist/src/physical-device-control.js +1 -1
- package/dist/src/platform-runtime-app-log-android-transport.js +1 -0
- package/dist/src/platform-runtime-app-log-process.js +1 -0
- package/dist/src/platform-runtime-host.js +1 -0
- package/dist/src/platform-runtime-network-web-transport.js +1 -0
- package/dist/src/platform-runtime-operation-host.js +5 -0
- package/dist/src/platform-runtime-toolchain-host.js +1 -0
- package/dist/src/platform-runtime.js +1 -0
- package/dist/src/prepare-kind.js +15 -0
- package/dist/src/process-entry.js +1 -0
- package/dist/src/process-lock.js +1 -1
- package/dist/src/provider-webdriver.js +1 -0
- package/dist/src/provider.js +1 -0
- package/dist/src/proxy.js +2 -0
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/registry.js +24 -24
- package/dist/src/remote-config2.js +1 -1
- package/dist/src/replay.js +3 -0
- package/dist/src/reporting.js +3 -3
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-disposal.js +1 -1
- package/dist/src/runner-lease.js +1 -1
- package/dist/src/runtime.js +2 -2
- package/dist/src/runtime2.js +4 -0
- package/dist/src/runtime3.js +3 -0
- package/dist/src/runtime4.js +1 -0
- package/dist/src/runtime5.js +1 -0
- package/dist/src/runtime6.js +1 -0
- package/dist/src/runtime7.js +1 -0
- package/dist/src/screenshot-result.js +4 -4
- package/dist/src/screenshot.js +1 -0
- package/dist/src/sdk-android-adb.js +2 -2
- package/dist/src/sdk-batch-runner.js +3 -3
- package/dist/src/sdk-contracts.d.ts +31 -5
- package/dist/src/sdk-contracts.js +1 -1
- package/dist/src/sdk-device.js +1 -1
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.d.ts +280 -4
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selector-vocabulary.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +3 -3
- package/dist/src/session-target-evidence.js +1 -1
- package/dist/src/session.js +10 -9
- package/dist/src/shared.js +2 -0
- package/dist/src/shell-quote.js +1 -0
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -0
- package/dist/src/snapshot-session.js +1 -0
- package/dist/src/snapshot.js +1 -1
- package/dist/src/snapshot2.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src2.js +2 -0
- package/dist/src/src3.js +1 -0
- package/dist/src/text-surface.js +1 -1
- package/dist/src/timing-safe-equal.js +1 -0
- package/dist/src/tool-provider.js +3 -3
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/tool-provider3.js +1 -1
- package/dist/src/update-check.js +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/web.js +1 -1
- package/package.json +36 -20
- package/server.json +2 -2
- package/skills/agent-device/SKILL.md +6 -31
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.6.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.6.apk.sha256 +0 -1
- package/dist/src/app-log-request-scope.js +0 -1
- package/dist/src/devices.js +0 -1
- package/dist/src/devices2.js +0 -1
- package/dist/src/devices3.js +0 -1
- package/dist/src/devices4.js +0 -1
- package/dist/src/provider-limrun-runtime.js +0 -1
- package/dist/src/register-builtins.js +0 -1
- package/dist/src/screenshot-geometry.js +0 -1
- package/dist/src/viewport-dimension.js +0 -15
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{E as e,_ as t,h as n}from"./sdk-contracts.js";import{B as r,Ct as i,Dt as a,Ot as o,St as s,X as c,b as l,ot as u,ut as ee,z as te}from"./screenshot-geometry.js";import{A as ne,D as re,L as ie,at as ae,ct as oe,hn as se,mn as ce,ot as le,pn as d,st as ue,x as de}from"./sdk-batch-runner.js";import{h as fe,n as pe,r as me,t as he}from"./sdk-device.js";import{$t as ge,Gt as _e,Kt as f,Ut as ve,Yt as ye,fn as be}from"./viewport-dimension.js";import{t as xe}from"./device.js";import{N as p,j as m}from"./sdk-android-adb.js";import{n as Se,t as Ce}from"./version.js";import{n as we,t as Te}from"./path-resolution.js";import{a as Ee,n as De,o as Oe,u as ke}from"./host-process.js";import h from"node:path";import Ae from"node:crypto";import g from"node:fs";import{StringDecoder as je}from"node:string_decoder";function _(e){return e.startsWith(`@`)?n(e)?.base??e:e}const v=/^-?\d+(\.\d+)?$/,Me=/^[^\s"\\]+$/,Ne=new Map([[`--count`,`count`],[`--interval-ms`,`intervalMs`],[`--hold-ms`,`holdMs`],[`--jitter-px`,`jitterPx`]]),Pe=new Map([[`--count`,`count`],[`--pause-ms`,`pauseMs`]]),Fe=new Map([[`--pointer-count`,`pointerCount`]]),Ie=new Map([[`--delay-ms`,`delayMs`]]);function y(e){return e===`click`||e===`press`}function b(e){return y(e)||e===`longpress`}function Le(e){return e===`type`||e===`fill`}function x(e){return ze(e,Be)}function Re(e){return JSON.stringify(e)}function S(e){return ze(e,Ve)}function ze(e,t){return t(e)?e:Re(e)}function Be(e){return Ve(e)&&e.startsWith(`@`)||v.test(e)}function Ve(e){return Me.test(e)}const He=new Set([`fill`,`type`]);function Ue(e){if(!He.has(e.command)){let t=(e.positionals??[]).map(e=>x(e));return[e.command,...t].join(` `)}let t=We(e).map(e=>x(e)).join(` `);return[e.command,t,`<text>`].filter(e=>e.length>0).join(` `)}function We(e){if(e.command===`type`)return[];let t=e.positionals??[],n=t[0];return n===void 0?[]:n.startsWith(`@`)?[n]:t.length>=3&&v.test(n)&&v.test(t[1]??``)?[n,t[1]]:[n]}function C(e,t){let n=t.flags??{};if(y(t.command)){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.intervalMs==`number`&&e.push(`--interval-ms`,String(n.intervalMs)),typeof n.holdMs==`number`&&e.push(`--hold-ms`,String(n.holdMs)),typeof n.jitterPx==`number`&&e.push(`--jitter-px`,String(n.jitterPx)),n.doubleTap===!0&&e.push(`--double-tap`);let t=n.clickButton;t&&t!==`primary`&&e.push(`--button`,t);return}if(t.command===`swipe`){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.pauseMs==`number`&&e.push(`--pause-ms`,String(n.pauseMs)),(n.pattern===`one-way`||n.pattern===`ping-pong`)&&e.push(`--pattern`,n.pattern);return}if(t.command===`gesture`){typeof n.pointerCount==`number`&&e.push(`--pointer-count`,String(n.pointerCount));return}Le(t.command)&&typeof n.delayMs==`number`&&e.push(`--delay-ms`,String(n.delayMs))}function Ge(e,t){t&&((t.platform===`ios`||t.platform===`android`)&&e.push(`--platform`,t.platform),typeof t.metroHost==`string`&&t.metroHost.length>0&&e.push(`--metro-host`,S(t.metroHost)),typeof t.metroPort==`number`&&e.push(`--metro-port`,String(t.metroPort)),typeof t.bundleUrl==`string`&&t.bundleUrl.length>0&&e.push(`--bundle-url`,S(t.bundleUrl)),typeof t.launchUrl==`string`&&t.launchUrl.length>0&&e.push(`--launch-url`,S(t.launchUrl)))}function Ke(e,t){let[n,...r]=t.positionals??[];n&&e.push(S(n));for(let t of r)e.push(x(t));typeof t.flags?.fps==`number`&&e.push(`--fps`,String(t.flags.fps)),(typeof t.flags?.quality==`number`||typeof t.flags?.quality==`string`)&&e.push(`--quality`,String(t.flags.quality)),t.flags?.hideTouches&&e.push(`--hide-touches`)}function qe(e,t){t.flags?.snapshotInteractiveOnly&&e.push(`-i`),typeof t.flags?.snapshotDepth==`number`&&e.push(`-d`,String(t.flags.snapshotDepth)),t.flags?.snapshotScope&&e.push(`-s`,x(t.flags.snapshotScope)),t.flags?.snapshotRaw&&e.push(`--raw`)}function Je(e,t){for(let n of t.positionals??[])e.push(x(n));a(e,t.flags)}function Ye(e,t,n={}){let r=t.positionals??[],i=n.includeAllPositionals?r:r.slice(0,1);for(let t of i)e.push(S(t));Ge(e,t.flags)}function Xe(e,t){for(let n of t.positionals??[])e.push(x(t.command===`wait`?_(n):n));C(e,t)}function w(e,t){let n=[],r={},i=y(e)?Ne:e===`swipe`?Pe:e===`gesture`?Fe:Le(e)?Ie:void 0;for(let a=0;a<t.length;a+=1){let o=t[a];if(y(e)&&o===`--double-tap`){r.doubleTap=!0;continue}let s=t[a+1];if(y(e)&&o===`--button`&&s!==void 0){let e=s;(e===`primary`||e===`secondary`||e===`middle`)&&(r.clickButton=e),a+=1;continue}let c=i?.get(o);if(c&&s!==void 0){let e=Qe(s);if(e!==null){r[c]=e,a+=1;continue}}if(e===`swipe`&&o===`--pattern`&&s!==void 0){let e=s;(e===`one-way`||e===`ping-pong`)&&(r.pattern=e),a+=1;continue}n.push(o)}return{positionals:n,flags:r}}function Ze(e){let t=[],n={};for(let r=0;r<e.length;r+=1){let i=e[r],a=e[r+1];if(i===`--platform`&&a!==void 0){let e=a;(e===`ios`||e===`android`)&&(n.platform=e),r+=1;continue}if(i===`--metro-host`&&a!==void 0){n.metroHost=a,r+=1;continue}if(i===`--metro-port`&&a!==void 0){let e=Qe(a);e!==null&&(n.metroPort=e),r+=1;continue}if(i===`--bundle-url`&&a!==void 0){n.bundleUrl=a,r+=1;continue}if(i===`--launch-url`&&a!==void 0){n.launchUrl=a,r+=1;continue}t.push(i)}return{positionals:t,flags:n}}function Qe(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function $e(e){let t;for(let n of e){if(n.command===`runtime`&&typeof n.flags.platform==`string`){t=n.flags.platform;continue}if(n.command===`open`)return n.runtime?.platform??t}return t}function et(e,t){for(let n of t.positionals??[])e.push(x(n));t.flags?.relaunch&&e.push(`--relaunch`),Ge(e,t.runtime)}function tt(e){let t=[],n={};for(let r of e){if(r===`--relaunch`){n.relaunch=!0;continue}t.push(r)}let r=Ze(t);return{positionals:r.positionals,flags:n,runtime:nt(r.flags)?r.flags:void 0}}function nt(e){return!!(e.platform||e.metroHost||e.metroPort!==void 0||e.bundleUrl||e.launchUrl)}const T=/^[A-Z_][A-Z0-9_]*$/,rt=new Set(pe.filter(e=>e!==`web`)),it=new Set([`mobile`,`tv`,`desktop`]);function at(e){let n=[],r=[],i=e.split(/\r?\n/),a=!1,o,s=(e,n,r)=>{throw new t(`INVALID_ARGS`,`${e.kind===`multiple`?`targets-v1`:`target-v1`} annotation on line ${e.line} must be immediately followed by its action line (line ${n+1} ${r}).`)};for(let[e,c]of i.entries()){let i=c.trim();if(i.length===0){o&&s(o,e,`is blank`);continue}if(i.startsWith(`#`)){let t=ue(i);if(t.kind===`v1`){o&&s(o,e,`is another target annotation`),o={kind:`multiple`,evidence:t.evidence,line:e+1};continue}let n=oe(i);if(n.kind===`v1`){o&&s(o,e,`is another target annotation`),o={kind:`single`,evidence:n.evidence,line:e+1};continue}o&&s(o,e,`is a comment`);continue}if(st(i)){if(o&&s(o,e,`is an env directive`),a)throw new t(`INVALID_ARGS`,`env directives must precede all actions (line ${e+1}).`);continue}let l=dt(c);if(!l){o&&s(o,e,`did not parse as an action`);continue}let u=te(l.command,l.positionals??[],`line ${e+1}`);if(u)throw new t(`INVALID_ARGS`,u);o&&=(o.kind===`single`?l.targetEvidence=o.evidence:l.targetEvidences=o.evidence,void 0),n.push(l),r.push(e+1),a=!0}if(o)throw new t(`INVALID_ARGS`,`${o.kind===`multiple`?`targets-v1`:`target-v1`} annotation on line ${o.line} must be immediately followed by its action line (end of script reached).`);return{actions:n,actionLines:r}}function ot(e){let t=e.split(/\r?\n/),n={};for(let[e,r]of t.entries()){let t=r.trim();if(t.length===0||t.startsWith(`#`))continue;if(st(t)){ut(n,t,e+1);continue}if(!t.startsWith(`context `))break;let i=t.match(/(?:^|\s)platform=([^\s]+)/);if(i){let e=i[1];e&&rt.has(e)&&E(n,`platform`,e)}let a=t.match(/(?:^|\s)target=([^\s]+)/);if(a){let e=a[1];e&&it.has(e)&&E(n,`target`,e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&E(n,`timeoutMs`,Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&E(n,`retries`,Math.floor(e))}}return n}function st(e){return e===`env`||e.startsWith(`env `)||e.startsWith(`env `)}function ct(e,n){let r=e.slice(3).replace(/^[\s]+/,``),i=r.indexOf(`=`);if(i<=0)throw new t(`INVALID_ARGS`,`Invalid env directive on line ${n}: expected "env KEY=VALUE".`);let a=r.slice(0,i);if(!T.test(a))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(a.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: the AD_* namespace is reserved for built-in variables. Rename ${a} to avoid the AD_ prefix.`);return{key:a,value:lt(r.slice(i+1),n)}}function lt(e,n){if(e.length===0)return``;if(e.startsWith(`"`))try{let t=JSON.parse(e);if(typeof t!=`string`)throw Error(`not a string literal`);return t}catch{throw new t(`INVALID_ARGS`,`Invalid quoted env value on line ${n}.`)}return e}function ut(e,n,r){let{key:i,value:a}=ct(n,r),o=e.env??{};if(Object.prototype.hasOwnProperty.call(o,i))throw new t(`INVALID_ARGS`,`Duplicate env directive "${i}" on line ${r}.`);o[i]=a,e.env=o}function E(e,n,r){let i=e[n];if(i!==void 0)throw new t(`INVALID_ARGS`,i===r?`Duplicate replay test metadata "${n}" in context header.`:`Conflicting replay test metadata "${n}" in context header: ${String(i)} vs ${String(r)}.`);e[n]=r}function dt(e){let n=e.trim();if(n.length===0||n.startsWith(`#`))return null;let[r,...i]=pt(n);if(r===void 0||r===`context`)return null;let a={ts:Date.now(),command:r,positionals:[],flags:{}};if(r===`snapshot`){a.positionals=[];for(let e=0;e<i.length;e+=1){let t=i[e];if(t===`-i`){a.flags.snapshotInteractiveOnly=!0;continue}if(t!==`-c`){if(t===`--raw`){a.flags.snapshotRaw=!0;continue}if(t===`--force-full`){a.flags.snapshotForceFull=!0;continue}if((t===`-d`||t===`--depth`)&&e+1<i.length){let t=Number(i[e+1]);Number.isFinite(t)&&t>=0&&(a.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if((t===`-s`||t===`--scope`)&&e+1<i.length){a.flags.snapshotScope=i[e+1],e+=1;continue}if(t===`--backend`&&e+1<i.length){e+=1;continue}}}return a}if(r===`open`){let e=tt(i);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a.runtime=e.runtime,a}if(r===`runtime`){let e=Ze(i);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a}if(y(r)){let e=w(r,i);Object.assign(a.flags,e.flags);let t=e.positionals[0];if(t===void 0)return a;if(t.startsWith(`@`))return a.positionals=[_(t)],e.positionals[1]&&(a.result={refLabel:e.positionals[1]}),a;let n=e.positionals[0],o=e.positionals[1];return D(n)&&D(o)&&e.positionals.length>=2?(a.positionals=[n,o],a):(a.positionals=[e.positionals.join(` `)],a)}if(r===`fill`){let e=w(r,i);if(Object.assign(a.flags,e.flags),!ft(e.positionals))return a.positionals=e.positionals,a;let[t,n,...o]=e.positionals;if(D(t)&&D(n))return a.positionals=[t,n,o.join(` `)],a;let[s,c,...l]=e.positionals;if(s.startsWith(`@`)){let e=_(s);return l.length>0?(a.positionals=[e,l.join(` `)],a.result={refLabel:c},a):(a.positionals=[e,c],a)}return a.positionals=[s,[c,...l].join(` `)],a}if(r===`get`){let e=i[0],t=i[1];return e===void 0||t===void 0?(a.positionals=i,a):t.startsWith(`@`)?(a.positionals=[e,_(t)],i[2]&&(a.result={refLabel:i[2]}),a):(a.positionals=[e,i.slice(1).join(` `)],a)}if(r===`swipe`||r===`type`||r===`gesture`){let e=w(r,i);return Object.assign(a.flags,e.flags),a.positionals=e.positionals,a}if(r===`record`){let e=[];for(let n=0;n<i.length;n+=1){let r=i[n];if(r===s.cliToken)throw new t(`INVALID_ARGS`,s.migration.record);if(r===`--hide-touches`){a.flags.hideTouches=!0;continue}if(r===`--fps`&&n+1<i.length){let e=Number(i[n+1]);Number.isFinite(e)&&(a.flags.fps=Math.floor(e)),n+=1;continue}if(r===`--quality`&&n+1<i.length){let e=i[n+1],t=ge(e);t!==void 0&&(a.flags.quality=t),n+=1;continue}e.push(r)}return a.positionals=e,a}if(r===`screenshot`){let e=[];for(let t=0;t<i.length;t+=1){let n=i[t],r=o({args:i,index:t,flags:a.flags});if(r.handled){t=r.nextIndex;continue}e.push(n)}return a.positionals=e,a}return a.positionals=r===`wait`||r===`longpress`?i.map(e=>_(e)):i,a}function ft(e){return e.length>=2}function D(e){return e?!Number.isNaN(Number(e)):!1}function pt(e){let t=[],n=0;for(;n<e.length&&(n=mt(e,n),!(n>=e.length));){let r=e[n]===`"`?ht(e,n):gt(e,n);t.push(r.value),n=r.nextCursor}return t}function mt(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}function ht(e,n){let r=n+1,i=!1,a=r;for(;a<e.length;a+=1){let t=e.charAt(a);if(t===`"`&&!i)break;if(i){i=!1;continue}i=t===`\\`}if(a>=e.length)throw new t(`INVALID_ARGS`,`Invalid replay script line: ${e}`);let o=e.slice(n,a+1),s;try{s=JSON.parse(o)}catch{throw new t(`INVALID_ARGS`,`Invalid quoted value ${o} in replay script line: ${e}`,{hint:`Quoted replay values are JSON strings: escape backslashes, quotes, tabs, and newlines (\\\\, \\", \\t, \\n).`})}return{value:s,nextCursor:a+1}}function gt(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}function _t(e,t={}){let n=[e.command];return e.command===`snapshot`?qe(n,e):e.command===`open`?et(n,e):e.command===`runtime`?Ye(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?Ke(n,e):e.command===`screenshot`?Je(n,e):Xe(n,e),n.join(` `)}function vt(e){return e.targetEvidences?[ae(e.targetEvidences)]:e.targetEvidence?[le(e.targetEvidence)]:[]}const yt=`/agent-device`,bt=`x-agent-device-tenant`;function xt(e){return St(e,yt)}function St(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t.replace(/^\/+/,``),n).toString()}function Ct(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function wt(e){let t=e?.trim();return t?{[bt]:t}:{}}const Tt=`.webm`;function Et(e){return e===`web`?Tt:`.mp4`}function Dt(e,t){return h.extname(e)?e:`${e}${t}`}function Ot(e){return`./recording-${Date.now()}${Et(e)}`}function kt(e){return new Promise((t,n)=>{let r=``;e.setEncoding(`utf8`),e.on(`data`,e=>{r+=e}),e.on(`end`,()=>t(r)),e.on(`error`,n)})}async function At(e,n,r){let i=[],a=0;for await(let o of e){let e=Buffer.isBuffer(o)?o:Buffer.from(o);if(a+=e.length,a>n)throw new t(`INVALID_ARGS`,r);i.push(e)}return Buffer.concat(i)}const O={kind:`none`};function k(e,t){if(t.path===void 0){let n=e??{kind:`default`,force:!1};return t.force?{...n,force:!0}:n}let n=e?.force===!0&&(e.kind==="default"||e.path===t.path);return{kind:`explicit`,path:t.path,force:t.force||n}}function jt(e){return e.kind===`repair`?{...e,status:`armed`}:e}function Mt(e){return e.kind===`none`?void 0:e.target}function Nt(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function Pt(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function Ft(e){return{kind:`authoring`,status:`armed`,target:k(void 0,e)}}function It(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function Lt(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function Rt(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:k(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function zt(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function Bt(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function Vt(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function Ht(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function Ut(e){return e.kind===`repair`?e.boundary:void 0}function Wt(e){return e.kind===`repair`?e.sourcePath:void 0}function Gt(e){return e.kind===`repair`&&e.status!==`committed`}function Kt(e){let t=Mt(e);return t?.kind===`explicit`?t.path:void 0}function qt(e){return Mt(e)?.force===!0}function A(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function j(e,t){return we(e,{cwd:t})}function M(e){return e?.scriptPublication??O}function Jt(e){let t=M(e);return t.kind===`authoring`&&t.status===`armed`}function Yt(e,t){e.recordSession=!0,e.scriptPublication=Ft({path:t.path===void 0?void 0:j(t.path),force:t.force===!0})}function Xt(e){e.recordSession=!1,e.scriptPublication=It(M(e))}function Zt(e,t){if(!t.saveScript)return;e.recordSession=!0;let n={path:typeof t.saveScript==`string`?j(t.saveScript):void 0,force:t.force===!0},r=M(e);if(r.kind===`repair`){e.scriptPublication=Rt(r,{requested:n,boundary:r.boundary,sourcePath:r.sourcePath});return}if(r.kind===`authoring`){e.scriptPublication={...r,target:k(r.target,n)};return}e.scriptPublication=Ft(n)}function Qt(e,t){let n=M(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:k(n.target,{path:t.explicitPath===void 0?void 0:j(t.explicitPath),force:t.liveForce===!0})})}function $t(e,t){e.scriptPublication=Lt(M(e),t),e.recordSession=!1}function en(e,t){let n=M(e);n.kind===`authoring`&&(e.scriptPublication=Lt(n,t))}function tn(e,t){return t===!0||qt(M(e))}function nn(e){return Pt(M(e))}function N(e){return e?.scriptPublication??O}function rn(e,t){e.recordSession=!0;let n=N(e);e.scriptPublication=Rt(n,{requested:{path:typeof t.saveScript==`string`?j(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function an(e){e.scriptPublication=jt(N(e))}function on(e){e.scriptPublication=zt(N(e))}function sn(e,t){e.scriptPublication=Bt(N(e),t)}function cn(e){e.scriptPublication=Ht(N(e))}function ln(e,t){let n=N(e);return n.kind===`repair`&&n.closeReceipt===t}function un(e){return N(e).kind===`repair`}function dn(e){return Gt(N(e))}function P(e){return Ut(N(e))}function fn(e){return Wt(N(e))}function F(e){let t=e.result?.text;if(typeof t==`string`)return t;let n=e.positionals??[];return n.length===0?``:n[0]?.startsWith(`@`)?n.length>=3?n.slice(2).join(` `):n.slice(1).join(` `):n.length>=3&&!Number.isNaN(Number(n[0]))&&!Number.isNaN(Number(n[1]))?n.slice(2).join(` `):n.slice(1).join(` `)}const pn=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function mn(e){if(e!==e.trim()||!T.test(e))throw new t(`INVALID_ARGS`,`Invalid --record-as variable "${e}": use uppercase letters, digits, and underscores (for example PASSWORD).`);if(e.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid --record-as variable "${e}": the AD_* namespace is reserved for built-in replay variables.`);return e}function hn(e){return`\${${e}}`}function gn(e){let t=pn.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}const _n=new Set(`action.backend.cost.delayMs.evidence.gesture.hint.kind.maestroFallbackReason.maestroNonHittableCoordinateFallbackAllowed.maestroNonHittableCoordinateFallbackUsed.message.platform.ref.referenceHeight.referenceWidth.refLabel.resolution.selector.selectorChain.settle.targetHittable.targetKind.text.warning.x.y`.split(`.`)),vn=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),yn=new Set([`cost`,`evidence`,`resolution`,`settle`]),bn=new Map([[`cost`,new Set([`nodeCount`,`runnerRoundTrips`,`wallClockMs`])],[`evidence`,new Set([`changedFromBefore`,`digest`,`foregroundApp`,`interactiveNodeCount`,`nodeCount`])],[`resolution`,new Set([`alternatives`,`kind`,`matchCount`,`phase`,`source`,`tiebreak`,`winnerDiagnostic`])],[`resolution.alternatives`,new Set([`diagnosticRef`,`label`,`role`])],[`resolution.winnerDiagnostic`,new Set([`diagnosticRef`,`label`,`role`])],[`settle`,new Set([`captures`,`diff`,`hint`,`quietMs`,`refs`,`refsGeneration`,`settled`,`tail`,`tailTruncated`,`timeoutMs`,`waitedMs`])],[`settle.diff`,new Set([`lines`,`summary`,`truncated`])],[`settle.diff.lines`,new Set([`kind`,`ref`,`text`])],[`settle.diff.summary`,new Set([`additions`,`removals`,`unchanged`])],[`settle.refs`,new Set([`ref`])],[`settle.tail`,new Set([`label`,`ref`,`role`])]]),xn=new Set([`evidence.digest`,`evidence.foregroundApp`,`resolution.alternatives.diagnosticRef`,`resolution.alternatives.role`,`resolution.kind`,`resolution.phase`,`resolution.source`,`resolution.tiebreak`,`resolution.winnerDiagnostic.diagnosticRef`,`resolution.winnerDiagnostic.role`,`settle.diff.lines.kind`,`settle.diff.lines.ref`,`settle.refs.ref`,`settle.tail.ref`,`settle.tail.role`]);function Sn(e,t,n){if(!e)return e;let r=kn(e.selectorChain);return{...Tn(e,t,n),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!wn(e,t))}:{}}}function Cn(e,t,n){return e&&{...e,...e.label===t?{label:n}:{},ancestry:e.ancestry.map(e=>({...e,...e.label===t?{label:n}:{}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===t?{label:n}:{}}}:{}}}function wn(e,t){return ie(e,t)}function Tn(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[_n.has(e)?e:L(e,t,n),En(r,e,t,n)]))}function En(e,t,n,r){return typeof e==`string`&&vn.has(t)?e:t===`selectorChain`&&On(e)?Dn(e,n):I(e,n,r,yn.has(t)?t:void 0)}function I(e,t,n,r){if(typeof e==`string`)return r&&xn.has(r)?e:L(e,t,n);if(Array.isArray(e))return e.map(e=>I(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?bn.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:L(e,t,n),I(a,t,n,o?`${r}.${e}`:void 0)]}))}function Dn(e,t){return e.filter(e=>!wn(e,t))}function L(e,t,n){if(!t)return e===t?n:e;let r=n?e.split(n):[e];return r.every(e=>!e.includes(t))?e:t.trim()?r.map(e=>e.replaceAll(t,n)).join(n):n}function On(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function kn(e){return On(e)?e:void 0}function An(e,t){if(t.flags?.noRecord||Fn(e,t))return;t.flags&&Zt(e,t.flags);let n=jn(t),r={ts:Date.now(),command:n.command,positionals:n.positionals,runtime:n.runtime,flags:Ln(n.flags),result:n.result,...n.targetEvidence?{targetEvidence:n.targetEvidence}:{},...n.targetEvidences?{targetEvidences:n.targetEvidences}:{}};return e.actions.push(r),m({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),r}function jn(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return e;let t=hn(mn(e.flags.recordAs)),n=F({ts:0,command:e.command,positionals:e.positionals,flags:e.flags});return{...e,positionals:Mn(e.positionals,t),result:Sn(e.result,n,t),targetEvidence:Cn(e.targetEvidence,n,t)}}function Mn(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const Nn=new Set([`snapshot`,`get`,`is`,`find`]);function Pn(e){return e.internal?.replayPlanStep===!0?!1:Nn.has(e.command)}function Fn(e,t){return!t.interactiveObservation||P(e)===void 0?!1:t.flags?.record!==!0}const In=[`platform`,`device`,`udid`,`serial`,`out`,`verbose`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`,`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`,...i,`relaunch`,`saveScript`,`force`,`noRecord`,`record`,`fps`,`quality`,`hideTouches`,`count`,`pointerCount`,`intervalMs`,`delayMs`,`holdMs`,`jitterPx`,`doubleTap`,`clickButton`,`pauseMs`,`pattern`];function Ln(e){if(!e)return{};let t={};for(let n of In)e[n]!==void 0&&(t[n]=e[n]);return t}function Rn(e){let n=e.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new t(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(e.some(e=>e.command===`close`))throw new t(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[t,n]of e.entries())de({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=t);if(!e.slice(r+1).some(Wn))throw new t(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function zn(e){for(let n of e){if(Bn(n)){Vn(n);continue}let e=Gn(n),r=e??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&de(n)===`mutates-app`)throw new t(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=e;if(!(!i||!ne(i)||n.targetEvidence))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function Bn(e){return Hn(e)!==void 0}function Vn(e){let n=Hn(e);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!ne(n))&&!e.targetEvidences)throw new t(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function Hn(e){return e.command===`gesture`?r(e.positionals):void 0}function Un(e,n){if(e instanceof t){if(e.details?.reason===`script_target_exists`)return new t(e.code,`A file already exists at ${String(e.details.path)}.`,{...e.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=e.details?.retriable===!0;return new t(e.code,e.message,{...e.details,retriable:n,hint:e.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Wn(e){if(e.command!==`wait`)return!1;let t=re(e.positionals);return t?.kind!==`selector`||!ne(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function Gn(e){if(e.command===`get`)return e.positionals[1];if(b(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&Kn(t)&&Kn(n)?void 0:t}}function Kn(e){return e.trim().length>0&&Number.isFinite(Number(e))}function qn(e){let t=e.scriptPublication??O;return t.kind===`repair`?t.status===`committed`?!0:!Nt(t):!1}var Jn=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=un(e),r=t?.publication===`active`,i;try{if(!e.recordSession||qn(e))return{written:!1};let a=Yn(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=h.dirname(i);return g.existsSync(o)||g.mkdirSync(o,{recursive:!0}),Qn({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=Vt(e.scriptPublication??O)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return Xn({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=Kt(e.scriptPublication??O);if(t)return j(t);let n=A(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,`-`);return h.join(this.sessionsDir,`${n}-${r}.ad`)}};function Yn(e,t){let n=$n(e,{strictPortableRefs:t.activePublication});return t.activePublication&&Rn(n),{script:lr(e,n,t.appendCompleteSentinel),actionCount:n.length}}function Xn(e){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=e;if(m({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:Zn(r,i)};if(o)return{written:!1,error:Un(r,i)};if(r instanceof t)throw r;return{written:!1}}function Zn(e,n){if(e instanceof t)return e;let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to write the healed script${n?` to ${n}`:``}: ${r}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function Qn(e){let{scriptPath:n,script:r,force:i}=e,a=h.dirname(n),o=h.join(a,`.${h.basename(n)}.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`);g.writeFileSync(o,r);try{if(i){g.renameSync(o,n);return}g.linkSync(o,n)}catch(e){throw e.code===`EEXIST`?new t(`COMMAND_FAILED`,`A file already exists at ${n}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:n}):e}finally{g.rmSync(o,{force:!0})}}function $n(e,t={}){let n=P(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=nr(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&er(n);let o=cr(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&zn(a),a}function er(e){let n=e.command===`gesture`?r(e.positionals??[]):void 0;if(n){tr(n);return}if(!R(e.command))return;let i=e.command===`get`?e.positionals?.[1]:e.positionals?.[0];if(i?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot write recorded step "${e.command} ${i}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function tr(e){let n=[e.source,e.destination].find(e=>e.startsWith(`@`));if(n)throw new t(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function nr(e){let t=rr(e);if(!(!t||!R(e.command)))return y(e.command)?{...e,positionals:[t]}:e.command===`longpress`?ar(e,t):e.command===`fill`?ir(e,t):or(e,t)}function rr(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function R(e){return b(e)||e===`fill`||e===`get`}function ir(e,t){let n=F(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function ar(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):sr(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function or(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function sr(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function cr(e,t){if(!R(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r}}}function lr(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${fe(e.device)} device=${Re(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...vt(e)),r.push(ur(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
|
|
2
|
-
`)}\n`}function ur(e){return dr([e.command],e)||_t(e)}function dr(e,t){if(y(t.command))return fr(e,t);if(t.command===`fill`)return pr(e,t);if(t.command===`get`)return mr(e,t)}function fr(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(x(_(n))),z(e,t),C(e,t),e.join(` `);if(t.positionals.length===1)return e.push(x(n)),C(e,t),e.join(` `)}}function pr(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(x(_(n))),z(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(x(r)),C(e,t),e.join(` `)}function mr(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(x(n)),e.push(x(_(r))),r.startsWith(`@`)&&z(e,t),e.join(` `)}function z(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(x(n))}const hr=[`status`,`get`,`dismiss`,`enter`,`return`];function B(e){return hr.includes(e)}const gr=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],_r={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function vr(e,t){let n=t??{};switch(e.command){case f.devices:return yr(n.devices);case f.apps:return br(n.apps,e.flags?.appsFilter);case f.boot:return xr(`Booted`,n,!0);case f.shutdown:return xr(`Shut down`,n,!1);case f.install:return Sr(`Installed`,n);case f.reinstall:return Sr(`Reinstalled`,n);case f.screenshot:return Cr(e,n);default:return{}}}function yr(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=Tr(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:Fr(`Found ${t.length} ${Ir(`device`,t.length)}`,i.map(e=>Mr(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function br(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=H(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:Fr(`Found ${n.length} ${Ir(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function xr(e,t,n){let r=Er(t);if(!r)return{};let i={device:r,...jr(t),booted:n};return{summary:`${e} ${Mr(i,!1)}`,details:i}}function Sr(e,t){let n=H(t.appName),r=H(t.bundleId),i=Pr(t,[`packageName`,`package`]),a=H(t.platform),o=H(t.launchTarget),s=Pr(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=Nr(n,s);if(!c)return{};let l={};return V(l,`appName`,n),V(l,`bundleId`,r),V(l,`packageName`,i),V(l,`platform`,a),o!==s&&V(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function Cr(e,t){let n=wr(e,t);return n?{details:{requestedFileName:n}}:{}}function wr(e,t){let n=J(e.meta?.clientArtifactPaths?.path)??J(t.path);if(n)return q(n)}function Tr(e){if(!d(e))return;let t=Er(e);if(t)return{name:t,...jr(e)}}function Er(e){let t=Pr(e,[`name`,`deviceName`,`device`]);return!t||!Dr(e,t)?t:kr(e)}function Dr(e,t){let n=Or(t);return gr.some(t=>{let r=H(e[t]);return r!==void 0&&Or(r)===n})}function Or(e){return e.toLowerCase()}function kr(e){let t=H(e.appleOs),n=H(e.platform),r=H(e.kind),i=Ar(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function Ar(e,t){let n=e??t;if(!(!n||!Object.hasOwn(_r,n)))return _r[n]}function jr(e){let t=H(e.platform),n=H(e.appleOs),r=H(e.kind),i=H(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function Mr(e,t){let n=H(e.name)??H(e.device)??`device`,r=H(e.platform),i=H(e.appleOs),a=[r,i===r?void 0:i,H(e.kind),H(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function Nr(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function Pr(e,t){for(let n of t){let t=H(e[n]);if(t)return t}}function V(e,t,n){n&&(e[t]=n)}function Fr(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function Ir(e,t){return t===1?e:`${e}s`}function H(e){let t=J(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function U(e){return H(e)}function W(e){return typeof e==`boolean`?e:void 0}function G(e,t){let n=U(e);return n&&t.includes(n)?n:void 0}function K(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function q(e){let t=J(e);return t?H(t.split(/[\\/]/).at(-1)):void 0}function J(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function Y(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const Lr=[`up`,`down`,`left`,`right`],Rr=[`top`,`bottom`];function zr(e){return`${e.command===f.reinstall?`Reinstalled`:`Installed`} ${Ur(e.result??{})??`app`}`}function Br(e){let t=e.result??{};switch(e.command){case f.scroll:return Gr(t);case f.screenshot:return Jr(t);case f.home:return`Went home`;case f.back:return Xr(t);case f.appSwitcher:return`Opened app switcher`;case f.orientation:return Zr(t);case f.viewport:return Qr(t);case f.clipboard:return $r(t);case f.keyboard:return ei(t);case f.tvRemote:return ri(t);case f.gesture:return ii(t);case f.swipe:return ai(t);case f.trace:return si(`trace`,e);case f.record:return si(`recording`,e);default:return}}function Vr(e){let t=e.result??{};switch(e.command){case f.scroll:return K({direction:G(t.direction,Lr),edge:G(t.edge,Rr),passes:Y(t.passes),amount:Y(t.amount),pixels:Y(t.pixels),durationMs:Y(t.durationMs),x1:Y(t.x1),y1:Y(t.y1),x2:Y(t.x2),y2:Y(t.y2)});case f.screenshot:return K({requestedFileName:Yr(t)});case f.back:return K({mode:G(t.mode,ee)});case f.orientation:return K({orientation:G(t.orientation,xe)});case f.viewport:return K({width:Y(t.width),height:Y(t.height)});case f.clipboard:return K({action:G(t.action,[`read`,`write`])});case f.keyboard:return ni(t);case f.tvRemote:return K({button:G(t.button,l),durationMs:Y(t.durationMs)});case f.gesture:case f.swipe:return oi(t);case f.trace:case f.record:return K({action:G(t.action,[`start`,`stop`]),fileName:li(e),showTouches:W(t.showTouches)});default:return{}}}function Hr(e,t){if(e.command!==f.screenshot)return t;let n=wr(e,t);return n?{...t,requestedFileName:n}:t}function Ur(e){let t=U(e.appName),n=ui(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??Wr(e)}function Wr(e){let t=U(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function Gr(e){let t=G(e.direction,Lr),n=G(e.edge,Rr),r=Y(e.passes);return n?Kr(n,r):t?qr(t,e):`Scrolled`}function Kr(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function qr(e,t){let n=Y(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=Y(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function Jr(e){let t=Yr(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function Yr(e){return q(e.requestedFileName)??q(e.path)}function Xr(e){return G(e.mode,ee)===`system`?`Went back using system navigation`:`Went back`}function Zr(e){let t=G(e.orientation,xe);return t?`Rotated to ${t}`:`Changed orientation`}function Qr(e){let t=Y(e.width),n=Y(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function $r(e){let t=G(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function ei(e){let t=J(e.action);if(!t||!B(t))return`Used keyboard`;if(t===`dismiss`)return ti(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=W(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function ti(e){return W(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function ni(e){let t=J(e.action);return K({action:t&&B(t)?t:void 0,platform:G(e.platform,[`ios`,`android`]),visible:W(e.visible),wasVisible:W(e.wasVisible),dismissed:W(e.dismissed),attempts:Y(e.attempts),mechanism:G(e.mechanism,[`dismissKey`])})}function ri(e){let t=G(e.button,l);return t?`Pressed TV remote ${t}`:`Used TV remote`}function ii(e){let t=G(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function ai(e){let t=Y(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function oi(e){return K({kind:G(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:Y(e.durationMs),pointerCount:Y(e.pointerCount),x1:Y(e.x1),y1:Y(e.y1),x2:Y(e.x2),y2:Y(e.y2),count:Y(e.count),pauseMs:Y(e.pauseMs),pattern:G(e.pattern,[`one-way`,`ping-pong`]),scale:Y(e.scale)})}function si(e,t){let n=ci(e,G(t.result?.action,[`start`,`stop`])),r=li(t);return r?`${n} ${r}`:n}function ci(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function li(e){let t=e.result??{};return q(t.requestedFileName)??q(t.outPath)??q(t.path)??q(e.positionals[1])}function ui(e,t){for(let n of t){let t=U(e[n]);if(t)return t}}function di(e){switch(e.command){case f.open:return`Opened ${X(e)??`session`}`;case f.close:return`Closed ${U(e.result?.session)??`session`}`;case f.click:case f.press:return`Tapped ${X(e)??`target`}`;case f.longPress:return`Long pressed ${X(e)??`target`}`;case f.fill:return`Filled ${X(e)??`target`}`;case f.type:return`Typed text`;case f.install:case f.reinstall:case _e.installSource:return zr(e);default:return Br(e)??`Ran ${e.command}`}}function fi(e){return K({command:e.command,positionals:xi(e),flags:Mi(e),...pi(e),...mi(e),...hi(e),...Vr(e)})}function pi(e){if(!gi(e.command))return{};let t=e.result??{};return K({ref:Bi(t),targetLabel:X(e),selectorChainLength:ki(t.selectorChain)?.length,x:Y(t.x),y:Y(t.y),x2:Y(t.x2),y2:Y(t.y2),durationMs:Y(t.durationMs)})}function mi(e){if(!_i(e.command))return{};let t=e.result??{};return K({platform:G(t.platform,me),target:G(t.target,he),appName:U(t.appName),appBundleId:U(t.appBundleId),bundleId:U(t.bundleId),packageName:U(t.packageName),launchTarget:U(t.launchTarget)})}function hi(e){let t=e.result??{};return e.command===f.snapshot?{...Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}}:e.command!==f.wait&&e.command!==f.find&&e.command!==f.get&&e.command!==f.is?{}:K({waitedMs:Y(t.waitedMs),found:W(t.found)})}function gi(e){return e===f.click||e===f.press||e===f.longPress||e===f.focus||e===f.fill}function _i(e){return e===f.open||e===f.install||e===f.reinstall||e===_e.installSource}function X(e){let t=e.result??{};return vi(t)??yi(t)??bi(t)??Di(e.positionals[0])}function vi(e){let t=Bi(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function yi(e){let t=Y(e.x),n=Y(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function bi(e){return U(e.appName)??U(e.appBundleId)??U(e.bundleId)??U(e.packageName)}function xi(e){if(e.positionals.length!==0)return e.command===f.type?[Q(`text`)]:e.command===f.fill?Si(e):e.command===f.find?Ci(e):e.command===f.clipboard?wi(e):e.command===f.push?Ti(e,`app`,`payload`):e.command===f.triggerAppEvent?Ti(e,`event`,`payload`):e.positionals.map(Z)}function Si(e){let t=Q(`text`),n=e.result??{},r=Bi(n);if(r)return[`@${r}`,t];if(U(n.selector))return[Q(`target`),t];let i=Y(n.x),a=Y(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function Ci(e){let t=+!!Oi(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],Q(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,Q(`text`)]:[...r,...e.positionals.slice(n).map(Ei)]:r}function wi(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,Q(`text`)]:e.positionals.map(Z)}function Ti(e,t,n){let[r,i,...a]=e.positionals;return[...r?[Q(t)]:[],...i?[Q(n)]:[],...a.map(Z)]}function Ei(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:Z(e)}function Z(e){return Di(e)??Q(`arg`)}function Di(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function Q(e){return`<${e}>`}function Oi(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function ki(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const Ai={enums:[{source:`platform`,values:pe},{source:`target`,values:he}]},ji={[f.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:ve}]},[f.click]:Ni(),[f.press]:Ni(),[f.longPress]:Ni(),[f.fill]:Pi(),[f.type]:Pi(),[f.scroll]:{booleans:[{source:`settle`}],numbers:[{source:`pixels`},{source:`durationMs`},{source:`settleQuietMs`}]},[f.gesture]:Fi(),[f.swipe]:Fi(),[f.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[f.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[f.back]:{booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}],enums:[{source:`backMode`,output:`mode`,values:ee}]},[f.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:ye}]},[f.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[f.boot]:{booleans:[{source:`headless`}]},[f.close]:{booleans:[{source:`shutdown`}]}};function Mi(e){let t=e.flags??{},n={},r=Object.hasOwn(ji,e.command)?ji[e.command]:void 0;return Ii(n,t,Ai),Ii(n,t,r),Object.keys(n).length>0?n:void 0}function Ni(){return{booleans:[{source:`doubleTap`},{source:`settle`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`},{source:`settleQuietMs`}],enums:[{source:`clickButton`,values:u}]}}function Pi(){return{booleans:[{source:`settle`}],numbers:[{source:`delayMs`},{source:`settleQuietMs`}]}}function Fi(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:c}]}}function Ii(e,t,n){n&&(Li(e,t,n.booleans??[]),Ri(e,t,n.numbers??[]),zi(e,t,n.enums??[]))}function Li(e,t,n){for(let r of n)Vi(e,r.output??r.source,t[r.source])}function Ri(e,t,n){for(let r of n)Hi(e,r.output??r.source,t[r.source])}function zi(e,t,n){for(let r of n)Ui(e,r.output??r.source,t[r.source],r.values)}function Bi(e){let t=U(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function Vi(e,t,n){typeof n==`boolean`&&(e[t]=n)}function Hi(e,t,n){let r=Y(n);r!==void 0&&(e[t]=r)}function Ui(e,t,n,r){let i=G(n,r);i!==void 0&&(e[t]=i)}const $=new Map,Wi=new Set;function Gi(e){return h.join(e,`events.ndjson`)}function Ki(e){return e.command!==f.events}function qi(t,n,r){let i=e({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});Yi(t,`${JSON.stringify(i)}\n`)}async function Ji(e){await(e?$.get(e):Promise.all($.values()))}function Yi(e,t){let n=($.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await Xi(e),await g.promises.appendFile(e,t,`utf8`)}).catch(t=>{m({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{$.get(e)===n&&$.delete(e)});$.set(e,n)}async function Xi(e){let t=h.dirname(e);if(!Wi.has(t))try{await g.promises.mkdir(t,{recursive:!0}),Wi.add(t)}catch(t){throw m({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function Zi(e,t,n){qi(e,t,{kind:`action.recorded`,requestId:p().requestId,command:n.command,summary:di(n),details:fi(n)})}function Qi(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??p().requestId,command:t.command,summary:`Started ${t.command}`}}function $i(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=vr(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??p().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??p().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function ea(e,t={}){let n=aa(t.cursor),r=oa(t.limit);if(!g.existsSync(e))return{path:e,cursor:String(n),limit:r,events:[]};let i=ta(e,n,r),a=i.lines.flatMap(e=>{let t=sa(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:a,...i.nextCursor===void 0?{}:{nextCursor:String(i.nextCursor)}}}function ta(e,t,n){let r=g.openSync(e,`r`);try{let e=new je(`utf8`),i=Buffer.allocUnsafe(65536),a=na(t,n),o=``,s=0;do{s=g.readSync(r,i,0,i.length,null);let t=e.write(i.subarray(0,s));o=ra(`${o}${t}`,a)}while(s>0&&a.nextCursor===void 0);let c=`${o}${e.end()}`;return a.nextCursor===void 0&&c.length>0&&ia(c,a),{lines:a.lines,nextCursor:a.nextCursor}}finally{g.closeSync(r)}}function na(e,t){return{cursor:e,limit:t,lineIndex:0,lines:[]}}function ra(e,t){let n=0;for(let r=e.indexOf(`
|
|
1
|
+
import{E as e,_ as t,h as n}from"./sdk-contracts.js";import{$ as r,At as i,Et as a,H as o,S as s,Tt as c,U as l,jt as u,lt as ee,n as te,pt as ne,t as re}from"./version.js";import{Gn as ie,It as ae,Kn as oe,Lt as se,Rt as ce,Wn as d,it as le,mt as ue,st as f,x as de,zt as fe}from"./sdk-batch-runner.js";import{_ as pe,i as me,r as he,t as ge}from"./sdk-device.js";import{$t as _e,Xt as p,Yt as ve,gn as ye,qt as be,rn as xe}from"./prepare-kind.js";import{t as Se}from"./device.js";import{A as m,M as h}from"./sdk-android-adb.js";import{n as Ce,t as we}from"./path-resolution.js";import{d as Te,n as Ee,o as De,s as Oe}from"./host-process.js";import g from"node:path";import ke from"node:crypto";import _ from"node:fs";import{StringDecoder as Ae}from"node:string_decoder";function v(e){return e.startsWith(`@`)?n(e)?.base??e:e}const y=/^-?\d+(\.\d+)?$/,je=/^[^\s"\\]+$/,Me=new Map([[`--count`,`count`],[`--interval-ms`,`intervalMs`],[`--hold-ms`,`holdMs`],[`--jitter-px`,`jitterPx`]]),Ne=new Map([[`--count`,`count`],[`--pause-ms`,`pauseMs`]]),Pe=new Map([[`--pointer-count`,`pointerCount`]]),Fe=new Map([[`--delay-ms`,`delayMs`]]);function b(e){return e===`click`||e===`press`}function Ie(e){return b(e)||e===`longpress`}function Le(e){return e===`type`||e===`fill`}function x(e){return ze(e,Be)}function Re(e){return JSON.stringify(e)}function S(e){return ze(e,Ve)}function ze(e,t){return t(e)?e:Re(e)}function Be(e){return Ve(e)&&e.startsWith(`@`)||y.test(e)}function Ve(e){return je.test(e)}const He=new Set([`fill`,`type`]);function Ue(e){if(!He.has(e.command)){let t=(e.positionals??[]).map(e=>x(e));return[e.command,...t].join(` `)}let t=We(e).map(e=>x(e)).join(` `);return[e.command,t,`<text>`].filter(e=>e.length>0).join(` `)}function We(e){if(e.command===`type`)return[];let t=e.positionals??[],n=t[0];return n===void 0?[]:n.startsWith(`@`)?[n]:t.length>=3&&y.test(n)&&y.test(t[1]??``)?[n,t[1]]:[n]}function C(e,t){let n=t.flags??{};if(b(t.command)){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.intervalMs==`number`&&e.push(`--interval-ms`,String(n.intervalMs)),typeof n.holdMs==`number`&&e.push(`--hold-ms`,String(n.holdMs)),typeof n.jitterPx==`number`&&e.push(`--jitter-px`,String(n.jitterPx)),n.doubleTap===!0&&e.push(`--double-tap`);let t=n.clickButton;t&&t!==`primary`&&e.push(`--button`,t);return}if(t.command===`swipe`){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.pauseMs==`number`&&e.push(`--pause-ms`,String(n.pauseMs)),(n.pattern===`one-way`||n.pattern===`ping-pong`)&&e.push(`--pattern`,n.pattern);return}if(t.command===`gesture`){typeof n.pointerCount==`number`&&e.push(`--pointer-count`,String(n.pointerCount));return}Le(t.command)&&typeof n.delayMs==`number`&&e.push(`--delay-ms`,String(n.delayMs))}function Ge(e,t){t&&((t.platform===`ios`||t.platform===`android`)&&e.push(`--platform`,t.platform),typeof t.metroHost==`string`&&t.metroHost.length>0&&e.push(`--metro-host`,S(t.metroHost)),typeof t.metroPort==`number`&&e.push(`--metro-port`,String(t.metroPort)),typeof t.bundleUrl==`string`&&t.bundleUrl.length>0&&e.push(`--bundle-url`,S(t.bundleUrl)),typeof t.launchUrl==`string`&&t.launchUrl.length>0&&e.push(`--launch-url`,S(t.launchUrl)))}function Ke(e,t){let[n,...r]=t.positionals??[];n&&e.push(S(n));for(let t of r)e.push(x(t));typeof t.flags?.fps==`number`&&e.push(`--fps`,String(t.flags.fps)),(typeof t.flags?.quality==`number`||typeof t.flags?.quality==`string`)&&e.push(`--quality`,String(t.flags.quality)),t.flags?.hideTouches&&e.push(`--hide-touches`)}function qe(e,t){t.flags?.snapshotInteractiveOnly&&e.push(`-i`),typeof t.flags?.snapshotDepth==`number`&&e.push(`-d`,String(t.flags.snapshotDepth)),t.flags?.snapshotScope&&e.push(`-s`,x(t.flags.snapshotScope)),t.flags?.snapshotRaw&&e.push(`--raw`)}function Je(e,t){for(let n of t.positionals??[])e.push(x(n));i(e,t.flags)}function Ye(e,t,n={}){let r=t.positionals??[],i=n.includeAllPositionals?r:r.slice(0,1);for(let t of i)e.push(S(t));Ge(e,t.flags)}function Xe(e,t){for(let n of t.positionals??[])e.push(x(t.command===`wait`?v(n):n));C(e,t)}function w(e,t){let n=[],r={},i=b(e)?Me:e===`swipe`?Ne:e===`gesture`?Pe:Le(e)?Fe:void 0;for(let a=0;a<t.length;a+=1){let o=t[a];if(b(e)&&o===`--double-tap`){r.doubleTap=!0;continue}let s=t[a+1];if(b(e)&&o===`--button`&&s!==void 0){let e=s;(e===`primary`||e===`secondary`||e===`middle`)&&(r.clickButton=e),a+=1;continue}let c=i?.get(o);if(c&&s!==void 0){let e=Qe(s);if(e!==null){r[c]=e,a+=1;continue}}if(e===`swipe`&&o===`--pattern`&&s!==void 0){let e=s;(e===`one-way`||e===`ping-pong`)&&(r.pattern=e),a+=1;continue}n.push(o)}return{positionals:n,flags:r}}function Ze(e){let t=[],n={};for(let r=0;r<e.length;r+=1){let i=e[r],a=e[r+1];if(i===`--platform`&&a!==void 0){let e=a;(e===`ios`||e===`android`)&&(n.platform=e),r+=1;continue}if(i===`--metro-host`&&a!==void 0){n.metroHost=a,r+=1;continue}if(i===`--metro-port`&&a!==void 0){let e=Qe(a);e!==null&&(n.metroPort=e),r+=1;continue}if(i===`--bundle-url`&&a!==void 0){n.bundleUrl=a,r+=1;continue}if(i===`--launch-url`&&a!==void 0){n.launchUrl=a,r+=1;continue}t.push(i)}return{positionals:t,flags:n}}function Qe(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function $e(e){let t;for(let n of e){if(n.command===`runtime`&&typeof n.flags.platform==`string`){t=n.flags.platform;continue}if(n.command===`open`)return n.runtime?.platform??t}return t}function et(e,t){for(let n of t.positionals??[])e.push(x(n));t.flags?.relaunch&&e.push(`--relaunch`),Ge(e,t.runtime)}function tt(e){let t=[],n={};for(let r of e){if(r===`--relaunch`){n.relaunch=!0;continue}t.push(r)}let r=Ze(t);return{positionals:r.positionals,flags:n,runtime:nt(r.flags)?r.flags:void 0}}function nt(e){return!!(e.platform||e.metroHost||e.metroPort!==void 0||e.bundleUrl||e.launchUrl)}const rt=/^[A-Z_][A-Z0-9_]*$/,it=new Set(he.filter(e=>e!==`web`)),at=new Set([`mobile`,`tv`,`desktop`]);function ot(e){let n=[],r=[],i=e.split(/\r?\n/),a=!1,s,c=(e,n,r)=>{throw new t(`INVALID_ARGS`,`${e.kind===`multiple`?`targets-v1`:`target-v1`} annotation on line ${e.line} must be immediately followed by its action line (line ${n+1} ${r}).`)};for(let[e,l]of i.entries()){let i=l.trim();if(i.length===0){s&&c(s,e,`is blank`);continue}if(i.startsWith(`#`)){let t=ce(i);if(t.kind===`v1`){s&&c(s,e,`is another target annotation`),s={kind:`multiple`,evidence:t.evidence,line:e+1};continue}let n=fe(i);if(n.kind===`v1`){s&&c(s,e,`is another target annotation`),s={kind:`single`,evidence:n.evidence,line:e+1};continue}s&&c(s,e,`is a comment`);continue}if(ct(i)){if(s&&c(s,e,`is an env directive`),a)throw new t(`INVALID_ARGS`,`env directives must precede all actions (line ${e+1}).`);continue}let u=ft(l);if(!u){s&&c(s,e,`did not parse as an action`);continue}let ee=o(u.command,u.positionals??[],`line ${e+1}`);if(ee)throw new t(`INVALID_ARGS`,ee);s&&=(s.kind===`single`?u.targetEvidence=s.evidence:u.targetEvidences=s.evidence,void 0),n.push(u),r.push(e+1),a=!0}if(s)throw new t(`INVALID_ARGS`,`${s.kind===`multiple`?`targets-v1`:`target-v1`} annotation on line ${s.line} must be immediately followed by its action line (end of script reached).`);return{actions:n,actionLines:r}}function st(e){let t=e.split(/\r?\n/),n={};for(let[e,r]of t.entries()){let t=r.trim();if(t.length===0||t.startsWith(`#`))continue;if(ct(t)){dt(n,t,e+1);continue}if(!t.startsWith(`context `))break;let i=t.match(/(?:^|\s)platform=([^\s]+)/);if(i){let e=i[1];e&&it.has(e)&&T(n,`platform`,e)}let a=t.match(/(?:^|\s)target=([^\s]+)/);if(a){let e=a[1];e&&at.has(e)&&T(n,`target`,e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&T(n,`timeoutMs`,Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&T(n,`retries`,Math.floor(e))}}return n}function ct(e){return e===`env`||e.startsWith(`env `)||e.startsWith(`env `)}function lt(e,n){let r=e.slice(3).replace(/^[\s]+/,``),i=r.indexOf(`=`);if(i<=0)throw new t(`INVALID_ARGS`,`Invalid env directive on line ${n}: expected "env KEY=VALUE".`);let a=r.slice(0,i);if(!rt.test(a))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(a.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: the AD_* namespace is reserved for built-in variables. Rename ${a} to avoid the AD_ prefix.`);return{key:a,value:ut(r.slice(i+1),n)}}function ut(e,n){if(e.length===0)return``;if(e.startsWith(`"`))try{let t=JSON.parse(e);if(typeof t!=`string`)throw Error(`not a string literal`);return t}catch{throw new t(`INVALID_ARGS`,`Invalid quoted env value on line ${n}.`)}return e}function dt(e,n,r){let{key:i,value:a}=lt(n,r),o=e.env??{};if(Object.prototype.hasOwnProperty.call(o,i))throw new t(`INVALID_ARGS`,`Duplicate env directive "${i}" on line ${r}.`);o[i]=a,e.env=o}function T(e,n,r){let i=e[n];if(i!==void 0)throw new t(`INVALID_ARGS`,i===r?`Duplicate replay test metadata "${n}" in context header.`:`Conflicting replay test metadata "${n}" in context header: ${String(i)} vs ${String(r)}.`);e[n]=r}function ft(e){let n=e.trim();if(n.length===0||n.startsWith(`#`))return null;let[r,...i]=mt(n);if(r===void 0||r===`context`)return null;let a={ts:Date.now(),command:r,positionals:[],flags:{}};if(r===`snapshot`){a.positionals=[];for(let e=0;e<i.length;e+=1){let t=i[e];if(t===`-i`){a.flags.snapshotInteractiveOnly=!0;continue}if(t!==`-c`){if(t===`--raw`){a.flags.snapshotRaw=!0;continue}if(t===`--force-full`){a.flags.snapshotForceFull=!0;continue}if((t===`-d`||t===`--depth`)&&e+1<i.length){let t=Number(i[e+1]);Number.isFinite(t)&&t>=0&&(a.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if((t===`-s`||t===`--scope`)&&e+1<i.length){a.flags.snapshotScope=i[e+1],e+=1;continue}if(t===`--backend`&&e+1<i.length){e+=1;continue}}}return a}if(r===`open`){let e=tt(i);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a.runtime=e.runtime,a}if(r===`runtime`){let e=Ze(i);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a}if(b(r)){let e=w(r,i);Object.assign(a.flags,e.flags);let t=e.positionals[0];if(t===void 0)return a;if(t.startsWith(`@`))return a.positionals=[v(t)],e.positionals[1]&&(a.result={refLabel:e.positionals[1]}),a;let n=e.positionals[0],o=e.positionals[1];return E(n)&&E(o)&&e.positionals.length>=2?(a.positionals=[n,o],a):(a.positionals=[e.positionals.join(` `)],a)}if(r===`fill`){let e=w(r,i);if(Object.assign(a.flags,e.flags),!pt(e.positionals))return a.positionals=e.positionals,a;let[t,n,...o]=e.positionals;if(E(t)&&E(n))return a.positionals=[t,n,o.join(` `)],a;let[s,c,...l]=e.positionals;if(s.startsWith(`@`)){let e=v(s);return l.length>0?(a.positionals=[e,l.join(` `)],a.result={refLabel:c},a):(a.positionals=[e,c],a)}return a.positionals=[s,[c,...l].join(` `)],a}if(r===`get`){let e=i[0],t=i[1];return e===void 0||t===void 0?(a.positionals=i,a):t.startsWith(`@`)?(a.positionals=[e,v(t)],i[2]&&(a.result={refLabel:i[2]}),a):(a.positionals=[e,i.slice(1).join(` `)],a)}if(r===`swipe`||r===`type`||r===`gesture`){let e=w(r,i);return Object.assign(a.flags,e.flags),a.positionals=e.positionals,a}if(r===`record`){let e=[];for(let n=0;n<i.length;n+=1){let r=i[n];if(r===c.cliToken)throw new t(`INVALID_ARGS`,c.migration.record);if(r===`--hide-touches`){a.flags.hideTouches=!0;continue}if(r===`--fps`&&n+1<i.length){let e=Number(i[n+1]);Number.isFinite(e)&&(a.flags.fps=Math.floor(e)),n+=1;continue}if(r===`--quality`&&n+1<i.length){let e=i[n+1],t=xe(e);t!==void 0&&(a.flags.quality=t),n+=1;continue}e.push(r)}return a.positionals=e,a}if(r===`screenshot`){let e=[];for(let t=0;t<i.length;t+=1){let n=i[t],r=u({args:i,index:t,flags:a.flags});if(r.handled){t=r.nextIndex;continue}e.push(n)}return a.positionals=e,a}return a.positionals=r===`wait`||r===`longpress`?i.map(e=>v(e)):i,a}function pt(e){return e.length>=2}function E(e){return e?!Number.isNaN(Number(e)):!1}function mt(e){let t=[],n=0;for(;n<e.length&&(n=ht(e,n),!(n>=e.length));){let r=e[n]===`"`?gt(e,n):_t(e,n);t.push(r.value),n=r.nextCursor}return t}function ht(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}function gt(e,n){let r=n+1,i=!1,a=r;for(;a<e.length;a+=1){let t=e.charAt(a);if(t===`"`&&!i)break;if(i){i=!1;continue}i=t===`\\`}if(a>=e.length)throw new t(`INVALID_ARGS`,`Invalid replay script line: ${e}`);let o=e.slice(n,a+1),s;try{s=JSON.parse(o)}catch{throw new t(`INVALID_ARGS`,`Invalid quoted value ${o} in replay script line: ${e}`,{hint:`Quoted replay values are JSON strings: escape backslashes, quotes, tabs, and newlines (\\\\, \\", \\t, \\n).`})}return{value:s,nextCursor:a+1}}function _t(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}function vt(e,t={}){let n=[e.command];return e.command===`snapshot`?qe(n,e):e.command===`open`?et(n,e):e.command===`runtime`?Ye(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?Ke(n,e):e.command===`screenshot`?Je(n,e):Xe(n,e),n.join(` `)}function yt(e){return e.targetEvidences?[ae(e.targetEvidences)]:e.targetEvidence?[se(e.targetEvidence)]:[]}async function bt(e){return e===`https:`?(await import(`node:https`)).default:(await import(`node:http`)).default}function xt(e){return new Promise((t,n)=>{let r=``;e.setEncoding(`utf8`),e.on(`data`,e=>{r+=e}),e.on(`end`,()=>t(r)),e.on(`error`,n)})}async function St(e,n,r){let i=[],a=0;for await(let o of e){let e=Buffer.isBuffer(o)?o:Buffer.from(o);if(a+=e.length,a>n)throw new t(`INVALID_ARGS`,r);i.push(e)}return Buffer.concat(i)}const Ct=`/agent-device`,wt=`x-agent-device-tenant`;function Tt(e){return Et(e,Ct)}function Et(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t.replace(/^\/+/,``),n).toString()}function Dt(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function Ot(e){let t=e?.trim();return t?{[wt]:t}:{}}const kt=`.webm`;function At(e){return e===`web`?kt:`.mp4`}function jt(e,t){return g.extname(e)?e:`${e}${t}`}function Mt(e){return`./recording-${Date.now()}${At(e)}`}const D={kind:`none`};function O(e,t){if(t.path===void 0){let n=e??{kind:`default`,force:!1};return t.force?{...n,force:!0}:n}let n=e?.force===!0&&(e.kind==="default"||e.path===t.path);return{kind:`explicit`,path:t.path,force:t.force||n}}function Nt(e){return e.kind===`repair`?{...e,status:`armed`}:e}function Pt(e){return e.kind===`none`?void 0:e.target}function Ft(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function It(e){return e.kind===`authoring`&&e.status===`aborted`}function Lt(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function Rt(e){return{kind:`authoring`,status:`armed`,target:O(void 0,e)}}function zt(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function Bt(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function Vt(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:O(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function Ht(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function Ut(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function Wt(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function Gt(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function Kt(e){return e.kind===`repair`?e.boundary:void 0}function qt(e){return e.kind===`repair`?e.sourcePath:void 0}function Jt(e){return e.kind===`repair`&&e.status!==`committed`}function Yt(e){let t=Pt(e);return t?.kind===`explicit`?t.path:void 0}function Xt(e){return Pt(e)?.force===!0}function k(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function A(e,t){return Ce(e,{cwd:t})}function j(e){return e?.scriptPublication??D}function Zt(e){let t=j(e);return t.kind===`authoring`&&t.status===`armed`}function Qt(e,t){e.recordSession=!0,e.scriptPublication=Rt({path:t.path===void 0?void 0:A(t.path),force:t.force===!0})}function $t(e){e.recordSession=!1,e.scriptPublication=zt(j(e))}function en(e,t){return It(j(e))?!1:e.recordSession===!0||t}function tn(e,t){if(!t.saveScript||It(j(e)))return;e.recordSession=!0;let n={path:typeof t.saveScript==`string`?A(t.saveScript):void 0,force:t.force===!0},r=j(e);if(r.kind===`repair`){e.scriptPublication=Vt(r,{requested:n,boundary:r.boundary,sourcePath:r.sourcePath});return}if(r.kind===`authoring`){e.scriptPublication={...r,target:O(r.target,n)};return}e.scriptPublication=Rt(n)}function nn(e,t){let n=j(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:O(n.target,{path:t.explicitPath===void 0?void 0:A(t.explicitPath),force:t.liveForce===!0})})}function rn(e,t){e.scriptPublication=Bt(j(e),t),e.recordSession=!1}function an(e,t){let n=j(e);n.kind===`authoring`&&(e.scriptPublication=Bt(n,t))}function on(e,t){return t===!0||Xt(j(e))}function sn(e){return Lt(j(e))}function M(e){return e?.scriptPublication??D}function cn(e,t){e.recordSession=!0;let n=M(e);e.scriptPublication=Vt(n,{requested:{path:typeof t.saveScript==`string`?A(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function ln(e){e.scriptPublication=Nt(M(e))}function un(e){e.scriptPublication=Ht(M(e))}function dn(e,t){e.scriptPublication=Ut(M(e),t)}function fn(e){e.scriptPublication=Gt(M(e))}function pn(e,t){let n=M(e);return n.kind===`repair`&&n.closeReceipt===t}function mn(e){return M(e).kind===`repair`}function hn(e){return Jt(M(e))}function N(e){return Kt(M(e))}function gn(e){return qt(M(e))}function P(e){let t=e.result?.text;if(typeof t==`string`)return t;let n=e.positionals??[];return n.length===0?``:n[0]?.startsWith(`@`)?n.length>=3?n.slice(2).join(` `):n.slice(1).join(` `):n.length>=3&&!Number.isNaN(Number(n[0]))&&!Number.isNaN(Number(n[1]))?n.slice(2).join(` `):n.slice(1).join(` `)}const _n=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function vn(e){if(e!==e.trim()||!rt.test(e))throw new t(`INVALID_ARGS`,`Invalid --record-as variable "${e}": use uppercase letters, digits, and underscores (for example PASSWORD).`);if(e.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid --record-as variable "${e}": the AD_* namespace is reserved for built-in replay variables.`);return e}function yn(e){return`\${${e}}`}function bn(e){let t=_n.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}const xn=new Set(`action.backend.cost.delayMs.evidence.gesture.hint.kind.maestroFallbackReason.maestroNonHittableCoordinateFallbackAllowed.maestroNonHittableCoordinateFallbackUsed.message.platform.ref.referenceHeight.referenceWidth.refLabel.resolution.selector.selectorChain.settle.targetHittable.targetKind.text.warning.x.y`.split(`.`)),Sn=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),Cn=new Set([`cost`,`evidence`,`resolution`,`settle`]),wn=new Map([[`cost`,new Set([`nodeCount`,`runnerRoundTrips`,`wallClockMs`])],[`evidence`,new Set([`changedFromBefore`,`digest`,`foregroundApp`,`interactiveNodeCount`,`nodeCount`])],[`resolution`,new Set([`alternatives`,`kind`,`matchCount`,`phase`,`source`,`tiebreak`,`winnerDiagnostic`])],[`resolution.alternatives`,new Set([`diagnosticRef`,`label`,`role`])],[`resolution.winnerDiagnostic`,new Set([`diagnosticRef`,`label`,`role`])],[`settle`,new Set([`captures`,`diff`,`hint`,`quietMs`,`refs`,`refsGeneration`,`settled`,`tail`,`tailTruncated`,`timeoutMs`,`waitedMs`])],[`settle.diff`,new Set([`lines`,`summary`,`truncated`])],[`settle.diff.lines`,new Set([`kind`,`ref`,`text`])],[`settle.diff.summary`,new Set([`additions`,`removals`,`unchanged`])],[`settle.refs`,new Set([`ref`])],[`settle.tail`,new Set([`label`,`ref`,`role`])]]),Tn=new Set([`evidence.digest`,`evidence.foregroundApp`,`resolution.alternatives.diagnosticRef`,`resolution.alternatives.role`,`resolution.kind`,`resolution.phase`,`resolution.source`,`resolution.tiebreak`,`resolution.winnerDiagnostic.diagnosticRef`,`resolution.winnerDiagnostic.role`,`settle.diff.lines.kind`,`settle.diff.lines.ref`,`settle.refs.ref`,`settle.tail.ref`,`settle.tail.role`]);function En(e,t,n){if(!e)return e;let r=Nn(e.selectorChain);return{...kn(e,t,n),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!On(e,t))}:{}}}function Dn(e,t,n){return e&&{...e,...e.label===t?{label:n}:{},ancestry:e.ancestry.map(e=>({...e,...e.label===t?{label:n}:{}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===t?{label:n}:{}}}:{}}}function On(e,t){return ue(e,t)}function kn(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[xn.has(e)?e:I(e,t,n),An(r,e,t,n)]))}function An(e,t,n,r){return typeof e==`string`&&Sn.has(t)?e:t===`selectorChain`&&Mn(e)?jn(e,n):F(e,n,r,Cn.has(t)?t:void 0)}function F(e,t,n,r){if(typeof e==`string`)return r&&Tn.has(r)?e:I(e,t,n);if(Array.isArray(e))return e.map(e=>F(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?wn.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:I(e,t,n),F(a,t,n,o?`${r}.${e}`:void 0)]}))}function jn(e,t){return e.filter(e=>!On(e,t))}function I(e,t,n){if(!t)return e===t?n:e;let r=n?e.split(n):[e];return r.every(e=>!e.includes(t))?e:t.trim()?r.map(e=>e.replaceAll(t,n)).join(n):n}function Mn(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Nn(e){return Mn(e)?e:void 0}function Pn(e,t){if(t.flags?.noRecord||zn(e,t))return;t.flags&&tn(e,t.flags);let n=Fn(t),r={ts:Date.now(),command:n.command,positionals:n.positionals,runtime:n.runtime,flags:Vn(n.flags),result:n.result,...n.targetEvidence?{targetEvidence:n.targetEvidence}:{},...n.targetEvidences?{targetEvidences:n.targetEvidences}:{}};return e.actions.push(r),m({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),r}function Fn(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return e;let t=yn(vn(e.flags.recordAs)),n=P({ts:0,command:e.command,positionals:e.positionals,flags:e.flags});return{...e,positionals:In(e.positionals,t),result:En(e.result,n,t),targetEvidence:Dn(e.targetEvidence,n,t)}}function In(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const Ln=new Set([`snapshot`,`get`,`is`,`find`]);function Rn(e){return e.internal?.replayPlanStep===!0?!1:Ln.has(e.command)}function zn(e,t){return!t.interactiveObservation||N(e)===void 0?!1:t.flags?.record!==!0}const Bn=[`platform`,`device`,`udid`,`serial`,`out`,`verbose`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`,`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`,`snapshotCustomActions`,...a,`relaunch`,`saveScript`,`force`,`noRecord`,`record`,`fps`,`quality`,`hideTouches`,`count`,`pointerCount`,`intervalMs`,`delayMs`,`holdMs`,`jitterPx`,`doubleTap`,`clickButton`,`pauseMs`,`pattern`];function Vn(e){if(!e)return{};let t={};for(let n of Bn)e[n]!==void 0&&(t[n]=e[n]);return t}function Hn(e){let n=e.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new t(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(e.some(e=>e.command===`close`))throw new t(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[t,n]of e.entries())de({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=t);if(!e.slice(r+1).some(Jn))throw new t(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function Un(e){for(let n of e){if(Wn(n)){Gn(n);continue}let e=Yn(n),r=e??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&de(n)===`mutates-app`)throw new t(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=e;if(!(!i||!f(i)||n.targetEvidence))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function Wn(e){return Kn(e)!==void 0}function Gn(e){let n=Kn(e);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!f(n))&&!e.targetEvidences)throw new t(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function Kn(e){return e.command===`gesture`?l(e.positionals):void 0}function qn(e,n){if(e instanceof t){if(e.details?.reason===`script_target_exists`)return new t(e.code,`A file already exists at ${String(e.details.path)}.`,{...e.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=e.details?.retriable===!0;return new t(e.code,e.message,{...e.details,retriable:n,hint:e.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Jn(e){if(e.command!==`wait`)return!1;let t=le(e.positionals);return t?.kind!==`selector`||!f(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function Yn(e){if(e.command===`get`)return e.positionals[1];if(Ie(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&Xn(t)&&Xn(n)?void 0:t}}function Xn(e){return e.trim().length>0&&Number.isFinite(Number(e))}function Zn(e){let t=e.scriptPublication??D;return t.kind===`repair`?t.status===`committed`?!0:!Ft(t):!1}function Qn(e){return!e.recordSession||It(e.scriptPublication??D)?!0:Zn(e)}var $n=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=mn(e),r=t?.publication===`active`,i;try{if(Qn(e))return{written:!1};let a=er(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=g.dirname(i);return _.existsSync(o)||_.mkdirSync(o,{recursive:!0}),rr({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=Wt(e.scriptPublication??D)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return tr({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=Yt(e.scriptPublication??D);if(t)return A(t);let n=k(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,`-`);return g.join(this.sessionsDir,`${n}-${r}.ad`)}};function er(e,t){let n=ir(e,{strictPortableRefs:t.activePublication});return t.activePublication&&Hn(n),{script:mr(e,n,t.appendCompleteSentinel),actionCount:n.length}}function tr(e){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=e;if(m({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:nr(r,i)};if(o)return{written:!1,error:qn(r,i)};if(r instanceof t)throw r;return{written:!1}}function nr(e,n){if(e instanceof t)return e;let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to write the healed script${n?` to ${n}`:``}: ${r}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function rr(e){let{scriptPath:n,script:r,force:i}=e,a=g.dirname(n),o=g.join(a,`.${g.basename(n)}.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`);_.writeFileSync(o,r);try{if(i){_.renameSync(o,n);return}_.linkSync(o,n)}catch(e){throw e.code===`EEXIST`?new t(`COMMAND_FAILED`,`A file already exists at ${n}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:n}):e}finally{_.rmSync(o,{force:!0})}}function ir(e,t={}){let n=N(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=sr(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&ar(n);let o=pr(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&Un(a),a}function ar(e){let n=e.command===`gesture`?l(e.positionals??[]):void 0;if(n){or(n);return}if(!L(e.command))return;let r=e.command===`get`?e.positionals?.[1]:e.positionals?.[0];if(r?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot write recorded step "${e.command} ${r}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function or(e){let n=[e.source,e.destination].find(e=>e.startsWith(`@`));if(n)throw new t(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function sr(e){let t=cr(e);if(!(!t||!L(e.command)))return b(e.command)?{...e,positionals:[t]}:e.command===`longpress`?ur(e,t):e.command===`fill`?lr(e,t):dr(e,t)}function cr(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function L(e){return Ie(e)||e===`fill`||e===`get`}function lr(e,t){let n=P(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function ur(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):fr(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function dr(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function fr(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function pr(e,t){if(!L(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r}}}function mr(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${pe(e.device)} device=${Re(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...yt(e)),r.push(hr(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
|
|
2
|
+
`)}\n`}function hr(e){return gr([e.command],e)||vt(e)}function gr(e,t){if(b(t.command))return _r(e,t);if(t.command===`fill`)return vr(e,t);if(t.command===`get`)return yr(e,t)}function _r(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(x(v(n))),R(e,t),C(e,t),e.join(` `);if(t.positionals.length===1)return e.push(x(n)),C(e,t),e.join(` `)}}function vr(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(x(v(n))),R(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(x(r)),C(e,t),e.join(` `)}function yr(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(x(n)),e.push(x(v(r))),r.startsWith(`@`)&&R(e,t),e.join(` `)}function R(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(x(n))}const br=[`status`,`get`,`dismiss`,`enter`,`return`];function z(e){return br.includes(e)}const xr=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],Sr={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function Cr(e,t){let n=t??{};switch(e.command){case p.devices:return wr(n.devices);case p.apps:return Tr(n.apps,e.flags?.appsFilter);case p.boot:return Er(`Booted`,n,!0);case p.shutdown:return Er(`Shut down`,n,!1);case p.install:return Dr(`Installed`,n);case p.reinstall:return Dr(`Reinstalled`,n);case p.screenshot:return Or(e,n);default:return{}}}function wr(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=Ar(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:zr(`Found ${t.length} ${Br(`device`,t.length)}`,i.map(e=>Lr(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function Tr(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=H(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:zr(`Found ${n.length} ${Br(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function Er(e,t,n){let r=jr(t);if(!r)return{};let i={device:r,...Ir(t),booted:n};return{summary:`${e} ${Lr(i,!1)}`,details:i}}function Dr(e,t){let n=H(t.appName),r=H(t.bundleId),i=B(t,[`packageName`,`package`]),a=H(t.platform),o=H(t.launchTarget),s=B(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=Rr(n,s);if(!c)return{};let l={};return V(l,`appName`,n),V(l,`bundleId`,r),V(l,`packageName`,i),V(l,`platform`,a),o!==s&&V(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function Or(e,t){let n=kr(e,t);return n?{details:{requestedFileName:n}}:{}}function kr(e,t){let n=J(e.meta?.clientArtifactPaths?.path)??J(t.path);if(n)return q(n)}function Ar(e){if(!d(e))return;let t=jr(e);if(t)return{name:t,...Ir(e)}}function jr(e){let t=B(e,[`name`,`deviceName`,`device`]);return!t||!Mr(e,t)?t:Pr(e)}function Mr(e,t){let n=Nr(t);return xr.some(t=>{let r=H(e[t]);return r!==void 0&&Nr(r)===n})}function Nr(e){return e.toLowerCase()}function Pr(e){let t=H(e.appleOs),n=H(e.platform),r=H(e.kind),i=Fr(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function Fr(e,t){let n=e??t;if(!(!n||!Object.hasOwn(Sr,n)))return Sr[n]}function Ir(e){let t=H(e.platform),n=H(e.appleOs),r=H(e.kind),i=H(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function Lr(e,t){let n=H(e.name)??H(e.device)??`device`,r=H(e.platform),i=H(e.appleOs),a=[r,i===r?void 0:i,H(e.kind),H(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function Rr(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function B(e,t){for(let n of t){let t=H(e[n]);if(t)return t}}function V(e,t,n){n&&(e[t]=n)}function zr(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function Br(e,t){return t===1?e:`${e}s`}function H(e){let t=J(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function U(e){return H(e)}function W(e){return typeof e==`boolean`?e:void 0}function G(e,t){let n=U(e);return n&&t.includes(n)?n:void 0}function K(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function q(e){let t=J(e);return t?H(t.split(/[\\/]/).at(-1)):void 0}function J(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function Y(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const Vr=[`up`,`down`,`left`,`right`],Hr=[`top`,`bottom`];function Ur(e){return`${e.command===p.reinstall?`Reinstalled`:`Installed`} ${qr(e.result??{})??`app`}`}function Wr(e){let t=e.result??{};switch(e.command){case p.scroll:return Yr(t);case p.screenshot:return Qr(t);case p.home:return`Went home`;case p.back:return ei(t);case p.appSwitcher:return`Opened app switcher`;case p.orientation:return ti(t);case p.viewport:return ni(t);case p.clipboard:return ri(t);case p.keyboard:return ii(t);case p.tvRemote:return si(t);case p.gesture:return ci(t);case p.swipe:return li(t);case p.trace:return di(`trace`,e);case p.record:return di(`recording`,e);default:return}}function Gr(e){let t=e.result??{};switch(e.command){case p.scroll:return K({direction:G(t.direction,Vr),edge:G(t.edge,Hr),passes:Y(t.passes),amount:Y(t.amount),pixels:Y(t.pixels),durationMs:Y(t.durationMs),x1:Y(t.x1),y1:Y(t.y1),x2:Y(t.x2),y2:Y(t.y2)});case p.screenshot:return K({requestedFileName:$r(t)});case p.back:return K({mode:G(t.mode,ne)});case p.orientation:return K({orientation:G(t.orientation,Se)});case p.viewport:return K({width:Y(t.width),height:Y(t.height)});case p.clipboard:return K({action:G(t.action,[`read`,`write`])});case p.keyboard:return oi(t);case p.tvRemote:return K({button:G(t.button,s),durationMs:Y(t.durationMs)});case p.gesture:case p.swipe:return ui(t);case p.trace:case p.record:return K({action:G(t.action,[`start`,`stop`]),fileName:pi(e),showTouches:W(t.showTouches)});default:return{}}}function Kr(e,t){if(e.command!==p.screenshot)return t;let n=kr(e,t);return n?{...t,requestedFileName:n}:t}function qr(e){let t=U(e.appName),n=mi(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??Jr(e)}function Jr(e){let t=U(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function Yr(e){let t=G(e.direction,Vr),n=G(e.edge,Hr),r=Y(e.passes);return n?Xr(n,r):t?Zr(t,e):`Scrolled`}function Xr(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function Zr(e,t){let n=Y(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=Y(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function Qr(e){let t=$r(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function $r(e){return q(e.requestedFileName)??q(e.path)}function ei(e){return G(e.mode,ne)===`system`?`Went back using system navigation`:`Went back`}function ti(e){let t=G(e.orientation,Se);return t?`Rotated to ${t}`:`Changed orientation`}function ni(e){let t=Y(e.width),n=Y(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function ri(e){let t=G(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function ii(e){let t=J(e.action);if(!t||!z(t))return`Used keyboard`;if(t===`dismiss`)return ai(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=W(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function ai(e){return W(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function oi(e){let t=J(e.action);return K({action:t&&z(t)?t:void 0,platform:G(e.platform,[`ios`,`android`]),visible:W(e.visible),wasVisible:W(e.wasVisible),dismissed:W(e.dismissed),attempts:Y(e.attempts),mechanism:G(e.mechanism,[`dismissKey`])})}function si(e){let t=G(e.button,s);return t?`Pressed TV remote ${t}`:`Used TV remote`}function ci(e){let t=G(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function li(e){let t=Y(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function ui(e){return K({kind:G(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:Y(e.durationMs),pointerCount:Y(e.pointerCount),x1:Y(e.x1),y1:Y(e.y1),x2:Y(e.x2),y2:Y(e.y2),count:Y(e.count),pauseMs:Y(e.pauseMs),pattern:G(e.pattern,[`one-way`,`ping-pong`]),scale:Y(e.scale)})}function di(e,t){let n=fi(e,G(t.result?.action,[`start`,`stop`])),r=pi(t);return r?`${n} ${r}`:n}function fi(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function pi(e){let t=e.result??{};return q(t.requestedFileName)??q(t.outPath)??q(t.path)??q(e.positionals[1])}function mi(e,t){for(let n of t){let t=U(e[n]);if(t)return t}}function hi(e){switch(e.command){case p.open:return`Opened ${X(e)??`session`}`;case p.close:return`Closed ${U(e.result?.session)??`session`}`;case p.click:case p.press:return`Tapped ${X(e)??`target`}`;case p.longPress:return`Long pressed ${X(e)??`target`}`;case p.fill:return`Filled ${X(e)??`target`}`;case p.type:return`Typed text`;case p.install:case p.reinstall:case ve.installSource:return Ur(e);default:return Wr(e)??`Ran ${e.command}`}}function gi(e){return K({command:e.command,positionals:Ti(e),flags:Ii(e),..._i(e),...vi(e),...yi(e),...Gr(e)})}function _i(e){if(!bi(e.command))return{};let t=e.result??{};return K({ref:Wi(t),targetLabel:X(e),selectorChainLength:Ni(t.selectorChain)?.length,x:Y(t.x),y:Y(t.y),x2:Y(t.x2),y2:Y(t.y2),durationMs:Y(t.durationMs)})}function vi(e){if(!xi(e.command))return{};let t=e.result??{};return K({platform:G(t.platform,me),target:G(t.target,ge),appName:U(t.appName),appBundleId:U(t.appBundleId),bundleId:U(t.bundleId),packageName:U(t.packageName),launchTarget:U(t.launchTarget)})}function yi(e){let t=e.result??{};return e.command===p.snapshot?{...Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}}:e.command!==p.wait&&e.command!==p.find&&e.command!==p.get&&e.command!==p.is?{}:K({waitedMs:Y(t.waitedMs),found:W(t.found)})}function bi(e){return e===p.click||e===p.press||e===p.longPress||e===p.focus||e===p.fill}function xi(e){return e===p.open||e===p.install||e===p.reinstall||e===ve.installSource}function X(e){let t=e.result??{};return Si(t)??Ci(t)??wi(t)??ji(e.positionals[0])}function Si(e){let t=Wi(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function Ci(e){let t=Y(e.x),n=Y(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function wi(e){return U(e.appName)??U(e.appBundleId)??U(e.bundleId)??U(e.packageName)}function Ti(e){if(e.positionals.length!==0)return e.command===p.type?[Q(`text`)]:e.command===p.fill?Ei(e):e.command===p.find?Di(e):e.command===p.clipboard?Oi(e):e.command===p.push?ki(e,`app`,`payload`):e.command===p.triggerAppEvent?ki(e,`event`,`payload`):e.positionals.map(Z)}function Ei(e){let t=Q(`text`),n=e.result??{},r=Wi(n);if(r)return[`@${r}`,t];if(U(n.selector))return[Q(`target`),t];let i=Y(n.x),a=Y(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function Di(e){let t=+!!Mi(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],Q(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,Q(`text`)]:[...r,...e.positionals.slice(n).map(Ai)]:r}function Oi(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,Q(`text`)]:e.positionals.map(Z)}function ki(e,t,n){let[r,i,...a]=e.positionals;return[...r?[Q(t)]:[],...i?[Q(n)]:[],...a.map(Z)]}function Ai(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:Z(e)}function Z(e){return ji(e)??Q(`arg`)}function ji(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function Q(e){return`<${e}>`}function Mi(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function Ni(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const Pi={enums:[{source:`platform`,values:he},{source:`target`,values:ge}]},Fi={[p.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:be}]},[p.click]:Li(),[p.press]:Li(),[p.longPress]:Li(),[p.fill]:Ri(),[p.type]:Ri(),[p.scroll]:{booleans:[{source:`settle`}],numbers:[{source:`pixels`},{source:`durationMs`},{source:`settleQuietMs`}]},[p.gesture]:zi(),[p.swipe]:zi(),[p.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[p.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[p.back]:{booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}],enums:[{source:`backMode`,output:`mode`,values:ne}]},[p.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:_e}]},[p.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[p.boot]:{booleans:[{source:`headless`}]},[p.close]:{booleans:[{source:`shutdown`}]}};function Ii(e){let t=e.flags??{},n={},r=Object.hasOwn(Fi,e.command)?Fi[e.command]:void 0;return Bi(n,t,Pi),Bi(n,t,r),Object.keys(n).length>0?n:void 0}function Li(){return{booleans:[{source:`doubleTap`},{source:`settle`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`},{source:`settleQuietMs`}],enums:[{source:`clickButton`,values:ee}]}}function Ri(){return{booleans:[{source:`settle`}],numbers:[{source:`delayMs`},{source:`settleQuietMs`}]}}function zi(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:r}]}}function Bi(e,t,n){n&&(Vi(e,t,n.booleans??[]),Hi(e,t,n.numbers??[]),Ui(e,t,n.enums??[]))}function Vi(e,t,n){for(let r of n)Gi(e,r.output??r.source,t[r.source])}function Hi(e,t,n){for(let r of n)Ki(e,r.output??r.source,t[r.source])}function Ui(e,t,n){for(let r of n)qi(e,r.output??r.source,t[r.source],r.values)}function Wi(e){let t=U(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function Gi(e,t,n){typeof n==`boolean`&&(e[t]=n)}function Ki(e,t,n){let r=Y(n);r!==void 0&&(e[t]=r)}function qi(e,t,n,r){let i=G(n,r);i!==void 0&&(e[t]=i)}const $=new Map,Ji=new Set;function Yi(e){return g.join(e,`events.ndjson`)}function Xi(e){return e.command!==p.events}function Zi(t,n,r){let i=e({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});$i(t,`${JSON.stringify(i)}\n`)}async function Qi(e){await(e?$.get(e):Promise.all($.values()))}function $i(e,t){let n=($.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await ea(e),await _.promises.appendFile(e,t,`utf8`)}).catch(t=>{m({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{$.get(e)===n&&$.delete(e)});$.set(e,n)}async function ea(e){let t=g.dirname(e);if(!Ji.has(t))try{await _.promises.mkdir(t,{recursive:!0}),Ji.add(t)}catch(t){throw m({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function ta(e,t,n){Zi(e,t,{kind:`action.recorded`,requestId:h().requestId,command:n.command,summary:hi(n),details:gi(n)})}function na(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??h().requestId,command:t.command,summary:`Started ${t.command}`}}function ra(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=Cr(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??h().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??h().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function ia(e,t={}){let n=la(t.cursor),r=ua(t.limit);if(!_.existsSync(e))return{path:e,cursor:String(n),limit:r,events:[]};let i=aa(e,n,r),a=i.lines.flatMap(e=>{let t=da(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:a,...i.nextCursor===void 0?{}:{nextCursor:String(i.nextCursor)}}}function aa(e,t,n){let r=_.openSync(e,`r`);try{let e=new Ae(`utf8`),i=Buffer.allocUnsafe(65536),a=oa(t,n),o=``,s=0;do{s=_.readSync(r,i,0,i.length,null);let t=e.write(i.subarray(0,s));o=sa(`${o}${t}`,a)}while(s>0&&a.nextCursor===void 0);let c=`${o}${e.end()}`;return a.nextCursor===void 0&&c.length>0&&ca(c,a),{lines:a.lines,nextCursor:a.nextCursor}}finally{_.closeSync(r)}}function oa(e,t){return{cursor:e,limit:t,lineIndex:0,lines:[]}}function sa(e,t){let n=0;for(let r=e.indexOf(`
|
|
3
3
|
`);r!==-1;r=e.indexOf(`
|
|
4
|
-
`,n))if(
|
|
4
|
+
`,n))if(ca(e.slice(n,r),t),n=r+1,t.nextCursor!==void 0)return``;return e.slice(n)}function ca(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0){if(t.lineIndex>=t.cursor+t.limit){t.nextCursor=t.cursor+t.limit;return}t.lineIndex>=t.cursor&&t.lines.push(n),t.lineIndex+=1}}function la(e){if(e===void 0||e.trim()===``)return 0;let n=Number(e);if(Number.isInteger(n)&&n>=0)return n;throw new t(`INVALID_ARGS`,`events cursor must be a non-negative integer string.`)}function ua(e){if(e===void 0||typeof e==`string`&&e.trim()===``)return 100;let n=typeof e==`string`?Number(e):e;if(Number.isInteger(n)&&n>=1&&n<=500)return n;throw new t(`INVALID_ARGS`,`events limit must be between 1 and 500.`)}function da(e){try{let t=fa(JSON.parse(e));return t?pa(t):void 0}catch{return}}function fa(e){if(d(e)&&e.version===1&&!(typeof e.ts!=`string`||typeof e.session!=`string`)&&ma(e.kind))return e}function pa(e){let t=d(e.details)?e.details:void 0;return{version:1,ts:e.ts,session:e.session,kind:e.kind,...typeof e.requestId==`string`?{requestId:e.requestId}:{},...typeof e.command==`string`?{command:e.command}:{},...ha(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function ma(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function ha(e){return e===`ok`||e===`error`}const ga=60*6e4;var _a=class{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new $n(e)}get(e){return this.sessions.get(e)}set(e,t){this.sessions.set(e,t)}delete(e){return this.runtimeHints.delete(e),this.sessions.delete(e)}values(){return this.sessions.values()}toArray(){return Array.from(this.sessions.values())}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){this.runtimeHints.set(e,t)}clearRuntimeHints(e){return this.runtimeHints.delete(e)}recordAction(e,t){let n=Pn(e,t);if(n){let t=this.resolveStoredSessionName(e);ta(this.resolveEventLogPath(t),t,n)}}recordEvent(e,t){Zi(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return ia(this.resolveEventLogPath(e),t)}async flushEvents(e){await Qi(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.scriptWriter.write(e,t);return n.written&&m({level:`info`,phase:`session_script_written`,data:{session:e.name,path:n.path}}),n}finalizeRepairTeardown(e){this.recordRepairFinalizeCloseIfCommitting(e);let t=this.writeSessionLog(e,{force:on(e,void 0)});hn(e)&&(!t.written&&t.error?this.writeRepairTombstone(e,ga,{code:String(t.error.code),message:t.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){Ft(e.scriptPublication??D)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:e.name,...ye(`Closed: ${e.name}`)}})}writeRepairTombstone(e,t=ga,n){try{let r=this.resolveSessionDir(e.name);_.mkdirSync(r,{recursive:!0});let i={owner:e.name,reapedAt:Date.now(),expiresAt:Date.now()+t,...gn(e)?{sourcePath:gn(e)}:{},...n?{commitFailure:n}:{}};_.writeFileSync(this.repairTombstonePath(e.name),`${JSON.stringify(i)}\n`)}catch(t){m({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.name,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return va(this.repairTombstonePath(e))}clearRepairTombstone(e){try{_.rmSync(this.repairTombstonePath(e),{force:!0})}catch{}}repairTombstonePath(e){return g.join(this.resolveSessionDir(e),`repair-tombstone.json`)}defaultTracePath(e){let t=k(e.name),n=new Date().toISOString().replace(/[:.]/g,`-`);return g.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(e){return g.join(this.sessionsDir,k(e))}resolveDaemonStateDir(){return g.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return _.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return g.join(this.resolveSessionDir(e),`app.log`)}resolveAppLogPidPath(e){return g.join(this.resolveSessionDir(e),`app-log.pid`)}resolveEventLogPath(e){return Yi(this.resolveSessionDir(e))}static expandHome(e,t){return A(e,t)}resolveStoredSessionName(e){for(let[t,n]of this.sessions)if(n===e)return t;return e.name}};function va(e){let t;try{t=_.readFileSync(e,`utf8`)}catch{return}let n;try{n=JSON.parse(t)}catch{return}if(!(typeof n?.expiresAt!=`number`||n.expiresAt<=Date.now()))return n}function ya(e){let t;try{t=_.readdirSync(e,{withFileTypes:!0})}catch{return}for(let n of t){if(!n.isDirectory())continue;let t=va(g.join(e,n.name,`repair-tombstone.json`));if(t?.commitFailure)return{sessionName:n.name,tombstone:{...t,commitFailure:t.commitFailure}}}}function ba(e){return g.join(e,`runner.log`)}function xa(e,t){let n=k(t&&t.length>0?t:`unknown`);return g.join(e,`requests`,`${n}.ndjson`)}function Sa(e,t={}){let n=Ca(e,t);return{baseDir:n,infoPath:g.join(n,`daemon.json`),lockPath:g.join(n,`daemon.lock`),logPath:g.join(n,`daemon.log`),sessionsDir:g.join(n,`sessions`)}}function Ca(e,t){let n=(e??``).trim();return n?Ce(n,{env:t.env}):wa(t)}function wa(e={}){let t=g.join(we(`~`,{env:e.env}),`.agent-device`),n=e.projectRoot??re();return Ta(n)?g.join(t,`dev`,Ea(n)):t}function Ta(e){return _.existsSync(g.join(e,`package.json`))&&_.existsSync(g.join(e,`src`,`daemon.ts`))}function Ea(e){let t=Da(e),n=g.basename(t).replaceAll(/[^a-zA-Z0-9._-]+/g,`-`),r=ke.createHash(`sha1`).update(t).digest(`hex`).slice(0,12);return`${n||`agent-device`}-${r}`}function Da(e){try{return _.realpathSync.native(e)}catch{return g.resolve(e)}}function Oa(e){let t=(e??``).trim().toLowerCase();return t===`http`?`http`:t===`dual`?`dual`:`socket`}function ka(e){let t=(e??``).trim().toLowerCase();return t===`auto`?`auto`:t===`socket`?`socket`:t===`http`?`http`:`auto`}function Aa(e){return(e??``).trim().toLowerCase()===`tenant`?`tenant`:`none`}function ja(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}const Ma=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,Na=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,Pa=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`];function Fa(){let e=process.argv[1];return e?Ia(e):`unknown`}function Ia(e,t=re()){try{let n=g.resolve(t),r=[g.resolve(e)],i=new Set,a=[];for(;r.length>0;){let e=r.pop();if(!e||i.has(e))continue;i.add(e);let t=_.statSync(e);if(!t.isFile())continue;let o=g.relative(n,e)||e;a.push(`${o}:${t.size}:${Math.trunc(t.mtimeMs)}`);let s=_.readFileSync(e,`utf8`);for(let t of La(s)){let n=za(e,t);n&&r.push(n)}}let o=a.sort().join(`|`),s=ke.createHash(`sha1`).update(o).digest(`hex`);return`graph:${a.length}:${s}`}catch{return`unknown`}}function La(e){let t=new Set;return Ra(e,Ma,t),Ra(e,Na,t),[...t]}function Ra(e,t,n){t.lastIndex=0;let r=null;for(;(r=t.exec(e))!==null;){let e=r[1]?.trim();e?.startsWith(`.`)&&n.add(e)}}function za(e,t){let n=g.resolve(g.dirname(e),t),r=Ba(n);if(r)return r;for(let e of Pa){let t=Ba(`${n}${e}`);if(t)return t}for(let e of Pa){let t=Ba(g.join(n,`index${e}`));if(t)return t}return null}function Ba(e){try{return _.statSync(e).isFile()?e:null}catch{return null}}const Va=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])dist\/src\/internal\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function Ha(e){let t=e.toLowerCase().replaceAll(`\\`,`/`);return t.includes(`agent-device`)?Va.some(e=>e.test(t)):!1}function Ua(e,t){if(!Ee(e))return!1;if(t){let n=Oe(e);if(!n||n!==t)return!1}let n=De(e);return n?Ha(n):!1}function Wa(e,t){try{return process.kill(e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}async function Ga(e,t){Ua(e,t.expectedStartTime)&&Wa(e,`SIGTERM`)&&(await Te(e,t.termTimeoutMs)||Wa(e,`SIGKILL`)&&await Te(e,t.killTimeoutMs))}function Ka(e,t){let n=[],r=e+t.toString(),i=r.indexOf(`
|
|
5
5
|
`);for(;i!==-1;){let e=r.slice(0,i).trim();r=r.slice(i+1),e&&n.push(e),i=r.indexOf(`
|
|
6
|
-
`)}return{lines:n,buffer:r}}function
|
|
6
|
+
`)}return{lines:n,buffer:r}}function qa(e){return e.meta?.requestProgress===`replay-test`||e.meta?.requestProgress===`command`}function Ja(e){return!!e&&typeof e==`object`&&e.type===`progress`&&!!e.event}function Ya(e){return!!e&&typeof e==`object`&&e.type===`response`&&!!e.response}function Xa(e){return`${JSON.stringify({type:`progress`,event:e})}\n`}function Za(e){return`${JSON.stringify({type:`response`,response:e})}\n`}function Qa(e){return`${JSON.stringify({type:`response`,response:e})}\n`}function $a(e,t={}){return{ok:!0,service:e,version:te(),rpcProtocolVersion:2,...t.upstream===void 0?{}:{upstream:t.upstream}}}function eo(e){return{...typeof e.path==`string`?{path:e.path}:{},...typeof e.width==`number`?{width:e.width}:{},...typeof e.height==`number`?{height:e.height}:{},...typeof e.logicalWidth==`number`?{logicalWidth:e.logicalWidth}:{},...typeof e.logicalHeight==`number`?{logicalHeight:e.logicalHeight}:{},...typeof e.pixelDensity==`number`?{pixelDensity:e.pixelDensity}:{},...e.overlayRefs?{overlayRefs:e.overlayRefs}:{}}}function to(e){if(d(e))return eo({path:typeof e.path==`string`?e.path:void 0,width:typeof e.width==`number`?e.width:void 0,height:typeof e.height==`number`?e.height:void 0,logicalWidth:typeof e.logicalWidth==`number`?e.logicalWidth:void 0,logicalHeight:typeof e.logicalHeight==`number`?e.logicalHeight:void 0,pixelDensity:typeof e.pixelDensity==`number`?e.pixelDensity:void 0,overlayRefs:Array.isArray(e.overlayRefs)?e.overlayRefs.filter(ao).flatMap(e=>{let t=no(e);return t?[t]:[]}):void 0})}function no(e){if(typeof e.ref!=`string`||e.ref.length===0)return;let t=ro(e);if(t)return{ref:e.ref,...io(e),...t}}function ro(e){let t=oe(e.rect);if(!t)return;let n=oe(e.overlayRect);if(!n)return;let r=ie(e.center);return r?{rect:t,overlayRect:n,center:r}:void 0}function io(e){return typeof e.label==`string`&&e.label.length>0?{label:e.label}:{}}function ao(e){return d(e)}export{en as $,z as A,mn as B,xa as C,Ue as Ct,Xi as D,na as E,vn as F,ln as G,un as H,P as I,on as J,$t as K,fn as L,En as M,bn as N,Ti as O,yn as P,an as Q,cn as R,ya as S,$e as St,ra as T,Ie as Tt,dn as U,hn as V,N as W,sn as X,Zt as Y,rn as Z,Sa as _,St as _t,Ya as a,Yt as at,Aa as b,ot as bt,Qa as c,Mt as ct,Ua as d,wt as dt,nn as et,Ga as f,Dt as ft,ja as g,bt as gt,Fa as h,Et as ht,Ja as i,Xt as it,Rn as j,Kr as k,qa as l,At as lt,Ia as m,Ot as mt,to as n,k as nt,Xa as o,kt as ot,Wa as p,Tt as pt,Qt as q,$a as r,D as rt,Za as s,jt as st,eo as t,A as tt,Ka as u,Ct as ut,Oa as v,xt as vt,ba as w,x as wt,_a as x,st as xt,ka as y,rt as yt,pn as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_ as e,a as t}from"./sdk-contracts.js";import{gt as n,ht as r}from"./prepare-kind.js";import{t as i}from"./screenshot-result.js";import{n as a}from"./path-resolution.js";import{t as o}from"./shared.js";import{t as s}from"./cli-runner.js";const c=async({positionals:e,flags:n,client:r})=>{let a=await s({client:r,command:`screenshot`,positionals:e,flags:n});return t(n.responseLevel)?(o(n,a,()=>JSON.stringify(a,null,2)),!0):(o(n,i(a),()=>a.overlayRefs?`Annotated ${a.overlayRefs.length} refs onto ${a.path}`:d(a)),!0)},l=async({positionals:t,flags:i,client:c})=>{if(t[0]===`snapshot`){let e=await s({client:c,command:`diff`,positionals:t,flags:i});return o(i,e,()=>n(e)),!0}if(t[0]!==`screenshot`)return!1;let l=i.baseline;if(!l||typeof l!=`string`)throw new e(`INVALID_ARGS`,`diff screenshot requires --baseline <path>`);let d=a(l),f=typeof i.out==`string`?a(i.out):void 0,m=t[1];if(t.length>2)throw new e(`INVALID_ARGS`,`diff screenshot accepts at most one current screenshot path`);let[{createAgentDevice:h,localCommandPolicy:g},{createLocalArtifactAdapter:_}]=await Promise.all([import(`./runtime.js`).then(e=>e.r),import(`./sdk-io.js`).then(e=>e.n)]),v=await h({backend:u(c,i),artifacts:_(),sessions:{get:e=>({name:e}),set:()=>{}},policy:g()}).capture.diffScreenshot({session:i.session,baseline:{kind:`path`,path:d},current:m?{kind:`path`,path:a(m)}:{kind:`live`},...f?{out:{kind:`path`,path:f}}:{},threshold:p(i.threshold),overlayRefs:i.overlayRefs,normalizeStatusBar:i.screenshotNormalizeStatusBar,surface:i.surface});return o(i,v,()=>r(v)),!0};function u(e,t){return{platform:f(t),captureScreenshot:async(t,n,r)=>i(await e.capture.screenshot({path:n,session:t.session,overlayRefs:r?.overlayRefs,pixelDensity:r?.pixelDensity,fullscreen:r?.fullscreen,normalizeStatusBar:r?.normalizeStatusBar,stabilize:r?.stabilize,surface:r?.surface}))}}function d(e){if(typeof e.width!=`number`||typeof e.height!=`number`)return e.path;let t=typeof e.pixelDensity==`number`?` @${e.pixelDensity}x`:``;return`${e.path} (${e.width}x${e.height}${t})`}function f(e){switch(e.platform){case`android`:case`linux`:case`macos`:return e.platform;default:return`ios`}}function p(e){if(!(e==null||e===``))return Number(e)}export{l as diffCommand,c as screenshotCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{o as e}from"./png-worker-contract.js";import{E as t,_ as n}from"./sdk-contracts.js";import r from"node:path";import i from"node:crypto";import{AsyncLocalStorage as a}from"node:async_hooks";import o,{constants as s}from"node:fs";import c from"node:os";import{pipeline as l}from"node:stream/promises";import{Readable as u}from"node:stream";import{access as d,stat as f}from"node:fs/promises";import{spawn as p,spawnSync as m}from"node:child_process";const h=new a;function g(){return i.randomBytes(8).toString(`hex`)}function ee(){return`${Date.now().toString(36)}-${i.randomBytes(4).toString(`hex`)}`}async function te(e,t){let n={...e,diagnosticId:ee(),events:[],liveWrittenEventCount:0,phaseCounts:new Map,sensitiveValues:new Set};return await h.run(n,t)}function _(e){let t=h.getStore();t&&Object.assign(t,e)}function ne(){let e=h.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug,flushOnSuccess:e.flushOnSuccess}:{}}function re(e){e&&h.getStore()?.sensitiveValues.add(e)}function ie(e){let t=h.getStore();if(!t)return 0;let n=0;for(let r of e)n+=t.phaseCounts.get(r)??0;return n}function v(e){let t=h.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??`info`,phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?y(t,e.data):void 0};if(t.events.push(n),t.phaseCounts.set(e.phase,(t.phaseCounts.get(e.phase)??0)+1),!t.debug&&!t.traceLogPath)return;let r=`${JSON.stringify(n)}\n`;try{t.debug&&t.logPath&&(x(t.logPath,r),t.liveWrittenEventCount=t.events.length),t.traceLogPath&&x(t.traceLogPath,r),t.debug&&!t.logPath&&!t.traceLogPath&&process.stderr.write(`[agent-device][diag] ${r}`)}catch{}}async function ae(e,t,n){let r=Date.now();try{let i=await t();return v({level:`info`,phase:e,durationMs:Date.now()-r,data:n}),i}catch(t){throw v({level:`error`,phase:e,durationMs:Date.now()-r,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function oe(e={}){let t=h.getStore();if(!t||!e.force&&!t.debug&&!t.flushOnSuccess||t.events.length===0)return null;try{if(t.logPath){let e=t.events.slice(t.liveWrittenEventCount);if(e.length>0){let n=e.map(e=>JSON.stringify(y(t,e)));x(t.logPath,`${n.join(`
|
|
2
2
|
`)}\n`)}let n=t.logPath;return t.events=[],t.liveWrittenEventCount=0,n}let e=se(t.session??`default`),n=new Date().toISOString().slice(0,10),i=r.join(c.homedir(),`.agent-device`,`logs`,e,n);o.mkdirSync(i,{recursive:!0});let a=new Date().toISOString().replace(/[:.]/g,`-`),s=r.join(i,`${a}-${t.diagnosticId}.ndjson`),l=t.events.map(e=>JSON.stringify(y(t,e)));return o.writeFileSync(s,`${l.join(`
|
|
3
|
-
`)}\n`),t.events=[],s}catch{return null}}function y(e,n){return b(t(n),[...e.sensitiveValues].sort((e,t)=>t.length-e.length))}function b(e,t){return typeof e==`string`?t.reduce((e,t)=>e.replaceAll(t,`[REDACTED]`),e):Array.isArray(e)?e.map(e=>b(e,t)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,b(n,t)]))}function se(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function x(e,t){o.mkdirSync(r.dirname(e),{recursive:!0}),o.appendFileSync(e,t,`utf8`)}const ce=new Set([`1`,`true`,`yes`,`on`]),le=new Set([`0`,`false`,`no`,`off`]);function ue(e){return`AGENT_DEVICE_${e.replace(/([A-Z])/g,`_$1`).replace(/[^A-Za-z0-9_]/g,`_`).toUpperCase()}`}function de(e,t,r,i){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>de({...e,multiple:!1},t,r,i));if(e.type===`boolean`)return fe(t,r,i);if(e.type===`booleanOrString`){if(typeof t==`boolean`)return t;if(typeof t==`string`&&S(t)!==void 0)return S(t);if(typeof t==`string`&&t.trim().length>0)return t;throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected boolean or non-empty string.`)}if(e.type===`string`){if(typeof t==`string`&&t.trim().length>0)return t;throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected non-empty string.`)}if(e.type===`enum`){if(e.setValue!==void 0)return pe(e,t,r,i);if(typeof t!=`string`||!e.enumValues?.includes(t))throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected one of: ${e.enumValues?.join(`, `)}.`);return t}let a=typeof t==`number`?t:typeof t==`string`?Number(t):NaN;if(!Number.isFinite(a)||e.type===`int`&&!Number.isInteger(a))throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected ${e.type===`int`?`integer`:`number`}.`);if(typeof e.min==`number`&&a<e.min)throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Must be >= ${e.min}.`);if(typeof e.max==`number`&&a>e.max)throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Must be <= ${e.max}.`);return a}function fe(e,t,r){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=S(e);if(t!==void 0)return t}throw new n(`INVALID_ARGS`,`Invalid value for "${r}" in ${t}. Expected boolean.`)}function S(e){let t=e.trim().toLowerCase();if(ce.has(t))return!0;if(le.has(t))return!1}function pe(e,t,r,i){let a=e.setValue;if(t===a)return a;if(typeof t==`string`){let e=t.trim();if(e===``||e===`true`||e===`1`)return a;if(e===`false`||e===`0`)return}if(t===!0)return a;if(t!==!1)throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected boolean-like value for enum flag.`)}const me=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,he=[`.com`,`.exe`,`.bat`,`.cmd`],C=new a;async function ge(e,t){return e?await C.run(e,t):await t()}async function w(e){return await C.run(void 0,e)}async function T(e,t,n={}){let r=C.getStore()?.(e,t,n);return r?E(await r):await D(e,t,n)}async function _e(e,t,n={}){let r=C.getStore()?.(e,t,n);return r?E(await r):await D(e,t,n)}function E(e){let t=typeof e.stdout==`string`?e.stdout:String(e.stdout??``),n=typeof e.stderr==`string`?e.stderr:String(e.stderr??``),r=typeof e.exitCode==`number`?e.exitCode:1;return t===e.stdout&&n===e.stderr&&r===e.exitCode?e:{...e,stdout:t,stderr:n,exitCode:r}}function D(e,t,n={}){let r=M(e),i=A();return new Promise((a,o)=>{let s=p(r,t,{cwd:n.cwd,env:n.env,stdio:[`pipe`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});n.onSpawn?.(s);let c=``,l=n.binaryStdout?[]:void 0,u=``,d=!1,f=H(n.timeoutMs),m=f?setTimeout(()=>{d=!0,U(s,n.detached)},f):null,h=Me(s,n);n.binaryStdout||s.stdout.setEncoding(`utf8`),s.stderr.setEncoding(`utf8`),Ne(s,n.stdin).catch(i=>{h.didAbort||d||Pe(i)||(o(Te(r,e,t,i)),U(s,n.detached))}),s.stdout.on(`data`,e=>{if(n.binaryStdout){l?.push(Buffer.isBuffer(e)?e:Buffer.from(e));return}let t=String(e);c+=t,n.onStdoutChunk?.(t)}),s.stderr.on(`data`,e=>{let t=String(e);u+=t,n.onStderrChunk?.(t)}),s.on(`error`,n=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t),o(R(h,r,e,t,n))}),s.on(`close`,s=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t);let p=s??1;if(!h.didAbort&&d&&f){o(Ee(r,e,t,f,p,c,u));return}let g=z(h,r,e,t,p,n.allowFailure,c,u);if(g){o(g);return}a({stdout:c,stderr:u,exitCode:p,stdoutBuffer:l?Buffer.concat(l):void 0})})})}async function ve(e){let t=Oe(e);if(!t)return!1;if(r.isAbsolute(t))return V(t);let n=process.env.PATH;if(!n)return!1;let i=ke();for(let e of n.split(r.delimiter)){let n=e.trim();if(n){for(let e of Ae(t,i))if(await V(r.join(n,e)))return!0}}return!1}async function ye(e,t){let r=B(e,t,`executable`);if(r){if(!await V(r))throw new n(`TOOL_MISSING`,`${t} points to a missing or non-executable file: ${r}`,{envName:t,path:r});return r}}async function be(e,t){let r=B(e,t,`file`);if(r){if(!await je(r))throw new n(`TOOL_MISSING`,`${t} points to a missing or non-file path: ${r}`,{envName:t,path:r});return r}}function xe(e,t,r={}){let i=M(e),a=m(i,t,{cwd:r.cwd,env:r.env,stdio:[`pipe`,`pipe`,`pipe`],encoding:r.binaryStdout?void 0:`utf8`,input:r.stdin,timeout:H(r.timeoutMs),windowsHide:!0,shell:!1,...r.maxBuffer===void 0?{}:{maxBuffer:r.maxBuffer}});if(a.error){let o=a.error.code;throw o===`ETIMEDOUT`?new n(`COMMAND_FAILED`,`${i} timed out after ${H(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:H(r.timeoutMs)},a.error):o===`ENOENT`?N(i,e,a.error):P(i,e,t,a.error)}let o=r.binaryStdout?Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(a.stdout??``):void 0,s=r.binaryStdout?``:typeof a.stdout==`string`?a.stdout:(a.stdout??``).toString(),c=typeof a.stderr==`string`?a.stderr:(a.stderr??``).toString(),l=a.status??1;if(l!==0&&!r.allowFailure)throw I(i,e,t,l,s,c);return{stdout:s,stderr:c,exitCode:l,stdoutBuffer:o}}function Se(e,t,n={}){return O(e,t,n).pid}function O(e,t,n={}){let r=p(M(e),t,{cwd:n.cwd,env:n.env,stdio:n.stdio??`ignore`,detached:!0,windowsHide:!0,shell:!1}),i=r.pid??0,a=new Promise(e=>{r.once(`error`,t=>{e({pid:i,error:t.message})}),r.once(`exit`,(t,n)=>{e({pid:i,...typeof t==`number`?{exitCode:t}:{},...n?{signal:n}:{}})})});return r.unref(),{pid:i,exited:a}}function k(e,t,n={}){let r=M(e),i=A(),a=p(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??[`ignore`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});i.emitBackgroundSpawn(e,t);let o=``,s=``,c=n.captureOutput??!0,l=Me(a,n);return c&&(a.stdout?.setEncoding(`utf8`),a.stderr?.setEncoding(`utf8`),a.stdout?.on(`data`,e=>{o+=e}),a.stderr?.on(`data`,e=>{s+=e})),{child:a,wait:new Promise((c,u)=>{a.on(`error`,n=>{l.dispose(),i.emitBackgroundCompletion(e,t,`error`),u(R(l,r,e,t,n))}),a.on(`close`,a=>{l.dispose(),i.emitBackgroundCompletion(e,t,`exit`);let d=a??1,f=z(l,r,e,t,d,n.allowFailure,o,s);if(f){u(f);return}c({stdout:o,stderr:s,exitCode:d})})})}}function A(){let e=ne(),t=e.debug===!0,n=S(process.env.AGENT_DEVICE_EXEC_TRACE??``)===!0;if(!t&&!n)return Ce();n&&e.flushOnSuccess!==!0&&_({flushOnSuccess:!0});let r=Date.now(),i=!1;return{emitForegroundCompletion:(e,t)=>{i||(i=!0,j({cmd:e,args:t,startedAtMs:r}))},emitBackgroundSpawn:(e,t)=>{j({cmd:e,args:t,data:{event:`spawn`}})},emitBackgroundCompletion:(e,t,n)=>{i||(i=!0,j({cmd:e,args:t,startedAtMs:r,data:{event:n}}))}}}function Ce(){return{emitForegroundCompletion:()=>{},emitBackgroundSpawn:()=>{},emitBackgroundCompletion:()=>{}}}function j(e){let t=e.args.slice(0,6);v({level:`debug`,phase:`exec_command`,durationMs:e.startedAtMs===void 0?void 0:Math.max(0,Date.now()-e.startedAtMs),data:{command:e.cmd,argsPrefix:t,...e.args.length>t.length?{omittedArgCount:e.args.length-t.length}:{},...e.data??{}}})}function M(e){let t=Oe(e);if(!t)throw new n(`INVALID_ARGS`,`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e,hint:`Use a bare command name from PATH or an absolute executable path.`});return t}function we(e,t,n,r){return r.code===`ENOENT`?N(e,t,r):P(e,t,n,r)}function N(e,t,r){return new n(`TOOL_MISSING`,`${e} not found in PATH`,{cmd:t},r)}function P(e,t,r,i){return new n(`COMMAND_FAILED`,`Failed to run ${e}`,{cmd:t,args:r},i)}function Te(e,t,r,i){return new n(`COMMAND_FAILED`,`Failed to write stdin for ${e}`,{cmd:t,args:r},i instanceof Error?i:void 0)}function F(e,t,r){return new n(`COMMAND_FAILED`,`request canceled`,{cmd:t,args:r,executable:e,reason:`request_canceled`})}function Ee(e,t,r,i,a,o,s){return new n(`COMMAND_FAILED`,`${e} timed out after ${i}ms`,{cmd:t,args:r,stdout:o,stderr:s,exitCode:a,timeoutMs:i})}function I(e,t,r,i,a,o){return new n(`COMMAND_FAILED`,`${e} exited with code ${i}`,L({stdout:a,stderr:o,exitCode:i},{cmd:t,args:r}))}function De(e,t,r){if(e.exitCode===0)return e;throw new n(`COMMAND_FAILED`,t,L(e,typeof r==`function`?r(e):r))}function L(e,t){return{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,processExitError:!0,...t}}function R(e,t,n,r,i){return e.didAbort?F(t,n,r):we(t,n,r,i)}function z(e,t,n,r,i,a,o,s){return e.didAbort?F(t,n,r):i!==0&&!a?I(t,n,r,i,o,s):null}function B(e,t,i){let a=e?.trim();if(a){if(!r.isAbsolute(a)||a.includes(`\0`))throw new n(`INVALID_ARGS`,`${t} must be an absolute ${i} path, not ${JSON.stringify(e)}`,{envName:t,path:e});return a}}function Oe(e){let t=e.trim();return!t||t.includes(`\0`)?null:r.isAbsolute(t)?t:t.includes(`/`)||t.includes(`\\`)?null:me.test(t)?t:null}function ke(){if(process.platform!==`win32`)return[``];let e=process.env.PATHEXT;if(!e)return he;let t=e.split(`;`).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:he}function Ae(e,t){if(process.platform!==`win32`)return[e];let n=e.toLowerCase();return t.some(e=>n.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}async function V(e){try{return await je(e)?(await d(e,process.platform===`win32`?s.F_OK:s.X_OK),!0):!1}catch{return!1}}async function je(e){try{return(await f(e)).isFile()}catch{return!1}}function H(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function Me(e,t){let n=!1,r=()=>{n=!0,U(e,t.detached)};return t.signal?.aborted?r():t.signal?.addEventListener(`abort`,r,{once:!0}),{get didAbort(){return n},dispose:()=>{t.signal?.removeEventListener(`abort`,r)}}}function U(e,t){if(t&&e.pid&&process.platform!==`win32`)try{process.kill(-e.pid,`SIGKILL`);return}catch{}e.kill(`SIGKILL`)}async function Ne(e,t){if(e.stdin){if(t===void 0){e.stdin?.end();return}await l(u.from([t]),e.stdin)}}function Pe(e){return e instanceof Error&&`code`in e&&e.code===`EPIPE`}var Fe=e({androidAdbResultError:()=>K,attachAdbFailureHint:()=>G,classifyAdbFailure:()=>Re,createAndroidPortReverseManager:()=>qe,createDeviceAdbExecutor:()=>Y,createLocalAndroidAdbProvider:()=>We,installAndroidAdbPackage:()=>Ye,pullAndroidAdbFile:()=>Je,resolveAndroidAdbExecutor:()=>Ge,resolveAndroidAdbProvider:()=>X,resolveAndroidTextInjector:()=>Ke,resolveAndroidTouchProvider:()=>Z,withAndroidAdbProvider:()=>Ze});const W=new a,Ie=[{reason:`device_unauthorized`,pattern:/device unauthorized|device still authorizing/,hint:`USB debugging is not authorized — accept the authorization prompt on the device screen (re-plug the cable if none appears), then retry.`},{reason:`device_offline`,pattern:/device offline/,hint:`The device is connected but offline — wait for it to finish booting or run adb reconnect, then retry.`,retriable:!0},{reason:`multiple_devices`,pattern:/more than one (?:device\/emulator|device and emulator)/,hint:`Multiple Android devices are connected — pass --serial <serial> (see adb devices) to select one.`},{reason:`no_devices`,pattern:/no devices\/emulators found|no devices found/,hint:`No Android devices detected — boot an emulator or connect a device and verify it appears in adb devices.`},{reason:`device_not_found`,pattern:/device (?:'[^']*' )?not found/,hint:`The device disconnected or is restarting — verify it is listed in adb devices, then retry.`,retriable:!0},{reason:`server_version_mismatch`,pattern:/adb server version \(\d+\) doesn't match this client/,hint:`Multiple adb installs conflict — adb restarts its server automatically, so retry; align PATH to a single adb to stop recurrences.`,retriable:!0},{reason:`connection_dropped`,pattern:/transport error|connection reset|broken pipe|protocol fault/,hint:`The adb connection dropped — retry; if it persists, run adb kill-server and reconnect the device.`,retriable:!0},{reason:`install_insufficient_storage`,pattern:/install_failed_insufficient_storage/,hint:`The device is out of storage — free up space or uninstall unused apps, then retry the install.`,matchStdout:!0},{reason:`install_update_incompatible`,pattern:/install_failed_update_incompatible/,hint:`The installed app has an incompatible signature — uninstall the existing app first, then retry the install.`,matchStdout:!0},{reason:`install_version_downgrade`,pattern:/install_failed_version_downgrade/,hint:`The APK is older than the installed app — uninstall the app first (or install with downgrade allowed), then retry.`,matchStdout:!0},{reason:`install_failed`,pattern:/install_failed_\w+|install_parse_failed_\w+/,hint:`The Android package installer rejected the APK — see the INSTALL_FAILED code in the error output for the exact cause.`,matchStdout:!0}],Le={reason:`timeout`,hint:`adb timed out — the adb server may be wedged. Run adb kill-server && adb start-server, check adb devices, then retry.`};function Re(e,t=``){let n=e.toLowerCase(),r=t.toLowerCase();for(let{pattern:e,matchStdout:t,...i}of Ie)if(e.test(n)||t&&e.test(r))return i}function G(e){if(!(e instanceof n)||e.code!==`COMMAND_FAILED`)return e;let t=ze(e);return t&&(e.details={...e.details,adbFailure:t.reason,...typeof e.details?.hint==`string`?{}:{hint:t.hint},...t.retriable!==void 0&&e.details?.retriable===void 0?{retriable:t.retriable}:{}}),e}function ze(e){return typeof e.details?.timeoutMs==`number`?Le:Re(typeof e.details?.stderr==`string`?e.details.stderr:``,typeof e.details?.stdout==`string`?e.details.stdout:``)}function K(e,t,r){return G(new n(`COMMAND_FAILED`,e,t.exitCode===0?{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode,...r}:L(t,r)))}function q(e){return async(...t)=>{try{return await e(...t)}catch(e){throw G(e)}}}const Be=new WeakSet;function Ve(e){if(Be.has(e))return e;let t={...e,exec:q(J(e.exec)),...e.pull?{pull:q(J(e.pull))}:{},...e.install?{install:q(J(e.install))}:{},...e.installBundle?{installBundle:q(e.installBundle)}:{}};return Be.add(t),t}function J(e){return async(...t)=>E(await e(...t))}function Y(e){return He(e.id)}function He(e){return q(async(t,n)=>await w(async()=>await T(`adb`,[`-s`,e,...t],{...n,detached:process.platform!==`win32`})))}function Ue(e){return(t,n)=>{let r=k(`adb`,[`-s`,e,...t],{...n,allowFailure:!0,captureOutput:!1});return r.wait.catch(()=>{}),r.child}}function We(e){let t=Y(e);return{exec:t,spawn:Ue(e.id),reverse:tt(t),pull:async(e,n,r)=>await t([`pull`,e,n],r),install:async(e,n)=>{let{installArgs:r,execOptions:i}=$(n);return await t([`install`,...r,e],i)}}}function Ge(e,t){let n=W.getStore();return t||(n?.serial===e.id?n.provider.exec:Y(e))}function X(e,t){if(t)return Q(t);let n=W.getStore();return n?.serial===e.id?Q(n.provider):We(e)}function Ke(e){let t=W.getStore();return t?.serial===e.id?t.provider.text:void 0}function Z(e){let t=W.getStore();return t?.serial===e.id&&t.provider.touch?t.provider:void 0}function qe(e){let t=Q(e);if(t.reverse&&et.has(t.reverse))return t.reverse;let r=t.reverse??tt(t.exec),i=new Map,a={async ensure(e,t){let a=i.get(e.local);if(a&&a.ownerId!==e.ownerId)throw new n(`COMMAND_FAILED`,`Android port reverse ${e.local} is already owned by ${a.ownerId??`another session`}`,{current:a,requested:e});a?.remote!==e.remote&&(await r.ensure(e,t),i.set(e.local,{...e}))},async remove(e,t){if(!i.has(e)){await r.remove(e,t);return}await r.remove(e,t),i.delete(e)},async removeAllOwned(e,t){let n=[...i.values()].filter(t=>t.ownerId===e).map(e=>e.local);if(n.length===0){await r.removeAllOwned(e,t);return}for(let e of n)await r.remove(e,t),i.delete(e)},async list(e){return r.list?await r.list(e):[...i.values()]}};return et.add(a),a}function Q(e){return Ve(typeof e==`function`?{exec:e}:e)}async function Je(e,t,r){let{device:i,provider:a,...o}=r??{},s=Xe(i,a),c=s?.pull;if(c)return await w(async()=>await c(e,t,o));let l=s?.exec;if(!l)throw new n(`COMMAND_FAILED`,`Android adb pull requires an adb provider`);return await w(async()=>await l([`pull`,e,t],o))}async function Ye(e,t){let{device:r,provider:i,...a}=t??{},o=Xe(r,i),s=o?.install;if(s)return await w(async()=>await s(e,a));let c=o?.exec;if(!c)throw new n(`COMMAND_FAILED`,`Android adb install requires an adb provider`);let{installArgs:l,execOptions:u}=$(a);return await w(async()=>await c([`install`,...l,e],u))}function Xe(e,t){if(t)return Q(t);if(e)return X(e);let n=W.getStore();if(n)return Q(n.provider)}async function Ze(e,t,n){if(!e)return await n();let r={provider:Q(e),serial:t.serial},i=Qe(r);return await W.run(r,async()=>await ge(i,n))}function Qe(e){return(t,n,r)=>{if(t!==`adb`)return;let i=$e(n,e.serial);if(i)return w(async()=>await e.provider.exec(i,r))}}function $e(e,t){if(!(e[0]!==`-s`||!e[1])&&e[1]===t)return e.slice(2)}const et=new WeakSet;function tt(e){let t=new Map;return{async ensure(n,r){if(await e([`reverse`,n.local,n.remote],{allowFailure:!1,signal:r?.signal,timeoutMs:r?.timeoutMs}),n.ownerId){let e=t.get(n.ownerId)??new Set;e.add(n.local),t.set(n.ownerId,e)}},async remove(n,r){let i=await e([`reverse`,`--remove`,n],{allowFailure:!0,signal:r?.signal,timeoutMs:r?.timeoutMs});if(i.exitCode!==0&&!rt(i.stdout,i.stderr))throw K(`Failed to remove Android port reverse ${n}`,i,{local:n});for(let e of t.values())e.delete(n)},async removeAllOwned(e,n){let r=[...t.get(e)??[]];for(let e of r)await this.remove(e,n);t.delete(e)},async list(n){let r=await e([`reverse`,`--list`],{allowFailure:!0,signal:n?.signal,timeoutMs:n?.timeoutMs});return r.exitCode===0?nt(r.stdout,t):[]}}}function nt(e,t){let n=new Map;for(let[e,r]of t)for(let t of r)n.set(t,e);return e.split(`
|
|
4
|
-
`).map(e=>e.trim().split(/\s+/)).filter(e=>e.length>=3).map(([,e,t])=>{let r=e;return{local:r,remote:t,ownerId:n.get(r)}})}function
|
|
3
|
+
`)}\n`),t.events=[],s}catch{return null}}function y(e,n){return b(t(n),[...e.sensitiveValues].sort((e,t)=>t.length-e.length))}function b(e,t){return typeof e==`string`?t.reduce((e,t)=>e.replaceAll(t,`[REDACTED]`),e):Array.isArray(e)?e.map(e=>b(e,t)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,b(n,t)]))}function se(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function x(e,t){o.mkdirSync(r.dirname(e),{recursive:!0}),o.appendFileSync(e,t,`utf8`)}const ce=new Set([`1`,`true`,`yes`,`on`]),le=new Set([`0`,`false`,`no`,`off`]);function ue(e){return`AGENT_DEVICE_${e.replace(/([A-Z])/g,`_$1`).replace(/[^A-Za-z0-9_]/g,`_`).toUpperCase()}`}function de(e,t,r,i){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>de({...e,multiple:!1},t,r,i));if(e.type===`boolean`)return fe(t,r,i);if(e.type===`booleanOrString`){if(typeof t==`boolean`)return t;if(typeof t==`string`&&S(t)!==void 0)return S(t);if(typeof t==`string`&&t.trim().length>0)return t;throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected boolean or non-empty string.`)}if(e.type===`string`){if(typeof t==`string`&&t.trim().length>0)return t;throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected non-empty string.`)}if(e.type===`enum`){if(e.setValue!==void 0)return pe(e,t,r,i);if(typeof t!=`string`||!e.enumValues?.includes(t))throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected one of: ${e.enumValues?.join(`, `)}.`);return t}let a=typeof t==`number`?t:typeof t==`string`?Number(t):NaN;if(!Number.isFinite(a)||e.type===`int`&&!Number.isInteger(a))throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected ${e.type===`int`?`integer`:`number`}.`);if(typeof e.min==`number`&&a<e.min)throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Must be >= ${e.min}.`);if(typeof e.max==`number`&&a>e.max)throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Must be <= ${e.max}.`);return a}function fe(e,t,r){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=S(e);if(t!==void 0)return t}throw new n(`INVALID_ARGS`,`Invalid value for "${r}" in ${t}. Expected boolean.`)}function S(e){let t=e.trim().toLowerCase();if(ce.has(t))return!0;if(le.has(t))return!1}function pe(e,t,r,i){let a=e.setValue;if(t===a)return a;if(typeof t==`string`){let e=t.trim();if(e===``||e===`true`||e===`1`)return a;if(e===`false`||e===`0`)return}if(t===!0)return a;if(t!==!1)throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected boolean-like value for enum flag.`)}const me=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,he=[`.com`,`.exe`,`.bat`,`.cmd`],C=new a;async function ge(e,t){return e?await C.run(e,t):await t()}async function w(e){return await C.run(void 0,e)}async function T(e,t,n={}){let r=C.getStore()?.(e,t,n);return r?E(await r):await D(e,t,n)}async function _e(e,t,n={}){let r=C.getStore()?.(e,t,n);return r?E(await r):await D(e,t,n)}function E(e){let t=typeof e.stdout==`string`?e.stdout:String(e.stdout??``),n=typeof e.stderr==`string`?e.stderr:String(e.stderr??``),r=typeof e.exitCode==`number`?e.exitCode:1;return t===e.stdout&&n===e.stderr&&r===e.exitCode?e:{...e,stdout:t,stderr:n,exitCode:r}}function D(e,t,n={}){let r=M(e),i=A();return new Promise((a,o)=>{let s=p(r,t,{cwd:n.cwd,env:n.env,stdio:[`pipe`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});n.onSpawn?.(s);let c=``,l=n.binaryStdout?[]:void 0,u=``,d=!1,f=H(n.timeoutMs),m=f?setTimeout(()=>{d=!0,U(s,n.detached)},f):null,h=Me(s,n);n.binaryStdout||s.stdout.setEncoding(`utf8`),s.stderr.setEncoding(`utf8`),Ne(s,n.stdin).catch(i=>{h.didAbort||d||Pe(i)||(o(Te(r,e,t,i)),U(s,n.detached))}),s.stdout.on(`data`,e=>{if(n.binaryStdout){l?.push(Buffer.isBuffer(e)?e:Buffer.from(e));return}let t=String(e);c+=t,n.onStdoutChunk?.(t)}),s.stderr.on(`data`,e=>{let t=String(e);u+=t,n.onStderrChunk?.(t)}),s.on(`error`,n=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t),o(R(h,r,e,t,n))}),s.on(`close`,s=>{m&&clearTimeout(m),h.dispose(),i.emitForegroundCompletion(e,t);let p=s??1;if(!h.didAbort&&d&&f){o(Ee(r,e,t,f,p,c,u));return}let g=z(h,r,e,t,p,n.allowFailure,c,u);if(g){o(g);return}a({stdout:c,stderr:u,exitCode:p,stdoutBuffer:l?Buffer.concat(l):void 0})})})}async function ve(e){let t=Oe(e);if(!t)return!1;if(r.isAbsolute(t))return V(t);let n=process.env.PATH;if(!n)return!1;let i=ke();for(let e of n.split(r.delimiter)){let n=e.trim();if(n){for(let e of Ae(t,i))if(await V(r.join(n,e)))return!0}}return!1}async function ye(e,t){let r=B(e,t,`executable`);if(r){if(!await V(r))throw new n(`TOOL_MISSING`,`${t} points to a missing or non-executable file: ${r}`,{envName:t,path:r});return r}}async function be(e,t){let r=B(e,t,`file`);if(r){if(!await je(r))throw new n(`TOOL_MISSING`,`${t} points to a missing or non-file path: ${r}`,{envName:t,path:r});return r}}function xe(e,t,r={}){let i=M(e),a=m(i,t,{cwd:r.cwd,env:r.env,stdio:[`pipe`,`pipe`,`pipe`],encoding:r.binaryStdout?void 0:`utf8`,input:r.stdin,timeout:H(r.timeoutMs),windowsHide:!0,shell:!1,...r.maxBuffer===void 0?{}:{maxBuffer:r.maxBuffer}});if(a.error){let o=a.error.code;throw o===`ETIMEDOUT`?new n(`COMMAND_FAILED`,`${i} timed out after ${H(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:H(r.timeoutMs)},a.error):o===`ENOENT`?N(i,e,a.error):P(i,e,t,a.error)}let o=r.binaryStdout?Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(a.stdout??``):void 0,s=r.binaryStdout?``:typeof a.stdout==`string`?a.stdout:(a.stdout??``).toString(),c=typeof a.stderr==`string`?a.stderr:(a.stderr??``).toString(),l=a.status??1;if(l!==0&&!r.allowFailure)throw I(i,e,t,l,s,c);return{stdout:s,stderr:c,exitCode:l,stdoutBuffer:o}}function Se(e,t,n={}){return O(e,t,n).pid}function O(e,t,n={}){let r=p(M(e),t,{cwd:n.cwd,env:n.env,stdio:n.stdio??`ignore`,detached:!0,windowsHide:!0,shell:!1}),i=r.pid??0,a=new Promise(e=>{r.once(`error`,t=>{e({pid:i,error:t.message})}),r.once(`exit`,(t,n)=>{e({pid:i,...typeof t==`number`?{exitCode:t}:{},...n?{signal:n}:{}})})});return r.unref(),{pid:i,exited:a}}function k(e,t,n={}){let r=M(e),i=A(),a=p(r,t,{cwd:n.cwd,env:n.env,stdio:n.stdio??[`ignore`,`pipe`,`pipe`],detached:n.detached,windowsHide:!0,shell:!1});i.emitBackgroundSpawn(e,t);let o=``,s=``,c=n.captureOutput??!0,l=Me(a,n);return c&&(a.stdout?.setEncoding(`utf8`),a.stderr?.setEncoding(`utf8`),a.stdout?.on(`data`,e=>{o+=e}),a.stderr?.on(`data`,e=>{s+=e})),{child:a,wait:new Promise((c,u)=>{a.on(`error`,n=>{l.dispose(),i.emitBackgroundCompletion(e,t,`error`),u(R(l,r,e,t,n))}),a.on(`close`,a=>{l.dispose(),i.emitBackgroundCompletion(e,t,`exit`);let d=a??1,f=z(l,r,e,t,d,n.allowFailure,o,s);if(f){u(f);return}c({stdout:o,stderr:s,exitCode:d})})})}}function A(){let e=ne(),t=e.debug===!0,n=S(process.env.AGENT_DEVICE_EXEC_TRACE??``)===!0;if(!t&&!n)return Ce();n&&e.flushOnSuccess!==!0&&_({flushOnSuccess:!0});let r=Date.now(),i=!1;return{emitForegroundCompletion:(e,t)=>{i||(i=!0,j({cmd:e,args:t,startedAtMs:r}))},emitBackgroundSpawn:(e,t)=>{j({cmd:e,args:t,data:{event:`spawn`}})},emitBackgroundCompletion:(e,t,n)=>{i||(i=!0,j({cmd:e,args:t,startedAtMs:r,data:{event:n}}))}}}function Ce(){return{emitForegroundCompletion:()=>{},emitBackgroundSpawn:()=>{},emitBackgroundCompletion:()=>{}}}function j(e){let t=e.args.slice(0,6);v({level:`debug`,phase:`exec_command`,durationMs:e.startedAtMs===void 0?void 0:Math.max(0,Date.now()-e.startedAtMs),data:{command:e.cmd,argsPrefix:t,...e.args.length>t.length?{omittedArgCount:e.args.length-t.length}:{},...e.data??{}}})}function M(e){let t=Oe(e);if(!t)throw new n(`INVALID_ARGS`,`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e,hint:`Use a bare command name from PATH or an absolute executable path.`});return t}function we(e,t,n,r){return r.code===`ENOENT`?N(e,t,r):P(e,t,n,r)}function N(e,t,r){return new n(`TOOL_MISSING`,`${e} not found in PATH`,{cmd:t},r)}function P(e,t,r,i){return new n(`COMMAND_FAILED`,`Failed to run ${e}`,{cmd:t,args:r},i)}function Te(e,t,r,i){return new n(`COMMAND_FAILED`,`Failed to write stdin for ${e}`,{cmd:t,args:r},i instanceof Error?i:void 0)}function F(e,t,r){return new n(`COMMAND_FAILED`,`request canceled`,{cmd:t,args:r,executable:e,reason:`request_canceled`})}function Ee(e,t,r,i,a,o,s){return new n(`COMMAND_FAILED`,`${e} timed out after ${i}ms`,{cmd:t,args:r,stdout:o,stderr:s,exitCode:a,timeoutMs:i})}function I(e,t,r,i,a,o){return new n(`COMMAND_FAILED`,`${e} exited with code ${i}`,L({stdout:a,stderr:o,exitCode:i},{cmd:t,args:r}))}function De(e,t,r){if(e.exitCode===0)return e;throw new n(`COMMAND_FAILED`,t,L(e,typeof r==`function`?r(e):r))}function L(e,t){return{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,processExitError:!0,...t}}function R(e,t,n,r,i){return e.didAbort?F(t,n,r):we(t,n,r,i)}function z(e,t,n,r,i,a,o,s){return e.didAbort?F(t,n,r):i!==0&&!a?I(t,n,r,i,o,s):null}function B(e,t,i){let a=e?.trim();if(a){if(!r.isAbsolute(a)||a.includes(`\0`))throw new n(`INVALID_ARGS`,`${t} must be an absolute ${i} path, not ${JSON.stringify(e)}`,{envName:t,path:e});return a}}function Oe(e){let t=e.trim();return!t||t.includes(`\0`)?null:r.isAbsolute(t)?t:t.includes(`/`)||t.includes(`\\`)?null:me.test(t)?t:null}function ke(){if(process.platform!==`win32`)return[``];let e=process.env.PATHEXT;if(!e)return he;let t=e.split(`;`).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:he}function Ae(e,t){if(process.platform!==`win32`)return[e];let n=e.toLowerCase();return t.some(e=>n.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}async function V(e){try{return await je(e)?(await d(e,process.platform===`win32`?s.F_OK:s.X_OK),!0):!1}catch{return!1}}async function je(e){try{return(await f(e)).isFile()}catch{return!1}}function H(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function Me(e,t){let n=!1,r=()=>{n=!0,U(e,t.detached)};return t.signal?.aborted?r():t.signal?.addEventListener(`abort`,r,{once:!0}),{get didAbort(){return n},dispose:()=>{t.signal?.removeEventListener(`abort`,r)}}}function U(e,t){if(t&&e.pid&&process.platform!==`win32`)try{process.kill(-e.pid,`SIGKILL`);return}catch{}e.kill(`SIGKILL`)}async function Ne(e,t){if(e.stdin){if(t===void 0){e.stdin?.end();return}await l(u.from([t]),e.stdin)}}function Pe(e){return e instanceof Error&&`code`in e&&e.code===`EPIPE`}var Fe=e({androidAdbResultError:()=>K,attachAdbFailureHint:()=>G,classifyAdbFailure:()=>Re,createAndroidPortReverseManager:()=>Ye,createDeviceAdbExecutor:()=>Y,createLocalAndroidAdbProvider:()=>We,installAndroidAdbPackage:()=>Xe,pullAndroidAdbFile:()=>Q,resolveAndroidAdbExecutor:()=>Ge,resolveAndroidAdbProvider:()=>X,resolveAndroidTextInjector:()=>qe,resolveAndroidTouchProvider:()=>Je,resolveScopedAndroidAdbBackgroundTransport:()=>Ke,withAndroidAdbProvider:()=>Qe});const Ie=[{reason:`device_unauthorized`,pattern:/device unauthorized|device still authorizing/,hint:`USB debugging is not authorized — accept the authorization prompt on the device screen (re-plug the cable if none appears), then retry.`},{reason:`device_offline`,pattern:/device offline/,hint:`The device is connected but offline — wait for it to finish booting or run adb reconnect, then retry.`,retriable:!0},{reason:`multiple_devices`,pattern:/more than one (?:device\/emulator|device and emulator)/,hint:`Multiple Android devices are connected — pass --serial <serial> (see adb devices) to select one.`},{reason:`no_devices`,pattern:/no devices\/emulators found|no devices found/,hint:`No Android devices detected — boot an emulator or connect a device and verify it appears in adb devices.`},{reason:`device_not_found`,pattern:/device (?:'[^']*' )?not found/,hint:`The device disconnected or is restarting — verify it is listed in adb devices, then retry.`,retriable:!0},{reason:`server_version_mismatch`,pattern:/adb server version \(\d+\) doesn't match this client/,hint:`Multiple adb installs conflict — adb restarts its server automatically, so retry; align PATH to a single adb to stop recurrences.`,retriable:!0},{reason:`connection_dropped`,pattern:/transport error|connection reset|broken pipe|protocol fault/,hint:`The adb connection dropped — retry; if it persists, run adb kill-server and reconnect the device.`,retriable:!0},{reason:`install_insufficient_storage`,pattern:/install_failed_insufficient_storage/,hint:`The device is out of storage — free up space or uninstall unused apps, then retry the install.`,matchStdout:!0},{reason:`install_update_incompatible`,pattern:/install_failed_update_incompatible/,hint:`The installed app has an incompatible signature — uninstall the existing app first, then retry the install.`,matchStdout:!0},{reason:`install_version_downgrade`,pattern:/install_failed_version_downgrade/,hint:`The APK is older than the installed app — uninstall the app first (or install with downgrade allowed), then retry.`,matchStdout:!0},{reason:`install_failed`,pattern:/install_failed_\w+|install_parse_failed_\w+/,hint:`The Android package installer rejected the APK — see the INSTALL_FAILED code in the error output for the exact cause.`,matchStdout:!0}],Le=Object.freeze({reason:`timeout`,hint:`adb timed out — the adb server may be wedged. Run adb kill-server && adb start-server, check adb devices, then retry.`});function Re(e,t=``){let n=e.toLowerCase(),r=t.toLowerCase();for(let{pattern:e,matchStdout:t,...i}of Ie)if(e.test(n)||t&&e.test(r))return i}const W=new a;function G(e){if(!(e instanceof n)||e.code!==`COMMAND_FAILED`)return e;let t=ze(e);return t&&(e.details={...e.details,adbFailure:t.reason,...typeof e.details?.hint==`string`?{}:{hint:t.hint},...t.retriable!==void 0&&e.details?.retriable===void 0?{retriable:t.retriable}:{}}),e}function ze(e){return typeof e.details?.timeoutMs==`number`?Le:Re(typeof e.details?.stderr==`string`?e.details.stderr:``,typeof e.details?.stdout==`string`?e.details.stdout:``)}function K(e,t,r){return G(new n(`COMMAND_FAILED`,e,t.exitCode===0?{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode,...r}:L(t,r)))}function q(e){return async(...t)=>{try{return await e(...t)}catch(e){throw G(e)}}}const Be=new WeakSet;function Ve(e){if(Be.has(e))return e;let t={...e,exec:q(J(e.exec)),...e.pull?{pull:q(J(e.pull))}:{},...e.install?{install:q(J(e.install))}:{},...e.installBundle?{installBundle:q(e.installBundle)}:{}};return Be.add(t),t}function J(e){return async(...t)=>E(await e(...t))}function Y(e){return He(e.id)}function He(e){return q(async(t,n)=>await w(async()=>await T(`adb`,[`-s`,e,...t],{...n,detached:process.platform!==`win32`})))}function Ue(e){return(t,n)=>{let r=k(`adb`,[`-s`,e,...t],{...n,allowFailure:!0,captureOutput:!1});return r.wait.catch(()=>{}),r.child}}function We(e){let t=Y(e);return{exec:t,spawn:Ue(e.id),reverse:nt(t),pull:async(e,n,r)=>await t([`pull`,e,n],r),install:async(e,n)=>{let{installArgs:r,execOptions:i}=$(n);return await t([`install`,...r,e],i)}}}function Ge(e,t){let n=W.getStore();return t||(n?.serial===e.id?n.provider.exec:Y(e))}function X(e,t){if(t)return Z(t);let n=W.getStore();return n?.serial===e.id?Z(n.provider):We(e)}function Ke(e){let t=W.getStore();return t?.serial===e.id?{mode:`transport-composed`,...t.provider.spawn?{spawn:t.provider.spawn}:{}}:{mode:`local`}}function qe(e){let t=W.getStore();return t?.serial===e.id?t.provider.text:void 0}function Je(e){let t=W.getStore();return t?.serial===e.id&&t.provider.touch?t.provider:void 0}function Ye(e){let t=Z(e);if(t.reverse&&tt.has(t.reverse))return t.reverse;let r=t.reverse??nt(t.exec),i=new Map,a={async ensure(e,t){let a=i.get(e.local);if(a&&a.ownerId!==e.ownerId)throw new n(`COMMAND_FAILED`,`Android port reverse ${e.local} is already owned by ${a.ownerId??`another session`}`,{current:a,requested:e});a?.remote!==e.remote&&(await r.ensure(e,t),i.set(e.local,{...e}))},async remove(e,t){if(!i.has(e)){await r.remove(e,t);return}await r.remove(e,t),i.delete(e)},async removeAllOwned(e,t){let n=[...i.values()].filter(t=>t.ownerId===e).map(e=>e.local);if(n.length===0){await r.removeAllOwned(e,t);return}for(let e of n)await r.remove(e,t),i.delete(e)},async list(e){return r.list?await r.list(e):[...i.values()]}};return tt.add(a),a}function Z(e){return Ve(typeof e==`function`?{exec:e}:e)}async function Q(e,t,r){let{device:i,provider:a,...o}=r??{},s=Ze(i,a),c=s?.pull;if(c)return await w(async()=>await c(e,t,o));let l=s?.exec;if(!l)throw new n(`COMMAND_FAILED`,`Android adb pull requires an adb provider`);return await w(async()=>await l([`pull`,e,t],o))}async function Xe(e,t){let{device:r,provider:i,...a}=t??{},o=Ze(r,i),s=o?.install;if(s)return await w(async()=>await s(e,a));let c=o?.exec;if(!c)throw new n(`COMMAND_FAILED`,`Android adb install requires an adb provider`);let{installArgs:l,execOptions:u}=$(a);return await w(async()=>await c([`install`,...l,e],u))}function Ze(e,t){if(t)return Z(t);if(e)return X(e);let n=W.getStore();if(n)return Z(n.provider)}async function Qe(e,t,n){if(!e)return await n();let r={provider:Z(e),serial:t.serial},i=$e(r);return await W.run(r,async()=>await ge(i,n))}function $e(e){return(t,n,r)=>{if(t!==`adb`)return;let i=et(n,e.serial);if(i)return w(async()=>await e.provider.exec(i,r))}}function et(e,t){if(!(e[0]!==`-s`||!e[1])&&e[1]===t)return e.slice(2)}const tt=new WeakSet;function nt(e){let t=new Map;return{async ensure(n,r){if(await e([`reverse`,n.local,n.remote],{allowFailure:!1,signal:r?.signal,timeoutMs:r?.timeoutMs}),n.ownerId){let e=t.get(n.ownerId)??new Set;e.add(n.local),t.set(n.ownerId,e)}},async remove(n,r){let i=await e([`reverse`,`--remove`,n],{allowFailure:!0,signal:r?.signal,timeoutMs:r?.timeoutMs});if(i.exitCode!==0&&!it(i.stdout,i.stderr))throw K(`Failed to remove Android port reverse ${n}`,i,{local:n});for(let e of t.values())e.delete(n)},async removeAllOwned(e,n){let r=[...t.get(e)??[]];for(let e of r)await this.remove(e,n);t.delete(e)},async list(n){let r=await e([`reverse`,`--list`],{allowFailure:!0,signal:n?.signal,timeoutMs:n?.timeoutMs});return r.exitCode===0?rt(r.stdout,t):[]}}}function rt(e,t){let n=new Map;for(let[e,r]of t)for(let t of r)n.set(t,e);return e.split(`
|
|
4
|
+
`).map(e=>e.trim().split(/\s+/)).filter(e=>e.length>=3).map(([,e,t])=>{let r=e;return{local:r,remote:t,ownerId:n.get(r)}})}function it(e,t){let n=`${e}\n${t}`.toLowerCase();return n.includes(`listener`)&&n.includes(`not found`)}function $(e){let{replace:t,allowTestPackages:n,allowDowngrade:r,grantPermissions:i,...a}=e??{},o=[];return t&&o.push(`-r`),n&&o.push(`-t`),r&&o.push(`-d`),i&&o.push(`-g`),{installArgs:o,execOptions:a}}export{v as A,ve as C,de as D,S as E,ae as F,te as I,ne as M,re as N,ie as O,_ as P,xe as S,ue as T,T as _,Q as a,O as b,qe as c,E as d,L as f,be as g,ye as h,Xe as i,oe as j,g as k,Je as l,De as m,K as n,Ge as o,V as p,Ye as r,X as s,Fe as t,Qe as u,k as v,w,_e as x,Se as y};
|