agent-device 0.20.7 → 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.
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.7.apk → agent-device-android-ime-helper-0.20.8.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.8.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.20.7.manifest.json → agent-device-android-ime-helper-0.20.8.manifest.json} +4 -4
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.7.apk → agent-device-android-snapshot-helper-0.20.8.apk} +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.8.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.20.7.manifest.json → agent-device-android-snapshot-helper-0.20.8.manifest.json} +6 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +5 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+RecordingTests.swift +4 -0
- package/dist/src/agent-browser-tool.js +1 -1
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/android.js +1 -1
- package/dist/src/app-lifecycle.js +7 -7
- package/dist/src/app-lifecycle2.js +1 -1
- package/dist/src/app-log-reconnect.js +1 -1
- package/dist/src/app-log-runtime.js +3 -3
- package/dist/src/app-resolution.js +2 -2
- package/dist/src/apps.js +5 -5
- package/dist/src/auth-session.js +1 -1
- package/dist/src/boot-diagnostics.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +1 -1
- package/dist/src/cli.js +4 -4
- package/dist/src/client-metro.js +1 -1
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/debug-symbols.js +3 -3
- package/dist/src/device-claim-inspection.js +1 -1
- package/dist/src/device-input-state.js +1 -1
- package/dist/src/device-ready.js +1 -0
- package/dist/src/dispatch.js +1 -0
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/generic-settle.js +1 -1
- package/dist/src/handler-utils.js +1 -0
- package/dist/src/harmonyos.js +1 -1
- package/dist/src/hdc.js +1 -0
- package/dist/src/helper.js +1 -1
- package/dist/src/host-process.js +3 -2
- package/dist/src/ime-lifecycle.js +5 -5
- package/dist/src/index.d.ts +21 -21
- package/dist/src/input-actions.js +4 -4
- package/dist/src/input-actions2.js +1 -1
- package/dist/src/install-artifact.js +1 -1
- package/dist/src/interaction-runtime.js +1 -1
- package/dist/src/interaction-snapshot.js +1 -1
- package/dist/src/interaction-touch-reference-frame.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interactor.js +1 -1
- package/dist/src/interactor2.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +7 -29
- package/dist/src/inventory2.js +1 -1
- package/dist/src/lease-context.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun-runtime-dependencies.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/manifest.js +1 -1
- package/dist/src/notifications.js +1 -1
- package/dist/src/output-path.js +1 -0
- package/dist/src/owner-identity.js +1 -1
- package/dist/src/physical-device-control.js +1 -1
- package/dist/src/platform-runtime-app-log-process.js +1 -1
- package/dist/src/platform-runtime-host.js +1 -1
- package/dist/src/platform-runtime-network-web-transport.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +4 -4
- package/dist/src/platform-runtime-screen-recording-android-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-apple-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-apple-runner-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -0
- package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-apple-transport.js +1 -0
- package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-harmony-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-output-host.js +1 -0
- package/dist/src/platform-runtime-screen-recording-web-host.js +1 -0
- package/dist/src/platform-runtime-toolchain-host.js +1 -1
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/prepare-kind.js +13 -13
- package/dist/src/provider-webdriver.js +1 -1
- package/dist/src/proxy.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime.js +1 -0
- package/dist/src/record-trace.js +1 -1
- package/dist/src/recording-telemetry.js +1 -0
- package/dist/src/registry.js +4 -4
- package/dist/src/remote-config2.js +1 -1
- package/dist/src/replay.js +2 -2
- package/dist/src/runner-disposal.js +1 -1
- package/dist/src/runner-lease.js +1 -1
- package/dist/src/runtime.js +3 -3
- package/dist/src/runtime2.js +3 -3
- package/dist/src/runtime3.js +3 -3
- package/dist/src/runtime4.js +1 -1
- package/dist/src/runtime7.js +1 -1
- package/dist/src/screenshot-result.js +4 -4
- package/dist/src/sdk-android-adb.js +4 -4
- package/dist/src/sdk-batch-runner.js +2 -2
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.d.ts +5 -1
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +2 -2
- package/dist/src/session-target-evidence.js +1 -1
- package/dist/src/session.js +10 -10
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot-session.js +1 -1
- package/dist/src/snapshot.js +1 -1
- package/dist/src/snapshot2.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src2.js +2 -2
- package/dist/src/src3.js +1 -1
- package/dist/src/text-surface.js +1 -1
- package/dist/src/tool-provider.js +3 -3
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/tool-provider3.js +1 -1
- package/dist/src/update-check.js +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/video.js +23 -0
- package/dist/src/web.js +1 -1
- package/package.json +2 -4
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.7.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.7.apk.sha256 +0 -1
- package/dist/src/context.js +0 -1
- package/dist/src/provider.js +0 -1
- package/dist/src/runner-client.js +0 -1
- package/dist/src/runner-provider.js +0 -1
- package/skills/agent-device/SKILL.md +0 -20
- package/skills/dogfood/SKILL.md +0 -27
package/dist/src/runtime2.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{F as t,L as n,P as r,W as i}from"./sdk-batch-runner.js";import{C as a}from"./sdk-device.js";import{S as o,a as s,b as c,c as l,h as u,n as d,o as f,s as p,t as m}from"./src2.js";import h from"node:path";function g(t){if(!/^[a-zA-Z0-9._:-]+$/.test(t))throw new e(`INVALID_ARGS`,`Invalid Android package name for logs: ${t}`)}const _=Object.freeze({resourceKind:t,version:1,encode:e=>({...e}),decode:e=>e.transport!==`android-logcat-local`&&e.transport!==`android-logcat-transport-composed`||!y(e.outputPath)||!y(e.pidPath)?{status:`invalid`,message:`Invalid Android app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:e.transport,outputPath:e.outputPath,pidPath:e.pidPath})}});function v(e){let n=_.decode(e.descriptor);if(n.status!==`decoded`)throw TypeError(n.message);return c({resourceKind:t,sessionId:e.sessionId,device:{id:e.device.id,family:`android`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:o(_,n.descriptor)})}function y(e){return typeof e==`string`&&e.trim().length>0}function b(e){return p(e,{family:`android`,backend:`android`,label:`Android`,codec:_,startUnavailableHint:`The selected Android transport cannot start a background adb logcat stream.`,cleanupFailureMessage:`Android app-log cleanup did not settle every owned resource`,doctor:async({host:e,device:t,signal:n},r)=>await x(e,t.id,r,n),validateStart:({input:e})=>g(e.appBundleId),process:async({host:e,device:t,input:n})=>({resolvePid:async r=>await l(e,S(t.id,n.appBundleId),r),command:e=>({kind:`android-adb`,serial:t.id,args:[`logcat`,`-v`,`time`,`--pid`,e],options:{allowFailure:!0}})}),descriptor:({artifacts:e,transport:t})=>({transport:t.mode===`transport-composed`?`android-logcat-transport-composed`:`android-logcat-local`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>v({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function x(e,t,n,r){let i={};return i.adbAvailable=await f(async()=>s(await e.commands.run({executable:`adb`,args:[`-s`,t,`shell`,`echo`,`ok`],allowFailure:!0,timeoutMs:1e3},r)),r),n&&(i.androidPidVisible=await f(async()=>!!await l(e,S(t,n),r),r)),{backend:`android`,checks:i,notes:n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}}function S(e,t){return{executable:`adb`,args:[`-s`,e,`shell`,`pidof`,t],allowFailure:!0,timeoutMs:5e3}}async function C(e,t,n,r){let i=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),a=d(i.text,{...n,path:i.path,exists:i.exists,lineNumberOffset:i.skippedLines,backend:`android`}),o=[],s=await ee(e,t,n,r);if(s&&n.appBundleId){g(n.appBundleId);let c=await ne(e,t,n.appBundleId,r);if(c){let e=d(c.text,{...n,path:`${i.path} (adb logcat recovery)`,exists:!0,backend:`android`});e.entries.length>0&&(a=m(e,a,n.maxEntries),o.push(s.reason===`stale-active`?`Session app log stream was still bound to prior Android PID ${s.trackedPid}. Recovered recent Android HTTP entries from adb logcat for PID set ${c.pids.join(`, `)}.`:`Session app log stream was inactive. Recovered recent Android HTTP entries from adb logcat for PID set ${c.pids.join(`, `)}.`))}}return n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&o.length===0&&o.push(`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):o.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`),a.entries.length===0&&o.push(`No HTTP(s) entries were found in recent session app logs.`),Object.freeze({source:`app-log`,backend:`android`,dump:a,notes:Object.freeze(o)})}async function w(e,t,n){n.throwIfAborted();try{let r=await e.commands.run(t,n);return n.throwIfAborted(),r}catch{n.throwIfAborted();return}}async function ee(e,t,n,r){if(!n.appBundleId||n.appLogSnapshot?.state===void 0)return;if(n.appLogSnapshot.state!==`active`)return{reason:`inactive`};let i=te(await e.appLogs.readProcessMarker(n.sessionId));if(!i)return;let a=await T(e,t.id,n.appBundleId,r);if(!(!a||a===i))return{reason:`stale-active`,trackedPid:i}}function te(e){if(e.status===`decoded`)return/(?:^|\s)--pid\s+(\d+)(?:\s|$)/.exec(e.marker.command)?.[1]}async function ne(e,t,n,r){let i=await T(e,t.id,n,r),a=await w(e,{executable:`adb`,args:[`-s`,t.id,`logcat`,`-d`,`-v`,`time`,`-t`,`4000`],allowFailure:!0,timeoutMs:3e3},r);if(!a||a.exitCode!==0||!a.stdout.trim())return;let o=re(a.stdout,n,i);if(o.length===0)return;let s=new Set(o),c=a.stdout.split(`
|
|
2
2
|
`).filter(e=>{if(!e.trim())return!1;if(e.includes(n))return!0;let t=/\(\s*(\d+)\)\s*:/.exec(e)?.[1];return!!(t&&s.has(t))}).join(`
|
|
3
|
-
`);return c.trim()?{text:c,pids:o}:void 0}async function
|
|
4
|
-
`))if(n.includes(t))for(let e of a){let t=e.exec(n)?.[1];t&&/^\d+$/.test(t)&&r.add(t)}return Object.freeze([...r])}const T=t(`android`),E=Object.freeze({available:!0});function D(e){let t=h(e);return Object.freeze({owner:T,ownsDevice:e=>e.platform===`android`,bind:async n=>{let r=await t.bind(n);return Object.freeze({device:r.device,owner:T,facts:Object.freeze({device:r.facts.device,operations:{...r.facts.operations,networkDump:E}}),operations:Object.freeze({...r.operations,networkDump:async t=>await v(e,n.device,t,n.scope.signal)}),[Symbol.asyncDispose]:async()=>await r[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}export{D as createAndroidPlatformRuntime};
|
|
3
|
+
`);return c.trim()?{text:c,pids:o}:void 0}async function T(e,t,n,r){let i=await w(e,{executable:`adb`,args:[`-s`,t,`shell`,`pidof`,n],allowFailure:!0},r);if(!i)return;let a=i.stdout.trim().split(/\s+/)[0];return a&&/^\d+$/.test(a)?a:void 0}function re(e,t,n){let r=new Set(n?[n]:[]),i=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),a=[RegExp(`\\bStart proc\\s+(\\d+):${i}(?:\\b|/)`,`i`),RegExp(`\\b(\\d+):${i}(?:\\b|/)`,`i`),RegExp(`${i}.*?\\bpid\\s*[=:]?\\s*(\\d+)\\b`,`i`),RegExp(`\\bpid\\s*[=:]?\\s*(\\d+)\\b.*${i}`,`i`)];for(let n of e.split(`
|
|
4
|
+
`))if(n.includes(t))for(let e of a){let t=e.exec(n)?.[1];t&&/^\d+$/.test(t)&&r.add(t)}return Object.freeze([...r])}const ie=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-\d{1,20}\.mp4$/,ae=/^(?:\/sdcard|\/data\/local\/tmp)\/agent-device-recording-active\.json$/;function oe(e){return le(e)&&ue(e)&&de(e)}function se(e){if(!O(e))return!1;let t=e;return fe(t)&&pe(t)&&me(t)&&he(t)&&(t.completion===void 0||xe(t))}function ce(e,t){return E(e,t)&&D(e,t.outputPath,t.clientOutputPath)}function le(e){return e.backend===`adb-screenrecord`&&typeof e.manifestPath==`string`&&ae.test(e.manifestPath)&&typeof e.outputPath==`string`}function ue(e){return(e.clientOutputPath===void 0||typeof e.clientOutputPath==`string`)&&k(e.scope)&&typeof e.showTouches==`boolean`&&typeof e.recordOnlySession==`boolean`}function de(e){return A(e.transportMode)&&j(e.exportQuality)&&M(e.activeSessionApp)}function fe(e){return e.version===1&&e.resourceKind===`screen-recording`&&typeof e.fenceToken==`string`&&Number.isInteger(e.fenceGeneration)&&typeof e.sessionId==`string`&&typeof e.deviceId==`string`&&Number.isFinite(e.startedAt)}function pe(e){return typeof e.outputPath==`string`&&(e.clientOutputPath===void 0||typeof e.clientOutputPath==`string`)&&k(e.scope)&&typeof e.showTouches==`boolean`&&typeof e.recordOnlySession==`boolean`}function me(e){return M(e.activeSessionApp)&&j(e.exportQuality)&&A(e.transportMode)&&(e.pendingRemotePath===void 0||N(e.pendingRemotePath))}function he(e){return Array.isArray(e.chunks)&&e.chunks.every(ge)&&(e.chunks.length>0||e.pendingRemotePath!==void 0)&&(e.completion===void 0||_e(e.completion))}function ge(e,t){if(!O(e))return!1;let n=e;return n.index===t+1&&N(n.remotePath)&&P(n.remotePid)&&P(n.remoteStartTime)}function _e(e){if(!O(e))return!1;let t=e;return ve(t)&&ye(t)&&(t.chunks===void 0||t.chunks.every(be))}function ve(e){return typeof e.backend==`string`&&typeof e.outPath==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)&&Number.isFinite(e.startedAt)&&Number.isFinite(e.completedAt)}function ye(e){return k(e.scope)&&typeof e.showTouches==`boolean`&&typeof e.recordOnlySession==`boolean`&&M(e.activeSessionApp)}function be(e,t){return e.index===t+1&&typeof e.path==`string`&&(e.clientOutPath===void 0||typeof e.clientOutPath==`string`)}function xe(e){let t=e.completion;return t!==void 0&&E(t,e)&&t.startedAt===e.startedAt&&D(t,e.outputPath,e.clientOutputPath,e.chunks.length)}function E(e,t){return e.backend===`adb screenrecord`&&e.outPath===t.outputPath&&e.clientOutPath===t.clientOutputPath&&e.scope===t.scope&&e.showTouches===t.showTouches&&e.recordOnlySession===t.recordOnlySession&&Se(e.activeSessionApp,t.activeSessionApp)}function D(e,t,n,r=e.chunks===void 0?1:e.chunks.length){return r===1?e.chunks===void 0:e.chunks?.length===r&&e.chunks.every((e,r)=>e.path===F(t,r+1)&&e.clientOutPath===(n===void 0?void 0:F(n,r+1)))}function O(e){return typeof e==`object`&&!!e}function k(e){return e===`app`||e===`device`||e===`system`}function A(e){return e===`local`||e===`transport-composed`}function j(e){return e===void 0||e===`medium`||e===`high`}function M(e){return e===void 0||O(e)&&typeof e.bundleId==`string`&&(e.name===void 0||typeof e.name==`string`)}function N(e){return typeof e==`string`&&ie.test(e)}function P(e){return typeof e==`string`&&/^\d+$/.test(e)}function Se(e,t){return JSON.stringify(e)===JSON.stringify(t)}function F(e,t){if(t===1)return e;let n=e.lastIndexOf(`.`),r=n>e.lastIndexOf(`/`)?e.slice(0,n):e,i=n>e.lastIndexOf(`/`)?e.slice(n):`.mp4`;return`${r}.part-${String(t).padStart(3,`0`)}${i}`}const I=Object.freeze({resourceKind:r,version:1,encode:e=>({...e}),decode:e=>oe(e)?{status:`decoded`,descriptor:Object.freeze({backend:`adb-screenrecord`,manifestPath:e.manifestPath,outputPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutputPath:e.clientOutputPath},scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,transportMode:e.transportMode,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality}})}:{status:`invalid`,message:`Invalid Android screen-recording descriptor`}});function L(e,t,n,r,i,a=`local`){return Object.freeze({version:1,resourceKind:`screen-recording`,fenceToken:t.fence.token,fenceGeneration:t.fence.generation,sessionId:t.sessionId,deviceId:e.id,startedAt:n,outputPath:t.outputPath,...t.clientOutputPath===void 0?{}:{clientOutputPath:t.clientOutputPath},scope:t.scope,showTouches:t.showTouches,recordOnlySession:t.recordOnlySession,...t.activeSessionApp===void 0?{}:{activeSessionApp:t.activeSessionApp},...t.exportQuality===void 0?{}:{exportQuality:t.exportQuality},chunks:r,...i===void 0?{}:{pendingRemotePath:i},transportMode:a})}function Ce(e,t){return Object.freeze({...e,completion:t})}function R(e){try{let t=e&&JSON.parse(e);return se(t)?t:void 0}catch{return}}function we(e,t,n){return e.deviceId===t.id&&e.deviceId===n.device.id&&e.fenceToken===n.fence.token&&e.fenceGeneration===n.fence.generation&&e.sessionId===n.sessionId}function Te(e,t){return e.outputPath===t.outputPath&&e.clientOutputPath===t.clientOutputPath&&e.scope===t.scope&&e.showTouches===t.showTouches&&e.recordOnlySession===t.recordOnlySession&&JSON.stringify(e.activeSessionApp)===JSON.stringify(t.activeSessionApp)&&e.exportQuality===t.exportQuality&&e.transportMode===t.transportMode&&(e.completion===void 0||ce(e.completion,t))}const z=1e4,B=1e3;var V=class extends Error{constructor(e){super(`Android screenrecord launch rollback could not be confirmed`,{cause:e})}};function H(e,t=Date.now()){return[...new Set(e?[e,`/sdcard`,`/data/local/tmp`]:[`/sdcard`,`/data/local/tmp`])].map(e=>`${e}/agent-device-recording-${t}.mp4`)}async function U(e,t,n,r){let i;try{if(i=(await e.start({remotePath:t,quality:n.exportQuality??`medium`},r)).process,!/^\d+$/.test(i.pid)||!/^\d+$/.test(i.startTime)||i.remotePath!==t)throw Error(`Android screenrecord returned an invalid process identity`);if(!await ke(e,t,i,r))throw Error(`Android screenrecord did not begin producing frames`);return{index:1,remotePath:t,remotePid:i.pid,remoteStartTime:i.startTime}}catch(t){throw i&&Ee(i)&&!await Ae(e,i)?new V(t):r?.aborted?r.reason:t}}function Ee(e){return/^\d+$/.test(e.pid)&&/^\d+$/.test(e.startTime)&&e.remotePath.length>0}async function W(e,t){let n=!1,r;for(let i of[...t].reverse())try{n=await q(e,i)||n}catch(e){r??=e}if(r)throw r;return n}async function De(e,t){for(let n of t){let t;for(let r=0;r<3;r+=1){let i=await e.size(n.remotePath);if(typeof i==`number`&&i>0&&i===t)break;if(t=typeof i==`number`&&i>0?i:void 0,r===2)throw Error(`Android recording artifact is not stable: ${n.remotePath}`);await new Promise(e=>setTimeout(e,250))}}}async function Oe(e,t,n,r){let i=[];for(let[a,o]of t.entries()){let t=a===0?n:Pe(n,a+1);await je(e,o.remotePath,t);let s=a===0||r===void 0?r:Pe(r,a+1);i.push({index:a+1,path:t,...s===void 0?{}:{clientOutPath:s}})}return Object.freeze(i)}async function G(e,t){let n;for(let r of t)try{if(!await e.remove(r.remotePath))throw Error(`failed to remove Android recording artifact: ${r.remotePath}`)}catch(e){n??=e}if(n)throw n}async function K(e,t){try{await W(e,t)}finally{await G(e,t)}}async function ke(e,t,n,r){for(let i=0;i<3;i+=1){if(r?.throwIfAborted(),await e.exists(t,r)===!0)return!0;if(await e.inspect(n,r)!==`owned-alive`)return!1;i<2&&await new Promise(e=>setTimeout(e,250))}return!0}async function Ae(e,t){try{let n=await e.stop(t,{force:!0});return(n===`stopped`||n===`already-missing`)&&await e.remove(t.remotePath)}catch{return!1}}async function q(e,t){if(!t)return!1;let n={pid:t.remotePid,remotePath:t.remotePath,startTime:t.remoteStartTime},r=await e.stop(n);if(r===`already-missing`)return!0;if(r===`ownership-lost`)throw Error(`Android screenrecord ownership could not be confirmed for pid ${t.remotePid}`);if(await Me(e,n))return!1;let i=await e.stop(n,{force:!0});if(i===`stopped`||i===`already-missing`)return!1;throw Error(`failed to stop Android screenrecord pid ${t.remotePid}`)}async function je(e,t,n){for(let r=0;r<3;r+=1){let i=await e.pullPlayable({remotePath:t,outputPath:n});if(i.exitCode===0&&i.playable)return;r+1<3&&await Ne(1e3)}throw Error(`failed to retrieve playable Android recording`)}async function Me(e,t){for(let n=0;n<=z;n+=B){let r=await e.inspect(t);if(r===`missing`)return!0;if(r===`ownership-lost`)throw Error(`Android screenrecord ownership could not be confirmed for pid ${t.pid}`);n<z&&await Ne(B)}return!1}function Ne(e){return new Promise(t=>setTimeout(t,e))}function Pe(e,t){let n=h.parse(e);return h.join(n.dir,`${n.name}.part-${String(t).padStart(3,`0`)}${n.ext||`.mp4`}`)}async function Fe(e){let{transport:t,device:n,input:r,startedAt:i,signal:a,prepareOutput:o}=e;await Ie(t,n),await o();let s;for(let e of H(void 0)){let o=t.manifestPathFor(e);await J(t,o,L(n,r,i,[],e,t.mode),a);let c;try{c=await U(t,e,r,a)}catch(e){if(a.aborted)throw a.reason;await We(t,o,e),s=e;continue}try{await J(t,o,L(n,r,i,[c],void 0,t.mode),a)}catch(e){throw await K(t,[c]).catch(()=>{}),e}return{chunk:c,manifestPath:o}}throw s??Error(`Android screenrecord did not begin producing frames`)}async function Ie(e,t){let n=(await Le(e)).flatMap(n=>Re(n,t,e.mode));for(let t of n)await He(e,t.evidence,t.manifestPath)}async function Le(e){return await Promise.all(H(void 0).map(async t=>{let n=e.manifestPathFor(t);return{manifestPath:n,read:await e.readManifest(n)}}))}function Re(e,t,n){if(e.read.status===`missing`)return[];if(e.read.status!==`read`)throw Be();let r=R(e.read.contents);if(!ze(r,t,n))throw Ve();return[{manifestPath:e.manifestPath,evidence:r}]}function ze(e,t,n){return e!==void 0&&e.completion!==void 0&&e.pendingRemotePath===void 0&&e.deviceId===t.id&&e.transportMode===n}function Be(){return Error(`Android screenrecord native recovery evidence is unavailable`)}function Ve(){return Error(`Android screenrecord native recovery evidence already exists`)}async function He(e,t,n){for(let n of t.chunks)if(await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime})!==`missing`)throw Error(`Android screenrecord completed evidence cannot be safely retired`);if(await G(e,t.chunks),await Y(e,n),(await e.readManifest(n)).status!==`missing`)throw Error(`Android screenrecord completed evidence removal could not be confirmed`)}async function Ue(e){let{transport:t,device:n,input:r,startedAt:i,chunks:a,manifestPath:o,preferredDir:s}=e,c;for(let e of H(s)){await J(t,o,L(n,r,i,a,e,t.mode));try{return await U(t,e,r)}catch(e){if(e instanceof V)throw e;try{await J(t,o,L(n,r,i,a,void 0,t.mode))}catch{throw new V(e)}c=e}}throw c??Error(`failed to start next Android recording chunk`)}async function We(e,t,n){if(n instanceof V)throw n;try{await Y(e,t)}catch{throw new V(n)}}async function J(e,t,n,r){await e.writeManifest({manifestPath:t,contents:JSON.stringify(n)},r)}async function Y(e,t){if(!await e.removeManifest(t))throw Error(`failed to remove Android recording manifest: ${t}`)}function Ge(e,t){return Object.freeze({backend:`adb screenrecord`,outPath:e.outputPath,...e.clientOutputPath?{clientOutPath:e.clientOutputPath}:{},startedAt:t,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp?{activeSessionApp:e.activeSessionApp}:{},...e.exportQuality?{exportQuality:e.exportQuality}:{},gestureEvents:[]})}async function Ke(e,t,n,r,i=!1){let a=n.length>1,o=await e.screenRecording.finalize.complete({outputPath:t.outPath,showTouches:a?!1:t.showTouches,gestureEvents:t.gestureEvents,exportQuality:t.exportQuality??`medium`,targetLabel:r}),s=[...i?[`Android adb screenrecord stopped before record stop, likely after reaching the 180s platform limit. The MP4 may be truncated; final interactions after the limit are not in the video.`]:[],...a?[`Android adb screenrecord is capped at 180s, so this recording was split into multiple MP4 chunks.`]:[]];return{status:`completed`,result:{backend:t.backend,outPath:t.outPath,...t.clientOutPath?{clientOutPath:t.clientOutPath}:{},startedAt:t.startedAt,completedAt:Date.now(),scope:t.scope,showTouches:t.showTouches,recordOnlySession:t.recordOnlySession,...t.activeSessionApp?{activeSessionApp:t.activeSessionApp}:{},...a?{chunks:n}:{},...s.length?{warning:s.join(` `)}:{},...o,...a&&t.showTouches&&t.gestureEvents.length>0?{overlayWarning:`touch overlay burn-in is skipped for chunked Android recordings; returning raw chunks plus gesture telemetry`}:{}}}}function qe(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:String(e)}}async function Je(e){let t=await W(e.transport,e.evidence.chunks)||e.reachedLimit===!0;await De(e.transport,e.evidence.chunks);let n=await Oe(e.transport,e.evidence.chunks,e.recording.outPath,e.recording.clientOutPath),r=await Ke(e.host,e.recording,n,`Android recording`,t);return await J(e.transport,e.manifestPath,Ce(e.evidence,r.result)),await G(e.transport,e.evidence.chunks),r}async function Ye(e,t,n){try{let r=t.pendingRemotePath,i=r===void 0?[]:(await e.findRunning(r)).map(e=>({index:t.chunks.length+1,remotePath:r,remotePid:e.pid,remoteStartTime:e.startTime}));if(await W(e,[...t.chunks,...i]),await G(e,t.chunks),r!==void 0&&!await e.remove(r))throw Error(`failed to remove Android recording artifact: ${r}`);return await Y(e,n),{status:`cleaned`}}catch(e){return qe(e)}}async function Xe(e){let{transport:t,device:n,envelope:r,descriptor:i}=e;if(i.transportMode!==t.mode)return{status:`transport-unavailable`};let a=await t.readManifest(i.manifestPath);if(a.status===`unavailable`)return{status:`transport-unavailable`};let o=a.status===`read`?R(a.contents):void 0;return o&&we(o,n,r)&&Te(o,i)?{status:`matched`,evidence:o}:{status:`ownership-lost`}}async function Ze(e){let t=await e.transport.readManifest(e.manifestPath);if(t.status!==`read`)return;let n=R(t.contents);return n&&Qe(n,e)?n:void 0}function Qe(e,t){return e.deviceId===t.deviceId&&e.sessionId===t.sessionId&&e.fenceToken===t.fence.token&&e.fenceGeneration===t.fence.generation}async function $e(e){let{host:t,transport:n,device:r,input:i}=e,a=I.decode(i.envelope.descriptor.body);if(a.status!==`decoded`)return Z(`descriptor-invalid`);let o=await Xe({transport:n,device:r,envelope:i.envelope,descriptor:a.descriptor});return o.status===`matched`?await et({host:t,transport:n,device:r,input:i,descriptor:a.descriptor,evidence:o.evidence}):Z(o.status===`transport-unavailable`?`transport-not-reattachable`:`ownership-fence-lost`)}async function X(e){let t=I.decode(e.input.envelope.descriptor.body);if(t.status!==`decoded`)return{status:`cleanup-pending`,reason:`manual-recovery-required`};let n=await Xe({transport:e.transport,device:e.device,envelope:e.input.envelope,descriptor:t.descriptor});return n.status===`matched`?await Ye(e.transport,n.evidence,t.descriptor.manifestPath):n.status===`transport-unavailable`?{status:`cleanup-pending`,reason:`owner-unavailable`}:{status:`cleanup-pending`,reason:`ownership-fence-lost`}}async function et(e){let{host:t,transport:n,device:r,input:i,descriptor:a,evidence:o}=e;if(o.completion!==void 0&&await tt(n,o))return{status:`completed`,result:o.completion};if(o.completion!==void 0)return Z(`ownership-fence-lost`,`Android recording completed evidence still names a live or unverifiable recorder.`);if(o.pendingRemotePath!==void 0)return Z(`transport-not-reattachable`,`Android recording launch was interrupted before its process identity was committed.`);let s=o.chunks.at(-1);if(!s)return{status:`missing`};let c=await n.inspect({pid:s.remotePid,remotePath:s.remotePath,startTime:s.remoteStartTime});if(c!==`owned-alive`&&await n.exists(s.remotePath)!==!0)return Z(`transport-not-reattachable`,`Android recording process ended before its artifact could be recovered.`);let l=nt(i.envelope.sessionId,i.envelope.fence,a),d=!1;return{status:`active`,handle:u(Ge(l,o.startedAt),{finish:async e=>{let r=await Je({host:t,transport:n,evidence:o,manifestPath:a.manifestPath,recording:e,reachedLimit:c===`missing`});return d=!0,r},forceCleanup:async()=>d?{status:`cleaned`}:await X({transport:n,device:r,input:i})})}}async function tt(e,t){try{for(let n of t.chunks)if(await e.inspect({pid:n.remotePid,remotePath:n.remotePath,startTime:n.remoteStartTime})!==`missing`)return!1;return!0}catch{return!1}}function nt(e,t,n){return{sessionId:e,outputPath:n.outputPath,...n.clientOutputPath===void 0?{}:{clientOutputPath:n.clientOutputPath},scope:n.scope,showTouches:n.showTouches,hideTouchesRequested:!1,recordOnlySession:n.recordOnlySession,...n.activeSessionApp===void 0?{}:{activeSessionApp:n.activeSessionApp},...n.exportQuality===void 0?{}:{exportQuality:n.exportQuality},fence:t}}function Z(e,t){return{status:`unreattachable`,reason:e,...t===void 0?{}:{message:t}}}async function rt(e){let{host:t,device:n,owner:r,signal:i}=e,a=await t.screenRecording.android.resolve(n);return Object.freeze({screenRecordingStart:async e=>await it({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await $e({host:t,transport:a,device:n,input:e}),screenRecordingCleanup:async e=>await X({transport:a,device:n,input:e})})}async function it(e){let{host:t,transport:n,device:s,owner:l,input:d,signal:f}=e;f.throwIfAborted();let p=Date.now(),m=await Fe({transport:n,device:s,input:d,startedAt:p,signal:f,prepareOutput:async()=>await t.screenRecording.outputs.prepare(d.outputPath)}),g=m.manifestPath,_=[m.chunk],v,y,b,x=!1,S=()=>{v=setTimeout(()=>{y=C().catch(e=>{b=e})},17e4),v.unref?.()},C=async()=>{let e=_.at(-1);if(!e)throw Error(`Android recording has no active chunk`);let t=!1,r;try{r=await Ue({transport:n,device:s,input:d,startedAt:p,chunks:_,manifestPath:g,preferredDir:h.posix.dirname(e.remotePath)})}catch(i){await q(n,e),t=!0;try{r=await Ue({transport:n,device:s,input:d,startedAt:p,chunks:_,manifestPath:g,preferredDir:h.posix.dirname(e.remotePath)})}catch(e){throw e instanceof Error?e:i}}let i=[..._,{...r,index:_.length+1}];try{await J(n,g,L(s,d,p,i,void 0,n.mode))}catch(i){if(await K(n,[r]).catch(()=>{}),t)await J(n,g,L(s,d,p,_,r.remotePath,n.mode)).catch(()=>{});else try{await J(n,g,L(s,d,p,_,void 0,n.mode))}catch{await q(n,e).catch(()=>{}),await J(n,g,L(s,d,p,_,r.remotePath,n.mode)).catch(()=>{})}throw i}_=i,t||await q(n,e),S()};S();let w=u(Ge(d,p),{finish:async e=>{if(v&&clearTimeout(v),await y,b)throw b;let r=await Je({host:t,transport:n,evidence:L(s,d,p,_,void 0,n.mode),manifestPath:g,recording:e});return x=!0,r},forceCleanup:async()=>{if(v&&clearTimeout(v),x)return{status:`cleaned`};try{await y}catch(e){b=e}let e=await Ze({transport:n,deviceId:s.id,sessionId:d.sessionId,fence:d.fence,manifestPath:g});return e?await Ye(n,e,g):{status:`cleanup-pending`,reason:`ownership-fence-lost`}}});return Object.freeze({pendingHandle:new i(w),envelope:c({resourceKind:r,sessionId:d.sessionId,device:a(s),owner:l,fence:d.fence,lifecycle:`open`,descriptor:o(I,{backend:`adb-screenrecord`,manifestPath:g,outputPath:d.outputPath,...d.clientOutputPath===void 0?{}:{clientOutputPath:d.clientOutputPath},scope:d.scope,showTouches:d.showTouches,recordOnlySession:d.recordOnlySession,...d.activeSessionApp===void 0?{}:{activeSessionApp:d.activeSessionApp},...d.exportQuality===void 0?{}:{exportQuality:d.exportQuality},transportMode:n.mode})})})}const Q=n(`android`),$=Object.freeze({available:!0});function at(e){let t=b(e);return Object.freeze({owner:Q,ownsDevice:e=>e.platform===`android`,bind:async n=>{let r=await t.bind(n),i=await rt({host:e,device:n.device,owner:Q,signal:n.scope.signal});return Object.freeze({device:r.device,owner:Q,facts:Object.freeze({device:r.facts.device,operations:{...r.facts.operations,networkDump:$,screenRecordingStart:$,screenRecordingReattach:$,screenRecordingCleanup:$}}),operations:Object.freeze({...r.operations,networkDump:async t=>await C(e,n.device,t,n.scope.signal),...i}),[Symbol.asyncDispose]:async()=>await r[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}export{at as createAndroidPlatformRuntime};
|
package/dist/src/runtime3.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";import{N as t,R as n,j as r,z as i}from"./sdk-batch-runner.js";import{c as a,l as o}from"./sdk-device.js";import{_ as s,a as c,d as l,f as u,h as d,l as f,m as p,n as m,o as h,p as g,t as _,u as v,y}from"./src2.js";import b from"node:path";const x=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function S(e){return o(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const C=Object.freeze({resourceKind:r,version:1,encode:e=>({...e}),decode:e=>!T(e.transport)||!E(e.backend)||!k(e.outputPath)||!D(e.pidPath)||!ee(e.transport,e.backend)?w():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function w(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function T(e){return e===`apple-log-stream`||e===`coredevice-console`}function E(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function ee(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function D(e){return e===void 0||k(e)}function O(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return s({resourceKind:r,sessionId:e.sessionId,device:{id:e.device.id,family:`apple`,appleOs:e.device.appleOs,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:y(C,e.descriptor)})}function k(e){return typeof e==`string`&&e.trim().length>0}const A={message:`iOS physical-device app console capture is not supported by the installed devicectl.`,hint:`This devicectl does not expose process launch --console. Markers can still be written to app.log, but app output is not being captured. Use an iOS simulator for agent-device app logs or inspect physical-device logs in Console.app/Xcode until this Xcode toolchain exposes scriptable console capture.`},j={message:`Could not verify iOS physical-device app console capture support.`,hint:`Retry logs clear --restart. If the probe keeps failing, run logs doctor and inspect the request diagnostics for the devicectl help command.`};async function M(e,t){try{let n=await e.appleTools.run({tool:`devicectl`,args:[`device`,`process`,`launch`,`--help`],allowFailure:!0,timeoutMs:5e3},t),r=n.stderr.trim()||void 0;if(n.exitCode!==0)return{supported:!1,reason:`probe-failed`,stderr:r};let i=`${n.stdout}\n${n.stderr}`;return/\bUSAGE:\s+devicectl device process launch\b/i.test(i)&&/--console\b/.test(i)&&/--terminate-existing\b/.test(i)?{supported:!0,...r?{stderr:r}:{}}:{supported:!1,reason:`unsupported`,...r?{stderr:r}:{}}}catch(e){if(t?.aborted)throw t.reason;return{supported:!1,reason:`probe-failed`,...e instanceof Error?{stderr:e.message}:{}}}}async function N(e,t,n,r){let i={},a=n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`];if(o(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await h(async()=>c(await e.appleTools.run({tool:`simctl`,args:[`help`],allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(x);else{i.devicectlAvailable=await h(async()=>c(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await M(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?A:j;a.push(`${e.message} ${e.hint}`)}}return{backend:S(t),checks:i,notes:a}}function P(e,t){let n=L(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=L(t);r.push(`process == "${e}"`,`processImagePath ENDSWITH[c] "/${e}"`,`senderImagePath ENDSWITH[c] "/${e}"`,`processImagePath CONTAINS[c] "/${e}.app/"`,`senderImagePath CONTAINS[c] "/${e}.app/"`)}return r.join(` OR `)}function F(e){return[...e.simulatorSetPath?[`simctl`,`--set`,e.simulatorSetPath]:[`simctl`],`spawn`,e.deviceId,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,P(e.appBundleId,e.executableName)]}function I(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function L(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}async function R(e,t,n,r,a){z(t),v(e,n);let o=S(t),s=await V(e,t,n.appBundleId,a),c=new i,l=!1;try{let i=await e.outputs.openAppend(n.outputPath);c.defer(async()=>{l||await i[Symbol.asyncDispose]()}),a?.throwIfAborted();let u=await B(e,t,s,i,n.pidPath,a);c.defer(async()=>{l||await u[Symbol.asyncDispose]()});let f=te(e,u,i,o,n.outputPath),p={transport:o===`ios-device`?`coredevice-console`:`apple-log-stream`,backend:o,outputPath:n.outputPath,...n.pidPath===void 0?{}:{pidPath:n.pidPath}},m=d(f,O({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:p}));return l=!0,m}finally{await c[Symbol.asyncDispose]()}}function z(t){if(t.appleOs===`watchos`)throw new e(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(a(t)&&t.kind===`device`&&t.iosPhysicalDeviceBackend===`xctest`)throw new e(`UNSUPPORTED_OPERATION`,x,{hint:x})}async function B(t,n,r,i,o,s){if(a(n)&&n.kind===`device`){let n=await M(t,s);if(!n.supported){let t=n.reason===`unsupported`?A:j;throw new e(n.reason===`unsupported`?`UNSUPPORTED_OPERATION`:`COMMAND_FAILED`,t.message,{backend:`ios-device`,hint:t.hint,stderr:n.stderr})}}return s?.throwIfAborted(),await t.processes.start({command:{kind:`host`,request:r},output:i,...o?{markerPath:o}:{}})}async function V(e,t,n,r){if(o(t))return{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,P(n)],allowFailure:!0};if(t.kind===`device`)return{executable:`xcrun`,args:I(t.id,n),allowFailure:!0};let i=await H(e,t,n,r);return{executable:`xcrun`,args:F({deviceId:t.id,appBundleId:n,executableName:i,simulatorSetPath:t.simulatorSetPath}),allowFailure:!0}}async function H(e,t,n,r){let i=t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],a=await e.appleTools.run({tool:`simctl`,args:[...i,`get_app_container`,t.id,n,`app`],allowFailure:!0,timeoutMs:4e3},r),o=a.exitCode===0?a.stdout.trim():``;if(!o)return;let s=await e.commands.run({executable:`plutil`,args:[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,b.join(o,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return s.exitCode===0&&s.stdout.trim()||void 0}function te(e,t,n,r,i){let a=e.clock.now(),o=`active`;t.wait.then(e=>{o=e.exitCode===0?`ended`:`failed`},()=>{o=`failed`});let s;return g({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await U([async()=>await t.terminate(),async()=>await t.wait.then(()=>void 0),async()=>await t[Symbol.asyncDispose](),async()=>await n[Symbol.asyncDispose]()])).length>0?(o=`failed`,{status:`cleanup-pending`,reason:`transport-failed`,message:`Apple app-log cleanup did not settle every owned resource`}):(o=`ended`,{status:`completed`,result:{backend:r,outputPath:i,completedAt:e.clock.now()}}))()})}async function U(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const W=t(`apple`),G=Object.freeze({available:!0});function K(t){return Object.freeze({owner:W,ownsDevice:e=>e.platform===`apple`,bind:async r=>{if(r.intent.kind===`exact-owner`&&!n(r.intent.owner,W))throw new e(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return q(t,r.device,r.scope.signal)},shutdown:async()=>void 0})}function q(t,n,r){if(n.platform!==`apple`)throw new e(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${n.platform}`);let i=p({codec:C,reattach:async(e,r)=>e.backend!==S(n)||!f(t,r.sessionId,e)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await u(t,e.pidPath),cleanup:async(e,r)=>e.backend===S(n)&&f(t,r.sessionId,e)?await l(t,e.pidPath):{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`Apple app-log descriptor does not match the bound device or owning session`}}),a=Object.freeze({appLogInspect:async()=>({backend:S(n)}),appLogDoctor:async({appBundleId:e})=>await N(t,n,e,r),appLogStart:async e=>await R(t,n,e,W,r),...i});return Object.freeze({device:n,owner:W,facts:J(n),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function J(e){if(e.appleOs===`watchos`)return Y(e);let t=a(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:x}:G;return Object.freeze({device:{family:`apple`,appleOs:e.appleOs,kind:e.kind,...e.target===void 0?{}:{target:e.target},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:G,appLogCleanup:G}})}function Y(e){let t=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS app logs are not supported.`});return Object.freeze({device:{family:`apple`,appleOs:`watchos`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:t,appLogCleanup:t}})}async function X(e,t,n,r){let i=S(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=m(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(Z(t,n,o)){let i=await Q(e,t,n,a.path,r);i&&(i.dump.entries.length>0?(o=_(i.dump,o,n.maxEntries),s.push(`Recovered ${i.dump.entries.length} iOS simulator HTTP entr${i.dump.entries.length===1?`y`:`ies`} from simctl log show (${i.lineCount} app log lines scanned).`)):i.lineCount>0&&s.push(`Recovered ${i.lineCount} recent iOS simulator app log lines from simctl log show, but none looked like HTTP traffic. This app may not emit request URLs, status, or timing into Unified Logging for this repro window.`))}return re(s,t,n),o.entries.length===0&&s.push(ie(t)),Object.freeze({source:`app-log`,backend:i,dump:o,notes:Object.freeze(s)})}function Z(e,t,n){return a(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function Q(e,t,n,r,i){let a=[...t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,ne(n.appBundleId)],o=n.appLogSnapshot?.startedAt;a.push(...typeof o==`number`&&Number.isFinite(o)&&o>0?[`--start`,`@${Math.floor(o/1e3)}`]:[`--last`,`5m`]);let s=await e.appleTools.run({tool:`simctl`,args:a,allowFailure:!0,timeoutMs:4e3},i);if(s.exitCode!==0||!s.stdout.trim())return;let c=s.stdout.split(`
|
|
2
|
-
`).map(e=>e.trimEnd()).filter(e=>e.trim()&&!e.trim().startsWith(`Timestamp Ty Process[PID:TID]`));if(c.length!==0)return{dump:
|
|
3
|
-
`)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function ne(e){let t=e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`);return[`subsystem == "${t}"`,`subsystem CONTAINS "${t}"`,`processImagePath ENDSWITH[c] "/${t}"`,`senderImagePath ENDSWITH[c] "/${t}"`].join(` OR `)}function re(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(a(t)&&t.kind===`simulator`?`Session app log stream is inactive. The iOS simulator recovery path scanned recent simctl log history, but a fresh logs clear --restart window is still the most reliable repro loop.`:`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):e.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`)}function ie(e){return a(e)&&e.kind===`simulator`?`No HTTP(s) entries were found in recent iOS simulator app logs. If the app only emits non-HTTP diagnostics, inspect logs path or add app-side URLSession/network logging for per-request timing and payload details.`:a(e)?`No HTTP(s) entries were found in recent iOS device app logs. iOS network dump only sees what the app emits into Unified Logging for this process.`:`No HTTP(s) entries were found in recent session app logs.`}const $=t(`apple`),ae=Object.freeze({available:!0});function oe(e){let t=K(e);return Object.freeze({owner:$,ownsDevice:e=>e.platform===`apple`,bind:async n=>{let r=await t.bind(n);return Object.freeze({device:r.device,owner:$,facts:Object.freeze({device:r.facts.device,operations:{...r.facts.operations,networkDump:ae}}),operations:Object.freeze({...r.operations,networkDump:async t=>await X(e,n.device,t,n.scope.signal)}),[Symbol.asyncDispose]:async()=>await r[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}export{oe as createApplePlatformRuntime};
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{F as t,H as n,L as r,P as i,U as a,W as o}from"./sdk-batch-runner.js";import{C as s,c,l}from"./sdk-device.js";import{S as u,_ as d,a as f,b as p,d as m,f as ee,g as te,h,l as g,m as ne,n as _,o as v,t as re,u as ie,v as ae}from"./src2.js";import y from"node:path";const b=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function x(e){return l(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const S=Object.freeze({resourceKind:t,version:1,encode:e=>({...e}),decode:e=>!se(e.transport)||!ce(e.backend)||!C(e.outputPath)||!ue(e.pidPath)||!le(e.transport,e.backend)?oe():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function oe(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function se(e){return e===`apple-log-stream`||e===`coredevice-console`}function ce(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function le(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function ue(e){return e===void 0||C(e)}function de(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return p({resourceKind:t,sessionId:e.sessionId,device:{id:e.device.id,family:`apple`,appleOs:e.device.appleOs,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:u(S,e.descriptor)})}function C(e){return typeof e==`string`&&e.trim().length>0}const w={message:`iOS physical-device app console capture is not supported by the installed devicectl.`,hint:`This devicectl does not expose process launch --console. Markers can still be written to app.log, but app output is not being captured. Use an iOS simulator for agent-device app logs or inspect physical-device logs in Console.app/Xcode until this Xcode toolchain exposes scriptable console capture.`},T={message:`Could not verify iOS physical-device app console capture support.`,hint:`Retry logs clear --restart. If the probe keeps failing, run logs doctor and inspect the request diagnostics for the devicectl help command.`};async function E(e,t){try{let n=await e.appleTools.run({tool:`devicectl`,args:[`device`,`process`,`launch`,`--help`],allowFailure:!0,timeoutMs:5e3},t),r=n.stderr.trim()||void 0;if(n.exitCode!==0)return{supported:!1,reason:`probe-failed`,stderr:r};let i=`${n.stdout}\n${n.stderr}`;return/\bUSAGE:\s+devicectl device process launch\b/i.test(i)&&/--console\b/.test(i)&&/--terminate-existing\b/.test(i)?{supported:!0,...r?{stderr:r}:{}}:{supported:!1,reason:`unsupported`,...r?{stderr:r}:{}}}catch(e){if(t?.aborted)throw t.reason;return{supported:!1,reason:`probe-failed`,...e instanceof Error?{stderr:e.message}:{}}}}async function fe(e,t,n,r){let i={},a=n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`];if(l(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await v(async()=>f(await e.appleTools.run({tool:`simctl`,args:[`help`],allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(b);else{i.devicectlAvailable=await v(async()=>f(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await E(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?w:T;a.push(`${e.message} ${e.hint}`)}}return{backend:x(t),checks:i,notes:a}}function D(e,t){let n=A(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=A(t);r.push(`process == "${e}"`,`processImagePath ENDSWITH[c] "/${e}"`,`senderImagePath ENDSWITH[c] "/${e}"`,`processImagePath CONTAINS[c] "/${e}.app/"`,`senderImagePath CONTAINS[c] "/${e}.app/"`)}return r.join(` OR `)}function O(e){return[...e.simulatorSetPath?[`simctl`,`--set`,e.simulatorSetPath]:[`simctl`],`spawn`,e.deviceId,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,D(e.appBundleId,e.executableName)]}function k(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function A(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)}async function j(e,t,n,r,i){M(t),ie(e,n);let o=x(t),s=await P(e,t,n.appBundleId,i),c=new a,l=!1;try{let a=await e.outputs.openAppend(n.outputPath);c.defer(async()=>{l||await a[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=await N(e,t,s,a,n.pidPath,i);c.defer(async()=>{l||await u[Symbol.asyncDispose]()});let d=I(e,u,a,o,n.outputPath),f={transport:o===`ios-device`?`coredevice-console`:`apple-log-stream`,backend:o,outputPath:n.outputPath,...n.pidPath===void 0?{}:{pidPath:n.pidPath}},p=ae(d,de({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:f}));return l=!0,p}finally{await c[Symbol.asyncDispose]()}}function M(t){if(t.appleOs===`watchos`)throw new e(`UNSUPPORTED_PLATFORM`,`watchOS app logs are not supported`);if(c(t)&&t.kind===`device`&&t.iosPhysicalDeviceBackend===`xctest`)throw new e(`UNSUPPORTED_OPERATION`,b,{hint:b})}async function N(t,n,r,i,a,o){if(c(n)&&n.kind===`device`){let n=await E(t,o);if(!n.supported){let t=n.reason===`unsupported`?w:T;throw new e(n.reason===`unsupported`?`UNSUPPORTED_OPERATION`:`COMMAND_FAILED`,t.message,{backend:`ios-device`,hint:t.hint,stderr:n.stderr})}}return o?.throwIfAborted(),await t.processes.start({command:{kind:`host`,request:r},output:i,...a?{markerPath:a}:{}})}async function P(e,t,n,r){if(l(t))return{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,D(n)],allowFailure:!0};if(t.kind===`device`)return{executable:`xcrun`,args:k(t.id,n),allowFailure:!0};let i=await F(e,t,n,r);return{executable:`xcrun`,args:O({deviceId:t.id,appBundleId:n,executableName:i,simulatorSetPath:t.simulatorSetPath}),allowFailure:!0}}async function F(e,t,n,r){let i=t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],a=await e.appleTools.run({tool:`simctl`,args:[...i,`get_app_container`,t.id,n,`app`],allowFailure:!0,timeoutMs:4e3},r),o=a.exitCode===0?a.stdout.trim():``;if(!o)return;let s=await e.commands.run({executable:`plutil`,args:[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,y.join(o,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return s.exitCode===0&&s.stdout.trim()||void 0}function I(e,t,n,r,i){let a=e.clock.now(),o=`active`;t.wait.then(e=>{o=e.exitCode===0?`ended`:`failed`},()=>{o=`failed`});let s;return te({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>s??=(async()=>(await L([async()=>await t.terminate(),async()=>await t.wait.then(()=>void 0),async()=>await t[Symbol.asyncDispose](),async()=>await n[Symbol.asyncDispose]()])).length>0?(o=`failed`,{status:`cleanup-pending`,reason:`transport-failed`,message:`Apple app-log cleanup did not settle every owned resource`}):(o=`ended`,{status:`completed`,result:{backend:r,outputPath:i,completedAt:e.clock.now()}}))()})}async function L(e){let t=[];for(let n of e)try{await n()}catch(e){t.push(e)}return t}const R=r(`apple`),z=Object.freeze({available:!0});function B(t){return Object.freeze({owner:R,ownsDevice:e=>e.platform===`apple`,bind:async r=>{if(r.intent.kind===`exact-owner`&&!n(r.intent.owner,R))throw new e(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return V(t,r.device,r.scope.signal)},shutdown:async()=>void 0})}function V(t,n,r){if(n.platform!==`apple`)throw new e(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${n.platform}`);let i=d({codec:S,reattach:async(e,r)=>e.backend!==x(n)||!g(t,r.sessionId,e)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await ee(t,e.pidPath),cleanup:async(e,r)=>e.backend===x(n)&&g(t,r.sessionId,e)?await m(t,e.pidPath):{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`Apple app-log descriptor does not match the bound device or owning session`}}),a=Object.freeze({appLogInspect:async()=>({backend:x(n)}),appLogDoctor:async({appBundleId:e})=>await fe(t,n,e,r),appLogStart:async e=>await j(t,n,e,R,r),...i});return Object.freeze({device:n,owner:R,facts:pe(n),operations:a,[Symbol.asyncDispose]:async()=>void 0})}function pe(e){if(e.appleOs===`watchos`)return me(e);let t=c(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:b}:z;return Object.freeze({device:{family:`apple`,appleOs:e.appleOs,kind:e.kind,...e.target===void 0?{}:{target:e.target},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:z,appLogCleanup:z}})}function me(e){let t=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`watchOS app logs are not supported.`});return Object.freeze({device:{family:`apple`,appleOs:`watchos`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:t,appLogCleanup:t}})}async function he(e,t,n,r){let i=x(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=_(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(ge(t,n,o)){let i=await _e(e,t,n,a.path,r);i&&(i.dump.entries.length>0?(o=re(i.dump,o,n.maxEntries),s.push(`Recovered ${i.dump.entries.length} iOS simulator HTTP entr${i.dump.entries.length===1?`y`:`ies`} from simctl log show (${i.lineCount} app log lines scanned).`)):i.lineCount>0&&s.push(`Recovered ${i.lineCount} recent iOS simulator app log lines from simctl log show, but none looked like HTTP traffic. This app may not emit request URLs, status, or timing into Unified Logging for this repro window.`))}return ye(s,t,n),o.entries.length===0&&s.push(be(t)),Object.freeze({source:`app-log`,backend:i,dump:o,notes:Object.freeze(s)})}function ge(e,t,n){return c(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function _e(e,t,n,r,i){let a=[...t.simulatorSetPath?[`--set`,t.simulatorSetPath]:[],`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,ve(n.appBundleId)],o=n.appLogSnapshot?.startedAt;a.push(...typeof o==`number`&&Number.isFinite(o)&&o>0?[`--start`,`@${Math.floor(o/1e3)}`]:[`--last`,`5m`]);let s=await e.appleTools.run({tool:`simctl`,args:a,allowFailure:!0,timeoutMs:4e3},i);if(s.exitCode!==0||!s.stdout.trim())return;let c=s.stdout.split(`
|
|
2
|
+
`).map(e=>e.trimEnd()).filter(e=>e.trim()&&!e.trim().startsWith(`Timestamp Ty Process[PID:TID]`));if(c.length!==0)return{dump:_(`${c.join(`
|
|
3
|
+
`)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function ve(e){let t=e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`);return[`subsystem == "${t}"`,`subsystem CONTAINS "${t}"`,`processImagePath ENDSWITH[c] "/${t}"`,`senderImagePath ENDSWITH[c] "/${t}"`].join(` OR `)}function ye(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(c(t)&&t.kind===`simulator`?`Session app log stream is inactive. The iOS simulator recovery path scanned recent simctl log history, but a fresh logs clear --restart window is still the most reliable repro loop.`:`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):e.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`)}function be(e){return c(e)&&e.kind===`simulator`?`No HTTP(s) entries were found in recent iOS simulator app logs. If the app only emits non-HTTP diagnostics, inspect logs path or add app-side URLSession/network logging for per-request timing and payload details.`:c(e)?`No HTTP(s) entries were found in recent iOS device app logs. iOS network dump only sees what the app emits into Unified Logging for this process.`:`No HTTP(s) entries were found in recent session app logs.`}async function H(e,t,n){if(t.invalidatedReason&&!t.showTouches)throw Error(`recording invalidated: ${t.invalidatedReason}`);return ne(t,{...await e.screenRecording.finalize.complete({outputPath:t.outPath,showTouches:t.invalidatedReason?!1:t.showTouches,gestureEvents:t.gestureEvents,exportQuality:t.exportQuality??`medium`,...t.runnerStartedAtUptimeMs!==void 0&&t.targetAppReadyUptimeMs!==void 0?{trimStartMs:Math.max(0,t.targetAppReadyUptimeMs-t.runnerStartedAtUptimeMs)}:{},targetLabel:n}),...t.invalidatedReason?{overlayWarning:`overlay unavailable: ${t.invalidatedReason}`}:{}})}const U=Object.freeze({resourceKind:i,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e}))}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>Ee(e)});function xe(e){let{device:t,owner:n,input:r,descriptor:a}=e;return p({resourceKind:i,sessionId:r.sessionId,device:s(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:u(U,a)})}async function Se(e,t,n){let r=U.decode(n);return r.status!==`decoded`||!K(t,r.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:r.descriptor.backend===`simctl`?await Ce(e,r.descriptor.processes):await we(e,t,r.descriptor)}async function Ce(e,t){let n=await Promise.all(t.map(async t=>await e.screenRecording.apple.inspectProcess(t)));if(n.includes(`ownership-lost`))return{status:`cleanup-pending`,reason:`ownership-fence-lost`};if(n.every(e=>e===`missing`))return{status:`already-missing`};let r=await Promise.all(t.flatMap((t,r)=>n[r]===`owned-alive`?[e.screenRecording.apple.terminateProcess(t)]:[]));return r.includes(`ownership-lost`)?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:r.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`}}async function we(e,t,n){try{let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`already-missing`}:r===`ownership-lost`?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(await e.screenRecording.apple.runRunner(t,{kind:`stop`,appBundleId:n.appBundleId,runnerSessionId:n.runnerSessionId,runnerAuthority:n.runnerAuthority}),{status:`cleaned`})}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple recording cleanup failed`}}}async function Te(e,t,n){let r=U.decode(n);if(r.status!==`decoded`)return{status:`unreattachable`,reason:`descriptor-invalid`,message:r.message};if(!K(t,r.descriptor))return{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple screen-recording descriptor does not match the bound device.`};let i=r.descriptor.backend===`simctl`?await Promise.all(r.descriptor.processes.map(async t=>await e.screenRecording.apple.inspectProcess(t))):[await e.screenRecording.apple.inspectRunner(t,r.descriptor.runnerSessionId,r.descriptor.runnerAuthority)];return i.every(e=>e===`missing`)?{status:`missing`}:{status:`unreattachable`,reason:`transport-not-reattachable`,message:i.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`}}function Ee(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?q():e.backend===`simctl`?De(e,e.outputPath):e.backend===`runner`?Oe(e,e.outputPath):q()}function De(e,t){let n=je(e.processes);return n?{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n})}:q()}function Oe(e,t){return!W(e.appBundleId)||!W(e.runnerSessionId)||!ke(e.runnerAuthority)||!Ae(e.remotePath)?q():{status:`decoded`,descriptor:Object.freeze({backend:`runner`,outputPath:t,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}})}}function W(e){return typeof e==`string`&&e.length>0}function ke(e){return e===`local-lease`||e===`scoped-provider`}function Ae(e){return e===void 0||G(e)}function G(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function K(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:c(e)?t.remotePath!==void 0&&G(t.remotePath):t.remotePath===void 0:!1}function je(e){if(!Array.isArray(e)||e.length===0)return;let t=e.filter(e=>typeof e==`object`&&!!e&&Number.isInteger(e.pid)&&(e.pid??0)>0&&typeof e.startTime==`string`&&e.startTime.length>0&&typeof e.command==`string`&&e.command.length>0);return t.length===e.length?Object.freeze([...t]):void 0}function q(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function Me(e,t,n){if(e.kind!==`simulator`||t.scope!==`app`)return;let r=t.activeSessionApp?.bundleId;if(!r)throw TypeError(`App-scoped recording requires an active app session; open the app under test before recording.`);if(await n(r))throw TypeError(`App-scoped recording requires a real application session; open the app under test before recording.`)}function Ne(e){return e.appleOs===`watchos`?Q(`unsupported-platform-leaf`,`watchOS recording is not supported.`):c(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?Q(`unsupported-device-backend`,`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`):Object.freeze({available:!0})}function Pe(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await Fe({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>await Te(t,n,e.envelope.descriptor.body),screenRecordingCleanup:async e=>await Se(t,n,e.envelope.descriptor.body)})}async function Fe(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await J(e):await Ie(e)}async function J(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await Me(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a):void 0;await t.screenRecording.outputs.prepare(i.outputPath);let s=await t.screenRecording.apple.startSimulator(n,i.outputPath,a),c=s.markers;if(!c||c.length===0)throw await Y(s).catch(()=>{}),Error(`simctl recordVideo did not expose durable process identity`);try{a.throwIfAborted()}catch(e){throw await Y(s).catch(()=>{}),e}return X({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:i.outputPath,processes:c},snapshot:Z(i,`simctl recordVideo`,{},o),finish:async e=>{await s.terminate();let n=await s.wait;if(n.exitCode!==0)throw Error(`simctl recordVideo exited with code ${n.exitCode}`);return await H(t,e,`iOS recording`)},cleanup:async()=>await Re(s)})}async function Ie(e){let{host:t,device:n,owner:r,input:i,signal:a}=e,o=i.activeSessionApp?.bundleId;if(!o)throw TypeError(`Apple runner recording requires an active app session identity`);await t.screenRecording.outputs.prepare(i.outputPath);let s=await t.screenRecording.apple.runRunner(n,{kind:`start`,appBundleId:o,outputPath:i.outputPath,...i.fps===void 0?{}:{fps:i.fps}},a);if(!s.runnerSessionId||!s.runnerAuthority)throw Error(`Apple runner recording did not expose durable session ownership`);let c={runnerSessionId:s.runnerSessionId,runnerAuthority:s.runnerAuthority},l,u=()=>l??=t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0);if(!Le(n,s.remotePath))throw await u().catch(()=>{}),Error(`Apple runner recording did not expose coherent durable media ownership`);try{a.throwIfAborted()}catch(e){throw await u().catch(()=>{}),e}return X({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:Z(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await H(t,e,n.appleOs===`macos`?`macOS recording`:`iOS recording`)),cleanup:async()=>(await u(),{status:`cleaned`})})}function Le(e,t){return e.appleOs===`macos`||!c(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function Y(e){return await e.terminate(),await e.wait}async function Re(e){try{return await Y(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function X(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:s,cleanup:c}=e,l=h(a,{finish:s,forceCleanup:c});return Object.freeze({pendingHandle:new o(l),envelope:xe({device:t,owner:n,input:r,descriptor:i})})}function Z(e,t,n={},r){let i=Date.now();return Object.freeze({backend:t,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:i,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},gestureEvents:[],...r===void 0?{}:{gestureClockOriginAtMs:r.wallClockAtMs,gestureClockOriginUptimeMs:r.uptimeMs},...n.recorderStartUptimeMs===void 0?{}:{gestureClockOriginAtMs:i,gestureClockOriginUptimeMs:n.recorderStartUptimeMs,runnerStartedAtUptimeMs:n.recorderStartUptimeMs},...n.targetAppReadyUptimeMs===void 0?{}:{targetAppReadyUptimeMs:n.targetAppReadyUptimeMs},...n.runnerSessionId===void 0?{}:{runnerSessionId:n.runnerSessionId}})}function Q(e,t){return Object.freeze({available:!1,reason:e,hint:t})}const $=r(`apple`),ze=Object.freeze({available:!0});function Be(e){let t=B(e);return Object.freeze({owner:$,ownsDevice:e=>e.platform===`apple`,bind:async n=>{let r=await t.bind(n),i=Ne(n.device),a=i.available?await e.screenRecording.apple.availability(n.device):void 0,o=i.available&&a?.available===!1?Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:a.hint}):i;return Object.freeze({device:r.device,owner:$,facts:Object.freeze({device:r.facts.device,operations:{...r.facts.operations,networkDump:ze,screenRecordingStart:o,screenRecordingReattach:o,screenRecordingCleanup:o}}),operations:Object.freeze({...r.operations,networkDump:async t=>await he(e,n.device,t,n.scope.signal),...o.available?Pe({host:e,device:n.device,owner:$,signal:n.scope.signal}):{}}),[Symbol.asyncDispose]:async()=>await r[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}export{Be as createApplePlatformRuntime};
|
package/dist/src/runtime4.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{F as t,L as n,P as r,W as i}from"./sdk-batch-runner.js";import{C as a}from"./sdk-device.js";import{S as o,b as s,c,h as l,m as u,p as d,s as f}from"./src2.js";import{randomUUID as p}from"node:crypto";const m=Object.freeze({resourceKind:t,version:1,encode:e=>({...e}),decode:e=>e.transport!==`harmony-hilog`||!g(e.outputPath)||!g(e.pidPath)?{status:`invalid`,message:`Invalid HarmonyOS app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:`harmony-hilog`,outputPath:e.outputPath,pidPath:e.pidPath})}});function h(e){return s({resourceKind:t,sessionId:e.sessionId,device:{id:e.device.id,family:`harmonyos`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:o(m,e.descriptor)})}function g(e){return typeof e==`string`&&e.trim().length>0}function _(e){return f(e,{family:`harmonyos`,backend:`harmonyos`,label:`HarmonyOS`,codec:m,startUnavailableHint:`The selected HarmonyOS transport cannot start a background hilog stream.`,cleanupFailureMessage:`HarmonyOS app-log cleanup did not settle every owned resource`,doctor:async(e,t)=>({backend:`harmonyos`,checks:{},notes:t?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}),process:async({host:e,device:t,input:n,signal:r})=>{let i=await v(e,r);return{resolvePid:async r=>await c(e,{executable:i,args:[`-t`,t.id,`shell`,`pidof`,n.appBundleId],allowFailure:!0,timeoutMs:5e3},r),command:e=>({kind:`host`,request:{executable:i,args:[`-t`,t.id,`shell`,`hilog`,`-P`,e],allowFailure:!0}})}},descriptor:({artifacts:e})=>({transport:`harmony-hilog`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>h({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function v(t,n){n.throwIfAborted(),await y(async()=>await t.toolchains.prepare(`harmonyos`),n),n.throwIfAborted();let r=await y(async()=>await t.commands.which(`hdc`),n);if(n.throwIfAborted(),!r)throw new e(`TOOL_MISSING`,`hdc not found in PATH`,{hint:`Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.`});return r}async function y(e,t){try{return await e()}catch(e){throw t.throwIfAborted(),e}}const b=Object.freeze({resourceKind:r,version:1,encode:e=>({...e}),decode:e=>e.backend===`harmony-screen-recorder`&&typeof e.fileName==`string`&&C(e.fileName)&&e.remotePath===`/data/local/tmp/${e.fileName}`?{status:`decoded`,descriptor:Object.freeze({backend:`harmony-screen-recorder`,fileName:e.fileName,remotePath:e.remotePath})}:{status:`invalid`,message:`Invalid HarmonyOS screen-recording descriptor`}});function x(e){let{device:t,owner:n,input:i,descriptor:c}=e;return s({resourceKind:r,sessionId:i.sessionId,device:a(t),owner:n,fence:i.fence,lifecycle:`open`,descriptor:o(b,c)})}function S(e){return b.decode(e).status===`decoded`?{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`HarmonyOS recorder ownership cannot be proven after daemon restart; no recorder was stopped.`}:{status:`cleanup-pending`,reason:`manual-recovery-required`}}function C(e){return/^agent-device-recording-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.mp4$/i.test(e)}function w(e){return e.kind===`device`?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS recording is supported on physical devices only.`})}function T(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await E({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`HarmonyOS recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async e=>S(e.envelope.descriptor.body)})}async function E(t){let{host:n,device:r,owner:a,input:o,signal:s}=t;if(o.scope===`app`)throw new e(`INVALID_ARGS`,`HarmonyOS recording captures the whole physical-device screen; use --scope device or --scope system`);d(o,{scopes:[`device`,`system`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`HarmonyOS recordings do not support ${e.join(`, `)}`),s.throwIfAborted(),await n.screenRecording.outputs.prepare(o.outputPath);let c=`agent-device-recording-${p()}.mp4`,u={backend:`harmony-screen-recorder`,fileName:c,remotePath:`/data/local/tmp/${c}`},f;try{f=await n.screenRecording.harmony.start(r,c,s),s.throwIfAborted()}catch(e){throw s.aborted?(await A(n,r,u).catch(()=>{}),s.reason):e}N(f,`start`);try{s.throwIfAborted()}catch(e){throw await A(n,r,u).catch(()=>{}),e}let m=D(o),h=!1,g=async()=>{h||=(N(await n.screenRecording.harmony.stop(r),`stop`),!0)},_=l(m,{finish:async e=>await O(n,r,e,u,g),forceCleanup:async()=>await A(n,r,u,g)});return Object.freeze({pendingHandle:new i(_),envelope:x({device:r,owner:a,input:o,descriptor:u})})}function D(e){return Object.freeze({backend:`HarmonyOS ScreenRecorder`,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:Date.now(),scope:e.scope,showTouches:!1,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},gestureEvents:[]})}async function O(e,t,n,r,i){await i();let a=await e.screenRecording.harmony.findMedia(t,r.fileName);if(!a)throw Error(`failed to find finalized HarmonyOS recording '${r.fileName}'`);if(!await k(e,t,r,a))throw Error(`failed to finalize HarmonyOS recording: ${r.fileName} did not produce a non-empty media file`);let o=!1;try{if((await e.screenRecording.harmony.pull(t,{remotePath:r.remotePath,outputPath:n.outPath})).exitCode!==0)throw Error(`failed to retrieve HarmonyOS recording`);let i=await e.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!1,gestureEvents:n.gestureEvents,targetLabel:`HarmonyOS recording`});return o=!0,u(n,i,!1)}finally{await e.screenRecording.harmony.remove(t,r.remotePath).catch(()=>{}),o&&await e.screenRecording.harmony.removeMedia(t,a).catch(()=>{})}}async function k(e,t,n,r){let i;for(let a=0;a<40;a+=1){if(await e.screenRecording.harmony.remove(t,n.remotePath).catch(()=>{}),await e.screenRecording.harmony.stageMedia(t,{mediaUri:r,remotePath:n.remotePath})){let r=await e.screenRecording.harmony.stagedFileSize(t,n.remotePath);if(r!==void 0&&r>0&&r===i)return!0;i=r!==void 0&&r>0?r:void 0}else i=void 0;a<39&&await e.clock.sleep(250)}return!1}async function A(e,t,n,r=async()=>{N(await e.screenRecording.harmony.stop(t),`stop`)}){let i=[await M(r),await M(async()=>{if(!await e.screenRecording.harmony.remove(t,n.remotePath))throw Error(`HarmonyOS recording staging artifact removal was not confirmed`)}),await M(async()=>await j(e,t,n.fileName))].find(e=>e!==void 0);return i===void 0?{status:`cleaned`}:{status:`cleanup-pending`,reason:`transport-failed`,message:i instanceof Error?i.message:`HarmonyOS recording cleanup failed`}}async function j(e,t,n){let r=await e.screenRecording.harmony.findMedia(t,n);if(r&&!await e.screenRecording.harmony.removeMedia(t,r))throw Error(`HarmonyOS recording media removal was not confirmed`)}async function M(e){try{await e();return}catch(e){return e}}function N(e,t){if(e.exitCode===0&&e.stdout.includes(`start ability successfully`))return;let n=e.stdout.trim()||e.stderr.trim()||`hdc exit ${e.exitCode}`;throw Error(`failed to ${t} HarmonyOS screen recording: ${n}`)}const P=n(`harmonyos`),F=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function I(e){let t=_(e);return Object.freeze({owner:P,ownsDevice:e=>e.platform===`harmonyos`,bind:async n=>{let r=await t.bind(n),i=w(n.device);return Object.freeze({device:r.device,owner:P,facts:Object.freeze({device:r.facts.device,operations:{...r.facts.operations,networkDump:F,screenRecordingStart:i,screenRecordingReattach:i,screenRecordingCleanup:i}}),operations:Object.freeze({...r.operations,...i.available?T({host:e,device:n.device,owner:P,signal:n.scope.signal}):{}}),[Symbol.asyncDispose]:async()=>await r[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}export{I as createHarmonyPlatformRuntime};
|
package/dist/src/runtime7.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{_ as e}from"./sdk-contracts.js";import{H as t,L as n,P as r,W as i}from"./sdk-batch-runner.js";import{C as a}from"./sdk-device.js";import{S as o,b as s,h as c,m as l,p as u}from"./src2.js";const d=Object.freeze({resourceKind:r,version:1,encode:e=>({...e}),decode:e=>e.backend===`agent-browser`&&typeof e.outputPath==`string`?{status:`decoded`,descriptor:Object.freeze({backend:`agent-browser`,outputPath:e.outputPath})}:{status:`invalid`,message:`Invalid web screen-recording descriptor`}});async function f(e){let{host:t,device:n,owner:r,signal:i}=e,a=await t.screenRecording.web.resolve(n);return a?{available:!0,operations:{screenRecordingStart:async e=>await p({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`Web recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async()=>m()}}:{available:!1,operations:{}}}async function p(t){let{host:n,transport:f,device:p,owner:m,input:h,signal:g}=t;if(h.recordOnlySession)throw new e(`INVALID_ARGS`,`record on web requires an active browser session; run open <url> --platform web first`);if(!h.outputPath.toLowerCase().endsWith(`.webm`))throw new e(`INVALID_ARGS`,`web recordings require a .webm output path; agent-browser records WebM directly`);u(h,{scopes:[`app`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`web recordings do not support ${e.join(`, `)}; agent-browser records WebM directly`),g.throwIfAborted(),await n.screenRecording.outputs.prepare(h.outputPath);let _=!1;try{await f.start(h.outputPath,g),_=!0,g.throwIfAborted()}catch(e){throw _&&await f.stop().catch(()=>{}),g.throwIfAborted(),e}let v=!1,y=async()=>{v||=(await f.stop(),!0)},b=c({backend:`agent-browser`,outPath:h.outputPath,...h.clientOutputPath===void 0?{}:{clientOutPath:h.clientOutputPath},startedAt:Date.now(),scope:h.scope,showTouches:!1,recordOnlySession:h.recordOnlySession,...h.activeSessionApp===void 0?{}:{activeSessionApp:h.activeSessionApp},gestureEvents:[]},{finish:async e=>(await y(),l(e,await n.screenRecording.finalize.complete({outputPath:e.outPath,showTouches:!1,gestureEvents:e.gestureEvents,targetLabel:`web recording`}),!1)),forceCleanup:async()=>{try{return await y(),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Web recording cleanup failed`}}}});return Object.freeze({pendingHandle:new i(b),envelope:s({resourceKind:r,sessionId:h.sessionId,device:a(p),owner:m,fence:h.fence,lifecycle:`open`,descriptor:o(d,{backend:`agent-browser`,outputPath:h.outputPath})})})}function m(){return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`Web recordings cannot be cleaned after daemon restart.`}}const h=n(`web`),g=Object.freeze({available:!0}),_=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),v=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`record is not supported by this web provider`});function y(n){return Object.freeze({owner:h,ownsDevice:e=>e.platform===`web`,bind:async r=>{if(r.intent.kind===`exact-owner`&&!t(r.intent.owner,h))throw new e(`UNSUPPORTED_OPERATION`,`Web runtime owner identity does not match`);if(r.device.platform!==`web`)throw new e(`UNSUPPORTED_PLATFORM`,`Web runtime owner cannot bind ${r.device.platform}`);let i=await n.networkTransports.resolve(r.device),a=await f({host:n,device:r.device,owner:h,signal:r.scope.signal});return b(r.device,r.scope.signal,i,a)},shutdown:async()=>void 0})}function b(e,t,n,r){let i=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`network is not supported by this web provider`}),a=n.dump,o={...a?{networkDump:async e=>{let n=await a({maxEntries:e.maxEntries,include:e.include},t);return Object.freeze({source:`provider`,...n})}}:{},...r.operations},s=Object.freeze({device:{family:`web`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:n.mode},operations:{appLogInspect:_,appLogDoctor:_,appLogStart:_,appLogReattach:_,appLogCleanup:_,networkDump:n.dump?g:i,screenRecordingStart:r.available?g:v,screenRecordingReattach:r.available?g:v,screenRecordingCleanup:r.available?g:v}});return Object.freeze({device:e,owner:h,facts:s,operations:Object.freeze(o),[Symbol.asyncDispose]:async()=>void 0})}export{y as createWebPlatformRuntime};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{E as e,_ as t,h as n}from"./sdk-contracts.js";import{$ as r,At as i,Et as a,H as o,S as s,Tt as c,U as l,jt as u,lt as ee,n as te,pt as ne,t as re}from"./version.js";import{Gn as ie,It as ae,Kn as oe,Lt as se,Rt as ce,Wn as d,it as le,mt as ue,st as f,x as de,zt as fe}from"./sdk-batch-runner.js";import{_ as pe,i as me,r as he,t as ge}from"./sdk-device.js";import{$t as _e,Xt as p,Yt as ve,gn as ye,qt as be,rn as xe}from"./prepare-kind.js";import{t as Se}from"./device.js";import{A as m,M as h}from"./sdk-android-adb.js";import{n as Ce,t as we}from"./path-resolution.js";import{d as Te,n as Ee,o as De,s as Oe}from"./host-process.js";import g from"node:path";import ke from"node:crypto";import _ from"node:fs";import{StringDecoder as Ae}from"node:string_decoder";function v(e){return e.startsWith(`@`)?n(e)?.base??e:e}const y=/^-?\d+(\.\d+)?$/,je=/^[^\s"\\]+$/,Me=new Map([[`--count`,`count`],[`--interval-ms`,`intervalMs`],[`--hold-ms`,`holdMs`],[`--jitter-px`,`jitterPx`]]),Ne=new Map([[`--count`,`count`],[`--pause-ms`,`pauseMs`]]),Pe=new Map([[`--pointer-count`,`pointerCount`]]),Fe=new Map([[`--delay-ms`,`delayMs`]]);function b(e){return e===`click`||e===`press`}function Ie(e){return b(e)||e===`longpress`}function Le(e){return e===`type`||e===`fill`}function x(e){return ze(e,Be)}function Re(e){return JSON.stringify(e)}function S(e){return ze(e,Ve)}function ze(e,t){return t(e)?e:Re(e)}function Be(e){return Ve(e)&&e.startsWith(`@`)||y.test(e)}function Ve(e){return je.test(e)}const He=new Set([`fill`,`type`]);function Ue(e){if(!He.has(e.command)){let t=(e.positionals??[]).map(e=>x(e));return[e.command,...t].join(` `)}let t=We(e).map(e=>x(e)).join(` `);return[e.command,t,`<text>`].filter(e=>e.length>0).join(` `)}function We(e){if(e.command===`type`)return[];let t=e.positionals??[],n=t[0];return n===void 0?[]:n.startsWith(`@`)?[n]:t.length>=3&&y.test(n)&&y.test(t[1]??``)?[n,t[1]]:[n]}function C(e,t){let n=t.flags??{};if(b(t.command)){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.intervalMs==`number`&&e.push(`--interval-ms`,String(n.intervalMs)),typeof n.holdMs==`number`&&e.push(`--hold-ms`,String(n.holdMs)),typeof n.jitterPx==`number`&&e.push(`--jitter-px`,String(n.jitterPx)),n.doubleTap===!0&&e.push(`--double-tap`);let t=n.clickButton;t&&t!==`primary`&&e.push(`--button`,t);return}if(t.command===`swipe`){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.pauseMs==`number`&&e.push(`--pause-ms`,String(n.pauseMs)),(n.pattern===`one-way`||n.pattern===`ping-pong`)&&e.push(`--pattern`,n.pattern);return}if(t.command===`gesture`){typeof n.pointerCount==`number`&&e.push(`--pointer-count`,String(n.pointerCount));return}Le(t.command)&&typeof n.delayMs==`number`&&e.push(`--delay-ms`,String(n.delayMs))}function Ge(e,t){t&&((t.platform===`ios`||t.platform===`android`)&&e.push(`--platform`,t.platform),typeof t.metroHost==`string`&&t.metroHost.length>0&&e.push(`--metro-host`,S(t.metroHost)),typeof t.metroPort==`number`&&e.push(`--metro-port`,String(t.metroPort)),typeof t.bundleUrl==`string`&&t.bundleUrl.length>0&&e.push(`--bundle-url`,S(t.bundleUrl)),typeof t.launchUrl==`string`&&t.launchUrl.length>0&&e.push(`--launch-url`,S(t.launchUrl)))}function Ke(e,t){let[n,...r]=t.positionals??[];n&&e.push(S(n));for(let t of r)e.push(x(t));typeof t.flags?.fps==`number`&&e.push(`--fps`,String(t.flags.fps)),(typeof t.flags?.quality==`number`||typeof t.flags?.quality==`string`)&&e.push(`--quality`,String(t.flags.quality)),t.flags?.hideTouches&&e.push(`--hide-touches`)}function qe(e,t){t.flags?.snapshotInteractiveOnly&&e.push(`-i`),typeof t.flags?.snapshotDepth==`number`&&e.push(`-d`,String(t.flags.snapshotDepth)),t.flags?.snapshotScope&&e.push(`-s`,x(t.flags.snapshotScope)),t.flags?.snapshotRaw&&e.push(`--raw`)}function Je(e,t){for(let n of t.positionals??[])e.push(x(n));i(e,t.flags)}function Ye(e,t,n={}){let r=t.positionals??[],i=n.includeAllPositionals?r:r.slice(0,1);for(let t of i)e.push(S(t));Ge(e,t.flags)}function Xe(e,t){for(let n of t.positionals??[])e.push(x(t.command===`wait`?v(n):n));C(e,t)}function w(e,t){let n=[],r={},i=b(e)?Me:e===`swipe`?Ne:e===`gesture`?Pe:Le(e)?Fe:void 0;for(let a=0;a<t.length;a+=1){let o=t[a];if(b(e)&&o===`--double-tap`){r.doubleTap=!0;continue}let s=t[a+1];if(b(e)&&o===`--button`&&s!==void 0){let e=s;(e===`primary`||e===`secondary`||e===`middle`)&&(r.clickButton=e),a+=1;continue}let c=i?.get(o);if(c&&s!==void 0){let e=Qe(s);if(e!==null){r[c]=e,a+=1;continue}}if(e===`swipe`&&o===`--pattern`&&s!==void 0){let e=s;(e===`one-way`||e===`ping-pong`)&&(r.pattern=e),a+=1;continue}n.push(o)}return{positionals:n,flags:r}}function Ze(e){let t=[],n={};for(let r=0;r<e.length;r+=1){let i=e[r],a=e[r+1];if(i===`--platform`&&a!==void 0){let e=a;(e===`ios`||e===`android`)&&(n.platform=e),r+=1;continue}if(i===`--metro-host`&&a!==void 0){n.metroHost=a,r+=1;continue}if(i===`--metro-port`&&a!==void 0){let e=Qe(a);e!==null&&(n.metroPort=e),r+=1;continue}if(i===`--bundle-url`&&a!==void 0){n.bundleUrl=a,r+=1;continue}if(i===`--launch-url`&&a!==void 0){n.launchUrl=a,r+=1;continue}t.push(i)}return{positionals:t,flags:n}}function Qe(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function $e(e){let t;for(let n of e){if(n.command===`runtime`&&typeof n.flags.platform==`string`){t=n.flags.platform;continue}if(n.command===`open`)return n.runtime?.platform??t}return t}function et(e,t){for(let n of t.positionals??[])e.push(x(n));t.flags?.relaunch&&e.push(`--relaunch`),Ge(e,t.runtime)}function tt(e){let t=[],n={};for(let r of e){if(r===`--relaunch`){n.relaunch=!0;continue}t.push(r)}let r=Ze(t);return{positionals:r.positionals,flags:n,runtime:nt(r.flags)?r.flags:void 0}}function nt(e){return!!(e.platform||e.metroHost||e.metroPort!==void 0||e.bundleUrl||e.launchUrl)}const rt=/^[A-Z_][A-Z0-9_]*$/,it=new Set(he.filter(e=>e!==`web`)),at=new Set([`mobile`,`tv`,`desktop`]);function ot(e){let n=[],r=[],i=e.split(/\r?\n/),a=!1,s,c=(e,n,r)=>{throw new t(`INVALID_ARGS`,`${e.kind===`multiple`?`targets-v1`:`target-v1`} annotation on line ${e.line} must be immediately followed by its action line (line ${n+1} ${r}).`)};for(let[e,l]of i.entries()){let i=l.trim();if(i.length===0){s&&c(s,e,`is blank`);continue}if(i.startsWith(`#`)){let t=ce(i);if(t.kind===`v1`){s&&c(s,e,`is another target annotation`),s={kind:`multiple`,evidence:t.evidence,line:e+1};continue}let n=fe(i);if(n.kind===`v1`){s&&c(s,e,`is another target annotation`),s={kind:`single`,evidence:n.evidence,line:e+1};continue}s&&c(s,e,`is a comment`);continue}if(ct(i)){if(s&&c(s,e,`is an env directive`),a)throw new t(`INVALID_ARGS`,`env directives must precede all actions (line ${e+1}).`);continue}let u=ft(l);if(!u){s&&c(s,e,`did not parse as an action`);continue}let ee=o(u.command,u.positionals??[],`line ${e+1}`);if(ee)throw new t(`INVALID_ARGS`,ee);s&&=(s.kind===`single`?u.targetEvidence=s.evidence:u.targetEvidences=s.evidence,void 0),n.push(u),r.push(e+1),a=!0}if(s)throw new t(`INVALID_ARGS`,`${s.kind===`multiple`?`targets-v1`:`target-v1`} annotation on line ${s.line} must be immediately followed by its action line (end of script reached).`);return{actions:n,actionLines:r}}function st(e){let t=e.split(/\r?\n/),n={};for(let[e,r]of t.entries()){let t=r.trim();if(t.length===0||t.startsWith(`#`))continue;if(ct(t)){dt(n,t,e+1);continue}if(!t.startsWith(`context `))break;let i=t.match(/(?:^|\s)platform=([^\s]+)/);if(i){let e=i[1];e&&it.has(e)&&T(n,`platform`,e)}let a=t.match(/(?:^|\s)target=([^\s]+)/);if(a){let e=a[1];e&&at.has(e)&&T(n,`target`,e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&T(n,`timeoutMs`,Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&T(n,`retries`,Math.floor(e))}}return n}function ct(e){return e===`env`||e.startsWith(`env `)||e.startsWith(`env `)}function lt(e,n){let r=e.slice(3).replace(/^[\s]+/,``),i=r.indexOf(`=`);if(i<=0)throw new t(`INVALID_ARGS`,`Invalid env directive on line ${n}: expected "env KEY=VALUE".`);let a=r.slice(0,i);if(!rt.test(a))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(a.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: the AD_* namespace is reserved for built-in variables. Rename ${a} to avoid the AD_ prefix.`);return{key:a,value:ut(r.slice(i+1),n)}}function ut(e,n){if(e.length===0)return``;if(e.startsWith(`"`))try{let t=JSON.parse(e);if(typeof t!=`string`)throw Error(`not a string literal`);return t}catch{throw new t(`INVALID_ARGS`,`Invalid quoted env value on line ${n}.`)}return e}function dt(e,n,r){let{key:i,value:a}=lt(n,r),o=e.env??{};if(Object.prototype.hasOwnProperty.call(o,i))throw new t(`INVALID_ARGS`,`Duplicate env directive "${i}" on line ${r}.`);o[i]=a,e.env=o}function T(e,n,r){let i=e[n];if(i!==void 0)throw new t(`INVALID_ARGS`,i===r?`Duplicate replay test metadata "${n}" in context header.`:`Conflicting replay test metadata "${n}" in context header: ${String(i)} vs ${String(r)}.`);e[n]=r}function ft(e){let n=e.trim();if(n.length===0||n.startsWith(`#`))return null;let[r,...i]=mt(n);if(r===void 0||r===`context`)return null;let a={ts:Date.now(),command:r,positionals:[],flags:{}};if(r===`snapshot`){a.positionals=[];for(let e=0;e<i.length;e+=1){let t=i[e];if(t===`-i`){a.flags.snapshotInteractiveOnly=!0;continue}if(t!==`-c`){if(t===`--raw`){a.flags.snapshotRaw=!0;continue}if(t===`--force-full`){a.flags.snapshotForceFull=!0;continue}if((t===`-d`||t===`--depth`)&&e+1<i.length){let t=Number(i[e+1]);Number.isFinite(t)&&t>=0&&(a.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if((t===`-s`||t===`--scope`)&&e+1<i.length){a.flags.snapshotScope=i[e+1],e+=1;continue}if(t===`--backend`&&e+1<i.length){e+=1;continue}}}return a}if(r===`open`){let e=tt(i);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a.runtime=e.runtime,a}if(r===`runtime`){let e=Ze(i);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a}if(b(r)){let e=w(r,i);Object.assign(a.flags,e.flags);let t=e.positionals[0];if(t===void 0)return a;if(t.startsWith(`@`))return a.positionals=[v(t)],e.positionals[1]&&(a.result={refLabel:e.positionals[1]}),a;let n=e.positionals[0],o=e.positionals[1];return E(n)&&E(o)&&e.positionals.length>=2?(a.positionals=[n,o],a):(a.positionals=[e.positionals.join(` `)],a)}if(r===`fill`){let e=w(r,i);if(Object.assign(a.flags,e.flags),!pt(e.positionals))return a.positionals=e.positionals,a;let[t,n,...o]=e.positionals;if(E(t)&&E(n))return a.positionals=[t,n,o.join(` `)],a;let[s,c,...l]=e.positionals;if(s.startsWith(`@`)){let e=v(s);return l.length>0?(a.positionals=[e,l.join(` `)],a.result={refLabel:c},a):(a.positionals=[e,c],a)}return a.positionals=[s,[c,...l].join(` `)],a}if(r===`get`){let e=i[0],t=i[1];return e===void 0||t===void 0?(a.positionals=i,a):t.startsWith(`@`)?(a.positionals=[e,v(t)],i[2]&&(a.result={refLabel:i[2]}),a):(a.positionals=[e,i.slice(1).join(` `)],a)}if(r===`swipe`||r===`type`||r===`gesture`){let e=w(r,i);return Object.assign(a.flags,e.flags),a.positionals=e.positionals,a}if(r===`record`){let e=[];for(let n=0;n<i.length;n+=1){let r=i[n];if(r===c.cliToken)throw new t(`INVALID_ARGS`,c.migration.record);if(r===`--hide-touches`){a.flags.hideTouches=!0;continue}if(r===`--fps`&&n+1<i.length){let e=Number(i[n+1]);Number.isFinite(e)&&(a.flags.fps=Math.floor(e)),n+=1;continue}if(r===`--quality`&&n+1<i.length){let e=i[n+1],t=xe(e);t!==void 0&&(a.flags.quality=t),n+=1;continue}e.push(r)}return a.positionals=e,a}if(r===`screenshot`){let e=[];for(let t=0;t<i.length;t+=1){let n=i[t],r=u({args:i,index:t,flags:a.flags});if(r.handled){t=r.nextIndex;continue}e.push(n)}return a.positionals=e,a}return a.positionals=r===`wait`||r===`longpress`?i.map(e=>v(e)):i,a}function pt(e){return e.length>=2}function E(e){return e?!Number.isNaN(Number(e)):!1}function mt(e){let t=[],n=0;for(;n<e.length&&(n=ht(e,n),!(n>=e.length));){let r=e[n]===`"`?gt(e,n):_t(e,n);t.push(r.value),n=r.nextCursor}return t}function ht(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}function gt(e,n){let r=n+1,i=!1,a=r;for(;a<e.length;a+=1){let t=e.charAt(a);if(t===`"`&&!i)break;if(i){i=!1;continue}i=t===`\\`}if(a>=e.length)throw new t(`INVALID_ARGS`,`Invalid replay script line: ${e}`);let o=e.slice(n,a+1),s;try{s=JSON.parse(o)}catch{throw new t(`INVALID_ARGS`,`Invalid quoted value ${o} in replay script line: ${e}`,{hint:`Quoted replay values are JSON strings: escape backslashes, quotes, tabs, and newlines (\\\\, \\", \\t, \\n).`})}return{value:s,nextCursor:a+1}}function _t(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}function vt(e,t={}){let n=[e.command];return e.command===`snapshot`?qe(n,e):e.command===`open`?et(n,e):e.command===`runtime`?Ye(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?Ke(n,e):e.command===`screenshot`?Je(n,e):Xe(n,e),n.join(` `)}function yt(e){return e.targetEvidences?[ae(e.targetEvidences)]:e.targetEvidence?[se(e.targetEvidence)]:[]}async function bt(e){return e===`https:`?(await import(`node:https`)).default:(await import(`node:http`)).default}function xt(e){return new Promise((t,n)=>{let r=``;e.setEncoding(`utf8`),e.on(`data`,e=>{r+=e}),e.on(`end`,()=>t(r)),e.on(`error`,n)})}async function St(e,n,r){let i=[],a=0;for await(let o of e){let e=Buffer.isBuffer(o)?o:Buffer.from(o);if(a+=e.length,a>n)throw new t(`INVALID_ARGS`,r);i.push(e)}return Buffer.concat(i)}const Ct=`/agent-device`,wt=`x-agent-device-tenant`;function Tt(e){return Et(e,Ct)}function Et(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t.replace(/^\/+/,``),n).toString()}function Dt(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}function Ot(e){let t=e?.trim();return t?{[wt]:t}:{}}const kt=`.webm`;function At(e){return e===`web`?kt:`.mp4`}function jt(e,t){return g.extname(e)?e:`${e}${t}`}function Mt(e){return`./recording-${Date.now()}${At(e)}`}const D={kind:`none`};function O(e,t){if(t.path===void 0){let n=e??{kind:`default`,force:!1};return t.force?{...n,force:!0}:n}let n=e?.force===!0&&(e.kind==="default"||e.path===t.path);return{kind:`explicit`,path:t.path,force:t.force||n}}function Nt(e){return e.kind===`repair`?{...e,status:`armed`}:e}function Pt(e){return e.kind===`none`?void 0:e.target}function Ft(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function It(e){return e.kind===`authoring`&&e.status===`aborted`}function Lt(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function Rt(e){return{kind:`authoring`,status:`armed`,target:O(void 0,e)}}function zt(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function Bt(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function Vt(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:O(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function Ht(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function Ut(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function Wt(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function Gt(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function Kt(e){return e.kind===`repair`?e.boundary:void 0}function qt(e){return e.kind===`repair`?e.sourcePath:void 0}function Jt(e){return e.kind===`repair`&&e.status!==`committed`}function Yt(e){let t=Pt(e);return t?.kind===`explicit`?t.path:void 0}function Xt(e){return Pt(e)?.force===!0}function k(e){return e.replace(/[^a-zA-Z0-9._-]/g,`_`)}function A(e,t){return Ce(e,{cwd:t})}function j(e){return e?.scriptPublication??D}function Zt(e){let t=j(e);return t.kind===`authoring`&&t.status===`armed`}function Qt(e,t){e.recordSession=!0,e.scriptPublication=Rt({path:t.path===void 0?void 0:A(t.path),force:t.force===!0})}function $t(e){e.recordSession=!1,e.scriptPublication=zt(j(e))}function en(e,t){return It(j(e))?!1:e.recordSession===!0||t}function tn(e,t){if(!t.saveScript||It(j(e)))return;e.recordSession=!0;let n={path:typeof t.saveScript==`string`?A(t.saveScript):void 0,force:t.force===!0},r=j(e);if(r.kind===`repair`){e.scriptPublication=Vt(r,{requested:n,boundary:r.boundary,sourcePath:r.sourcePath});return}if(r.kind===`authoring`){e.scriptPublication={...r,target:O(r.target,n)};return}e.scriptPublication=Rt(n)}function nn(e,t){let n=j(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:O(n.target,{path:t.explicitPath===void 0?void 0:A(t.explicitPath),force:t.liveForce===!0})})}function rn(e,t){e.scriptPublication=Bt(j(e),t),e.recordSession=!1}function an(e,t){let n=j(e);n.kind===`authoring`&&(e.scriptPublication=Bt(n,t))}function on(e,t){return t===!0||Xt(j(e))}function sn(e){return Lt(j(e))}function M(e){return e?.scriptPublication??D}function cn(e,t){e.recordSession=!0;let n=M(e);e.scriptPublication=Vt(n,{requested:{path:typeof t.saveScript==`string`?A(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function ln(e){e.scriptPublication=Nt(M(e))}function un(e){e.scriptPublication=Ht(M(e))}function dn(e,t){e.scriptPublication=Ut(M(e),t)}function fn(e){e.scriptPublication=Gt(M(e))}function pn(e,t){let n=M(e);return n.kind===`repair`&&n.closeReceipt===t}function mn(e){return M(e).kind===`repair`}function hn(e){return Jt(M(e))}function N(e){return Kt(M(e))}function gn(e){return qt(M(e))}function P(e){let t=e.result?.text;if(typeof t==`string`)return t;let n=e.positionals??[];return n.length===0?``:n[0]?.startsWith(`@`)?n.length>=3?n.slice(2).join(` `):n.slice(1).join(` `):n.length>=3&&!Number.isNaN(Number(n[0]))&&!Number.isNaN(Number(n[1]))?n.slice(2).join(` `):n.slice(1).join(` `)}const _n=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function vn(e){if(e!==e.trim()||!rt.test(e))throw new t(`INVALID_ARGS`,`Invalid --record-as variable "${e}": use uppercase letters, digits, and underscores (for example PASSWORD).`);if(e.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid --record-as variable "${e}": the AD_* namespace is reserved for built-in replay variables.`);return e}function yn(e){return`\${${e}}`}function bn(e){let t=_n.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}const xn=new Set(`action.backend.cost.delayMs.evidence.gesture.hint.kind.maestroFallbackReason.maestroNonHittableCoordinateFallbackAllowed.maestroNonHittableCoordinateFallbackUsed.message.platform.ref.referenceHeight.referenceWidth.refLabel.resolution.selector.selectorChain.settle.targetHittable.targetKind.text.warning.x.y`.split(`.`)),Sn=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),Cn=new Set([`cost`,`evidence`,`resolution`,`settle`]),wn=new Map([[`cost`,new Set([`nodeCount`,`runnerRoundTrips`,`wallClockMs`])],[`evidence`,new Set([`changedFromBefore`,`digest`,`foregroundApp`,`interactiveNodeCount`,`nodeCount`])],[`resolution`,new Set([`alternatives`,`kind`,`matchCount`,`phase`,`source`,`tiebreak`,`winnerDiagnostic`])],[`resolution.alternatives`,new Set([`diagnosticRef`,`label`,`role`])],[`resolution.winnerDiagnostic`,new Set([`diagnosticRef`,`label`,`role`])],[`settle`,new Set([`captures`,`diff`,`hint`,`quietMs`,`refs`,`refsGeneration`,`settled`,`tail`,`tailTruncated`,`timeoutMs`,`waitedMs`])],[`settle.diff`,new Set([`lines`,`summary`,`truncated`])],[`settle.diff.lines`,new Set([`kind`,`ref`,`text`])],[`settle.diff.summary`,new Set([`additions`,`removals`,`unchanged`])],[`settle.refs`,new Set([`ref`])],[`settle.tail`,new Set([`label`,`ref`,`role`])]]),Tn=new Set([`evidence.digest`,`evidence.foregroundApp`,`resolution.alternatives.diagnosticRef`,`resolution.alternatives.role`,`resolution.kind`,`resolution.phase`,`resolution.source`,`resolution.tiebreak`,`resolution.winnerDiagnostic.diagnosticRef`,`resolution.winnerDiagnostic.role`,`settle.diff.lines.kind`,`settle.diff.lines.ref`,`settle.refs.ref`,`settle.tail.ref`,`settle.tail.role`]);function En(e,t,n){if(!e)return e;let r=Nn(e.selectorChain);return{...kn(e,t,n),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!On(e,t))}:{}}}function Dn(e,t,n){return e&&{...e,...e.label===t?{label:n}:{},ancestry:e.ancestry.map(e=>({...e,...e.label===t?{label:n}:{}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===t?{label:n}:{}}}:{}}}function On(e,t){return ue(e,t)}function kn(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[xn.has(e)?e:I(e,t,n),An(r,e,t,n)]))}function An(e,t,n,r){return typeof e==`string`&&Sn.has(t)?e:t===`selectorChain`&&Mn(e)?jn(e,n):F(e,n,r,Cn.has(t)?t:void 0)}function F(e,t,n,r){if(typeof e==`string`)return r&&Tn.has(r)?e:I(e,t,n);if(Array.isArray(e))return e.map(e=>F(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?wn.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:I(e,t,n),F(a,t,n,o?`${r}.${e}`:void 0)]}))}function jn(e,t){return e.filter(e=>!On(e,t))}function I(e,t,n){if(!t)return e===t?n:e;let r=n?e.split(n):[e];return r.every(e=>!e.includes(t))?e:t.trim()?r.map(e=>e.replaceAll(t,n)).join(n):n}function Mn(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Nn(e){return Mn(e)?e:void 0}function Pn(e,t){if(t.flags?.noRecord||zn(e,t))return;t.flags&&tn(e,t.flags);let n=Fn(t),r={ts:Date.now(),command:n.command,positionals:n.positionals,runtime:n.runtime,flags:Vn(n.flags),result:n.result,...n.targetEvidence?{targetEvidence:n.targetEvidence}:{},...n.targetEvidences?{targetEvidences:n.targetEvidences}:{}};return e.actions.push(r),m({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),r}function Fn(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return e;let t=yn(vn(e.flags.recordAs)),n=P({ts:0,command:e.command,positionals:e.positionals,flags:e.flags});return{...e,positionals:In(e.positionals,t),result:En(e.result,n,t),targetEvidence:Dn(e.targetEvidence,n,t)}}function In(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const Ln=new Set([`snapshot`,`get`,`is`,`find`]);function Rn(e){return e.internal?.replayPlanStep===!0?!1:Ln.has(e.command)}function zn(e,t){return!t.interactiveObservation||N(e)===void 0?!1:t.flags?.record!==!0}const Bn=[`platform`,`device`,`udid`,`serial`,`out`,`verbose`,`metroHost`,`metroPort`,`bundleUrl`,`launchUrl`,`snapshotInteractiveOnly`,`snapshotDepth`,`snapshotScope`,`snapshotRaw`,`snapshotCustomActions`,...a,`relaunch`,`saveScript`,`force`,`noRecord`,`record`,`fps`,`quality`,`hideTouches`,`count`,`pointerCount`,`intervalMs`,`delayMs`,`holdMs`,`jitterPx`,`doubleTap`,`clickButton`,`pauseMs`,`pattern`];function Vn(e){if(!e)return{};let t={};for(let n of Bn)e[n]!==void 0&&(t[n]=e[n]);return t}function Hn(e){let n=e.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new t(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(e.some(e=>e.command===`close`))throw new t(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[t,n]of e.entries())de({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=t);if(!e.slice(r+1).some(Jn))throw new t(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function Un(e){for(let n of e){if(Wn(n)){Gn(n);continue}let e=Yn(n),r=e??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&de(n)===`mutates-app`)throw new t(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=e;if(!(!i||!f(i)||n.targetEvidence))throw new t(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function Wn(e){return Kn(e)!==void 0}function Gn(e){let n=Kn(e);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!f(n))&&!e.targetEvidences)throw new t(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function Kn(e){return e.command===`gesture`?l(e.positionals):void 0}function qn(e,n){if(e instanceof t){if(e.details?.reason===`script_target_exists`)return new t(e.code,`A file already exists at ${String(e.details.path)}.`,{...e.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=e.details?.retriable===!0;return new t(e.code,e.message,{...e.details,retriable:n,hint:e.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Jn(e){if(e.command!==`wait`)return!1;let t=le(e.positionals);return t?.kind!==`selector`||!f(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function Yn(e){if(e.command===`get`)return e.positionals[1];if(Ie(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&Xn(t)&&Xn(n)?void 0:t}}function Xn(e){return e.trim().length>0&&Number.isFinite(Number(e))}function Zn(e){let t=e.scriptPublication??D;return t.kind===`repair`?t.status===`committed`?!0:!Ft(t):!1}function Qn(e){return!e.recordSession||It(e.scriptPublication??D)?!0:Zn(e)}var $n=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=mn(e),r=t?.publication===`active`,i;try{if(Qn(e))return{written:!1};let a=er(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=g.dirname(i);return _.existsSync(o)||_.mkdirSync(o,{recursive:!0}),rr({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=Wt(e.scriptPublication??D)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return tr({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=Yt(e.scriptPublication??D);if(t)return A(t);let n=k(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,`-`);return g.join(this.sessionsDir,`${n}-${r}.ad`)}};function er(e,t){let n=ir(e,{strictPortableRefs:t.activePublication});return t.activePublication&&Hn(n),{script:mr(e,n,t.appendCompleteSentinel),actionCount:n.length}}function tr(e){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=e;if(m({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:nr(r,i)};if(o)return{written:!1,error:qn(r,i)};if(r instanceof t)throw r;return{written:!1}}function nr(e,n){if(e instanceof t)return e;let r=e instanceof Error?e.message:String(e);return new t(`COMMAND_FAILED`,`Failed to write the healed script${n?` to ${n}`:``}: ${r}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function rr(e){let{scriptPath:n,script:r,force:i}=e,a=g.dirname(n),o=g.join(a,`.${g.basename(n)}.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`);_.writeFileSync(o,r);try{if(i){_.renameSync(o,n);return}_.linkSync(o,n)}catch(e){throw e.code===`EEXIST`?new t(`COMMAND_FAILED`,`A file already exists at ${n}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:n}):e}finally{_.rmSync(o,{force:!0})}}function ir(e,t={}){let n=N(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=sr(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&ar(n);let o=pr(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&Un(a),a}function ar(e){let n=e.command===`gesture`?l(e.positionals??[]):void 0;if(n){or(n);return}if(!L(e.command))return;let r=e.command===`get`?e.positionals?.[1]:e.positionals?.[0];if(r?.startsWith(`@`))throw new t(`COMMAND_FAILED`,`Cannot write recorded step "${e.command} ${r}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function or(e){let n=[e.source,e.destination].find(e=>e.startsWith(`@`));if(n)throw new t(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function sr(e){let t=cr(e);if(!(!t||!L(e.command)))return b(e.command)?{...e,positionals:[t]}:e.command===`longpress`?ur(e,t):e.command===`fill`?lr(e,t):dr(e,t)}function cr(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function L(e){return Ie(e)||e===`fill`||e===`get`}function lr(e,t){let n=P(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function ur(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):fr(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function dr(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function fr(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function pr(e,t){if(!L(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r}}}function mr(e,t,n){let r=[],i=e.device.kind?` kind=${e.device.kind}`:``;r.push(`context platform=${pe(e.device)} device=${Re(e.device.name)}${i} theme=unknown`);for(let e of t)e.flags?.noRecord||(r.push(...yt(e)),r.push(hr(e)));return n&&r.push(`# agent-device:heal-complete`),`${r.join(`
|
|
2
|
-
`)}\n`}function hr(e){return gr([e.command],e)||vt(e)}function gr(e,t){if(b(t.command))return _r(e,t);if(t.command===`fill`)return vr(e,t);if(t.command===`get`)return yr(e,t)}function _r(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(x(v(n))),R(e,t),C(e,t),e.join(` `);if(t.positionals.length===1)return e.push(x(n)),C(e,t),e.join(` `)}}function vr(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(x(v(n))),R(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(x(r)),C(e,t),e.join(` `)}function yr(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(x(n)),e.push(x(v(r))),r.startsWith(`@`)&&R(e,t),e.join(` `)}function R(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(x(n))}const br=[`status`,`get`,`dismiss`,`enter`,`return`];function z(e){return br.includes(e)}const xr=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],Sr={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function Cr(e,t){let n=t??{};switch(e.command){case p.devices:return wr(n.devices);case p.apps:return Tr(n.apps,e.flags?.appsFilter);case p.boot:return Er(`Booted`,n,!0);case p.shutdown:return Er(`Shut down`,n,!1);case p.install:return Dr(`Installed`,n);case p.reinstall:return Dr(`Reinstalled`,n);case p.screenshot:return Or(e,n);default:return{}}}function wr(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=Ar(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:zr(`Found ${t.length} ${Br(`device`,t.length)}`,i.map(e=>Lr(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function Tr(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=H(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:zr(`Found ${n.length} ${Br(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function Er(e,t,n){let r=jr(t);if(!r)return{};let i={device:r,...Ir(t),booted:n};return{summary:`${e} ${Lr(i,!1)}`,details:i}}function Dr(e,t){let n=H(t.appName),r=H(t.bundleId),i=B(t,[`packageName`,`package`]),a=H(t.platform),o=H(t.launchTarget),s=B(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=Rr(n,s);if(!c)return{};let l={};return V(l,`appName`,n),V(l,`bundleId`,r),V(l,`packageName`,i),V(l,`platform`,a),o!==s&&V(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function Or(e,t){let n=kr(e,t);return n?{details:{requestedFileName:n}}:{}}function kr(e,t){let n=J(e.meta?.clientArtifactPaths?.path)??J(t.path);if(n)return q(n)}function Ar(e){if(!d(e))return;let t=jr(e);if(t)return{name:t,...Ir(e)}}function jr(e){let t=B(e,[`name`,`deviceName`,`device`]);return!t||!Mr(e,t)?t:Pr(e)}function Mr(e,t){let n=Nr(t);return xr.some(t=>{let r=H(e[t]);return r!==void 0&&Nr(r)===n})}function Nr(e){return e.toLowerCase()}function Pr(e){let t=H(e.appleOs),n=H(e.platform),r=H(e.kind),i=Fr(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function Fr(e,t){let n=e??t;if(!(!n||!Object.hasOwn(Sr,n)))return Sr[n]}function Ir(e){let t=H(e.platform),n=H(e.appleOs),r=H(e.kind),i=H(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function Lr(e,t){let n=H(e.name)??H(e.device)??`device`,r=H(e.platform),i=H(e.appleOs),a=[r,i===r?void 0:i,H(e.kind),H(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function Rr(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function B(e,t){for(let n of t){let t=H(e[n]);if(t)return t}}function V(e,t,n){n&&(e[t]=n)}function zr(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function Br(e,t){return t===1?e:`${e}s`}function H(e){let t=J(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function U(e){return H(e)}function W(e){return typeof e==`boolean`?e:void 0}function G(e,t){let n=U(e);return n&&t.includes(n)?n:void 0}function K(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function q(e){let t=J(e);return t?H(t.split(/[\\/]/).at(-1)):void 0}function J(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function Y(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const Vr=[`up`,`down`,`left`,`right`],Hr=[`top`,`bottom`];function Ur(e){return`${e.command===p.reinstall?`Reinstalled`:`Installed`} ${qr(e.result??{})??`app`}`}function Wr(e){let t=e.result??{};switch(e.command){case p.scroll:return Yr(t);case p.screenshot:return Qr(t);case p.home:return`Went home`;case p.back:return ei(t);case p.appSwitcher:return`Opened app switcher`;case p.orientation:return ti(t);case p.viewport:return ni(t);case p.clipboard:return ri(t);case p.keyboard:return ii(t);case p.tvRemote:return si(t);case p.gesture:return ci(t);case p.swipe:return li(t);case p.trace:return di(`trace`,e);case p.record:return di(`recording`,e);default:return}}function Gr(e){let t=e.result??{};switch(e.command){case p.scroll:return K({direction:G(t.direction,Vr),edge:G(t.edge,Hr),passes:Y(t.passes),amount:Y(t.amount),pixels:Y(t.pixels),durationMs:Y(t.durationMs),x1:Y(t.x1),y1:Y(t.y1),x2:Y(t.x2),y2:Y(t.y2)});case p.screenshot:return K({requestedFileName:$r(t)});case p.back:return K({mode:G(t.mode,ne)});case p.orientation:return K({orientation:G(t.orientation,Se)});case p.viewport:return K({width:Y(t.width),height:Y(t.height)});case p.clipboard:return K({action:G(t.action,[`read`,`write`])});case p.keyboard:return oi(t);case p.tvRemote:return K({button:G(t.button,s),durationMs:Y(t.durationMs)});case p.gesture:case p.swipe:return ui(t);case p.trace:case p.record:return K({action:G(t.action,[`start`,`stop`]),fileName:pi(e),showTouches:W(t.showTouches)});default:return{}}}function Kr(e,t){if(e.command!==p.screenshot)return t;let n=kr(e,t);return n?{...t,requestedFileName:n}:t}function qr(e){let t=U(e.appName),n=mi(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??Jr(e)}function Jr(e){let t=U(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function Yr(e){let t=G(e.direction,Vr),n=G(e.edge,Hr),r=Y(e.passes);return n?Xr(n,r):t?Zr(t,e):`Scrolled`}function Xr(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function Zr(e,t){let n=Y(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=Y(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function Qr(e){let t=$r(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function $r(e){return q(e.requestedFileName)??q(e.path)}function ei(e){return G(e.mode,ne)===`system`?`Went back using system navigation`:`Went back`}function ti(e){let t=G(e.orientation,Se);return t?`Rotated to ${t}`:`Changed orientation`}function ni(e){let t=Y(e.width),n=Y(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function ri(e){let t=G(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function ii(e){let t=J(e.action);if(!t||!z(t))return`Used keyboard`;if(t===`dismiss`)return ai(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=W(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function ai(e){return W(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function oi(e){let t=J(e.action);return K({action:t&&z(t)?t:void 0,platform:G(e.platform,[`ios`,`android`]),visible:W(e.visible),wasVisible:W(e.wasVisible),dismissed:W(e.dismissed),attempts:Y(e.attempts),mechanism:G(e.mechanism,[`dismissKey`])})}function si(e){let t=G(e.button,s);return t?`Pressed TV remote ${t}`:`Used TV remote`}function ci(e){let t=G(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function li(e){let t=Y(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function ui(e){return K({kind:G(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:Y(e.durationMs),pointerCount:Y(e.pointerCount),x1:Y(e.x1),y1:Y(e.y1),x2:Y(e.x2),y2:Y(e.y2),count:Y(e.count),pauseMs:Y(e.pauseMs),pattern:G(e.pattern,[`one-way`,`ping-pong`]),scale:Y(e.scale)})}function di(e,t){let n=fi(e,G(t.result?.action,[`start`,`stop`])),r=pi(t);return r?`${n} ${r}`:n}function fi(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function pi(e){let t=e.result??{};return q(t.requestedFileName)??q(t.outPath)??q(t.path)??q(e.positionals[1])}function mi(e,t){for(let n of t){let t=U(e[n]);if(t)return t}}function hi(e){switch(e.command){case p.open:return`Opened ${X(e)??`session`}`;case p.close:return`Closed ${U(e.result?.session)??`session`}`;case p.click:case p.press:return`Tapped ${X(e)??`target`}`;case p.longPress:return`Long pressed ${X(e)??`target`}`;case p.fill:return`Filled ${X(e)??`target`}`;case p.type:return`Typed text`;case p.install:case p.reinstall:case ve.installSource:return Ur(e);default:return Wr(e)??`Ran ${e.command}`}}function gi(e){return K({command:e.command,positionals:Ti(e),flags:Ii(e),..._i(e),...vi(e),...yi(e),...Gr(e)})}function _i(e){if(!bi(e.command))return{};let t=e.result??{};return K({ref:Wi(t),targetLabel:X(e),selectorChainLength:Ni(t.selectorChain)?.length,x:Y(t.x),y:Y(t.y),x2:Y(t.x2),y2:Y(t.y2),durationMs:Y(t.durationMs)})}function vi(e){if(!xi(e.command))return{};let t=e.result??{};return K({platform:G(t.platform,me),target:G(t.target,ge),appName:U(t.appName),appBundleId:U(t.appBundleId),bundleId:U(t.bundleId),packageName:U(t.packageName),launchTarget:U(t.launchTarget)})}function yi(e){let t=e.result??{};return e.command===p.snapshot?{...Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}}:e.command!==p.wait&&e.command!==p.find&&e.command!==p.get&&e.command!==p.is?{}:K({waitedMs:Y(t.waitedMs),found:W(t.found)})}function bi(e){return e===p.click||e===p.press||e===p.longPress||e===p.focus||e===p.fill}function xi(e){return e===p.open||e===p.install||e===p.reinstall||e===ve.installSource}function X(e){let t=e.result??{};return Si(t)??Ci(t)??wi(t)??ji(e.positionals[0])}function Si(e){let t=Wi(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function Ci(e){let t=Y(e.x),n=Y(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function wi(e){return U(e.appName)??U(e.appBundleId)??U(e.bundleId)??U(e.packageName)}function Ti(e){if(e.positionals.length!==0)return e.command===p.type?[Q(`text`)]:e.command===p.fill?Ei(e):e.command===p.find?Di(e):e.command===p.clipboard?Oi(e):e.command===p.push?ki(e,`app`,`payload`):e.command===p.triggerAppEvent?ki(e,`event`,`payload`):e.positionals.map(Z)}function Ei(e){let t=Q(`text`),n=e.result??{},r=Wi(n);if(r)return[`@${r}`,t];if(U(n.selector))return[Q(`target`),t];let i=Y(n.x),a=Y(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function Di(e){let t=+!!Mi(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],Q(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,Q(`text`)]:[...r,...e.positionals.slice(n).map(Ai)]:r}function Oi(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,Q(`text`)]:e.positionals.map(Z)}function ki(e,t,n){let[r,i,...a]=e.positionals;return[...r?[Q(t)]:[],...i?[Q(n)]:[],...a.map(Z)]}function Ai(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:Z(e)}function Z(e){return ji(e)??Q(`arg`)}function ji(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function Q(e){return`<${e}>`}function Mi(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function Ni(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const Pi={enums:[{source:`platform`,values:he},{source:`target`,values:ge}]},Fi={[p.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:be}]},[p.click]:Li(),[p.press]:Li(),[p.longPress]:Li(),[p.fill]:Ri(),[p.type]:Ri(),[p.scroll]:{booleans:[{source:`settle`}],numbers:[{source:`pixels`},{source:`durationMs`},{source:`settleQuietMs`}]},[p.gesture]:zi(),[p.swipe]:zi(),[p.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[p.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[p.back]:{booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}],enums:[{source:`backMode`,output:`mode`,values:ne}]},[p.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:_e}]},[p.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[p.boot]:{booleans:[{source:`headless`}]},[p.close]:{booleans:[{source:`shutdown`}]}};function Ii(e){let t=e.flags??{},n={},r=Object.hasOwn(Fi,e.command)?Fi[e.command]:void 0;return Bi(n,t,Pi),Bi(n,t,r),Object.keys(n).length>0?n:void 0}function Li(){return{booleans:[{source:`doubleTap`},{source:`settle`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`},{source:`settleQuietMs`}],enums:[{source:`clickButton`,values:ee}]}}function Ri(){return{booleans:[{source:`settle`}],numbers:[{source:`delayMs`},{source:`settleQuietMs`}]}}function zi(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:r}]}}function Bi(e,t,n){n&&(Vi(e,t,n.booleans??[]),Hi(e,t,n.numbers??[]),Ui(e,t,n.enums??[]))}function Vi(e,t,n){for(let r of n)Gi(e,r.output??r.source,t[r.source])}function Hi(e,t,n){for(let r of n)Ki(e,r.output??r.source,t[r.source])}function Ui(e,t,n){for(let r of n)qi(e,r.output??r.source,t[r.source],r.values)}function Wi(e){let t=U(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function Gi(e,t,n){typeof n==`boolean`&&(e[t]=n)}function Ki(e,t,n){let r=Y(n);r!==void 0&&(e[t]=r)}function qi(e,t,n,r){let i=G(n,r);i!==void 0&&(e[t]=i)}const $=new Map,Ji=new Set;function Yi(e){return g.join(e,`events.ndjson`)}function Xi(e){return e.command!==p.events}function Zi(t,n,r){let i=e({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});$i(t,`${JSON.stringify(i)}\n`)}async function Qi(e){await(e?$.get(e):Promise.all($.values()))}function $i(e,t){let n=($.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await ea(e),await _.promises.appendFile(e,t,`utf8`)}).catch(t=>{m({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{$.get(e)===n&&$.delete(e)});$.set(e,n)}async function ea(e){let t=g.dirname(e);if(!Ji.has(t))try{await _.promises.mkdir(t,{recursive:!0}),Ji.add(t)}catch(t){throw m({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function ta(e,t,n){Zi(e,t,{kind:`action.recorded`,requestId:h().requestId,command:n.command,summary:hi(n),details:gi(n)})}function na(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??h().requestId,command:t.command,summary:`Started ${t.command}`}}function ra(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=Cr(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??h().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??h().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function ia(e,t={}){let n=la(t.cursor),r=ua(t.limit);if(!_.existsSync(e))return{path:e,cursor:String(n),limit:r,events:[]};let i=aa(e,n,r),a=i.lines.flatMap(e=>{let t=da(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:a,...i.nextCursor===void 0?{}:{nextCursor:String(i.nextCursor)}}}function aa(e,t,n){let r=_.openSync(e,`r`);try{let e=new Ae(`utf8`),i=Buffer.allocUnsafe(65536),a=oa(t,n),o=``,s=0;do{s=_.readSync(r,i,0,i.length,null);let t=e.write(i.subarray(0,s));o=sa(`${o}${t}`,a)}while(s>0&&a.nextCursor===void 0);let c=`${o}${e.end()}`;return a.nextCursor===void 0&&c.length>0&&ca(c,a),{lines:a.lines,nextCursor:a.nextCursor}}finally{_.closeSync(r)}}function oa(e,t){return{cursor:e,limit:t,lineIndex:0,lines:[]}}function sa(e,t){let n=0;for(let r=e.indexOf(`
|
|
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(
|
|
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
|
|
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};
|