agent-device 0.20.6 → 0.20.8

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