agent-device 0.20.4 → 0.20.6
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 +2 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.4.apk → agent-device-android-ime-helper-0.20.6.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.6.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.4.manifest.json → agent-device-android-ime-helper-0.20.6.manifest.json} +4 -4
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.4.apk → agent-device-android-snapshot-helper-0.20.6.apk} +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.6.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.4.manifest.json → agent-device-android-snapshot-helper-0.20.6.manifest.json} +6 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +28 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h +1 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +41 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +298 -92
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +126 -187
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedTextEntry.h +32 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedTextEntry.m +212 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +118 -8
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +134 -27
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +23 -5
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +10 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LifecycleCacheTests.swift +0 -67
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +11 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +2 -22
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +48 -11
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotTraversalIdentityTests.swift +0 -20
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +177 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +105 -448
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryPolicyTests.swift +4 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +587 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +18 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.h +72 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerXCTestEventBridge.m +89 -0
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/android.js +1 -1
- package/dist/src/app-log-request-scope.js +1 -1
- package/dist/src/app-resolution.js +1 -1
- package/dist/src/apps.js +5 -5
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +34 -24
- package/dist/src/cli-runner.js +1 -1
- package/dist/src/cli.js +15 -15
- package/dist/src/command-metadata.js +1 -1
- package/dist/src/command-schema.js +3 -3
- package/dist/src/context.js +1 -1
- package/dist/src/debug-symbols.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/generic-settle.js +1 -0
- package/dist/src/generic.js +1 -1
- package/dist/src/ime-lifecycle.js +3 -3
- package/dist/src/index.d.ts +27 -7
- package/dist/src/input-actions.js +4 -4
- package/dist/src/interaction-runtime.js +1 -0
- package/dist/src/interaction-snapshot.js +1 -1
- package/dist/src/interaction-touch-reference-frame.js +1 -0
- 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 +15 -15
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun.d.ts +23 -2
- package/dist/src/linux.js +1 -1
- package/dist/src/process-exit.js +1 -0
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/register-builtins.js +1 -1
- package/dist/src/registry.js +25 -24
- package/dist/src/remote-config.js +1 -1
- package/dist/src/remote-config2.js +1 -1
- package/dist/src/reporting.js +2 -2
- 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 +3 -3
- package/dist/src/screenshot-geometry.js +1 -1
- package/dist/src/screenshot-result.js +4 -4
- package/dist/src/sdk-android-adb.d.ts +20 -2
- package/dist/src/sdk-android-adb.js +1 -1
- package/dist/src/sdk-batch-runner.js +3 -3
- package/dist/src/sdk-contracts.d.ts +17 -2
- package/dist/src/sdk-finders.d.ts +4 -20
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/{interaction.d.ts → sdk-selectors.d.ts} +98 -3
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selector-vocabulary.js +1 -1
- package/dist/src/selectors.d.ts +1 -46
- 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 +9 -8
- package/dist/src/snapshot2.js +1 -1
- package/dist/src/text-surface.js +1 -0
- package/dist/src/viewport-dimension.js +13 -12
- package/dist/src/web.js +1 -1
- package/package.json +42 -34
- package/server.json +3 -3
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.4.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.4.apk.sha256 +0 -1
- package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-resize.swift +0 -225
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{E as e,_ as t}from"./sdk-contracts.js";import{Ht as n,It as r,Pt as i,Vt as a,_n as o,rn as s}from"./viewport-dimension.js";import{F as c,J as l,W as ee,d as te}from"./screenshot-geometry.js";import{J as ne,O as re,S as ie,W as u,Y as ae,at as d,q as f}from"./sdk-batch-runner.js";import{h as oe,n as se,r as ce,t as le}from"./sdk-device.js";import{t as ue}from"./device.js";import{N as p,j as m}from"./sdk-android-adb.js";import{n as de,t as fe}from"./version.js";import{n as pe,t as me}from"./path-resolution.js";import{a as he,n as ge,o as _e,u as ve}from"./host-process.js";import h from"node:path";import ye from"node:crypto";import{REPLAY_VAR_KEY_RE as be,appendScriptSeriesFlags as g,formatPortableActionLine as xe,formatScriptArg as _,formatScriptStringLiteral as Se,formatTargetAnnotationLines as Ce,isClickLikeCommand as we,isTouchTargetCommand as Te,stripRecordedRefGeneration as v}from"@agent-device/ad-script";import y from"node:fs";import{StringDecoder as Ee}from"node:string_decoder";const b=1500;function De(e,t){e&&(e.snapshotDiagnostics??={samples:[]}).samples.push({...t,durationMs:Math.max(0,Math.round(t.durationMs))})}function Oe(e){let t=e?.snapshotDiagnostics?.samples;if(!(!t||t.length===0))return ke(t)}function ke(e){if(e.length===0)return;let t=Me(e);return{stats:t,...t.p95Ms>=b?{warning:Ie(t)}:{}}}function Ae(e){let t=e.flatMap(e=>Ve(e?.stats));if(t.length===0)return;let n=Me(t);return{stats:n,...n.p95Ms>=b?{warning:Ie(n)}:{}}}function je(e){if(!d(e))return;let t=Le(e.stats);if(!t)return;let n=typeof e.warning==`string`?e.warning:void 0;return{stats:t,...n?{warning:n}:{}}}function Me(e){let t=e.map(e=>e.durationMs).sort((e,t)=>e-t);return{count:t.length,p50Ms:Ne(t,50),p95Ms:Ne(t,95),maxMs:t[t.length-1]??0,slowThresholdMs:b,...Pe(e),...Fe(e)}}function Ne(e,t){if(e.length===0)return 0;let n=Math.max(0,Math.ceil(t/100*e.length)-1);return e[Math.min(n,e.length-1)]??0}function Pe(e){let t=e.map(e=>e.platform).filter(e=>!!e);return new Set(t).size===1?{platform:t[0]}:{}}function Fe(e){let t={};for(let n of e)n.backend&&(t[n.backend]=(t[n.backend]??0)+1);return Object.keys(t).length>0?{backends:t}:{}}function Ie(e){return`Warning: ${e.platform?`${e.platform} `:``}snapshots are slow in this run: p95 ${e.p95Ms}ms over ${e.count} captures. Possible causes: device load, app or dev server stuck, helper fallback, or stale daemon.`}function Le(e){if(!d(e))return;let t=Re(e);if(t)return{...t,...Be(e)}}function Re(e){let t={count:e.count,p50Ms:e.p50Ms,p95Ms:e.p95Ms,maxMs:e.maxMs,slowThresholdMs:e.slowThresholdMs};if(!Object.values(t).some(e=>typeof e!=`number`))return t}function ze(e){let t=Object.entries(e).filter(e=>typeof e[1]==`number`);return t.length>0?Object.fromEntries(t):void 0}function Be(e){let t=typeof e.platform==`string`?e.platform:void 0,n=d(e.backends)?ze(e.backends):void 0;return{...t?{platform:t}:{},...n?{backends:n}:{}}}function Ve(e){if(!e||e.count<=0)return[];let t=e.platform;return e.count===1?[{durationMs:e.maxMs,platform:t}]:e.count===2?[{durationMs:e.p50Ms,platform:t},{durationMs:e.maxMs,platform:t}]:[...Array.from({length:e.count-3},()=>({durationMs:e.p50Ms,platform:t})),{durationMs:e.p50Ms,platform:t},{durationMs:e.p95Ms,platform:t},{durationMs:e.maxMs,platform:t}]}const He=`/agent-device`,Ue=`x-agent-device-tenant`;function We(e){return Ge(e,He)}function Ge(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t.replace(/^\/+/,``),n).toString()}function Ke(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function qe(e){let t=e?.trim();return t?{[Ue]:t}:{}}const Je=`.webm`;function Ye(e){return e===`web`?Je:`.mp4`}function Xe(e,t){return h.extname(e)?e:`${e}${t}`}function Ze(e){return`./recording-${Date.now()}${Ye(e)}`}function Qe(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 $e(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 x={kind:`none`};function S(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 et(e){return e.kind===`repair`?{...e,status:`armed`}:e}function tt(e){return e.kind===`none`?void 0:e.target}function nt(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function rt(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function it(e){return{kind:`authoring`,status:`armed`,target:S(void 0,e)}}function at(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function ot(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function st(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:S(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function ct(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function lt(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function ut(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function dt(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function ft(e){return e.kind===`repair`?e.boundary:void 0}function pt(e){return e.kind===`repair`?e.sourcePath:void 0}function mt(e){return e.kind===`repair`&&e.status!==`committed`}function ht(e){let t=tt(e);return t?.kind===`explicit`?t.path:void 0}function gt(e){return tt(e)?.force===!0}function C(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function w(e,t){return pe(e,{cwd:t})}function T(e){return e?.scriptPublication??x}function _t(e){let t=T(e);return t.kind===`authoring`&&t.status===`armed`}function vt(e,t){e.recordSession=!0,e.scriptPublication=it({path:t.path===void 0?void 0:w(t.path),force:t.force===!0})}function yt(e){e.recordSession=!1,e.scriptPublication=at(T(e))}function bt(e,t){if(!t.saveScript)return;e.recordSession=!0;let n={path:typeof t.saveScript==`string`?w(t.saveScript):void 0,force:t.force===!0},r=T(e);if(r.kind===`repair`){e.scriptPublication=st(r,{requested:n,boundary:r.boundary,sourcePath:r.sourcePath});return}if(r.kind===`authoring`){e.scriptPublication={...r,target:S(r.target,n)};return}e.scriptPublication=it(n)}function xt(e,t){let n=T(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:S(n.target,{path:t.explicitPath===void 0?void 0:w(t.explicitPath),force:t.liveForce===!0})})}function St(e,t){e.scriptPublication=ot(T(e),t),e.recordSession=!1}function Ct(e,t){let n=T(e);n.kind===`authoring`&&(e.scriptPublication=ot(n,t))}function wt(e,t){return t===!0||gt(T(e))}function Tt(e){return rt(T(e))}function E(e){return e?.scriptPublication??x}function Et(e,t){e.recordSession=!0;let n=E(e);e.scriptPublication=st(n,{requested:{path:typeof t.saveScript==`string`?w(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function Dt(e){e.scriptPublication=et(E(e))}function Ot(e){e.scriptPublication=ct(E(e))}function kt(e,t){e.scriptPublication=lt(E(e),t)}function At(e){e.scriptPublication=dt(E(e))}function jt(e,t){let n=E(e);return n.kind===`repair`&&n.closeReceipt===t}function D(e){return E(e).kind===`repair`}function Mt(e){return mt(E(e))}function O(e){return ft(E(e))}function Nt(e){return pt(E(e))}function k(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 Pt=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function Ft(e){if(e!==e.trim()||!be.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 It(e){return`\${${e}}`}function Lt(e){let t=Pt.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}const Rt=new Set([`text`,`label`,`value`]),zt=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(`.`)),Bt=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),Vt=new Set([`cost`,`evidence`,`resolution`,`settle`]),Ht=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`])]]),Ut=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 Wt(e,t,n){if(!e)return e;let r=Zt(e.selectorChain);return{...qt(e,t,n),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!Kt(e,t))}:{}}}function Gt(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 Kt(e,t){return u(e)?.selectors.some(e=>e.terms.some(e=>Rt.has(e.key)&&typeof e.value==`string`&&j(e.value,t,``)!==e.value))??!1}function qt(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[zt.has(e)?e:j(e,t,n),Jt(r,e,t,n)]))}function Jt(e,t,n,r){return typeof e==`string`&&Bt.has(t)?e:t===`selectorChain`&&Xt(e)?Yt(e,n):A(e,n,r,Vt.has(t)?t:void 0)}function A(e,t,n,r){if(typeof e==`string`)return r&&Ut.has(r)?e:j(e,t,n);if(Array.isArray(e))return e.map(e=>A(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?Ht.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:j(e,t,n),A(a,t,n,o?`${r}.${e}`:void 0)]}))}function Yt(e,t){return e.filter(e=>!Kt(e,t))}function j(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 Xt(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Zt(e){return Xt(e)?e:void 0}function Qt(e,t){if(t.flags?.noRecord||rn(e,t))return;t.flags&&bt(e,t.flags);let n=$t(t),r={ts:Date.now(),command:n.command,positionals:n.positionals,runtime:n.runtime,flags:on(n.flags),result:n.result,...n.targetEvidence?{targetEvidence:n.targetEvidence}:{}};return e.actions.push(r),m({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),r}function $t(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return e;let t=It(Ft(e.flags.recordAs)),n=k({ts:0,command:e.command,positionals:e.positionals,flags:e.flags});return{...e,positionals:en(e.positionals,t),result:Wt(e.result,n,t),targetEvidence:Gt(e.targetEvidence,n,t)}}function en(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 tn=new Set([`snapshot`,`get`,`is`,`find`]);function nn(e){return e.internal?.replayPlanStep===!0?!1:tn.has(e.command)}function rn(e,t){return!t.interactiveObservation||O(e)===void 0?!1:t.flags?.record!==!0}const an=[`platform`,`device`,`udid`,`serial`,`out`,`verbose`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`,`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`,...o,`relaunch`,`saveScript`,`force`,`noRecord`,`record`,`fps`,`quality`,`hideTouches`,`count`,`pointerCount`,`intervalMs`,`delayMs`,`holdMs`,`jitterPx`,`doubleTap`,`clickButton`,`pauseMs`,`pattern`];function on(e){if(!e)return{};let t={};for(let n of an)e[n]!==void 0&&(t[n]=e[n]);return t}function sn(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())ie({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=t);if(!e.slice(r+1).some(un))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 cn(e){for(let n of e){let e=dn(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`&&ie(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||!u(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 ln(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 un(e){if(e.command!==`wait`)return!1;let t=re(e.positionals);return t?.kind!==`selector`||u(t.selectorExpression)===null?!1:e.targetEvidence?.verification===`verified`}function dn(e){if(e.command===`get`)return e.positionals[1];if(Te(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&fn(t)&&fn(n)?void 0:t}}function fn(e){return e.trim().length>0&&Number.isFinite(Number(e))}function pn(e){let t=e.scriptPublication??x;return t.kind===`repair`?t.status===`committed`?!0:!nt(t):!1}var mn=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=D(e),r=t?.publication===`active`,i;try{if(!e.recordSession||pn(e))return{written:!1};let a=hn(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=h.dirname(i);return y.existsSync(o)||y.mkdirSync(o,{recursive:!0}),vn({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=ut(e.scriptPublication??x)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return gn({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=ht(e.scriptPublication??x);if(t)return w(t);let n=C(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,`-`);return h.join(this.sessionsDir,`${n}-${r}.ad`)}};function hn(e,t){let n=yn(e,{strictPortableRefs:t.activePublication});return t.activePublication&&sn(n),{script:On(e,n,t.appendCompleteSentinel),actionCount:n.length}}function gn(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:_n(r,i)};if(o)return{written:!1,error:ln(r,i)};if(r instanceof t)throw r;return{written:!1}}function _n(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 vn(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`);y.writeFileSync(o,r);try{if(i){y.renameSync(o,n);return}y.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{y.rmSync(o,{force:!0})}}function yn(e,t={}){let n=O(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=xn(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&bn(n);let o=Dn(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&cn(a),a}function bn(e){if(!M(e.command))return;let n=e.command===`get`?e.positionals?.[1]:e.positionals?.[0];if(n?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot write recorded step "${e.command} ${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function xn(e){let t=Sn(e);if(!(!t||!M(e.command)))return we(e.command)?{...e,positionals:[t]}:e.command===`longpress`?wn(e,t):e.command===`fill`?Cn(e,t):Tn(e,t)}function Sn(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 M(e){return Te(e)||e===`fill`||e===`get`}function Cn(e,t){let n=k(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function wn(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):En(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Tn(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function En(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function Dn(e,t){if(!M(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 On(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${oe(e.device)} device=${Se(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...Ce(e)),r.push(kn(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
|
|
2
|
-
`)}\n`}function kn(e){return An([e.command],e)||xe(e)}function An(e,t){if(we(t.command))return jn(e,t);if(t.command===`fill`)return Mn(e,t);if(t.command===`get`)return Nn(e,t)}function jn(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(_(v(n))),N(e,t),g(e,t),e.join(` `);if(t.positionals.length===1)return e.push(_(n)),g(e,t),e.join(` `)}}function Mn(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(_(v(n))),N(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(_(r)),g(e,t),e.join(` `)}function Nn(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(_(n)),e.push(_(v(r))),r.startsWith(`@`)&&N(e,t),e.join(` `)}function N(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(_(n))}const Pn=[`status`,`get`,`dismiss`,`enter`,`return`];function P(e){return Pn.includes(e)}const Fn=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],In={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function Ln(e,t){let r=t??{};switch(e.command){case n.devices:return Rn(r.devices);case n.apps:return zn(r.apps,e.flags?.appsFilter);case n.boot:return Bn(`Booted`,r,!0);case n.shutdown:return Bn(`Shut down`,r,!1);case n.install:return Vn(`Installed`,r);case n.reinstall:return Vn(`Reinstalled`,r);case n.screenshot:return Hn(e,r);default:return{}}}function Rn(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=Wn(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:$n(`Found ${t.length} ${L(`device`,t.length)}`,i.map(e=>Zn(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function zn(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=R(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:$n(`Found ${n.length} ${L(`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 Bn(e,t,n){let r=Gn(t);if(!r)return{};let i={device:r,...Xn(t),booted:n};return{summary:`${e} ${Zn(i,!1)}`,details:i}}function Vn(e,t){let n=R(t.appName),r=R(t.bundleId),i=F(t,[`packageName`,`package`]),a=R(t.platform),o=R(t.launchTarget),s=F(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=Qn(n,s);if(!c)return{};let l={};return I(l,`appName`,n),I(l,`bundleId`,r),I(l,`packageName`,i),I(l,`platform`,a),o!==s&&I(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function Hn(e,t){let n=Un(e,t);return n?{details:{requestedFileName:n}}:{}}function Un(e,t){let n=W(e.meta?.clientArtifactPaths?.path)??W(t.path);if(n)return U(n)}function Wn(e){if(!f(e))return;let t=Gn(e);if(t)return{name:t,...Xn(e)}}function Gn(e){let t=F(e,[`name`,`deviceName`,`device`]);return!t||!Kn(e,t)?t:Jn(e)}function Kn(e,t){let n=qn(t);return Fn.some(t=>{let r=R(e[t]);return r!==void 0&&qn(r)===n})}function qn(e){return e.toLowerCase()}function Jn(e){let t=R(e.appleOs),n=R(e.platform),r=R(e.kind),i=Yn(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function Yn(e,t){let n=e??t;if(!(!n||!Object.hasOwn(In,n)))return In[n]}function Xn(e){let t=R(e.platform),n=R(e.appleOs),r=R(e.kind),i=R(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function Zn(e,t){let n=R(e.name)??R(e.device)??`device`,r=R(e.platform),i=R(e.appleOs),a=[r,i===r?void 0:i,R(e.kind),R(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 Qn(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function F(e,t){for(let n of t){let t=R(e[n]);if(t)return t}}function I(e,t,n){n&&(e[t]=n)}function $n(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function L(e,t){return t===1?e:`${e}s`}function R(e){let t=W(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function z(e){return R(e)}function B(e){return typeof e==`boolean`?e:void 0}function V(e,t){let n=z(e);return n&&t.includes(n)?n:void 0}function H(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function U(e){let t=W(e);return t?R(t.split(/[\\/]/).at(-1)):void 0}function W(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function G(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const er=[`up`,`down`,`left`,`right`],tr=[`top`,`bottom`];function nr(e){return`${e.command===n.reinstall?`Reinstalled`:`Installed`} ${or(e.result??{})??`app`}`}function rr(e){let t=e.result??{};switch(e.command){case n.scroll:return cr(t);case n.screenshot:return dr(t);case n.home:return`Went home`;case n.back:return pr(t);case n.appSwitcher:return`Opened app switcher`;case n.orientation:return mr(t);case n.viewport:return hr(t);case n.clipboard:return gr(t);case n.keyboard:return _r(t);case n.tvRemote:return yr(t);case n.gesture:return br(t);case n.swipe:return xr(t);case n.trace:return Cr(`trace`,e);case n.record:return Cr(`recording`,e);default:return}}function ir(e){let t=e.result??{};switch(e.command){case n.scroll:return H({direction:V(t.direction,er),edge:V(t.edge,tr),passes:G(t.passes),amount:G(t.amount),pixels:G(t.pixels),durationMs:G(t.durationMs),x1:G(t.x1),y1:G(t.y1),x2:G(t.x2),y2:G(t.y2)});case n.screenshot:return H({requestedFileName:fr(t)});case n.back:return H({mode:V(t.mode,l)});case n.orientation:return H({orientation:V(t.orientation,ue)});case n.viewport:return H({width:G(t.width),height:G(t.height)});case n.clipboard:return H({action:V(t.action,[`read`,`write`])});case n.keyboard:return vr(t);case n.tvRemote:return H({button:V(t.button,te),durationMs:G(t.durationMs)});case n.gesture:case n.swipe:return Sr(t);case n.trace:case n.record:return H({action:V(t.action,[`start`,`stop`]),fileName:Tr(e),showTouches:B(t.showTouches)});default:return{}}}function ar(e,t){if(e.command!==n.screenshot)return t;let r=Un(e,t);return r?{...t,requestedFileName:r}:t}function or(e){let t=z(e.appName),n=Er(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??sr(e)}function sr(e){let t=z(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function cr(e){let t=V(e.direction,er),n=V(e.edge,tr),r=G(e.passes);return n?lr(n,r):t?ur(t,e):`Scrolled`}function lr(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function ur(e,t){let n=G(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=G(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function dr(e){let t=fr(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function fr(e){return U(e.requestedFileName)??U(e.path)}function pr(e){return V(e.mode,l)===`system`?`Went back using system navigation`:`Went back`}function mr(e){let t=V(e.orientation,ue);return t?`Rotated to ${t}`:`Changed orientation`}function hr(e){let t=G(e.width),n=G(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function gr(e){let t=V(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function _r(e){let t=W(e.action);if(!t||!P(t))return`Used keyboard`;if(t===`dismiss`)return B(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`;if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=B(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function vr(e){let t=W(e.action);return H({action:t&&P(t)?t:void 0,platform:V(e.platform,[`ios`,`android`]),visible:B(e.visible),wasVisible:B(e.wasVisible),dismissed:B(e.dismissed),attempts:G(e.attempts)})}function yr(e){let t=V(e.button,te);return t?`Pressed TV remote ${t}`:`Used TV remote`}function br(e){let t=V(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function xr(e){let t=G(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function Sr(e){return H({kind:V(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:G(e.durationMs),pointerCount:G(e.pointerCount),x1:G(e.x1),y1:G(e.y1),x2:G(e.x2),y2:G(e.y2),count:G(e.count),pauseMs:G(e.pauseMs),pattern:V(e.pattern,[`one-way`,`ping-pong`]),scale:G(e.scale)})}function Cr(e,t){let n=wr(e,V(t.result?.action,[`start`,`stop`])),r=Tr(t);return r?`${n} ${r}`:n}function wr(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 Tr(e){let t=e.result??{};return U(t.requestedFileName)??U(t.outPath)??U(t.path)??U(e.positionals[1])}function Er(e,t){for(let n of t){let t=z(e[n]);if(t)return t}}function Dr(e){switch(e.command){case n.open:return`Opened ${K(e)??`session`}`;case n.close:return`Closed ${z(e.result?.session)??`session`}`;case n.click:case n.press:return`Tapped ${K(e)??`target`}`;case n.longPress:return`Long pressed ${K(e)??`target`}`;case n.fill:return`Filled ${K(e)??`target`}`;case n.type:return`Typed text`;case n.install:case n.reinstall:case a.installSource:return nr(e);default:return rr(e)??`Ran ${e.command}`}}function Or(e){return H({command:e.command,positionals:Lr(e),flags:Jr(e),...kr(e),...Ar(e),...jr(e),...ir(e)})}function kr(e){if(!Mr(e.command))return{};let t=e.result??{};return H({ref:X(t),targetLabel:K(e),selectorChainLength:Gr(t.selectorChain)?.length,x:G(t.x),y:G(t.y),x2:G(t.x2),y2:G(t.y2),durationMs:G(t.durationMs)})}function Ar(e){if(!Nr(e.command))return{};let t=e.result??{};return H({platform:V(t.platform,ce),target:V(t.target,le),appName:z(t.appName),appBundleId:z(t.appBundleId),bundleId:z(t.bundleId),packageName:z(t.packageName),launchTarget:z(t.launchTarget)})}function jr(e){let t=e.result??{};return e.command===n.snapshot?{...Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}}:e.command!==n.wait&&e.command!==n.find&&e.command!==n.get&&e.command!==n.is?{}:H({waitedMs:G(t.waitedMs),found:B(t.found)})}function Mr(e){return e===n.click||e===n.press||e===n.longPress||e===n.focus||e===n.fill}function Nr(e){return e===n.open||e===n.install||e===n.reinstall||e===a.installSource}function K(e){let t=e.result??{};return Pr(t)??Fr(t)??Ir(t)??Ur(e.positionals[0])}function Pr(e){let t=X(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function Fr(e){let t=G(e.x),n=G(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function Ir(e){return z(e.appName)??z(e.appBundleId)??z(e.bundleId)??z(e.packageName)}function Lr(e){if(e.positionals.length!==0)return e.command===n.type?[J(`text`)]:e.command===n.fill?Rr(e):e.command===n.find?zr(e):e.command===n.clipboard?Br(e):e.command===n.push?Vr(e,`app`,`payload`):e.command===n.triggerAppEvent?Vr(e,`event`,`payload`):e.positionals.map(q)}function Rr(e){let t=J(`text`),n=e.result??{},r=X(n);if(r)return[`@${r}`,t];if(z(n.selector))return[J(`target`),t];let i=G(n.x),a=G(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function zr(e){let t=+!!Wr(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],J(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,J(`text`)]:[...r,...e.positionals.slice(n).map(Hr)]:r}function Br(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,J(`text`)]:e.positionals.map(q)}function Vr(e,t,n){let[r,i,...a]=e.positionals;return[...r?[J(t)]:[],...i?[J(n)]:[],...a.map(q)]}function Hr(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:q(e)}function q(e){return Ur(e)??J(`arg`)}function Ur(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function J(e){return`<${e}>`}function Wr(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function Gr(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const Kr={enums:[{source:`platform`,values:se},{source:`target`,values:le}]},qr={[n.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:i}]},[n.click]:Y(),[n.press]:Y(),[n.longPress]:Y(),[n.fill]:Yr(),[n.type]:Yr(),[n.scroll]:{numbers:[{source:`pixels`},{source:`durationMs`}]},[n.gesture]:Xr(),[n.swipe]:Xr(),[n.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotMaxSize`,output:`maxSize`}]},[n.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[n.back]:{enums:[{source:`backMode`,output:`mode`,values:l}]},[n.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`},{source:`screenshotMaxSize`,output:`maxSize`}],enums:[{source:`recordingScope`,output:`scope`,values:r}]},[n.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[n.boot]:{booleans:[{source:`headless`}]},[n.close]:{booleans:[{source:`shutdown`}]}};function Jr(e){let t=e.flags??{},n={},r=Object.hasOwn(qr,e.command)?qr[e.command]:void 0;return Zr(n,t,Kr),Zr(n,t,r),Object.keys(n).length>0?n:void 0}function Y(){return{booleans:[{source:`doubleTap`},{source:`settle`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`},{source:`settleQuietMs`}],enums:[{source:`clickButton`,values:ee}]}}function Yr(){return{booleans:[{source:`settle`}],numbers:[{source:`delayMs`},{source:`settleQuietMs`}]}}function Xr(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:c}]}}function Zr(e,t,n){n&&(Qr(e,t,n.booleans??[]),$r(e,t,n.numbers??[]),ei(e,t,n.enums??[]))}function Qr(e,t,n){for(let r of n)ti(e,r.output??r.source,t[r.source])}function $r(e,t,n){for(let r of n)ni(e,r.output??r.source,t[r.source])}function ei(e,t,n){for(let r of n)ri(e,r.output??r.source,t[r.source],r.values)}function X(e){let t=z(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function ti(e,t,n){typeof n==`boolean`&&(e[t]=n)}function ni(e,t,n){let r=G(n);r!==void 0&&(e[t]=r)}function ri(e,t,n,r){let i=V(n,r);i!==void 0&&(e[t]=i)}const Z=new Map,ii=new Set;function ai(e){return h.join(e,`events.ndjson`)}function oi(e){return e.command!==n.events}function si(t,n,r){let i=e({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});li(t,`${JSON.stringify(i)}\n`)}async function ci(e){await(e?Z.get(e):Promise.all(Z.values()))}function li(e,t){let n=(Z.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await ui(e),await y.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(()=>{Z.get(e)===n&&Z.delete(e)});Z.set(e,n)}async function ui(e){let t=h.dirname(e);if(!ii.has(t))try{await y.promises.mkdir(t,{recursive:!0}),ii.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 di(e,t,n){si(e,t,{kind:`action.recorded`,requestId:p().requestId,command:n.command,summary:Dr(n),details:Or(n)})}function fi(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??p().requestId,command:t.command,summary:`Started ${t.command}`}}function pi(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=Ln(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 mi(e,t={}){let n=yi(t.cursor),r=bi(t.limit);if(!y.existsSync(e))return{path:e,cursor:String(n),limit:r,events:[]};let i=hi(e,n,r),a=i.lines.flatMap(e=>{let t=xi(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:a,...i.nextCursor===void 0?{}:{nextCursor:String(i.nextCursor)}}}function hi(e,t,n){let r=y.openSync(e,`r`);try{let e=new Ee(`utf8`),i=Buffer.allocUnsafe(65536),a=gi(t,n),o=``,s=0;do{s=y.readSync(r,i,0,i.length,null);let t=e.write(i.subarray(0,s));o=_i(`${o}${t}`,a)}while(s>0&&a.nextCursor===void 0);let c=`${o}${e.end()}`;return a.nextCursor===void 0&&c.length>0&&vi(c,a),{lines:a.lines,nextCursor:a.nextCursor}}finally{y.closeSync(r)}}function gi(e,t){return{cursor:e,limit:t,lineIndex:0,lines:[]}}function _i(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{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(`
|
|
3
3
|
`);r!==-1;r=e.indexOf(`
|
|
4
|
-
`,n))if(
|
|
4
|
+
`,n))if(ia(e.slice(n,r),t),n=r+1,t.nextCursor!==void 0)return``;return e.slice(n)}function ia(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 aa(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 oa(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 sa(e){try{let t=ca(JSON.parse(e));return t?la(t):void 0}catch{return}}function ca(e){if(d(e)&&e.version===1&&!(typeof e.ts!=`string`||typeof e.session!=`string`)&&ua(e.kind))return e}function la(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}:{},...da(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function ua(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function da(e){return e===`ok`||e===`error`}const fa=60*6e4;var pa=class{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new Jn(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=An(e,t);if(n){let t=this.resolveStoredSessionName(e);Zi(this.resolveEventLogPath(t),t,n)}}recordEvent(e,t){qi(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return ea(this.resolveEventLogPath(e),t)}async flushEvents(e){await Ji(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:tn(e,void 0)});dn(e)&&(!t.written&&t.error?this.writeRepairTombstone(e,fa,{code:String(t.error.code),message:t.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){Nt(e.scriptPublication??O)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:e.name,...be(`Closed: ${e.name}`)}})}writeRepairTombstone(e,t=fa,n){try{let r=this.resolveSessionDir(e.name);g.mkdirSync(r,{recursive:!0});let i={owner:e.name,reapedAt:Date.now(),expiresAt:Date.now()+t,...fn(e)?{sourcePath:fn(e)}:{},...n?{commitFailure:n}:{}};g.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 ma(this.repairTombstonePath(e))}clearRepairTombstone(e){try{g.rmSync(this.repairTombstonePath(e),{force:!0})}catch{}}repairTombstonePath(e){return h.join(this.resolveSessionDir(e),`repair-tombstone.json`)}defaultTracePath(e){let t=A(e.name),n=new Date().toISOString().replace(/[:.]/g,`-`);return h.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(e){return h.join(this.sessionsDir,A(e))}resolveDaemonStateDir(){return h.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return g.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return h.join(this.resolveSessionDir(e),`app.log`)}resolveAppLogPidPath(e){return h.join(this.resolveSessionDir(e),`app-log.pid`)}resolveEventLogPath(e){return Gi(this.resolveSessionDir(e))}static expandHome(e,t){return j(e,t)}resolveStoredSessionName(e){for(let[t,n]of this.sessions)if(n===e)return t;return e.name}};function ma(e){let t;try{t=g.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 ha(e){let t;try{t=g.readdirSync(e,{withFileTypes:!0})}catch{return}for(let n of t){if(!n.isDirectory())continue;let t=ma(h.join(e,n.name,`repair-tombstone.json`));if(t?.commitFailure)return{sessionName:n.name,tombstone:{...t,commitFailure:t.commitFailure}}}}function ga(e){return h.join(e,`runner.log`)}function _a(e,t){let n=A(t&&t.length>0?t:`unknown`);return h.join(e,`requests`,`${n}.ndjson`)}function va(e,t={}){let n=ya(e,t);return{baseDir:n,infoPath:h.join(n,`daemon.json`),lockPath:h.join(n,`daemon.lock`),logPath:h.join(n,`daemon.log`),sessionsDir:h.join(n,`sessions`)}}function ya(e,t){let n=(e??``).trim();return n?we(n,{env:t.env}):ba(t)}function ba(e={}){let t=h.join(Te(`~`,{env:e.env}),`.agent-device`),n=e.projectRoot??Ce();return xa(n)?h.join(t,`dev`,Sa(n)):t}function xa(e){return g.existsSync(h.join(e,`package.json`))&&g.existsSync(h.join(e,`src`,`daemon.ts`))}function Sa(e){let t=Ca(e),n=h.basename(t).replaceAll(/[^a-zA-Z0-9._-]+/g,`-`),r=Ae.createHash(`sha1`).update(t).digest(`hex`).slice(0,12);return`${n||`agent-device`}-${r}`}function Ca(e){try{return g.realpathSync.native(e)}catch{return h.resolve(e)}}function wa(e){let t=(e??``).trim().toLowerCase();return t===`http`?`http`:t===`dual`?`dual`:`socket`}function Ta(e){let t=(e??``).trim().toLowerCase();return t===`auto`?`auto`:t===`socket`?`socket`:t===`http`?`http`:`auto`}function Ea(e){return(e??``).trim().toLowerCase()===`tenant`?`tenant`:`none`}function Da(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}const Oa=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,ka=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,Aa=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`];function ja(){let e=process.argv[1];return e?Ma(e):`unknown`}function Ma(e,t=Ce()){try{let n=h.resolve(t),r=[h.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=g.statSync(e);if(!t.isFile())continue;let o=h.relative(n,e)||e;a.push(`${o}:${t.size}:${Math.trunc(t.mtimeMs)}`);let s=g.readFileSync(e,`utf8`);for(let t of Na(s)){let n=Fa(e,t);n&&r.push(n)}}let o=a.sort().join(`|`),s=Ae.createHash(`sha1`).update(o).digest(`hex`);return`graph:${a.length}:${s}`}catch{return`unknown`}}function Na(e){let t=new Set;return Pa(e,Oa,t),Pa(e,ka,t),[...t]}function Pa(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 Fa(e,t){let n=h.resolve(h.dirname(e),t),r=Ia(n);if(r)return r;for(let e of Aa){let t=Ia(`${n}${e}`);if(t)return t}for(let e of Aa){let t=Ia(h.join(n,`index${e}`));if(t)return t}return null}function Ia(e){try{return g.statSync(e).isFile()?e:null}catch{return null}}const La=/^[A-Za-z0-9_@%+=:,./-]+$/;function Ra(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function za(e){return La.test(e)?e:Ra(e)}const Ba=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])dist\/src\/internal\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function Va(e){let t=e.toLowerCase().replaceAll(`\\`,`/`);return t.includes(`agent-device`)?Ba.some(e=>e.test(t)):!1}function Ha(e,t){if(!De(e))return!1;if(t){let n=Oe(e);if(!n||n!==t)return!1}let n=Ee(e);return n?Va(n):!1}function Ua(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 Wa(e,t){Ha(e,t.expectedStartTime)&&Ua(e,`SIGTERM`)&&(await ke(e,t.termTimeoutMs)||Ua(e,`SIGKILL`)&&await ke(e,t.killTimeoutMs))}function Ga(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 Ka(e){return e.meta?.requestProgress===`replay-test`||e.meta?.requestProgress===`command`}function qa(e){return!!e&&typeof e==`object`&&e.type===`progress`&&!!e.event}function Ja(e){return!!e&&typeof e==`object`&&e.type===`response`&&!!e.response}function Ya(e){return`${JSON.stringify({type:`progress`,event:e})}\n`}function Xa(e){return`${JSON.stringify({type:`response`,response:e})}\n`}function Za(e){return`${JSON.stringify({type:`response`,response:e})}\n`}function Qa(e,t={}){return{ok:!0,service:e,version:Se(),rpcProtocolVersion:2,...t.upstream===void 0?{}:{upstream:t.upstream}}}function $a(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 eo(e){if(d(e))return $a({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(io).flatMap(e=>{let t=to(e);return t?[t]:[]}):void 0})}function to(e){if(typeof e.ref!=`string`||e.ref.length===0)return;let t=no(e);if(t)return{ref:e.ref,...ro(e),...t}}function no(e){let t=se(e.rect);if(!t)return;let n=se(e.overlayRect);if(!n)return;let r=ce(e.center);return r?{rect:t,overlayRect:n,center:r}:void 0}function ro(e){return typeof e.label==`string`&&e.label.length>0?{label:e.label}:{}}function io(e){return d(e)}export{$t as $,xi as A,rn as B,pa as C,Ue as Ct,$i as D,ga as E,gn as F,sn as G,un as H,hn as I,Xt as J,P as K,mn as L,B as M,Pn as N,Qi as O,Sn as P,nn as Q,F as R,Ea as S,$e as St,_a as T,b as Tt,dn as U,ln as V,on as W,tn as X,Yt as Y,Jt as Z,ja as _,wt as _t,Ja as a,qt as at,wa as b,at as bt,Za as c,kt as ct,Ha as d,Ot as dt,en as et,Wa as f,Et as ft,Ma as g,xt as gt,za as h,Ct as ht,qa as i,O as it,Hr as j,Ki as k,Ka as l,Tt as lt,Ra as m,bt as mt,eo as n,j as nt,Ya as o,Kt as ot,Ua as p,yt as pt,an as q,Qa as r,A as rt,Xa as s,At as st,$a as t,Qt as tt,Ga as u,Dt as ut,Da as v,St as vt,ha as w,x as wt,Ta as x,ot as xt,va as y,T as yt,cn as z};
|
|
@@ -55,13 +55,17 @@ type PointerTrajectory = {
|
|
|
55
55
|
pointerId: 0 | 1;
|
|
56
56
|
samples: readonly PointerTrajectorySample[];
|
|
57
57
|
};
|
|
58
|
+
type SinglePointerTrajectory = {
|
|
59
|
+
pointerId: 0;
|
|
60
|
+
samples: readonly [PointerTrajectorySample, PointerTrajectorySample, ...PointerTrajectorySample[]];
|
|
61
|
+
};
|
|
58
62
|
type SinglePointerGesturePlan = {
|
|
59
63
|
topology: 'single';
|
|
60
64
|
intent: 'fling' | 'pan';
|
|
61
65
|
executionProfile: GestureExecutionProfile;
|
|
62
66
|
durationMs: number;
|
|
63
67
|
viewport: Rect;
|
|
64
|
-
pointers: readonly [
|
|
68
|
+
pointers: readonly [SinglePointerTrajectory];
|
|
65
69
|
};
|
|
66
70
|
type MultiTouchGesturePlan = {
|
|
67
71
|
topology: 'two';
|
|
@@ -79,7 +83,21 @@ type AndroidLongPressTouchPlan = {
|
|
|
79
83
|
durationMs: number;
|
|
80
84
|
pointers: readonly [PointerTrajectory];
|
|
81
85
|
};
|
|
82
|
-
|
|
86
|
+
/**
|
|
87
|
+
* Transport samples are strictly denser than the canonical endpoint pair, so the shared plan a
|
|
88
|
+
* command builds cannot satisfy the transport types: skipping the lowering below is a type error
|
|
89
|
+
* at every injection seam rather than a silently sparse gesture.
|
|
90
|
+
*/
|
|
91
|
+
type AndroidTransportSamples = readonly [PointerTrajectorySample, PointerTrajectorySample, PointerTrajectorySample, ...PointerTrajectorySample[]];
|
|
92
|
+
type AndroidTransportSinglePointerTrajectory = {
|
|
93
|
+
pointerId: 0;
|
|
94
|
+
samples: AndroidTransportSamples;
|
|
95
|
+
};
|
|
96
|
+
type AndroidTransportSinglePointerGesturePlan = Omit<SinglePointerGesturePlan, 'pointers'> & {
|
|
97
|
+
pointers: readonly [AndroidTransportSinglePointerTrajectory];
|
|
98
|
+
};
|
|
99
|
+
type AndroidTransportGesturePlan = AndroidTransportSinglePointerGesturePlan | MultiTouchGesturePlan;
|
|
100
|
+
type AndroidProviderTouchPlan = AndroidTransportGesturePlan | (AndroidLongPressTouchPlan & {
|
|
83
101
|
viewport: Rect;
|
|
84
102
|
});
|
|
85
103
|
//#endregion
|
|
@@ -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)||!Number.isInteger(a))throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Expected integer.`);if(typeof e.min==`number`&&a<e.min)throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Must be >= ${e.min}.`);if(typeof e.max==`number`&&a>e.max)throw new n(`INVALID_ARGS`,`Invalid value for "${i}" in ${r}. Must be <= ${e.max}.`);return a}function fe(e,t,r){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=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(`
|
|
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
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 rt(e,t){let n=`${e}\n${t}`.toLowerCase();return n.includes(`listener`)&&n.includes(`not found`)}function $(e){let{replace:t,allowTestPackages:n,allowDowngrade:r,grantPermissions:i,...a}=e??{},o=[];return t&&o.push(`-r`),n&&o.push(`-t`),r&&o.push(`-d`),i&&o.push(`-g`),{installArgs:o,execOptions:a}}export{g as A,xe as C,S as D,ue as E,_ as F,ae as I,te as L,oe as M,ne as N,de as O,re as P,_e as S,w as T,be as _,Ye as a,Se as b,X as c,Ze as d,E as f,ye as g,De as h,qe as i,v as j,ie as k,Ke as l,V as m,K as n,Je as o,L as p,G as r,Ge as s,Fe as t,Z as u,T as v,ve as w,O as x,k as y};
|