agent-device 0.18.2 → 0.19.0
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-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.18.2.apk → agent-device-android-multitouch-helper-0.19.0.apk} +0 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.19.0.apk.sha256 +1 -0
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.18.2.manifest.json → agent-device-android-multitouch-helper-0.19.0.manifest.json} +4 -4
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.18.2.apk → agent-device-android-snapshot-helper-0.19.0.apk} +0 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.19.0.apk.sha256 +1 -0
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.18.2.manifest.json → agent-device-android-snapshot-helper-0.19.0.manifest.json} +6 -6
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTapPointPolicy.swift +28 -0
- package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +9 -120
- package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +132 -66
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +155 -0
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +67 -0
- package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +20 -74
- package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +64 -0
- package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +0 -177
- package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +81 -48
- package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +102 -129
- package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +208 -46
- package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +82 -11
- package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +72 -0
- package/dist/src/agent-browser-tool.js +1 -0
- package/dist/src/android-adb.d.ts +64 -234
- package/dist/src/android-adb.js +1 -1
- package/dist/src/android.js +1 -5
- package/dist/src/app-lifecycle.js +7 -0
- package/dist/src/apple-runner-options.js +1 -0
- package/dist/src/apps.js +5 -11
- package/dist/src/artifacts.d.ts +4 -3
- package/dist/src/artifacts.js +1 -1
- package/dist/src/audio-probe.js +1 -1
- package/dist/src/batch.d.ts +2 -177
- package/dist/src/batch.js +1 -1
- package/dist/src/cli-help.js +64 -38
- package/dist/src/cli-output.js +1 -1
- package/dist/src/cli-runner.js +2 -0
- package/dist/src/cli.js +12 -41
- package/dist/src/client-metro-companion.js +1 -0
- package/dist/src/client.js +3 -0
- package/dist/src/command-metadata.js +1 -0
- package/dist/src/command-schema.js +22 -0
- package/dist/src/command-surface.js +1 -1
- package/dist/src/contracts.d.ts +2 -213
- package/dist/src/contracts.js +1 -1
- package/dist/src/debug-symbols.js +5 -3
- package/dist/src/device-input-state.js +2 -0
- package/dist/src/device-rotation.js +14 -0
- package/dist/src/devices.js +1 -1
- package/dist/src/devices2.js +1 -0
- package/dist/src/devices3.js +1 -0
- package/dist/src/find.js +1 -1
- package/dist/src/finders.d.ts +2 -81
- package/dist/src/finders.js +1 -1
- package/dist/src/generic.js +1 -1
- package/dist/src/handler-utils.js +1 -1
- package/dist/src/helper.js +2 -0
- package/dist/src/host-process.js +2 -0
- package/dist/src/index.d.ts +1265 -1768
- package/dist/src/index.js +1 -1
- package/dist/src/input-actions.js +3 -1
- package/dist/src/input-actions2.js +1 -0
- package/dist/src/install-source.d.ts +13 -14
- package/dist/src/install-source.js +1 -1
- package/dist/src/install-source2.js +1 -0
- package/dist/src/interaction-snapshot.js +1 -0
- package/dist/src/interaction.js +1 -1
- package/dist/src/interactor.js +2 -1
- package/dist/src/internal/bin.d.ts +1 -1
- package/dist/src/internal/bin.js +2 -5
- package/dist/src/internal/companion-tunnel.d.ts +1 -1
- package/dist/src/internal/companion-tunnel.js +1 -1
- package/dist/src/internal/daemon.d.ts +1 -1
- package/dist/src/internal/daemon.js +16 -1
- package/dist/src/internal/png-worker.d.ts +29 -26
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/internal/update-check-entry.d.ts +1 -1
- package/dist/src/internal/update-check-entry.js +1 -1
- package/dist/src/io.d.ts +2 -85
- package/dist/src/io.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/logcat.js +6 -0
- package/dist/src/manifest.js +1 -0
- package/dist/src/metro.d.ts +70 -113
- package/dist/src/metro.js +1 -1
- package/dist/src/metro2.js +1 -0
- package/dist/src/notifications.js +1 -1
- package/dist/src/output-path.js +1 -0
- package/dist/src/path-resolution.js +1 -0
- package/dist/src/png-worker-contract.js +1 -0
- package/dist/src/points.js +4 -0
- package/dist/src/project-runtime.js +1 -0
- package/dist/src/provider.js +1 -1
- package/dist/src/providers.js +1 -0
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-trace-recording.js +2 -5
- package/dist/src/record-trace.js +1 -1
- package/dist/src/recording-provider.js +1 -1
- package/dist/src/registry.js +37 -0
- package/dist/src/remote-config.d.ts +2 -83
- package/dist/src/reporting.js +9 -0
- package/dist/src/rolldown-runtime.js +1 -0
- package/dist/src/runner-client.js +1 -0
- package/dist/src/runner-provider.js +1 -0
- package/dist/src/runner-sequence.js +1 -1
- package/dist/src/runtime-transport.js +1 -0
- package/dist/src/runtime.js +3 -0
- package/dist/src/scoped-provider.js +1 -0
- package/dist/src/sdk-android-adb.d.ts +144 -0
- package/dist/src/sdk-android-adb.js +4 -0
- package/dist/src/sdk-app-inventory.d.ts +4 -0
- package/dist/src/sdk-app-inventory.js +1 -0
- package/dist/src/sdk-batch-runner.d.ts +40 -0
- package/dist/src/sdk-batch-runner.js +2 -0
- package/dist/src/sdk-batch.js +2 -0
- package/dist/src/sdk-contracts.d.ts +386 -0
- package/dist/src/sdk-contracts.js +2 -0
- package/dist/src/sdk-finders.d.ts +61 -0
- package/dist/src/sdk-finders.js +1 -0
- package/dist/src/sdk-io.d.ts +79 -0
- package/dist/src/sdk-io.js +1 -0
- package/dist/src/sdk-remote-config.d.ts +140 -0
- package/dist/src/sdk-remote-config.js +1 -0
- package/dist/src/sdk-selectors.js +1 -0
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.d.ts +39 -137
- package/dist/src/selectors.js +1 -1
- package/dist/src/selectors2.js +1 -0
- package/dist/src/server.js +3 -2
- package/dist/src/session.js +10 -11
- package/dist/src/setting-state.js +1 -0
- package/dist/src/simctl.js +1 -0
- package/dist/src/simulator.js +1 -2
- package/dist/src/snapshot-diagnostics.js +3 -0
- package/dist/src/snapshot-helper.js +5 -0
- package/dist/src/snapshot-quality.js +1 -0
- package/dist/src/snapshot.js +1 -2
- package/dist/src/snapshot2.js +2 -0
- package/dist/src/{5560.js → timeouts.js} +1 -1
- package/dist/src/tool-provider.js +3 -0
- package/dist/src/tool-provider2.js +1 -0
- package/dist/src/ttl-memo.js +1 -0
- package/dist/src/update-check.js +1 -0
- package/dist/src/url.js +1 -0
- package/dist/src/version.js +1 -0
- package/dist/src/web.js +1 -1
- package/dist/src/xml.js +2 -0
- package/package.json +12 -19
- package/server.json +2 -2
- package/skills/agent-device/SKILL.md +2 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.18.2.apk.sha256 +0 -1
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.18.2.apk.sha256 +0 -1
- package/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +0 -443
- package/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +0 -169
- package/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +0 -220
- package/dist/src/1404.js +0 -1
- package/dist/src/1986.js +0 -1
- package/dist/src/2748.js +0 -1
- package/dist/src/2948.js +0 -30
- package/dist/src/3006.js +0 -1
- package/dist/src/314.js +0 -1
- package/dist/src/3340.js +0 -8
- package/dist/src/4418.js +0 -1
- package/dist/src/4428.js +0 -3
- package/dist/src/485.js +0 -1
- package/dist/src/4917.js +0 -1
- package/dist/src/495.js +0 -5
- package/dist/src/5448.js +0 -3
- package/dist/src/5484.js +0 -1
- package/dist/src/5643.js +0 -1
- package/dist/src/587.js +0 -1
- package/dist/src/5913.js +0 -4
- package/dist/src/6849.js +0 -1
- package/dist/src/6918.js +0 -1
- package/dist/src/6967.js +0 -1
- package/dist/src/760.js +0 -1
- package/dist/src/7871.js +0 -1
- package/dist/src/8184.js +0 -1
- package/dist/src/8225.js +0 -1
- package/dist/src/8391.js +0 -1
- package/dist/src/8404.js +0 -2
- package/dist/src/8414.js +0 -2
- package/dist/src/8875.js +0 -4
- package/dist/src/893.js +0 -1
- package/dist/src/8936.js +0 -1
- package/dist/src/9414.js +0 -1
- package/dist/src/9581.js +0 -22
- package/dist/src/9612.js +0 -1
- package/dist/src/9624.js +0 -1
- package/dist/src/9722.js +0 -38
- package/dist/src/devices~1.js +0 -1
- package/dist/src/devices~2.js +0 -1
- package/dist/src/input-actions~1.js +0 -1
- package/dist/src/rslib-runtime.js +0 -1
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/xcshareddata/xcschemes/AgentDeviceRunner.xcscheme +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests.entitlements +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.h +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.m +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Exceptions.swift +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests.xctestplan +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/RecordingScripts/recording-resize.swift +0 -0
- /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/RecordingScripts/recording-trim.swift +0 -0
|
@@ -1,83 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
providerOsVersion?: string;
|
|
4
|
-
providerProject?: string;
|
|
5
|
-
providerBuild?: string;
|
|
6
|
-
providerSessionName?: string;
|
|
7
|
-
awsProjectArn?: string;
|
|
8
|
-
awsDeviceArn?: string;
|
|
9
|
-
awsAppArn?: string;
|
|
10
|
-
awsRegion?: string;
|
|
11
|
-
awsInteractionMode?: 'INTERACTIVE' | 'NO_VIDEO' | 'VIDEO_ONLY';
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
declare const DAEMON_SERVER_MODES: readonly ['socket', 'http', 'dual'];
|
|
15
|
-
|
|
16
|
-
declare const DAEMON_TRANSPORT_PREFERENCES: readonly ['auto', 'socket', 'http'];
|
|
17
|
-
|
|
18
|
-
declare type DaemonServerMode = (typeof DAEMON_SERVER_MODES)[number];
|
|
19
|
-
|
|
20
|
-
declare type DaemonTransportPreference = (typeof DAEMON_TRANSPORT_PREFERENCES)[number];
|
|
21
|
-
|
|
22
|
-
declare const DEVICE_TARGETS: readonly ['mobile', 'tv', 'desktop'];
|
|
23
|
-
|
|
24
|
-
declare type DeviceTarget = (typeof DEVICE_TARGETS)[number];
|
|
25
|
-
|
|
26
|
-
declare const LEASE_BACKENDS: readonly ['ios-simulator', 'ios-instance', 'android-instance'];
|
|
27
|
-
|
|
28
|
-
declare type LeaseBackend = (typeof LEASE_BACKENDS)[number];
|
|
29
|
-
|
|
30
|
-
declare type MetroPrepareKind = 'auto' | 'react-native' | 'expo';
|
|
31
|
-
|
|
32
|
-
declare const PLATFORM_SELECTORS: readonly ["apple", "android", "linux", "web", "ios", "macos"];
|
|
33
|
-
|
|
34
|
-
declare type PlatformSelector = (typeof PLATFORM_SELECTORS)[number];
|
|
35
|
-
|
|
36
|
-
declare type RemoteConfigMetroOptions = {
|
|
37
|
-
metroProjectRoot?: string;
|
|
38
|
-
metroKind?: MetroPrepareKind;
|
|
39
|
-
metroPublicBaseUrl?: string;
|
|
40
|
-
metroProxyBaseUrl?: string;
|
|
41
|
-
metroBearerToken?: string;
|
|
42
|
-
metroPreparePort?: number;
|
|
43
|
-
metroListenHost?: string;
|
|
44
|
-
metroStatusHost?: string;
|
|
45
|
-
metroStartupTimeoutMs?: number;
|
|
46
|
-
metroProbeTimeoutMs?: number;
|
|
47
|
-
metroRuntimeFile?: string;
|
|
48
|
-
metroNoReuseExisting?: boolean;
|
|
49
|
-
metroNoInstallDeps?: boolean;
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
export declare type RemoteConfigProfile = RemoteConfigMetroOptions & CloudProviderProfileFields & RemoteConnectionProfileFields & {
|
|
53
|
-
platform?: PlatformSelector;
|
|
54
|
-
target?: DeviceTarget;
|
|
55
|
-
device?: string;
|
|
56
|
-
udid?: string;
|
|
57
|
-
serial?: string;
|
|
58
|
-
iosSimulatorDeviceSet?: string;
|
|
59
|
-
androidDeviceAllowlist?: string;
|
|
60
|
-
session?: string;
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
declare type RemoteConnectionProfileFields = {
|
|
64
|
-
stateDir?: string;
|
|
65
|
-
daemonBaseUrl?: string;
|
|
66
|
-
daemonAuthToken?: string;
|
|
67
|
-
daemonTransport?: DaemonTransportPreference;
|
|
68
|
-
daemonServerMode?: DaemonServerMode;
|
|
69
|
-
tenant?: string;
|
|
70
|
-
sessionIsolation?: SessionIsolationMode;
|
|
71
|
-
runId?: string;
|
|
72
|
-
leaseId?: string;
|
|
73
|
-
leaseBackend?: LeaseBackend;
|
|
74
|
-
leaseProvider?: string;
|
|
75
|
-
deviceKey?: string;
|
|
76
|
-
clientId?: string;
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
declare const SESSION_ISOLATION_MODES: readonly ['none', 'tenant'];
|
|
80
|
-
|
|
81
|
-
declare type SessionIsolationMode = (typeof SESSION_ISOLATION_MODES)[number];
|
|
82
|
-
|
|
83
|
-
export { }
|
|
1
|
+
import { n as RemoteConfigProfile } from "./sdk-remote-config.js";
|
|
2
|
+
export type { RemoteConfigProfile };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{F as e}from"./sdk-contracts.js";import{Mn as t,Nn as n,Rn as r,zn as i}from"./device-rotation.js";import a from"node:fs";import o from"node:os";import s from"node:path";import{pathToFileURL as c}from"node:url";const l=[`onSuiteStart`,`onTestStart`,`onTestStep`,`onTestResult`,`onSuiteEnd`,`getExitCode`];async function u(e){let t=ee(e.modulePath);return ne(await d(await te(t),e.modulePath)({spec:e.raw,modulePath:t}),e.modulePath)}function d(t,n){let r=t.createReporter??t.default??t.reporter;if(!r)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must export default, createReporter, or reporter.`);return typeof r==`function`?r:()=>r}function ee(e){if(e.startsWith(`file:`))return e;let t=e.startsWith(`~/`)?s.join(o.homedir(),e.slice(2)):e;return s.resolve(process.cwd(),t)}async function te(t){try{return await(t.startsWith(`file:`)?import(t):import(c(t).href))}catch(n){throw new e(`INVALID_ARGS`,`Failed to load custom test reporter ${t}: ${n instanceof Error?n.message:String(n)}`)}}function ne(t,n){if(!t||typeof t!=`object`)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must export a reporter object or factory.`);let r=t;if(typeof r.name!=`string`||r.name.trim().length===0)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must define name.`);for(let t of l)if(!(r[t]===void 0||typeof r[t]==`function`))throw new e(`INVALID_ARGS`,`Custom test reporter ${n} ${t} must be a function.`);return r}function f(e){let t=Math.max(0,e)/1e3;return t>=10?`${t.toFixed(1)}s`:t>=1?`${t.toFixed(2)}s`:`${t.toFixed(3).replace(/0+$/,``).replace(/\.$/,``)}s`}function re(e){if(e.status===`skipped`)return[];let t=p(e);return t.length===0?[]:[e.attempts>1?`steps (attempt ${e.attempts}):`:`steps:`,...t.map(({stop:e,start:t})=>_(e,t))]}function ie(e){let t=p(e),n=t.findIndex(({stop:e})=>e.ok===!1);if(n<0)return[];let r=t.slice(Math.max(0,n-2),n+1);return[e.attempts>1?`steps (attempt ${e.attempts}):`:`steps:`,...r.map(({stop:e,start:t})=>_(e,t))]}function p(e){let t=oe(e);if(!t)return[];let n=se(t);if(n.length===0)return[];let r=[],i=[];for(let e of n){if(ce(e)){r.push(e);continue}le(e)&&i.push({stop:e,start:ae(r,e)})}return i}function ae(e,t){let n=t.command,r=e.findIndex(e=>e.step===t.step&&(n===void 0||e.command===void 0||e.command===n));if(!(r<0))return e.splice(r,1)[0]}function oe(e){return e.artifactsDir?s.join(e.artifactsDir,`attempt-${e.attempts}`,`replay-timing.ndjson`):void 0}function se(e){try{return a.readFileSync(e,`utf8`).split(/\r?\n/).filter(e=>e.trim().length>0).flatMap(e=>{try{let t=JSON.parse(e);return y(t)?[t]:[]}catch{return[]}})}catch{return[]}}function ce(e){return e.type===`replay_action_start`&&m(e)&&h(e,`line`)&&g(e,`command`)&&(e.positionals===void 0||Array.isArray(e.positionals))}function le(e){return de([e.type===`replay_action_stop`&&m(e)&&h(e,`line`)&&g(e,`command`),ue(e,`ok`),h(e,`durationMs`),g(e,`errorCode`),e.resultTiming===void 0||y(e.resultTiming)])}function m(e){return typeof e.step==`number`}function h(e,t){return e[t]===void 0||typeof e[t]==`number`}function g(e,t){return e[t]===void 0||typeof e[t]==`string`}function ue(e,t){return e[t]===void 0||typeof e[t]==`boolean`}function de(e){return e.every(Boolean)}function _(e,t){return` ${e.ok===!1?`[FAIL] `:e.ok===!0?``:`[info] `}${fe(t,e)}${v(e,t)}`}function v(e,t){let n=t?.line??e.line,r=[typeof n==`number`?`line ${n}`:``,typeof e.durationMs==`number`?f(e.durationMs):``,e.errorCode??``,e.resultTiming?`timing ${JSON.stringify(e.resultTiming)}`:``].filter(Boolean);return r.length>0?` (${r.join(`, `)})`:``}function fe(e,t){return[pe(e?.command??t.command),...(e?.positionals??[]).map(me)].join(` `)}function pe(e){if(!e)return`unknown`;if(!e.startsWith(`__maestro`))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}function me(e){return typeof e==`string`?JSON.stringify(e):typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function y(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}const b={interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`]},he=b.interval;function ge(e={}){let t=new Set,n=!1,r=0;return{render(i){if(i.type===`suite-start`){t.clear(),n=!1;return}if(i.type===`test-step`){if(!e.liveProgress)return;n=!0;let t=_e(r);return r+=1,{text:O(ye(i.test,e,t)),newline:!1}}if(i.type!==`test-result`)return;if(Oe(i.test)){let e=ke(i.test);if(t.has(e))return;t.add(e)}let a=ve(i.test,e);if(!a)return;let o=n?O(a):a;return n=!1,{text:o,newline:!0}}}}function _e(e){return b.frames[e%b.frames.length]??b.frames[0]}function ve(e,t={}){if(e.status===`fail`&&e.retrying)return;let n=[S(e)];return Se(n,e,t),t.verbose&&n.push(...Ne(e)),n.join(`
|
|
2
|
+
`)}function ye(e,t,n){let r=e.title?.trim(),a=s.basename(e.file),o=i(process.stderr),c=be(n,{useColor:o}),l=`${E(e,{useColor:o})}${xe(e,{useColor:o})}`,u=`${c} `;return A(r?`${u}${A(r,Math.max(0,k(t.columns)-j(u)-j(l)))}${l}`:`${u}${a}${l}`,t.columns)}function be(e,t={}){return t.useColor?T(e,`blue`):e}function xe(e,t={}){let n=`${e.stepIndex??0}/${e.stepTotal??0}`,r=e.stepCommand?.trim(),i=e.stepValue?.trim();if(!t.useColor)return` [${[n,r,i].filter(Boolean).join(` `)}]`;let a=T(`[`,`dim`),o=T(`]`,`dim`);return` ${a}${[T(n,`dim`),r?T(r,`magenta`):``,i?T(i,`green`):``].filter(Boolean).join(` `)}${o}`}function Se(e,t,n){if(Ce(t,n))return;let r=we(t),i=Te(t);r&&e.push(r),i&&e.push(i),Ee(e,t),e.push(...x(t))}function Ce(e,t){return t.verbose===!0&&e.status===`fail`}function we(e){return e.status===`fail`&&e.title?.trim()?` file: ${s.basename(e.file)}`:void 0}function Te(e){let t=e.message?.replace(/\s+/g,` `).trim();if(t)return` ${e.status===`fail`?`failed at: ${t}`:t}`}function Ee(e,t){let n=t.hint?.replace(/\s+/g,` `).trim();t.status===`fail`&&n&&e.push(` hint: ${n}`)}function x(e){if(e.status!==`fail`||e.retrying)return[];let t=[];return e.session&&t.push(` session: ${e.session}`),e.artifactsDir&&t.push(` artifacts: ${e.artifactsDir}`),t}function S(e){let t=i(process.stderr);return`${w(e)} ${C(e)}${E(e,{useColor:t})}${e.durationMs===void 0?``:` ${De(e,{useColor:t})}`}`}function C(e){let t=e.title?.trim(),n=s.basename(e.file);return t||n}function w(e){return e.status===`pass`?t(`pass`,{passFormat:e.attempt&&e.attempt>1?`yellow`:`green`}):t(e.status===`fail`?`fail`:`skip`)}function T(e,t){return n(e,t,{validateStream:!1})}function E(e,t={}){if(typeof e.shardIndex!=`number`)return``;let n=typeof e.shardCount==`number`?e.shardCount:`?`,r=D(e),i=` [${e.shardIndex+1}/${n}${r?` ${r}`:``}]`;return t.useColor?T(i,`dim`):i}function D(e){return e.deviceName?.trim()||e.deviceId?.trim()||void 0}function De(e,t={}){let n=f(e.durationMs??0);return t.useColor?T(n,`yellow`):n}function Oe(e){return e.status===`pass`||e.status===`skip`||e.status===`fail`&&!e.retrying}function ke(e){let t=typeof e.shardIndex==`number`?e.shardIndex:``;return[e.status,e.index,e.total,e.file,e.title??``,t].join(`\0`)}function O(e){return`\r\x1B[2K${e}`}function k(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):80}function A(e,t){let n=k(t);return j(e)<=n?e:n<=0?``:n<=3?`.`.repeat(n):`${je(e,n-3)}...${Ae(e)?`\x1B[0m`:``}`}function j(e){let t=0;for(let n=0;n<e.length;){let r=M(e,n);if(r){n+=r.length;continue}t+=1,n+=1}return t}function Ae(e){return e.includes(`\x1B[`)}function je(e,t){if(t<=0)return``;let n=0,r=``;for(let i=0;i<e.length&&n<t;){let t=M(e,i);if(t){r+=t,i+=t.length;continue}r+=e[i],i+=1,n+=1}return r}function M(e,t){if(!e.startsWith(`\x1B[`,t))return null;for(let n=t+2;n<e.length;n+=1)if(Me(e.charCodeAt(n)))return e.slice(t,n+1);return null}function Me(e){return e>=64&&e<=126}function Ne(e){return e.status!==`pass`&&e.status!==`fail`||!e.artifactsDir||!e.attempt?[]:re(e.status===`pass`?Pe(e):Fe(e)).map(e=>` ${e}`)}function Pe(e){return{...N(e),status:`passed`,replayed:0,healed:0}}function Fe(e){return{...N(e),status:`failed`,error:{code:`COMMAND_FAILED`,message:e.message??`Unknown test failure`}}}function N(e){return{file:e.file,title:e.title,durationMs:e.durationMs??0,attempts:e.attempt??1,artifactsDir:e.artifactsDir,session:e.session??``}}function P(e){return+(e.failed>0)}function Ie(e){return e.status===`failed`}function F(e){return e.status===`passed`&&e.attempts>1}function I(e){let t=K(e),n=s.basename(e.file);return`${t&&t.length>0?t:n}${q(e)}`}function Le(e){return`${K(e)??s.basename(e.file)}${q(e)}`}function L(e,t){return`artifactsDir`in e&&e.artifactsDir?`${t}: ${e.artifactsDir}`:void 0}function Re(e){return K(e)?`file: ${s.basename(e.file)}`:void 0}function R(e){return e.hint?`hint: ${e.hint}`:void 0}function z(e,t){return e.diagnosticId?`${t}: ${e.diagnosticId}`:void 0}function B(e,t){return e.logPath?`${t}: ${e.logPath}`:void 0}function V(e,t,n={}){n.includeMessage&&e.push(`errorMessage: ${t.message}`),U(e,R(t)),U(e,z(t,`diagnosticId`)),U(e,B(t,`logPath`)),n.includeDetails!==!1&&H(e,t,n.detailsIndent)}function H(e,t,n){let r=t.details?JSON.stringify(t.details,null,n):void 0;r&&e.push(`details: ${r}`)}function ze(e,t){!(`shardIndex`in t)||typeof t.shardIndex!=`number`||(e.push(`shardIndex: ${t.shardIndex}`),U(e,typeof t.shardCount==`number`?`shardCount: ${t.shardCount}`:void 0),U(e,typeof t.deviceId==`string`?`deviceId: ${t.deviceId}`:void 0),U(e,typeof t.deviceName==`string`?`deviceName: ${t.deviceName}`:void 0))}function Be(e){return e.status===`passed`?(e.warnings??[]).map(e=>`warning: ${e}`):[]}function U(e,t){t&&e.push(t)}function W(e){return(Math.max(0,e)/1e3).toFixed(3)}function G(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`).replaceAll(`'`,`'`)}function Ve(e){return e!==void 0}function K(e){let t=e.title?.trim();return t&&t.length>0?t:void 0}function q(e){if(!(`shardIndex`in e)||typeof e.shardIndex!=`number`)return``;let t=typeof e.shardCount==`number`?e.shardCount:`?`,n=He(e);return` [${e.shardIndex+1}/${t}${n?` ${n}`:``}]`}function He(e){return(`deviceName`in e?e.deviceName?.trim():void 0)||(`deviceId`in e?e.deviceId?.trim():void 0)||void 0}function Ue(){let e,t,n,r=!1,i=(n,r)=>{o(),t=n.type===`test-step`?n:void 0,e??=ge({verbose:r.verbose,liveProgress:J(r),columns:r.stderr.columns});let i=e.render(n);i&&(r.stderr.write(i.newline?`${i.text}\n`:i.text),n.type===`test-step`&&J(r)&&a(r))},a=r=>{n||!t||(n=setInterval(()=>{if(!t)return;let n=e?.render(t);n&&r.stderr.write(n.newline?`${n.text}\n`:n.text)},he),n.unref?.())},o=()=>{n&&=(clearInterval(n),void 0)},s=e=>{r||!J(e)||(e.stderr.write(`\x1B[?25l`),r=!0)},c=e=>{r&&=(e.stderr.write(`\x1B[?25h`),!1)};return{name:`default`,onSuiteStart:(e,t)=>{s(t),i({type:`suite-start`,suite:e},t)},onTestStep:(e,t)=>{i({type:`test-step`,test:e},t)},onTestResult:(e,t)=>{i({type:`test-result`,test:e},t)},onSuiteEnd:(e,n)=>{o(),t=void 0,c(n),We(e,n)},getExitCode:P}}function J(e){return e.stderr.isTTY&&!process.env.CI}function We(e,t){let n=e.tests.filter(F);t.stdout.write(`${Ge(e,n.length)}\n`),Qe(e.tests.filter(Ie),t),Ze(n,t)}function Ge(e,t){let n=typeof e.durationMs==`number`?e.durationMs:void 0,r=i();return`Test summary: ${Ke(e.passed,{useColor:r})} ${qe(e.total,{useColor:r})}${e.failed>0?`, ${e.failed} failed`:``}${t>0?`, ${t} flaky`:``}${n===void 0?``:` in ${Je(n,{useColor:r})}`}`}function Ke(e,t={}){let r=`${e} passed`;return t.useColor?n(r,`green`):r}function qe(e,t={}){let r=`(${e})`;return t.useColor?n(r,`dim`):r}function Je(e,t={}){let r=f(e);return t.useColor?n(r,`yellow`):r}function Ye(){return i()?n(`✓`,`yellow`):`✓`}function Xe(e){return[R(e.error),L(e,`artifacts`),B(e.error,`log`),z(e.error,`diagnostic`)].filter(Ve)}function Ze(e,t){if(e.length!==0){t.stdout.write(`
|
|
3
|
+
`),t.stdout.write(`Flaky tests:
|
|
4
|
+
`);for(let n of e){t.stdout.write(` ${Ye()} ${I(n)} after ${n.attempts} attempts${et(n)}\n`);for(let e of n.attemptFailures??[]){let n=typeof e.durationMs==`number`?` (${f(e.durationMs)})`:``;t.stdout.write(` attempt ${e.attempt} failed${n}: ${e.message}\n`)}}}}function Qe(e,t){if(e.length!==0){t.stdout.write(`
|
|
5
|
+
`),t.stdout.write(`Failures:
|
|
6
|
+
`);for(let n of e)t.stdout.write(` ${I(n)}\n`),$e(n,t,` `)}}function $e(e,t,n){let r=Re(e);r&&t.stdout.write(`${n}${r}\n`),t.stdout.write(`${n}${e.error?.message??`Unknown test failure`}\n`);for(let r of Xe(e))t.stdout.write(`${n}${r}\n`);if(t.debug)for(let r of ie(e))t.stdout.write(`${n}${r}\n`)}function et(e){let t=[typeof e.finalAttemptDurationMs==`number`?`passed attempt ${f(e.finalAttemptDurationMs)}`:``,e.durationMs>0?`total ${f(e.durationMs)}`:``].filter(Boolean);return t.length>0?` (${t.join(`, `)})`:``}function tt(e){let t=nt(e);return{name:`junit`,onSuiteEnd:e=>rt(t,e),getExitCode:P}}function nt(t){if(t&&t.trim().length>0)return t;throw new e(`INVALID_ARGS`,`The junit test reporter requires an output path. Use --reporter junit:<path>.`)}function rt(t,n){let r=s.dirname(t);try{a.mkdirSync(r,{recursive:!0}),a.writeFileSync(t,it(n),`utf8`)}catch(n){throw new e(`COMMAND_FAILED`,`Failed to write JUnit report to ${t}: ${n instanceof Error?n.message:String(n)}`)}}function it(e){let t=[`<?xml version="1.0" encoding="UTF-8"?>`,`<testsuites>`,` <testsuite name="agent-device replay suite" tests="${e.total}" failures="${e.failed}" skipped="${e.skipped}" time="${W(e.durationMs)}">`];for(let n of e.tests)t.push(...at(n));return t.push(` </testsuite>`),t.push(`</testsuites>`),`${t.join(`
|
|
7
|
+
`)}\n`}function at(e){let t=G(Le(e)),n=[` <testcase classname="${G(`${s.dirname(e.file)===`.`?e.file:s.dirname(e.file)}${q(e)}`)}" name="${t}" file="${G(e.file)}" time="${W(e.durationMs)}">`];e.status===`failed`?n.push(` <failure message="${G(e.error.message)}">${G(ot(e))}</failure>`):e.status===`skipped`&&n.push(` <skipped message="${G(e.message)}" />`);let r=st(e);return r&&n.push(` <system-out>${G(r)}</system-out>`),n.push(` </testcase>`),n}function ot(e){let t=[e.error.message];return V(t,e.error,{includeDetails:!1}),U(t,L(e,`artifactsDir`)),H(t,e.error,2),t.join(`
|
|
8
|
+
`)}function st(e){let t=[`status: ${e.status}`,`durationMs: ${e.durationMs}`];return ct(t,e),t.join(`
|
|
9
|
+
`)}function ct(e,t){U(e,`attempts`in t?`attempts: ${t.attempts}`:void 0),U(e,`session`in t?`session: ${t.session}`:void 0),U(e,`replayed`in t?`replayed: ${t.replayed}`:void 0),U(e,`healed`in t?`healed: ${t.healed}`:void 0);for(let n of Be(t))e.push(n);U(e,L(t,`artifactsDir`)),ze(e,t),t.status===`failed`&<(e,t),U(e,F(t)?`flaky: true`:void 0)}function lt(e,t){e.push(`errorCode: ${t.error.code}`),V(e,t.error,{includeMessage:!0})}function ut(e){if(e.type===`command`)return;if(e.type===`replay-test-suite`)return{type:`suite-start`,suite:{total:e.total,runnable:e.runnable,skipped:e.skipped,artifactsDir:e.artifactsDir,shardMode:e.shardMode,shardCount:e.shardCount}};let t={file:e.file,title:e.title,index:e.index,total:e.total,attempt:e.attempt,maxAttempts:e.maxAttempts,session:e.session,artifactsDir:e.artifactsDir,shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.deviceId,deviceName:e.deviceName};return e.status===`start`?{type:`test-start`,test:t}:e.status===`progress`?{type:`test-step`,test:{...t,stepIndex:e.stepIndex,stepTotal:e.stepTotal,stepCommand:e.stepCommand,stepValue:e.stepValue}}:{type:`test-result`,test:{...t,status:e.status,durationMs:e.durationMs,retrying:e.retrying,message:e.message,hint:e.hint}}}function dt(e){let t=e.reporters&&e.reporters.length>0?e.reporters.map(Y):e.json?[]:[Y(`default`)];return e.reportJunit&&t.push(Y(`junit:${e.reportJunit}`)),t}function Y(t){let n=t.trim();if(!n)throw new e(`INVALID_ARGS`,`Test reporter spec cannot be empty.`);if(pt(n))return{kind:`custom`,modulePath:n,raw:n};let{name:r,value:i}=ft(n);if(r==="default"){if(i!==void 0)throw new e(`INVALID_ARGS`,`The default test reporter does not accept options.`);return{kind:`builtin`,name:r,raw:n}}if(r===`junit`)return i===void 0?{kind:`builtin`,name:r,raw:n}:{kind:`builtin`,name:r,raw:n,outputPath:i};throw new e(`INVALID_ARGS`,`Unknown test reporter "${r}". Built-in reporters: default, junit:<path>. Custom reporters must be file paths.`)}function ft(e){let t=e.indexOf(`:`);return t<0?{name:e.trim()}:{name:e.slice(0,t).trim(),value:e.slice(t+1)}}function pt(e){return e.startsWith(`.`)||e.startsWith(`/`)||e.startsWith(`~`)||e.startsWith(`file:`)}const mt={"suite-start":`onSuiteStart`,"test-start":`onTestStart`,"test-step":`onTestStep`,"test-result":`onTestResult`};async function ht(e){let t=dt(e);return await Promise.all(t.map(yt))}async function gt(e,t,n){for(let r of e)await r.onSuiteEnd?.(t,n)}function X(e,t,n){let r=ut(t);if(!r)return;let i=mt[r.type];for(let t of e)try{let e=_t(t,r,n);e instanceof Promise&&e.catch(e=>Z(t,i,n,e))}catch(e){Z(t,i,n,e)}}function _t(e,t,n){switch(t.type){case`suite-start`:return e.onSuiteStart?.(t.suite,n);case`test-start`:return e.onTestStart?.(t.test,n);case`test-step`:return e.onTestStep?.(t.test,n);case`test-result`:return e.onTestResult?.(t.test,n)}}function Z(e,t,n,r){let i=r instanceof Error?r.message:String(r);n.stderr.write(`Reporter ${e.name} ${String(t)} failed: ${i}\n`)}function vt(e,t){let n=P(t);for(let r of e){let e=r.getExitCode?.(t);e!==void 0&&(n=Math.max(n,e))}return n}async function yt(e){return e.kind===`custom`?await u(e):e.name==="default"?Ue():tt(e.outputPath)}async function bt(e){let{suite:t,json:n,debug:i,verbose:a,reporter:o,reportJunit:s}=e,c=e.reporterRuntime??await Q({debug:i,verbose:a,reporter:o,reportJunit:s,json:n});return await gt(c.reporters,t,c.context),n&&r({success:!0,data:t}),vt(c.reporters,t)}async function Q(e){let t=await ht({reporters:e.reporter,reportJunit:e.reportJunit,json:e.json}),n=xt({debug:e.debug,verbose:e.verbose});return{reporters:t,context:n,onProgress(e){X(t,e,n)}}}function xt(e){return{debug:e.debug,verbose:e.verbose??e.debug,stdout:$(process.stdout),stderr:$(process.stderr)}}function $(e){return{isTTY:e.isTTY===!0,columns:e.columns,write:t=>e.write(t)}}export{Q as createReplayTestReporterRuntime,bt as renderReplayTestResponse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};export{t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime.js";import{F as t,H as n,I as r,f as i,m as a,p as o,x as s}from"./sdk-contracts.js";import{C as c,D as l,F as u,S as d,h as f,j as p,y as ee}from"./sdk-android-adb.js";import{n as te,t as m}from"./version.js";import{n as h,o as ne,r as re,s as ie}from"./host-process.js";import{l as ae}from"./sdk-batch-runner.js";import{_ as oe,d as se,g as ce,h as le,u as ue,v as de,y as fe}from"./logcat.js";import{n as pe,t as me}from"./xml.js";import{a as g,o as _,r as he}from"./tool-provider.js";import{n as ge}from"./simctl.js";import{c as _e}from"./agent-browser-tool.js";import{t as ve}from"./ttl-memo.js";import{n as ye,t as be}from"./runner-provider.js";import{AsyncLocalStorage as xe}from"node:async_hooks";import v from"node:crypto";import y from"node:fs";import b from"node:os";import x from"node:path";import Se from"node:fs/promises";import Ce from"node:net";const S=new Set,C=new Map,we=`request_canceled`,Te=`request canceled`;function Ee(e,t){if(typeof e==`string`&&e.length>0)return e;let n=(typeof t==`string`?t:typeof t==`number`&&Number.isFinite(t)?String(t):`generated`).trim().replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,32)||`generated`,r=Math.random().toString(36).slice(2,10);return`req:${n}:${process.pid}:${Date.now()}:${r}`}const De=5e4,Oe=1e4;function ke(e){if(e.size<=De)return;let t=0;for(let n of e.keys()){if(t>=Oe)break;e.delete(n),t++}}function Ae(e){if(e.size<=De)return;let t=0;for(let n of e){if(t>=Oe)break;e.delete(n),t++}}function je(e){if(!e)return;ke(C);let t=new AbortController;C.set(e,t),S.has(e)&&t.abort()}function Me(e){e&&(Ae(S),S.add(e),C.get(e)?.abort())}function Ne(e){e&&(S.delete(e),C.delete(e))}function Pe(e){return e?S.has(e):!1}function Fe(e){if(e)return C.get(e)?.signal}function w(){return new t(`COMMAND_FAILED`,Te,{reason:we,hint:`The request was canceled intentionally (explicit cancel or client disconnect) — no retry is needed unless the cancellation was unintended.`})}function Ie(e){if(Pe(e))throw w()}function T(e){return!(e instanceof t)||e.code!==`COMMAND_FAILED`?!1:e.details?.reason===we?!0:e.message===Te}const Le=new xe,Re=new xe;async function ze(e,t){return await Le.run(e,t)}function Be(e){Le.getStore()?.(e)}async function Ve(e,t){return await Re.run(e,t)}function He(){return Re.getStore()}const Ue=new xe;async function We(e,t,n){let r=Ue.getStore()??[];if(r.some(n=>n.locks===e&&n.key===t))return await n();let i=(e.get(t)??Promise.resolve()).catch(()=>{}).then(()=>Ue.run([...r,{locks:e,key:t}],n));return e.set(t,i),i.finally(()=>{e.get(t)===i&&e.delete(t)})}const Ge="If runner build products look stale or corrupted, run `pnpm clean:xcuitest` in a local checkout, or remove ~/.agent-device/apple-runner/derived, then retry.";function E(e){if(!(e instanceof t)||e.code!==`COMMAND_FAILED`)return!1;if(e.details?.retriable===!0)return!0;let n=`${e.message??``}`.toLowerCase();return n.includes(`xcodebuild exited early`)||n.includes(`device is busy`)&&n.includes(`connecting`)?!1:!!(n.includes(`runner did not accept connection`)||n.includes(`fetch failed`)||n.includes(`econnrefused`)||n.includes(`socket hang up`))}function Ke(e){return!(e instanceof t)||e.code!==`COMMAND_FAILED`?!0:!String(e.message??``).toLowerCase().includes(`xcodebuild exited early`)}function qe(e,t,n){let r=`${e}\n${t}\n${n}`.toLowerCase();return r.includes(`device is busy`)&&r.includes(`connecting`)?`Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.`:`${ue(`IOS_RUNNER_CONNECT_TIMEOUT`)} ${Ge}`}function Je(e){let{port:n,endpoints:r,logPath:i,lastError:a}=e,o=`Runner did not accept connection`;return new t(`COMMAND_FAILED`,o,{port:n,endpoints:r,logPath:i,lastError:a?String(a):void 0,reason:se({error:a,message:o,context:{platform:`ios`,phase:`connect`}}),hint:ue(`IOS_RUNNER_CONNECT_TIMEOUT`)})}async function Ye(e){let{session:n,port:r,logPath:i}=e,a=await n.testPromise,o=`Runner did not accept connection (xcodebuild exited early)`,s=se({message:o,stdout:a.stdout,stderr:a.stderr,context:{platform:`ios`,phase:`connect`}});return new t(`COMMAND_FAILED`,o,{port:r,logPath:i,xcodebuild:{exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr},reason:s,hint:qe(o,a.stdout,a.stderr)})}function Xe(e){let t=e.details?JSON.stringify(e.details):``,n=`${e.message}\n${t}`.toLowerCase();if(n.includes(`failed registering bundle identifier`)||n.includes(`app identifier`)&&n.includes(`not available`))return`Set AGENT_DEVICE_IOS_BUNDLE_ID to a unique reverse-DNS value (for example, com.yourname.agentdevice.runner), then retry.`;if(n.includes(`requires a development team`))return`Configure signing in Xcode or set AGENT_DEVICE_IOS_TEAM_ID for physical-device runs.`;if(n.includes(`no profiles for`)||n.includes(`provisioning profile`))return`Install/select a valid iOS provisioning profile, or set AGENT_DEVICE_IOS_PROVISIONING_PROFILE.`;if(n.includes(`code signing`))return`Enable Automatic Signing in Xcode or provide AGENT_DEVICE_IOS_TEAM_ID and optional AGENT_DEVICE_IOS_SIGNING_IDENTITY.`}function Ze(e){return Xe(e)??Ge}function D(e){return e.command===`status`||e.commandId?.trim()?e:{...e,commandId:Qe()}}function Qe(){return`runner-${v.randomUUID()}`}function O(e){if(Pe(e))throw w()}const $e=45e3,et=45e3,tt=1e4,k=new Map;async function nt(e,t,n,r,i=$e,a,o){let s=ce.fromTimeoutMs(i),{getEndpoints:c}=ut(e,t),{endpoints:l}=await c(s.remainingMs()),u=null,d=Math.max(1,Math.ceil(i/250));try{return await de(async({deadline:s})=>{let d=await rt({device:e,port:t,command:n,timeoutMs:i,logPath:r,session:a,endpoints:l,getEndpoints:c,signal:o,attemptDeadline:s,setEndpoints:e=>{l=e},setLastError:e=>{u=e}});if(d)return d;throw ct({port:t,endpoints:l,lastError:u,signal:o})},{maxAttempts:d,baseDelayMs:300,maxDelayMs:2e3,jitter:.2,shouldRetry:Ke},{deadline:s,phase:`ios_runner_connect`,signal:o})}catch(e){if(o?.aborted||T(e))throw w();u||=e}if(o?.aborted)throw w();if(e.kind===`simulator`){let i=s.remainingMs();if(i<=0)throw Je({port:t,endpoints:l,logPath:r,lastError:u});let a=await bt(e,t,n,i,o);return new Response(a.body,{status:a.status})}throw Je({port:t,endpoints:l,logPath:r,lastError:u})}async function rt(e){await it(e);let t=await at(e);return t.response?t.response:await ot(e)||await st(e,t.usedCachedTunnelIp)}async function it(e){if(e.attemptDeadline?.isExpired())throw new t(`COMMAND_FAILED`,`Runner connection deadline exceeded`,{port:e.port,timeoutMs:e.timeoutMs});if(e.session?.child.exitCode!==null&&e.session?.child.exitCode!==void 0)throw await Ye({session:e.session,port:e.port,logPath:e.logPath})}async function at(e){let t=e.endpoints,n=!1;if(e.device.kind===`device`){let r=await e.getEndpoints(e.attemptDeadline?.remainingMs());t=r.endpoints,n=r.cached,e.setEndpoints(t)}let r=n?t[0]:null;return{response:await dt(t,{command:e.command,port:e.port,timeoutMs:e.timeoutMs,signal:e.signal,attemptDeadline:e.attemptDeadline,onError:(t,n)=>{e.setLastError(n),e.device.kind===`device`&&t===r&>(e.device.id)}}),usedCachedTunnelIp:n}}async function ot(e){return e.device.kind!==`simulator`||!e.session?.ready?null:await ft(e.device,e.port,e.command,{signal:e.signal,attemptDeadline:e.attemptDeadline,onError:e.setLastError})}async function st(e,t){if(e.device.kind!==`device`||!t)return null;gt(e.device.id);let n=await e.getEndpoints(e.attemptDeadline?.remainingMs(),!0);return e.setEndpoints(n.endpoints),await dt(n.endpoints,{command:e.command,port:e.port,timeoutMs:e.timeoutMs,signal:e.signal,attemptDeadline:e.attemptDeadline,onError:(t,n)=>{e.setLastError(n)}})}function ct(e){if(e.signal?.aborted)throw w();return new t(`COMMAND_FAILED`,`Runner endpoint probe failed`,{port:e.port,endpoints:e.endpoints,lastError:e.lastError?String(e.lastError):void 0})}async function lt(e,n,r,i=et,a){if(a?.aborted)throw w();let o=ce.fromTimeoutMs(i),{getEndpoints:s}=ut(e,n),{endpoints:c}=await s(o.remainingMs()),l=c[0];if(!l)throw new t(`COMMAND_FAILED`,`Runner command endpoint not available`,{port:n,endpoints:c});let u=o.remainingMs();if(u<=0)throw new t(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:i});return await vt(l,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)},u,a)}function ut(e,t){let n;return{getEndpoints:async(r,i=!1)=>{let a=await pt({device:e,timeoutBudgetMs:r,forceRefresh:i,requestTunnelIp:n,setRequestTunnelIp:e=>{n=e}});return{endpoints:_t(e,t,a.ip),cached:a.sharedCacheHit}}}}async function dt(e,n){let{command:r,port:i,timeoutMs:a,signal:o,attemptDeadline:s,onError:c}=n;for(let n of e)try{let e=s?.remainingMs()??a;if(e<=0)throw new t(`COMMAND_FAILED`,`Runner connection deadline exceeded`,{port:i,timeoutMs:a});return await vt(n,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)},Math.min(2e4,e),o)}catch(e){if(o?.aborted||T(e))throw w();c(n,e)}return null}async function ft(e,t,n,r){let{signal:i,attemptDeadline:a,onError:o}=r,s=a?.remainingMs()??45e3;if(s<=0)return null;try{let r=await bt(e,t,n,s,i);return new Response(r.body,{status:r.status})}catch(e){if(i?.aborted||T(e))throw w();return o(e),null}}async function pt(e){let{device:t,timeoutBudgetMs:n,forceRefresh:r,requestTunnelIp:i,setRequestTunnelIp:a}=e;if(t.kind!==`device`)return{ip:null,sharedCacheHit:!1};if(!r){let e=mt(t.id);if(e)return{ip:e,sharedCacheHit:!0};if(i!==void 0)return{ip:i,sharedCacheHit:!1}}let o=await yt(t.id,n);return a(o),o&&ht(t.id,o),{ip:o,sharedCacheHit:!1}}function mt(e){let t=k.get(e);return t?t.expiresAt<=Date.now()?(k.delete(e),null):t.ip:null}function ht(e,t){k.set(e,{ip:t,expiresAt:Date.now()+3e4})}function gt(e){k.delete(e)}function _t(e,t,n){let r=[`http://127.0.0.1:${t}/command`];return e.kind===`device`&&n&&r.unshift(`http://[${n}]:${t}/command`),r}async function vt(e,t,n,r){let i=AbortSignal.timeout(n),a=r?AbortSignal.any([r,i]):i;return await fetch(e,{...t,signal:a})}async function yt(e,t){if(typeof t==`number`&&t<=0)return null;let n=typeof t==`number`?Math.max(1,Math.min(tt,t)):tt,r=x.join(b.tmpdir(),`agent-device-devicectl-info-${process.pid}-${Date.now()}.json`);try{let t=Math.max(1,Math.ceil(n/1e3));if((await _([`devicectl`,`device`,`info`,`details`,`--device`,e,`--json-output`,r,`--timeout`,String(t)],{allowFailure:!0,timeoutMs:n})).exitCode!==0||!y.existsSync(r))return null;let i=JSON.parse(y.readFileSync(r,`utf8`));if(i.info?.outcome&&i.info.outcome!==`success`)return null;let a=(i.result?.connectionProperties?.tunnelIPAddress??i.result?.device?.connectionProperties?.tunnelIPAddress)?.trim();return a&&a.length>0?a:null}catch{return null}finally{Ct(r)}}async function bt(e,t,n,r,i){let a=JSON.stringify(n);return{status:200,body:f(await _(ge(e,[`spawn`,e.id,`/usr/bin/curl`,`-s`,`-X`,`POST`,`-H`,`Content-Type: application/json`,`--data`,a,`http://127.0.0.1:${t}/command`]),{allowFailure:!0,timeoutMs:r,signal:i}),`Runner did not accept connection (simctl spawn)`,e=>{let n=se({message:`Runner did not accept connection (simctl spawn)`,stdout:e.stdout,stderr:e.stderr,context:{platform:`ios`,phase:`connect`}});return{port:t,reason:n,hint:ue(n)}}).stdout}}async function xt(){return await new Promise((e,n)=>{let r=Ce.createServer();r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i?.port){let t=i.port;r.close(()=>e(t))}else r.close(()=>n(new t(`COMMAND_FAILED`,`Failed to allocate port`)))}),r.on(`error`,n)})}function A(e,t,n,r){t&&St(t,e),n&&St(n,e),r&&process.stderr.write(e)}const j=new Map;function St(e,t){let n=(j.get(e)??Promise.resolve()).catch(()=>{}).then(async()=>{await y.promises.mkdir(x.dirname(e),{recursive:!0}),await y.promises.appendFile(e,t)}).catch(()=>{}).finally(()=>{j.get(e)===n&&j.delete(e)});j.set(e,n)}function Ct(e){try{y.existsSync(e)&&y.unlinkSync(e)}catch{}}const wt=`XCTestDevices`,Tt=`.agent-device-backup`,Et=`.agent-device-xctestdevices-backup-`;function Dt(e=b.homedir()){return x.join(e,`Library`,`Developer`,`XCTestDevices`)}function Ot(e=b.homedir()){return x.join(e,`.agent-device`,`xctest-device-set.lock`)}function kt(e=Dt()){return`${e}${Tt}`}async function At(e,n={}){if(!o(e)||e.kind!==`simulator`)return null;let r=le(e.simulatorSetPath);if(!r)return null;let i=x.resolve(r),a=x.resolve(n.xctestDeviceSetPath??Dt()),s=x.resolve(n.backupPath??kt(a)),c=x.resolve(n.lockDirPath??Ot()),l=n.ownerStartTime??ne(process.pid),u=await It({lockDirPath:c,owner:{pid:n.ownerPid??process.pid,startTime:l,acquiredAtMs:n.nowMs??Date.now()}});try{if(jt({xctestDeviceSetPath:a,backupPath:s}),Ft(i,a))return await u(),null;y.mkdirSync(i,{recursive:!0}),y.existsSync(a)&&y.renameSync(a,s),Nt({requestedSetPath:i,xctestDeviceSetPath:a})}catch(e){throw jt({xctestDeviceSetPath:a,backupPath:s}),await u(),new t(`COMMAND_FAILED`,`Failed to redirect XCTest device set path`,{requestedSetPath:i,xctestDeviceSetPath:a,backupPath:s,error:String(e)})}let d=!1;return{release:async()=>{if(!d){d=!0;try{jt({xctestDeviceSetPath:a,backupPath:s})}finally{await u()}}}}}function jt(e){let{xctestDeviceSetPath:t,backupPath:n}=e,r=[n,...Mt(n)],i=r.find(e=>y.existsSync(e)),a=y.existsSync(t)&&y.lstatSync(t).isSymbolicLink();if(i){if(a&&Pt(t),!y.existsSync(t))y.mkdirSync(x.dirname(t),{recursive:!0}),y.renameSync(i,t);else if(a)i===n?y.rmSync(n,{recursive:!0,force:!0}):y.rmSync(i,{recursive:!0,force:!0});else{p({level:`warn`,phase:`ios_runner_xctest_device_set_restore_collision`,data:{xctestDeviceSetPath:t,activeBackupPath:i}});return}for(let e of r)e!==i&&y.existsSync(e)&&y.rmSync(e,{recursive:!0,force:!0});return}a&&(p({level:`warn`,phase:`ios_runner_xctest_device_set_orphaned_symlink`,data:{xctestDeviceSetPath:t}}),Pt(t))}function Mt(e){let t=x.dirname(e),n=x.basename(e).replace(Tt,``),r=n===wt?Et:`${n}${Et}`;try{return y.readdirSync(t).filter(e=>e.startsWith(r)).sort().map(e=>x.join(t,e))}catch{return[]}}function Nt(e){let{requestedSetPath:t,xctestDeviceSetPath:n}=e,r=x.dirname(n),i=x.join(r,`${wt}.agent-device-link-${process.pid}-${Date.now()}`);y.mkdirSync(r,{recursive:!0});try{y.symlinkSync(t,i,`dir`),y.renameSync(i,n)}catch(e){throw y.existsSync(i)&&Pt(i),e}}function Pt(e){y.existsSync(e)&&y.lstatSync(e).isSymbolicLink()&&y.unlinkSync(e)}function Ft(e,t){if(x.resolve(e)===x.resolve(t))return!0;try{return y.realpathSync.native(e)===y.realpathSync.native(t)}catch{return!1}}async function It(e){return await _e({lockDirPath:e.lockDirPath,owner:e.owner,timeoutMs:e.timeoutMs??3e4,pollMs:e.pollMs??100,ownerGraceMs:5e3,description:e.description??`XCTest device set lock`})}const Lt={iOS:{sdkName:{simulator:`iphonesimulator`,device:`iphoneos`},derivedBaseName:{simulator:`ios-simulator`,device:`ios-device`},xctestrunHints:{simulator:{preferred:[`iphonesimulator`],disallowed:[`iphoneos`,`appletvos`,`appletvsimulator`,`macos`]},device:{preferred:[`iphoneos`],disallowed:[`iphonesimulator`,`appletvos`,`appletvsimulator`,`macos`]}}},tvOS:{sdkName:{simulator:`appletvsimulator`,device:`appletvos`},derivedBaseName:{simulator:`tvos-simulator`,device:`tvos-device`},xctestrunHints:{simulator:{preferred:[`appletvsimulator`],disallowed:[`appletvos`,`iphoneos`,`iphonesimulator`,`macos`]},device:{preferred:[`appletvos`],disallowed:[`appletvsimulator`,`iphoneos`,`iphonesimulator`,`macos`]}}},macOS:{sdkName:{simulator:`macosx`,device:`macosx`},derivedBaseName:{simulator:`macos`,device:`macos`},xctestrunHints:{simulator:{preferred:[`macos`],disallowed:[`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`]},device:{preferred:[`macos`],disallowed:[`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`]}}},visionOS:{sdkName:{simulator:`xrsimulator`,device:`xros`},derivedBaseName:{simulator:`visionos-simulator`,device:`visionos-device`},xctestrunHints:{simulator:{preferred:[`xrsimulator`],disallowed:[`xros`,`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`,`macos`]},device:{preferred:[`xros`],disallowed:[`xrsimulator`,`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`,`macos`]}}}};function M(e){if(!i(e.platform))throw new t(`UNSUPPORTED_PLATFORM`,`Unsupported platform for Apple runner: ${e.platform}`);return a(e)?`macOS`:s(e.target,e.appleOs)}function Rt(e,t){return Lt[e].sdkName[Wt(t)]}function zt(e){return Lt[M(e)].derivedBaseName[Wt(e.kind)]}function Bt(e){return Lt[M(e)].xctestrunHints[Wt(e.kind)]}function Vt(e){let t=M(e);return t===`macOS`?`platform=macOS,arch=${Gt()}`:e.kind===`simulator`?`platform=${t} Simulator,id=${e.id}`:`platform=${t},id=${e.id}`}function Ht(e){let t=M(e);return t===`macOS`?`platform=macOS,arch=${Gt()}`:e.kind===`simulator`?`platform=${t} Simulator,id=${e.id}`:`generic/platform=${t}`}function Ut(e){let t=M(e);return t===`macOS`?`platform=macOS,arch=${Gt()}`:e.kind===`simulator`?`generic/platform=${t} Simulator`:`generic/platform=${t}`}function Wt(e){return e===`simulator`?`simulator`:`device`}function Gt(){return process.arch===`arm64`?`arm64`:`x86_64`}const Kt=x.join(`apple-runner`,`AgentDeviceRunner`),qt=x.join(`dist`,`apple-runner`,`AgentDeviceRunner`);function Jt(e){let t=x.join(e,Kt);return y.existsSync(t)?t:x.join(e,qt)}function Yt(e){return x.join(Jt(e),`AgentDeviceRunner.xcodeproj`)}const Xt=x.join(b.homedir(),`.agent-device`,`apple-runner`),Zt=`.agent-device-runner-cache.json`,Qt=[`-IDEPackageSupportDisableManifestSandbox=1`,`-IDEPackageSupportDisablePluginExecutionSandbox=1`,`ENABLE_USER_SCRIPT_SANDBOXING=NO`],$t=ve();function N(e){return e?.trim()??``}function P(e=process.env){return N(e.AGENT_DEVICE_IOS_BUNDLE_ID)||N(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||`com.callstack.agentdevice.runner`}function en(e=process.env){return N(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID)||`${P(e)}.uitests`}function tn(e=process.env){let t=P(e),n=en(e);return Array.from(new Set([N(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${n}.xctrunner`,t].filter(e=>e.length>0)))}const nn=tn(process.env);function F(e,t=m()){let n=M(e);return{schemaVersion:2,packageVersion:te(),runnerSourceFingerprint:pn(t),...rn(n,e.kind),platformName:n,deviceKind:e.kind,target:e.target??`mobile`,buildDestinationFamily:Ut(e),runnerBundleBuildSettings:yn(process.env),runnerSigningBuildSettings:vn(process.env,e.kind===`device`,e),runnerPerformanceBuildSettings:bn(),runnerSandboxBuildArgs:xn()}}function rn(e,t){let n=on(an(`xcodebuild`,[`-version`])),r=Rt(e,t);return{xcodeVersion:n.version,xcodeBuildVersion:n.buildVersion,sdkName:r,sdkVersion:an(`xcrun`,[`--sdk`,r,`--show-sdk-version`]),sdkBuildVersion:an(`xcrun`,[`--sdk`,r,`--show-sdk-build-version`])}}function an(e,t){let n=JSON.stringify([e,t]),r=$t.get(n);if(r!==void 0)return r;try{let r=c(e,t,{allowFailure:!0,timeoutMs:5e3,maxBuffer:128*1024}),i=r.exitCode===0&&r.stdout.trim()||`unknown`;return $t.set(n,i),i}catch{return $t.set(n,`unknown`),`unknown`}}function on(e){return{version:e.match(/^Xcode\s+(.+)$/m)?.[1]?.trim()||`unknown`,buildVersion:e.match(/^Build version\s+(.+)$/m)?.[1]?.trim()||`unknown`}}function I(e,t){let n=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim();if(n)return x.resolve(n);let r=cn(t),i=sn(e);return x.join(i,r)}function sn(e){return x.join(Xt,`derived`,zt(e))}function cn(e){return`cache-${v.createHash(`sha256`).update(un(ln(e))).digest(`hex`).slice(0,16)}`}function ln(e){let{artifacts:t,packageVersion:n,...r}=e;return r}function un(e){return JSON.stringify(dn(e))}function dn(e){return Array.isArray(e)?e.map(e=>dn(e)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,dn(t)]))}const fn=new Map;function pn(e){let t=Jt(e),n=hn(t),r=mn(t,n),i=fn.get(t);if(i?.fileStatsFingerprint===r)return i.sourceFingerprint;let a=v.createHash(`sha256`);for(let e of n){let n=x.relative(t,e);a.update(n),a.update(`\0`),a.update(y.readFileSync(e)),a.update(`\0`)}let o=a.digest(`hex`);return fn.set(t,{fileStatsFingerprint:r,sourceFingerprint:o}),o}function mn(e,t){let n=v.createHash(`sha256`);for(let r of t){let t=x.relative(e,r),i=y.statSync(r);n.update(t),n.update(`\0`),n.update(String(i.size)),n.update(`\0`),n.update(String(Math.trunc(i.mtimeMs))),n.update(`\0`)}return n.digest(`hex`)}function hn(e){if(!y.existsSync(e))return[];let t=[],n=[e];for(;n.length>0;){let e=n.pop();for(let r of y.readdirSync(e,{withFileTypes:!0})){let i=x.join(e,r.name);if(r.isDirectory()){if(r.name===`xcuserdata`)continue;n.push(i);continue}r.isFile()&&gn(r.name,i)&&t.push(i)}}return t.sort((e,t)=>e.localeCompare(t))}function gn(e,t){return e===`project.pbxproj`?t.includes(`${x.sep}.xcodeproj${x.sep}`):[`.jpg`,`.json`,`.png`,`.swift`,`.m`,`.h`,`.plist`,`.entitlements`,`.xctestplan`,`.xcconfig`,`.storyboard`,`.xib`].includes(x.extname(e))}function _n(e){return a(e)||e.kind===`device`?`-maximum-concurrent-test-device-destinations`:`-maximum-concurrent-test-simulator-destinations`}function vn(e=process.env,t=!1,n={platform:`apple`}){if(a(n))return[`CODE_SIGNING_ALLOWED=NO`,`CODE_SIGNING_REQUIRED=NO`,`CODE_SIGN_IDENTITY=`,`DEVELOPMENT_TEAM=`];if(!t)return[];let r=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||``,i=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||``,o=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||``,s=[`CODE_SIGN_STYLE=Automatic`];return r&&s.push(`DEVELOPMENT_TEAM=${r}`),i&&s.push(`CODE_SIGN_IDENTITY=${i}`),o&&s.push(`PROVISIONING_PROFILE_SPECIFIER=${o}`),s}function yn(e=process.env){let t=P(e),n=en(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${n}`]}function bn(){return[`COMPILER_INDEX_STORE_ENABLE=NO`,`ENABLE_CODE_COVERAGE=NO`,`ONLY_ACTIVE_ARCH=YES`,`ENABLE_PREVIEWS=NO`,`ENABLE_DEBUG_DYLIB=NO`]}function xn(){return[...Qt,`OTHER_SWIFT_FLAGS=${Sn(process.env)}`]}function Sn(e){return oe(e.AGENT_DEVICE_XCUITEST_INCLUDE_UNIT_TESTS)?`$(inherited) -disable-sandbox -D AGENT_DEVICE_RUNNER_UNIT_TESTS`:`$(inherited) -disable-sandbox`}const Cn=new Set;function wn(e){return x.join(e,Zt)}function Tn(e,t){y.mkdirSync(e,{recursive:!0}),y.writeFileSync(wn(e),`${JSON.stringify(t,null,2)}\n`)}async function En(e,t){if(e.cache===`external`){L(`preserve`,`external_bad_artifact`,{derived:e.derived,xctestrunPath:e.xctestrunPath,reason:t});return}Cn.add(e.derived);let n=await Dn(e.derived);try{L(`clean`,`bad_artifact`,{derived:e.derived,xctestrunPath:e.xctestrunPath,reason:t}),Kn(e.derived),Mn(e.derived)}finally{await n()}}async function Dn(e){return await On({lockDirPath:kn(e),owner:{pid:process.pid,startTime:ne(process.pid),acquiredAtMs:Date.now()},description:`iOS runner cache lock`})}async function On(e){return await _e({lockDirPath:e.lockDirPath,owner:e.owner,timeoutMs:e.timeoutMs??6e5,pollMs:100,ownerGraceMs:5e3,description:e.description??`iOS runner cache lock`})}function kn(e){return x.join(x.dirname(e),`${x.basename(e)}.lock`)}function An(e,t){!Gn()&&!t&&!Cn.has(e)||(L(`clean`,t?`forced_rebuild`:`forced_clean`,{derived:e}),Kn(e),Mn(e),Cn.delete(e))}function jn(e,t,n,r){Tn(e,Ln(t,n,r))}function Mn(e){try{if(!y.existsSync(e))return;if(x.basename(e)!==`derived`){y.rmSync(e,{recursive:!0,force:!0});return}for(let t of y.readdirSync(e,{withFileTypes:!0}))Pn(t.name)&&y.rmSync(x.join(e,t.name),{recursive:!0,force:!0})}catch{}}const Nn=new Set([Zt,`Build`,`BuildCache.noindex`,`Index.noindex`,`Logs`,`ModuleCache.noindex`,`SDKStatCaches.noindex`,`SourcePackages`,`TextBasedInstallAPI`,`info.plist`]);function Pn(e){return Nn.has(e)}function Fn(e){try{let t=JSON.parse(y.readFileSync(wn(e),`utf8`));return!t||typeof t!=`object`||Array.isArray(t)?null:t}catch{return null}}function In(e,t){let n=Fn(e);return n?un(ln(n))===un(ln(t))?{ok:!0,metadata:n}:{ok:!1,reason:`cache_metadata_mismatch`}:{ok:!1,reason:`cache_metadata_missing`}}function Ln(e,t,n){let r=Rn(t,n);return r?{...e,artifacts:r}:e}function Rn(e,t){let n=Hn(e);if(n===null||t.length===0)return null;let r=[];for(let e of t){let t=Hn(e);if(t===null)return null;r.push({path:e,...t})}return{xctestrunPath:e,xctestrunMtimeMs:n.mtimeMs,xctestrunSize:n.size,productPaths:r}}function zn(e,t){let n=t?.artifacts;if(!Bn(n)||!Wn(n.xctestrunPath,e)||!Un(n.xctestrunPath,{mtimeMs:n.xctestrunMtimeMs,size:n.xctestrunSize}))return null;let r=[];for(let t of n.productPaths){if(!Wn(t.path,e)||!Un(t.path,t))return null;r.push(t.path)}return{xctestrunPath:n.xctestrunPath,productPaths:r}}function Bn(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.xctestrunPath==`string`&&Number.isInteger(t.xctestrunMtimeMs)&&Number.isInteger(t.xctestrunSize)&&Array.isArray(t.productPaths)&&t.productPaths.length>0&&t.productPaths.every(Vn)}function Vn(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.path==`string`&&Number.isInteger(t.mtimeMs)&&Number.isInteger(t.size)}function Hn(e){try{let t=y.statSync(e);return{mtimeMs:Math.trunc(t.mtimeMs),size:t.size}}catch{return null}}function Un(e,t){let n=Hn(e);return n?.mtimeMs===t.mtimeMs&&n.size===t.size}function Wn(e,t){let n=x.relative(x.resolve(t),x.resolve(e));return n!==``&&!n.startsWith(`..`)&&!x.isAbsolute(n)}function Gn(){return oe(process.env.AGENT_DEVICE_IOS_CLEAN_DERIVED)}function Kn(e,n=process.env){if(n.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim()&&!qn(e))throw new t(`COMMAND_FAILED`,`Refusing to clean AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH automatically`,{derivedPath:e,hint:`Unset AGENT_DEVICE_IOS_CLEAN_DERIVED, or move AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH under a subdirectory of ${x.join(m(),`.tmp`)}.`})}function qn(e){let t=x.resolve(m(),`.tmp`),n=x.relative(t,x.resolve(e));return n!==``&&!n.startsWith(`..`)&&!x.isAbsolute(n)}async function Jn(e){let t=In(e.derived,e.expectedCacheMetadata),n=t.ok?zn(e.derived,t.metadata):null,r=n?.xctestrunPath??e.findXctestrun(e.derived);if(!r)return{reason:`missing_xctestrun`,xctestrunPath:null};let i=n?.xctestrunPath===r,a=i?`manifest`:`scan`,o=i?n.productPaths:await e.resolveExistingXctestrunProductPaths(r);return o?!e.xctestrunReferencesProjectRoot(r,e.projectRoot)&&!i?{reason:`project_root_mismatch`,xctestrunPath:r,productPaths:o,source:a}:t.ok?{reason:`reuse_ready`,xctestrunPath:r,productPaths:o,source:a}:{reason:t.reason,xctestrunPath:r,productPaths:o,source:a}:{reason:`missing_products`,xctestrunPath:r,productPaths:[],source:a}}function L(e,t,n){p({level:e===`rebuild`?`warn`:`info`,phase:`runner_xctestrun_cache`,data:{action:e,reason:t,...n}})}const Yn=new Set([`RUNNER_PRODUCT_MISSING`,`RUNNER_PRODUCT_REPAIR_FAILED`]);async function Xn(e,n,i){if(!a(e))return;if(n.length===0)throw new t(`COMMAND_FAILED`,`Missing macOS runner product`,{reason:`RUNNER_PRODUCT_MISSING`,xctestrunPath:i});let o=Array.from(new Set(n)).sort((e,t)=>t.length-e.length);for(let e of o)if(!y.existsSync(e))throw new t(`COMMAND_FAILED`,`Missing macOS runner product`,{reason:`RUNNER_PRODUCT_MISSING`,productPath:e,xctestrunPath:i});for(let e of o)if(!await Qn(e)){await g(`codesign`,[`--remove-signature`,e],{allowFailure:!0});try{await g(`codesign`,[`--force`,`--sign`,`-`,e])}catch(n){let a=r(n,`COMMAND_FAILED`);throw new t(`COMMAND_FAILED`,`Failed to repair macOS runner product signature`,{reason:`RUNNER_PRODUCT_REPAIR_FAILED`,productPath:e,xctestrunPath:i,error:a.message,details:a.details})}}}function Zn(e){if(!(e instanceof t))return!1;let n=e.details&&typeof e.details==`object`?e.details.reason:void 0;return typeof n==`string`&&Yn.has(n)}async function Qn(e){return(await g(`codesign`,[`--verify`,`--deep`,`--strict`,e],{allowFailure:!0})).exitCode===0}const $n=new Set([`ProductPaths`,`DependentProductPaths`,`TestHostPath`,`TestBundlePath`,`UITargetAppPath`]);async function er(e){let t=await rr(e);if(!t||t.length===0)return null;let n=x.dirname(e),r=new Set,i=tr(t,n);for(let e of i.testRootPaths){if(!y.existsSync(e))return null;r.add(e)}for(let e of nr(i)){if(!e)return null;r.add(e)}return Array.from(r)}function tr(e,t){let n=[],r=new Set,i=[];for(let a of e){if(a.startsWith(`__TESTHOST__/`)){i.push(a.slice(13));continue}if(!a.startsWith(`__TESTROOT__/`))continue;let e=a.slice(13);n.push(x.join(t,e));let o=ur(e);o&&r.add(x.join(t,o))}return{testRootPaths:n,hostRoots:Array.from(r),hostRelativePaths:i}}function nr(e){return e.hostRelativePaths.map(t=>{let n=e.hostRoots.find(e=>y.existsSync(x.join(e,t)));return n?x.join(n,t):null})}async function rr(e){let t=await he(e);if(t)return ir(t);if(process.platform===`darwin`)return null;try{return cr(y.readFileSync(e,`utf8`))}catch{return null}}function ir(e){let t=new Set;for(let n of[e,...ar(e),...or(e)])for(let e of sr(n))t.add(e);return Array.from(t)}function ar(e){let t=e.TestConfigurations;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!ae(e))continue;let t=e.TestTargets;Array.isArray(t)&&n.push(...t.filter(ae))}return n}function or(e){return Object.values(e).filter(e=>ae(e)&&`TestBundlePath`in e)}function sr(e){let t=new Set;for(let[n,r]of Object.entries(e))if($n.has(n)){if(typeof r==`string`){t.add(r);continue}if(Array.isArray(r))for(let e of r)typeof e==`string`&&t.add(e)}return Array.from(t)}function cr(e){return lr(me(e))}function lr(e){let t=new Set;return pe(e,(e,n)=>{if($n.has(e)){if(n.name===`string`&&n.text){t.add(n.text);return}if(n.name===`array`)for(let e of n.children)e.name===`string`&&e.text&&t.add(e.text)}}),Array.from(t)}function ur(e){let t=/\.app(?:\/|$)/.exec(e);return!t||t.index===void 0?null:e.slice(0,t.index+4)}const dr=[`CFBundleIcons`,`CFBundleIcons~ipad`];async function fr(e){let t=e.filter(Cr);if(t.length===0)return;let n=e.filter(e=>Tr(e)&&!wr(e));for(let e of t){let t=Sr(e,n);t&&await pr(t,e)}}async function pr(e,t){let n=mr(e,t),r=await hr(e,t);(n||r)&&(await vr(t),xr(t))}function mr(e,t){let n=!1;for(let r of y.readdirSync(e,{withFileTypes:!0}))!r.isFile()||!br(r.name)||yr(x.join(e,r.name),x.join(t,r.name))&&(n=!0);return n}async function hr(e,t){let n=x.join(e,`Info.plist`),r=x.join(t,`Info.plist`),i=await he(n),a=await he(r);if(!i||!a)return!1;let o=gr(i,a);if(o.length===0)return!1;for(let e of o)await _r(r,e.key,e.value,e.shouldInsert);return!0}function gr(e,t){return dr.flatMap(n=>{let r=e[n];return r===void 0||JSON.stringify(t[n])===JSON.stringify(r)?[]:[{key:n,value:r,shouldInsert:t[n]===void 0}]})}async function _r(e,t,n,r){f(await g(`plutil`,[r?`-insert`:`-replace`,t,`-json`,JSON.stringify(n),e],{allowFailure:!0}),`Failed to update XCTest runner icon plist`,{key:t,plistPath:e})}async function vr(e){f(await g(`codesign`,[`--force`,`--sign`,`-`,`--timestamp=none`,`--generate-entitlement-der`,e],{allowFailure:!0}),`Failed to sign XCTest runner app after icon update`,{runnerAppPath:e})}function yr(e,t){if(y.existsSync(t)){let n=y.readFileSync(e),r=y.readFileSync(t);return n.equals(r)?!1:(y.copyFileSync(e,t),!0)}return y.copyFileSync(e,t),!0}function br(e){return/^AppIcon.*\.png$/.test(e)||e===`Assets.car`}function xr(e){let t=new Date;y.utimesSync(e,t,t)}function Sr(e,t){let n=x.dirname(e);return t.find(e=>x.dirname(e)===n&&x.basename(e)===`AgentDeviceRunner.app`)??t.find(t=>x.dirname(t)===n&&t!==e)??null}function Cr(e){return Tr(e)&&wr(e)&&(e.includes(`Debug-iphonesimulator`)||e.includes(`Release-iphonesimulator`)||e.includes(`Debug-appletvsimulator`)||e.includes(`Release-appletvsimulator`))}function wr(e){return x.basename(e).endsWith(`-Runner.app`)}function Tr(e){return x.basename(e).endsWith(`.app`)}const Er={PreferredScreenCaptureFormat:`screenshots`,SystemAttachmentLifetime:`keepNever`,UserAttachmentLifetime:`keepNever`};async function Dr(e,t,n,r={}){let i=r.iosXctestEnvDir?.trim(),a=i?x.resolve(i):x.dirname(e);y.mkdirSync(a,{recursive:!0});let o=n.replace(/[^a-zA-Z0-9._-]/g,`_`),s=x.join(a,`AgentDeviceRunner.env.${o}.json`),c=x.join(a,`AgentDeviceRunner.env.${o}.xctestrun`),l=await Or(e);return Mr(l,e=>Ar(e,t)),jr(l),await kr(l,s,c),{xctestrunPath:c,jsonPath:s}}async function Or(e){let n=await g(`plutil`,[`-convert`,`json`,`-o`,`-`,e],{allowFailure:!0});if(n.exitCode!==0||!n.stdout.trim())throw new t(`COMMAND_FAILED`,`Failed to read xctestrun plist`,{xctestrunPath:e,stderr:n.stderr});try{let e=JSON.parse(n.stdout);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Root must be an object`);return e}catch(n){throw new t(`COMMAND_FAILED`,`Failed to parse xctestrun JSON`,{xctestrunPath:e,error:String(n)})}}async function kr(e,t,n){y.writeFileSync(t,JSON.stringify(e,null,2)),f(await g(`plutil`,[`-convert`,`xml1`,`-o`,n,t],{allowFailure:!0}),`Failed to write xctestrun plist`,{tmpXctestrunPath:n})}function Ar(e,t){e.EnvironmentVariables={...e.EnvironmentVariables??{},...t},e.UITestEnvironmentVariables={...e.UITestEnvironmentVariables??{},...t},e.UITargetAppEnvironmentVariables={...e.UITargetAppEnvironmentVariables??{},...t},e.TestingEnvironmentVariables={...e.TestingEnvironmentVariables??{},...t}}function jr(e){Mr(e,e=>Object.assign(e,Er),{requireTestBundlePath:!0})}function Mr(e,t,n={}){let r=e.TestConfigurations;if(Array.isArray(r))for(let e of r)!e||typeof e!=`object`||Nr(e.TestTargets,t,n);for(let n of Object.values(e)){let e=Pr(n,{requireTestBundlePath:!0});e&&t(e)}}function Nr(e,t,n){if(Array.isArray(e))for(let r of e){let e=Pr(r,n);e&&t(e)}}function Pr(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;return t.requireTestBundlePath&&!n.TestBundlePath?null:n}const Fr=new Map,R=new Set;async function Ir(e,t){let n=Lr(t);if(n)return n;let r=m(),i=F(e,r),a=I(e,i);return await We(Fr,a,async()=>{let n=await Dn(a);try{return await zr({device:e,options:t,projectRoot:r,expectedCacheMetadata:i,derived:a,forceRebuild:t.forceRunnerXctestrunRebuild===!0})}finally{await n()}})}function Lr(e){let n=e.iosXctestrunFile?.trim();if(!n)return null;let r=x.resolve(n);if(!y.existsSync(r))throw new t(`COMMAND_FAILED`,`Configured iOS XCTest runner .xctestrun file not found`,{configKey:`iosXctestrunFile`,xctestrunPath:r});let i=e.iosXctestDerivedDataPath?.trim(),a=i?x.resolve(i):Rr(r);return L(`reuse`,`external_xctestrun`,{derived:a,xctestrunPath:r}),{xctestrunPath:r,derived:a,cache:`external`,artifact:`valid`,buildMs:0,xctestrunPathSource:`external`}}function Rr(e){let t=v.createHash(`sha1`);t.update(e);let n=t.digest(`hex`).slice(0,12);return x.join(b.tmpdir(),`agent-device-ios-xctest-derived`,n)}async function zr(e){let{device:t,options:n,projectRoot:r,expectedCacheMetadata:i,derived:a}=e;An(a,e.forceRebuild);let o=await Wr({device:t,derived:a,projectRoot:r,expectedCacheMetadata:i}),s=o.reason===`reuse_ready`?`exact`:o.xctestrunPath?`restore-key`:`miss`;return o.reason!==`reuse_ready`&&L(`rebuild`,o.reason,{derived:a,xctestrunPath:o.xctestrunPath}),await Br({device:t,derived:a,expectedCacheMetadata:i,existing:o,cache:s})||(o.xctestrunPath&&(Kn(a),Mn(a)),await Vr({device:t,options:n,projectRoot:r,expectedCacheMetadata:i,derived:a,cache:s,reason:o.reason}))}async function Br(e){let{device:t,derived:n,expectedCacheMetadata:r,existing:i,cache:a}=e;if(i.reason!==`reuse_ready`)return null;let o=await Hr(t,n,r,i);return o?{xctestrunPath:o,derived:n,cache:a,artifact:`valid`,buildMs:0,xctestrunPathSource:i.source}:null}async function Vr(e){let{device:n,options:r,projectRoot:i,expectedCacheMetadata:a,derived:o,cache:s,reason:c}=e,l=Yt(i);if(!y.existsSync(l))throw new t(`COMMAND_FAILED`,`iOS runner project not found`,{projectPath:l});let u=Date.now();Be({type:`command`,status:`progress`,message:`Building Apple runner...`}),await Xr(n,l,o,r);let d=Math.max(0,Date.now()-u),f=Gr(o,n);if(!f)throw new t(`COMMAND_FAILED`,`Failed to locate .xctestrun after build`);let p=await er(f);if(!p)throw new t(`COMMAND_FAILED`,`Runner build is missing expected products`,{xctestrunPath:f});return await Xn(n,p,f),await fr(p),jn(o,a,f,p),L(`build`,`built_new`,{derived:o,xctestrunPath:f}),{xctestrunPath:f,derived:o,cache:s,artifact:`rebuilt`,buildMs:d,xctestrunPathSource:`build`,reason:c}}async function Hr(e,t,n,r){try{return await Xn(e,r.productPaths,r.xctestrunPath),L(`reuse`,`reuse_ready`,{derived:t,xctestrunPath:r.xctestrunPath}),jn(t,n,r.xctestrunPath,r.productPaths),r.xctestrunPath}catch(e){if(!Zn(e))throw e;return L(`rebuild`,`repair_failed`,{derived:t,xctestrunPath:r.xctestrunPath}),null}}async function Ur(e){try{let t=m(),n=F(e,t);return(await Wr({device:e,derived:I(e,n),projectRoot:t,expectedCacheMetadata:n})).reason===`reuse_ready`}catch{return!1}}function Wr(e){let{device:t,derived:n,projectRoot:r,expectedCacheMetadata:i}=e;return Jn({derived:n,projectRoot:r,expectedCacheMetadata:i,findXctestrun:e=>Gr(e,t),xctestrunReferencesProjectRoot:Yr,resolveExistingXctestrunProductPaths:er})}function Gr(e,t){let n=Kr(e);return n.length===0?null:(n.sort((e,n)=>qr(e,n,t)),n[0]?.path??null)}function Kr(e){if(!y.existsSync(e))return[];let t=[],n=[e];for(;n.length>0;){let e=n.pop(),r=y.readdirSync(e,{withFileTypes:!0});for(let i of r){let r=x.join(e,i.name);if(i.isDirectory()){n.push(r);continue}if(i.isFile()&&i.name.endsWith(`.xctestrun`))try{let e=y.statSync(r);t.push({path:r,mtimeMs:e.mtimeMs})}catch{}}}return t}function qr(e,t,n){if(n){let r=Jr(t.path,n)-Jr(e.path,n);if(r!==0)return r}return t.mtimeMs-e.mtimeMs||e.path.localeCompare(t.path)}function Jr(e,t){let n=0,r=e.toLowerCase();x.basename(r).startsWith(`agentdevicerunner.env.`)&&(n-=1e3),r.includes(`${x.sep}macos${x.sep}`)&&(n-=5e3);let i=Bt(t);return i.preferred.length>0&&(i.preferred.some(e=>r.includes(e))?n+=2e3:n-=500),i.disallowed.some(e=>r.includes(e))&&(n-=2500),n}function Yr(e,t){try{let n=y.readFileSync(e,`utf8`),r=new Set([t]);try{r.add(y.realpathSync(t))}catch{}for(let e of r)if(n.includes(e))return!0;return!1}catch{return!1}}async function Xr(e,n,r,i){let a=yn(process.env),o=vn(process.env,e.kind===`device`,e),s=e.kind===`device`?[`-allowProvisioningUpdates`]:[],c=bn(),l=xn(),u=await At(e);try{await d(`xcodebuild`,[`build-for-testing`,`-project`,n,`-scheme`,`AgentDeviceRunner`,`-parallel-testing-enabled`,`NO`,_n(e),`1`,`-destination`,Ht(e),`-derivedDataPath`,r,...c,...l,...a,...s,...o],{detached:!0,timeoutMs:i.buildTimeoutMs,onSpawn:e=>{R.add(e),e.on(`close`,()=>{R.delete(e)})},onStdoutChunk:e=>{A(e,i.logPath,i.traceLogPath,i.verbose)},onStderrChunk:e=>{A(e,i.logPath,i.traceLogPath,i.verbose)}})}catch(e){let n=e instanceof t?e:new t(`COMMAND_FAILED`,String(e)),r=Ze(n);throw new t(`COMMAND_FAILED`,`xcodebuild build-for-testing failed`,{error:n.message,details:n.details,logPath:i.logPath,hint:r})}finally{await u?.release()}}const Zr={tap:`preflightSkippableTouchMutation`,mouseClick:`default`,longPress:`preflightSkippableTouchMutation`,drag:`preflightSkippableTouchMutation`,remotePress:`default`,type:`default`,swipe:`preflightSkippableTouchMutation`,scroll:`preflightSkippableTouchMutation`,desktopScroll:`preflightSkippableTouchMutation`,findText:`readOnly`,querySelector:`readOnly`,readText:`readOnly`,snapshot:`readOnly`,screenshot:`readOnly`,back:`default`,backInApp:`default`,backSystem:`default`,home:`default`,rotate:`default`,rotateGesture:`default`,transformGesture:`default`,appSwitcher:`default`,keyboardDismiss:`default`,keyboardReturn:`default`,alert:`readOnly`,pinch:`default`,sequence:`preflightSkippableTouchMutation`,recordStart:`default`,recordStop:`default`,status:`readOnlyReadinessProbe`,uptime:`readOnlyReadinessProbe`,shutdown:`default`},Qr={readOnly:!1,readinessProbe:!1,readinessPreflightSkipEligibleAfterHealthyMutation:!1},$r={...Qr,readOnly:!0},ei={...$r,readinessProbe:!0},ti={...Qr,readinessPreflightSkipEligibleAfterHealthyMutation:!0},ni=Object.fromEntries(Object.entries(Zr).map(([e,t])=>[e,oi(t)]));function ri(e){return ni[e]}function z(e){return ri(e).readOnly}function ii(e){return ri(e).readinessProbe}function ai(e){return ri(e).readinessPreflightSkipEligibleAfterHealthyMutation}function oi(e){switch(e){case`default`:return Qr;case`readOnly`:return $r;case`readOnlyReadinessProbe`:return ei;case`preflightSkippableTouchMutation`:return ti}}const si=process.pid,ci=ne(process.pid),li=Ri(si,ci);let ui;function di(e){return{schemaVersion:1,deviceId:e.deviceId,ownerToken:li,ownerPid:si,ownerStartTime:ci,ownerStateDir:yi(),sessionId:e.sessionId,runnerPid:e.runnerPid??null,port:e.port,xctestrunPath:e.xctestrunPath,jsonPath:e.jsonPath,createdAtMs:Date.now()}}function fi(e){ui=e?.trim()||void 0}async function pi(e,t){let n=await _e({lockDirPath:`${V(e)}.lock`,owner:{pid:si,startTime:ci,acquiredAtMs:Date.now()},timeoutMs:3e4,pollMs:100,ownerGraceMs:5e3,description:`iOS runner lease for ${e}`});try{return await t()}finally{await n()}}function B(e){try{return Mi(JSON.parse(y.readFileSync(V(e),`utf8`)),e)}catch{return null}}function mi(e){return e?e.ownerToken===li?{type:`owned`,lease:e}:Li(e)?{type:`busy`,lease:e}:{type:`stale`,lease:e}:{type:`empty`}}async function hi(e,n,r){let i=mi(B(e));if(i.type===`empty`){await n.cleanupRunnerXcodebuildProcesses(e,void 0);return}if(i.type===`busy`){if(gi(i.lease)){await U(i.lease,`same-state-dir`,n);return}if(_i(i.lease,r)){await U(i.lease,`logical-lease-takeover`,n);return}throw new t(`COMMAND_FAILED`,r?`iOS runner for ${e} is busy after device lease admission`:`iOS runner for ${e} is already owned by another agent-device daemon`,{deviceId:e,logicalLeaseContext:r,ownerPid:i.lease.ownerPid,ownerStartTime:i.lease.ownerStartTime,ownerStateDir:i.lease.ownerStateDir,ownerToken:i.lease.ownerToken,sessionId:i.lease.sessionId,hint:bi(i.lease,r)})}await U(i.lease,i.type,n)}function gi(e){let t=yi();return!t||!e.ownerStateDir?!1:x.resolve(t)===x.resolve(e.ownerStateDir)}function _i(e,t){return!t||t.leaseProvider!==`proxy`||!t.leaseId||!t.clientId?!1:vi(t.deviceKey,e.deviceId)}function vi(e,t){if(!e)return!1;if(e===t)return!0;let[,,n]=e.split(`:`,3);return n===t}function yi(){return ui||process.env.AGENT_DEVICE_STATE_DIR?.trim()||void 0}function bi(e,t){let n=xi(e),r=Si(e);return t?[r,n,`The device is busy because another active device lease owns it, or the runner is owned by another daemon/process after lease admission.`,`Retry after the owning session closes or after the five-minute inactivity lease expires.`].join(` `):[r,n,`If the runner is still active, wait for it to finish. Do not run prepare ios-runner from another daemon/client to recover this.`].join(` `)}function xi(e){let t=`Runner owner: PID ${e.ownerPid}`;return e.ownerStateDir?`${t} with AGENT_DEVICE_STATE_DIR=${e.ownerStateDir}`:`${t}.`}function Si(e){return e.ownerStateDir?`If it is stuck, stop the owning agent-device daemon for ${Ci(`AGENT_DEVICE_STATE_DIR`,e.ownerStateDir)} and retry.`:`If it is stuck, stop the owning agent-device daemon and retry.`}function Ci(e,t){return`${e}=${wi(t)}`}function wi(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Ti(e){let t=mi(B(e));return t.type===`stale`?t.lease:null}function Ei(e){return{...e,ownerToken:`detached-${e.ownerToken}`}}async function Di(e,t){let n=mi(B(e));n.type===`owned`&&await U(n.lease,`owned`,t)}function Oi(e){e&&Ai({deviceId:e.deviceId,ownerToken:e.ownerToken,sessionId:e.sessionId})}function ki(e){let t=V(e.deviceId);y.mkdirSync(x.dirname(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;y.writeFileSync(n,JSON.stringify(e,null,2),`utf8`),y.renameSync(n,t)}function Ai(e){let t=B(e.deviceId);if(t&&!(e.ownerToken&&t.ownerToken!==e.ownerToken)&&!(e.sessionId&&t.sessionId!==e.sessionId))try{y.unlinkSync(V(e.deviceId))}catch{}}function V(e){return x.join(ji(),`${zi(e)}.json`)}function ji(){let e=process.env.AGENT_DEVICE_IOS_RUNNER_LEASE_DIR?.trim();return e?x.resolve(e):x.join(b.homedir(),`.agent-device`,`apple-runner`,`leases`)}function Mi(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;if(n.schemaVersion!==1||n.deviceId!==t)return null;let r=Ni(n);return r?{schemaVersion:1,deviceId:t,...r,ownerStartTime:Pi(n.ownerStartTime),ownerStateDir:Pi(n.ownerStateDir)??void 0,runnerPid:Fi(n.runnerPid)}:null}function Ni(e){let t={ownerToken:H(e.ownerToken),ownerPid:Fi(e.ownerPid),sessionId:H(e.sessionId),port:Fi(e.port),xctestrunPath:H(e.xctestrunPath),jsonPath:H(e.jsonPath),createdAtMs:Ii(e.createdAtMs)};return Object.values(t).some(e=>e===null)?null:t}function H(e){return typeof e==`string`&&e.length>0?e:null}function Pi(e){return typeof e==`string`?e:null}function Fi(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function Ii(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Li(e){return h(e.ownerPid)?e.ownerStartTime?ne(e.ownerPid)===e.ownerStartTime:!0:!1}async function U(e,t,n){p({level:t===`stale`||t===`same-state-dir`||t===`logical-lease-takeover`?`warn`:`debug`,phase:`ios_runner_lease_cleanup`,data:{deviceId:e.deviceId,ownerPid:e.ownerPid,ownerStateDir:e.ownerStateDir,ownerToken:e.ownerToken,runnerPid:e.runnerPid,sessionId:e.sessionId,reason:t}}),await n.cleanupRunnerProcessTree(e.runnerPid??void 0,`SIGTERM`),await n.cleanupRunnerXcodebuildProcesses(e.deviceId,e.ownerToken),await n.cleanupRunnerProcessTree(e.runnerPid??void 0,`SIGKILL`),n.cleanupTempFile(e.xctestrunPath),n.cleanupTempFile(e.jsonPath),Oi(e)}function Ri(e,t){let n=v.createHash(`sha256`);return n.update(String(e)),n.update(`\0`),n.update(t??`unknown-start`),`owner-${e}-${n.digest(`hex`).slice(0,8)}`}function zi(e){return e.replaceAll(/[^A-Za-z0-9._-]/g,`-`)||`unknown-device`}function Bi(e,t){return`${e}:${t}:${Date.now()}`}function Vi(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}function Hi(e=process.env){return l(e.AGENT_DEVICE_IOS_RUNNER_DETACH??``)!==!1}async function Ui(e,t){if(e.kind!==`simulator`||!Hi()||le(e.simulatorSetPath))return null;let n=Ti(e.id);if(!n)return null;let r=t=>(p({level:`debug`,phase:`ios_runner_lease_adoption_skipped`,data:{deviceId:e.id,runnerPid:n.runnerPid,port:n.port,reason:t}}),null),i=n.runnerPid;if(!i)return r(`runner_pid_missing`);if(!h(i))return r(`runner_process_dead`);let a=Gi(e);if(!a)return r(`expected_derived_unresolved`);if(!n.xctestrunPath.startsWith(`${a}${x.sep}`))return r(`artifact_fingerprint_mismatch`);if(!await Wi(e,n.port))return r(`probe_failed`);let o=Ki(e,n,i,a,t);try{ki(o.lease)}catch{return null}return p({level:`info`,phase:`ios_runner_lease_adopted`,data:{deviceId:e.id,sessionId:o.sessionId,runnerPid:i,port:n.port,previousOwnerPid:n.ownerPid}}),o}async function Wi(e,t){try{let n=await lt(e,t,D({command:`uptime`}),500);return JSON.parse(await n.text())?.ok===!0}catch{return!1}}function Gi(e){try{return I(e,F(e))}catch{return null}}function Ki(e,t,n,r,i){let a=Bi(e.id,t.port),o={xctestrunPath:t.xctestrunPath,derived:r,cache:`exact`,artifact:`valid`,buildMs:0,xctestrunPathSource:`manifest`,reason:`adopted_from_lease`},{child:s,wait:c}=qi(n);return{sessionId:a,device:e,deviceId:e.id,port:t.port,xctestrunPath:t.xctestrunPath,xctestrunArtifact:o,jsonPath:t.jsonPath,testPromise:c,child:s,ready:!0,startupTimeoutMs:Vi(i.startupTimeoutMs),lease:di({deviceId:e.id,sessionId:a,runnerPid:n,port:t.port,xctestrunPath:t.xctestrunPath,jsonPath:t.jsonPath})}}function qi(e){let t={pid:e,exitCode:null};return{child:t,wait:new Promise(n=>{let r=setInterval(()=>{h(e)||(clearInterval(r),t.exitCode=-1,n({stdout:``,stderr:``,exitCode:-1}))},1e3);r.unref?.()})}}const Ji=1e3,Yi=2e3,Xi={cleanupRunnerProcessTree:G,cleanupRunnerXcodebuildProcesses:ca,cleanupTempFile:Ct};async function Zi(e,t={}){t.graceful===!1?await G(e.child.pid,`SIGTERM`):await ta(e),await na(e,t.waitTimeoutMs??1e4),aa(e.child.pid)&&await G(e.child.pid,`SIGKILL`),await ra(e)}async function Qi(e){await Di(e,Xi)}async function $i(e){let t=Array.from(R);await oa(e,`SIGINT`),await sa(t,`SIGINT`),await oa(e,`SIGTERM`),await sa(t,`SIGTERM`),await oa(e,`SIGKILL`),await sa(t,`SIGKILL`),await Promise.allSettled(e.map(async e=>{await ra(e)}))}async function ea(){let e=Array.from(R);await Promise.allSettled(e.map(async e=>{try{await G(e.pid,`SIGTERM`),await G(e.pid,`SIGKILL`)}finally{R.delete(e)}}))}async function ta(e){try{await nt(e.device,e.port,D({command:`shutdown`}),void 0,15e3)}catch{await G(e.child.pid,`SIGTERM`)}}async function na(e,t){try{await Promise.race([e.testPromise,new Promise(e=>setTimeout(e,t))])}catch{}}async function ra(e){await ia(e.device),Ct(e.xctestrunPath),Ct(e.jsonPath);try{await e.simulatorSetRedirect?.release()}finally{Oi(e.lease)}}async function ia(e){e.kind===`simulator`&&await Promise.allSettled(nn.map(async t=>{try{await _(ge(e,[`terminate`,e.id,t]),{allowFailure:!0,timeoutMs:Yi})}catch(n){p({level:`warn`,phase:`ios_runner_simulator_app_terminate_failed`,data:{deviceId:e.id,bundleId:t,timeoutMs:Yi,error:n instanceof Error?n.message:String(n)}})}}))}function aa(e){return e?W(e)||re(e):!1}function W(e){return e?h(e):!1}async function oa(e,t){await Promise.allSettled(e.map(async e=>{await G(e.child.pid,t)}))}async function sa(e,t){await Promise.allSettled(e.map(async e=>{await G(e.pid,t),t===`SIGKILL`&&R.delete(e)}))}async function G(e,t){if(!e||e<=0)return;try{process.kill(-e,t)}catch{}ie([e],t);let n=t===`SIGINT`?`INT`:t===`SIGTERM`?`TERM`:`KILL`;try{await g(`pkill`,[`-${n}`,`-P`,String(e)],{allowFailure:!0})}catch{}}async function ca(e,t){let n=t?`xcodebuild.*test-without-building.*AgentDeviceRunner\\.env\\.session-${la(e)}-${la(t)}-`:`xcodebuild.*test-without-building.*AgentDeviceRunner\\.env\\.session-${la(e)}-[0-9]`;for(let t of[`TERM`,`KILL`])try{await g(`pkill`,[`-${t}`,`-f`,n],{allowFailure:!0,timeoutMs:2e3})}catch(n){p({level:`warn`,phase:`ios_runner_stale_xcodebuild_kill_failed`,data:{deviceId:e,signal:t,error:n instanceof Error?n.message:String(n)}})}}function la(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}async function ua(e){let n=await da(e.logPath)??pa(e.error);return n?new t(n.code??e.error.code,e.error.message,{...e.error.details??{},hint:typeof e.error.details?.hint==`string`?`${e.error.details.hint} ${n.hint}`:n.hint,runnerFailureReason:n.reason},e.error):e.error}async function da(e){if(!e)return;let t=await _a(e,65536);if(t)return fa(t)}function fa(e){let t=e.toLowerCase();if(ma(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_axruntime_coretext_crash`,hint:`The target iOS app appears to have crashed while XCTest/AXRuntime read accessibility attributes. This is usually a simulator/XCTest/runtime or app accessibility payload issue, not a text-entry failure. Reproduce on the latest stable simulator runtime, reinstall the app, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`};if(ha(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_crash`,hint:`The target iOS app appears to have crashed while the runner was executing the command. Reopen or reinstall the app, retry on a fresh/latest stable simulator runtime, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`}}function pa(e){if(ga(e.message))return{reason:`runner_main_thread_execution_timeout`,hint:`XCTest timed out waiting for main-thread work on the current iOS screen. The app may still be visually responsive, especially on focused React Native overlays or animating screens. Use screenshot as visual truth, use coordinate presses only to prove or leave the state, and retry snapshot -i after the UI settles or after navigating away.`}}function ma(e){return e.includes(`axruntime`)&&e.includes(`coretext`)&&(e.includes(`attributesforelement`)||e.includes(`axuielementcopymultipleattributevalues`)||e.includes(`reconstitutedsmuggledctfontfromdictionary`)||e.includes(`reconstitutedsmuggledattributedstringfromdictionary`))}function ha(e){return e.includes(`process crashed`)||e.includes(`the application under test`)||e.includes(`terminated unexpectedly`)||e.includes(`exception type:`)&&e.includes(`thread 0 crashed`)}function ga(e){return e.toLowerCase().includes(`main thread execution timed out`)}async function _a(e,t){let n;try{let r=await Se.stat(e),i=Math.max(0,r.size-t),a=r.size-i;if(a<=0)return;n=await Se.open(e,`r`);let o=Buffer.alloc(a);return await n.read(o,0,a,i),o.toString(`utf8`)}catch{return}finally{await n?.close().catch(()=>{})}}const K=new Map,va=new Map,q=new Map,ya=1e4;function ba(e,t){return We(va,e,t)}async function J(e,t){return Oa(e.id),await ba(e.id,async()=>{let n=K.get(e.id);if(n){let t=await Sa(e,n);if(t)return t}return await pi(e.id,async()=>await xa(e,t))})}async function xa(e,t){let n={},r=io(t.runnerLeaseContext,e.id);p({level:`debug`,phase:`ios_runner_session_startup`,data:{deviceId:e.id,logicalLeaseContext:r}});let i=await Z(n,`adopt_detached_runner`,async()=>await Ui(e,{startupTimeoutMs:t.startupTimeoutMs}));if(i)return i.startupTimings=n,i.logicalLeaseContext=r,K.set(e.id,i),i;await Z(n,`cleanup_stale_xcodebuild`,async()=>{await hi(e.id,Xi,r)}),await Z(n,`ensure_booted`,async()=>{await Pa(e)}),await Z(n,`verify_developer_mode`,async()=>{await Ia(e)}),t.cleanStaleBundles?await Z(n,`cleanup_stale_bundles`,async()=>{await Ca(e)}):(n.cleanup_stale_bundles=0,p({level:`debug`,phase:`ios_runner_startup_cleanup_stale_bundles_skipped`}));let a=await Z(n,`ensure_xctestrun`,async()=>await Ir(e,t));n.build_xctestrun=a.buildMs;let o=await Z(n,`allocate_port`,async()=>await xt()),{xctestrunPath:s,jsonPath:c}=await Z(n,`prepare_xctestrun_env`,async()=>await Dr(a.xctestrunPath,{AGENT_DEVICE_RUNNER_PORT:String(o)},`session-${e.id}-${li}-${o}`,{iosXctestEnvDir:t.iosXctestEnvDir})),l=await Z(n,`simulator_set_redirect`,async()=>await At(e)),u,d,f=[`test-without-building`,`-only-testing`,`AgentDeviceRunnerUITests/RunnerTests/testCommand`,`-parallel-testing-enabled`,`NO`,`-test-timeouts-enabled`,`NO`,`-collect-test-diagnostics`,`never`,_n(e),`1`,`-destination-timeout`,`20`,`-xctestrun`,s,`-derivedDataPath`,a.derived,`-destination`,Vt(e)];try{a.buildMs>0&&Be({type:`command`,status:`progress`,message:`Starting XCTest runner...`}),{child:u,wait:d}=await Z(n,`launch_xcodebuild`,()=>ee(`xcodebuild`,f,{allowFailure:!0,env:{...process.env,AGENT_DEVICE_RUNNER_PORT:String(o)},detached:!0}))}catch(e){throw await l?.release(),e}u.stdout?.on(`data`,e=>{A(e,t.logPath,t.traceLogPath,t.verbose)}),u.stderr?.on(`data`,e=>{A(e,t.logPath,t.traceLogPath,t.verbose)});let te=Bi(e.id,o),m=di({deviceId:e.id,sessionId:te,runnerPid:u.pid,port:o,xctestrunPath:s,jsonPath:c}),h={sessionId:te,device:e,deviceId:e.id,port:o,xctestrunPath:s,xctestrunArtifact:a,jsonPath:c,testPromise:d,child:u,ready:!1,startupTimeoutMs:Vi(t.startupTimeoutMs),startupTimings:n,logicalLeaseContext:r,simulatorSetRedirect:l??void 0,lease:m};try{ki(m)}catch(t){throw await X(e.id,h,{graceful:!1,waitTimeoutMs:Ji}),t}return K.set(e.id,h),h}async function Sa(e,t){if(!W(t.child.pid))return await Z({},`stop_stale_session`,async()=>{await X(e.id,t,{graceful:!1,waitTimeoutMs:Ji})}),null;let n=t.xctestrunArtifact;if(n?.cache===`external`)return p({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,cache:n.cache,logicalLeaseContext:t.logicalLeaseContext}}),t;let r=I(e,F(e));return n?.derived===r?(p({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,logicalLeaseContext:t.logicalLeaseContext}}),t):(p({level:`debug`,phase:`ios_runner_session_artifact_stale`,data:{deviceId:e.id,sessionId:t.sessionId,currentDerived:n?.derived,expectedDerived:r}}),await Z({},`stop_stale_artifact_session`,async()=>{await X(e.id,t)}),null)}async function Ca(e){if(e.kind===`simulator`)for(let t of nn){let n=await wa(e,t);!n||Ta(n)}}async function wa(e,t){try{return await _(ge(e,[`uninstall`,e.id,t]),{allowFailure:!0,timeoutMs:ya})}catch(n){p({level:`warn`,phase:`ios_runner_startup_cleanup_stale_bundle_failed`,data:{deviceId:e.id,bundleId:t,timeoutMs:ya,error:n instanceof Error?n.message:String(n)}});return}}function Ta(e){if(e.exitCode===0)return!0;let t=`${e.stdout}\n${e.stderr}`.toLowerCase();return t.includes(`not installed`)||t.includes(`found nothing`)||t.includes(`no such file`)||t.includes(`invalid device`)||t.includes(`could not find`)}function Ea(e){let t=K.get(e);return t?{sessionId:t.sessionId,alive:W(t.child.pid)}:null}async function Y(e,t){await ba(e.deviceId,async()=>{K.get(e.deviceId)===e&&(p({level:`warn`,phase:`ios_runner_session_invalidated`,data:{deviceId:e.deviceId,sessionId:e.sessionId,reason:t}}),await X(e.deviceId,e,{graceful:!1,waitTimeoutMs:Ji}))})}async function X(e,t,n={}){let r=t??K.get(e);r&&(await Zi(r,n),K.get(e)===r&&K.delete(e))}function Da(e){Oa(e);let t=ka();if(t<=0||!K.has(e))return;let n=setTimeout(()=>{q.delete(e),p({level:`info`,phase:`ios_runner_idle_stop`,data:{deviceId:e,idleMs:t}}),Aa(e).catch(t=>{p({level:`warn`,phase:`ios_runner_idle_stop_failed`,data:{deviceId:e,error:t instanceof Error?t.message:String(t)}})})},t);n.unref?.(),q.set(e,n),p({level:`debug`,phase:`ios_runner_idle_stop_scheduled`,data:{deviceId:e,idleMs:t}})}function Oa(e){let t=q.get(e);t&&(clearTimeout(t),q.delete(e))}function ka(e=process.env){let t=e.AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS?.trim();if(t){let e=Number(t);if(Number.isFinite(e)&&e>=0)return Math.floor(e)}return 3e5}async function Aa(e){Oa(e),await ba(e,async()=>{await pi(e,async()=>{await X(e),await Qi(e)})})}async function ja(){let e=Array.from(K.values());await $i(e);for(let t of e)K.get(t.deviceId)===t&&K.delete(t.deviceId)}async function Ma(){if(!Hi())return 0;let e=0;for(let[t,n]of K)if(n.device.kind===`simulator`&&!n.simulatorSetRedirect&&!(!n.lease||!W(n.child.pid))){try{ki(Ei(n.lease))}catch{continue}K.delete(t),Oa(t),e+=1,p({level:`info`,phase:`ios_runner_session_detached`,data:{deviceId:t,sessionId:n.sessionId,runnerPid:n.child.pid,port:n.port}})}return e}async function Na(){await ja();let e=Array.from(K.keys());await Promise.allSettled(e.map(async e=>{await Aa(e)})),await ea()}function Pa(e){return e.kind===`simulator`?e.booted?(p({level:`debug`,phase:`ios_runner_startup_ensure_booted_skipped`,data:{deviceId:e.id}}),Promise.resolve()):Fa(e):Promise.resolve()}async function Fa(e){await _(ge(e,[`bootstatus`,e.id,`-b`]),{timeoutMs:$e})}async function Ia(e){if(!o(e)||e.kind!==`device`)return;let n=await g(`DevToolsSecurity`,[`-status`],{allowFailure:!0,timeoutMs:2e3}),r=`${n.stdout}\n${n.stderr}`;if(/developer mode is currently disabled/i.test(r))throw new t(`COMMAND_FAILED`,`Developer mode is disabled for Apple development tools`,{hint:"Run `sudo DevToolsSecurity -enable`, then retry the iOS runner. UI test runners start suspended until Xcode/testmanagerd can attach.",devToolsSecurityStatus:r.trim()})}function La(e){if(!i(e.platform))throw new t(`UNSUPPORTED_PLATFORM`,`Unsupported platform for iOS runner: ${e.platform}`);if(e.kind!==`simulator`&&e.kind!==`device`)throw new t(`UNSUPPORTED_OPERATION`,`Unsupported iOS device kind for runner: ${e.kind}`)}async function Ra(e,t,n,r,i,a){ro(t,n.command);let o=D(n),s=z(o.command),c=ce.fromTimeoutMs(i),l=$a(t,o);l.action===`run`?await Ha({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,signal:a,decision:l}):Ua(o,t,l);let u;try{u=await Va({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,timeoutMs:i,signal:a,readOnlyCommand:s})}catch(e){throw Ba(e,t,l)}try{let e=await Wa(u,t,r),n=Za(e);return n?(t.lastHealthyMutation=void 0,await Y(t,n)):ai(o.command)&&(t.lastHealthyMutation={atMs:Date.now(),appBundleId:o.appBundleId}),e}catch(e){let n=Qa(e);throw n?(t.lastHealthyMutation=void 0,await Y(t,n),e):za(e)?e:Ba(e,t,l)}}function za(e){return e instanceof t&&e.details?.runner!==void 0}function Ba(e,t,n){return n.action!==`skip`||n.reason!==`recent_healthy_mutation`?e:(t.lastHealthyMutation=void 0,to(e,{runnerReadinessPreflightSkipped:!0,runnerReadinessPreflightSkipReason:n.reason,runnerReadinessPreflightSkippedAgeMs:n.lastHealthyMutationAgeMs}))}async function Va(e){let{device:n,session:r,runnerCommand:i,logPath:a,deadline:o,timeoutMs:s,signal:c,readOnlyCommand:l}=e,d=o.remainingMs();if(d<=0)throw new t(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:s});return await u(`ios_runner_command_send`,async()=>l?await nt(n,r.port,i,a,d,r,c):await lt(n,r.port,i,d,c),l?{command:i.command,commandId:i.commandId,readOnly:!0,sessionReady:r.ready,timeoutMs:d}:{command:i.command,commandId:i.commandId})}async function Ha(e){let{device:t,session:n,runnerCommand:r,logPath:i,deadline:a,signal:o,decision:s}=e,c=n.ready?Math.min(1e3,a.remainingMs()):Math.min(no(n),a.remainingMs());try{await Wa(await u(`ios_runner_readiness_preflight`,async()=>await nt(t,n.port,D({command:`uptime`}),i,c,n,o),{command:r.command,commandId:r.commandId,reason:s.reason,lastHealthyMutationAgeMs:s.lastHealthyMutationAgeMs,sessionReady:n.ready,timeoutMs:c}),n,i)}catch(e){throw eo(e)}}function Ua(e,t,n){p({level:`debug`,phase:`ios_runner_readiness_preflight_skipped`,data:{command:e.command,commandId:e.commandId,reason:n.reason,lastHealthyMutationAgeMs:n.reason===`recent_healthy_mutation`?n.lastHealthyMutationAgeMs:void 0,sessionReady:t.ready}})}async function Wa(e,t,n){let r=Ga(await e.text());if(!r.ok)throw await ua({error:Ka(r,n),logPath:n});return t.ready=!0,Ya(r)}function Ga(e){try{let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{throw new t(`COMMAND_FAILED`,`Invalid runner response`,{text:e})}}function Ka(e,n){let r=qa(e.error?.code),i=typeof e.error?.message==`string`?e.error.message:void 0,a=typeof e.error?.hint==`string`?e.error.hint:void 0;return new t(Ja(r),i??`Runner error`,{runner:e,runnerErrorCode:r,retriable:r===`RUNNER_BUSY`?!0:void 0,xcodebuild:{exitCode:1,stdout:``,stderr:``},hint:a,logPath:n})}function qa(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Ja(e){return e===`RUNNER_BUSY`?`COMMAND_FAILED`:e?n(e):`COMMAND_FAILED`}function Ya(e){if(!e.data||typeof e.data!=`object`||Array.isArray(e.data))return{};let t=e.data;return Xa(t),t}function Xa(e){let t=e.gestureFallback;typeof t!=`string`||t.length===0||p({level:`debug`,phase:`ios_runner_gesture_fallback`,data:{fallback:t,message:typeof e.gestureFallbackMessage==`string`?e.gestureFallbackMessage:void 0,hint:typeof e.gestureFallbackHint==`string`?e.gestureFallbackHint:void 0}})}function Za(e){if(e.runnerFatal===!0)return typeof e.runnerFatalReason==`string`&&e.runnerFatalReason.trim().length>0?e.runnerFatalReason:`runner_reported_fatal_response`}function Qa(e){if(e instanceof t){if(e.code===`IOS_AX_SNAPSHOT_FAILED`)return`ax_snapshot_failure`;if(e.code===`XCTEST_RECORDED_FAILURE`)return`xctest_recorded_failure`;if(e.code===`RUNNER_WEDGED`)return`runner_main_thread_wedged`}}function $a(e,t){let n=z(t.command);if(!e.ready)return n?{action:`skip`,reason:`read_only_startup_command`}:{action:`run`,reason:`startup`};if(ii(t.command))return{action:`skip`,reason:`readiness_probe_command`};if(!ai(t.command))return{action:`run`,reason:`conservative_command`};let r=e.lastHealthyMutation;if(!r)return{action:`run`,reason:`no_recent_healthy_mutation`};if(t.appBundleId!==r.appBundleId)return{action:`run`,reason:`app_activation_uncertain`};let i=Date.now()-r.atMs;return i>5e3?{action:`run`,reason:`healthy_mutation_stale`,lastHealthyMutationAgeMs:i}:{action:`skip`,reason:`recent_healthy_mutation`,lastHealthyMutationAgeMs:i}}function eo(e){return to(e,{runnerReadinessPreflightFailed:!0})}function to(e,n){let r=e instanceof t?e:new t(`COMMAND_FAILED`,e instanceof Error?e.message:String(e),void 0,e);return new t(r.code,r.message,{...r.details??{},...n},r.cause??e)}function no(e){return e.startupTimeoutMs??45e3}async function Z(e,t,n){let r=Date.now();try{return await n()}finally{let n=Date.now()-r;e[t]=n,p({level:`debug`,phase:`ios_runner_startup_${t}`,durationMs:n})}}function ro(e,t){e.startupTimingsReported||!e.startupTimings||(e.startupTimingsReported=!0,p({level:`info`,phase:`ios_runner_session_startup_timings`,durationMs:Object.values(e.startupTimings).reduce((e,t)=>e+t,0),data:{command:t,sessionId:e.sessionId,ready:e.ready,logicalLeaseContext:e.logicalLeaseContext,timings:e.startupTimings}}))}function io(e,t){if(!e)return;let n={leaseId:Q(e.leaseId),clientId:Q(e.clientId),tenantId:Q(e.tenantId),runId:Q(e.runId),leaseProvider:Q(e.leaseProvider),deviceKey:Q(e.deviceKey)??t},r=Object.entries(n).filter(([,e])=>e!==void 0);return r.length>0?Object.fromEntries(r):void 0}function Q(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}async function ao(e){let{device:t,session:n,command:r,transportError:i,options:a,signal:o,invalidationReason:s}=e;return await oo(await uo(t,n,r,i,a,o),{command:r,session:n,transportError:i,invalidationReason:s,invalidateSession:e.invalidateSession})}async function oo(e,t){if(!e)return await lo(t,`status_recovery_unavailable`);if(e.type===`recovered`)return so(e,t);if(e.type===`skipInvalidation`)throw co(e,t);return await lo(t,e.reason,e.lifecycleState,e.error)}function so(e,t){return Do({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.data}function co(e,t){return Do({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.error}async function lo(e,t,n,r){throw Do({command:e.command,session:e.session,transportError:e.transportError,decision:`retained`,reason:t,lifecycleState:n}),await e.invalidateSession(e.session,e.invalidationReason),r??e.transportError}async function uo(e,t,n,r,i,a){if(n.command===`status`||!n.commandId?.trim())return;let o=To(r),s;try{s=await Ra(e,t,{command:`status`,statusCommandId:n.commandId},i.logPath,3e3,a)}catch(e){return p({level:`debug`,phase:`ios_runner_command_status_recovery_failed`,data:{command:n.command,commandId:n.commandId,error:e instanceof Error?e.message:String(e),...o}}),{type:`retainInvalidation`,reason:`status_probe_failed`}}let c=typeof s.lifecycleState==`string`?s.lifecycleState:``;return p({level:`debug`,phase:`ios_runner_command_status_recovery`,data:{command:n.command,commandId:n.commandId,lifecycleState:c,...o}}),fo(s,c,n,r,i)}function fo(e,n,r,i,a){return n===`completed`?po(e,r,i,a):n===`failed`?{type:`skipInvalidation`,reason:`runner_reported_failure`,lifecycleState:n,error:mo(e,r,i,a)}:n===`accepted`||n===`started`?{type:`skipInvalidation`,reason:`command_still_in_flight`,lifecycleState:n,error:ho(n,r,i,a)}:{type:`retainInvalidation`,reason:n?`unknown_lifecycle_state`:`missing_lifecycle_state`,lifecycleState:n,error:new t(`COMMAND_FAILED`,`Runner command "${r.command}" lost its transport response and lifecycle status was ${n?`"${n}"`:`missing`}, so agent-device invalidated the runner session instead of replaying the command.`,{command:r.command,commandId:r.commandId,lifecycleState:n,recovery:`lifecycle_state_not_recoverable`,hint:Eo(r.command),logPath:a.logPath,transportError:i.message},i)}}function po(e,n,r,i){let a=go(e.lifecycleResponseJson);if(a)return{type:`recovered`,data:a,reason:`completed_with_retained_response`,lifecycleState:`completed`};if(z(n.command))return{type:`skipInvalidation`,error:r,reason:`read_only_completed_without_retained_response`,lifecycleState:`completed`};let o=To(r);return{type:`skipInvalidation`,reason:`completed_without_retained_response`,lifecycleState:`completed`,error:new t(`COMMAND_FAILED`,`Runner command "${n.command}" completed after the transport response was lost, but no recoverable response was retained.`,{command:n.command,commandId:n.commandId,lifecycleState:`completed`,recovery:`completed_without_retained_response`,...o,hint:vo(n.command,o),logPath:i.logPath,transportError:r.message},r)}}function mo(e,r,i,a){let o=typeof e.lifecycleErrorCode==`string`?e.lifecycleErrorCode:void 0,s=typeof e.lifecycleErrorMessage==`string`?e.lifecycleErrorMessage:`Runner command failed`,c=typeof e.lifecycleErrorHint==`string`?e.lifecycleErrorHint:void 0,l=To(i);return new t(n(o),s,{command:r.command,commandId:r.commandId,lifecycleState:`failed`,recovery:`runner_reported_failure`,...l,hint:c??yo(r.command,l),logPath:a.logPath,transportError:i.message},i)}function ho(e,n,r,i){if(z(n.command))return r;let a=To(r);return new t(`COMMAND_FAILED`,`Runner command "${n.command}" is still ${e} after the transport response was lost.`,{command:n.command,commandId:n.commandId,lifecycleState:e,recovery:`command_still_in_flight`,...a,hint:bo(n.command,e,a),logPath:i.logPath,transportError:r.message},r)}function go(e){if(typeof e!=`string`||e.trim().length===0)return;let t=_o(e);if(t.ok)return t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:{}}function _o(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`)return t}catch{}return{}}function vo(e,t){return`${xo(t)}The runner is still reachable and reports "${e}" already completed, so agent-device kept the session open and will not replay it. Run snapshot -i to inspect the current UI, then continue from that observed state.`}function yo(e,t){return`${xo(t)}The runner is still reachable and reports "${e}" failed after the transport response was lost, so agent-device kept the session open and did not replay it. Run snapshot -i to inspect the current UI and retry with a selector visible in that snapshot.`}function bo(e,t,n){return`${xo(n)}The runner is still reachable and reports "${e}" is ${t}, so agent-device kept the session open and will not replay it. Wait briefly, run snapshot -i to inspect the current UI, then continue from that observed state.`}function xo(e){return e.readinessPreflightSkipped===!0?`This hot command skipped the uptime preflight because the runner had just completed a healthy interaction; status recovery confirmed the runner still observed it. `:``}function So(e,t){let n=e.details?.[t];return typeof n==`boolean`?n:void 0}function Co(e,t){let n=e.details?.[t];return typeof n==`string`?n:void 0}function wo(e,t){let n=e.details?.[t];return typeof n==`number`?n:void 0}function To(e){let t={},n=So(e,`runnerReadinessPreflightSkipped`);n!==void 0&&(t.readinessPreflightSkipped=n);let r=Co(e,`runnerReadinessPreflightSkipReason`);r!==void 0&&(t.readinessPreflightSkipReason=r);let i=wo(e,`runnerReadinessPreflightSkippedAgeMs`);return i!==void 0&&(t.readinessPreflightSkippedAgeMs=i),t}function Eo(e){return`The runner did not confirm that "${e}" reached a safe terminal state, so agent-device kept the conservative invalidation path. Run snapshot -i before retrying if the UI may have changed.`}function Do(e){let{command:t,session:n,transportError:r,decision:i,reason:a,lifecycleState:o}=e;p({level:i===`retained`?`warn`:`debug`,phase:`ios_runner_command_invalidation_decision`,data:{command:t.command,commandId:t.commandId,decision:i,reason:a,lifecycleState:o,runnerReachable:o!==void 0,sessionId:n.sessionId,transportError:r.message}})}const $=new Map;function Oo(e,t){let n=e.requestId?.trim();if(n)return`request:${n}`;let r=t.commandId?.trim();if(r)return`command:${r}`}function ko(e){if(!e)return;let t=Po(e);t.touchedSession=!0,Fo(e,t)}function Ao(e){return e?$.get(e)?.touchedSession===!0:!1}function jo(e){if(!e)return!0;let t=Po(e);return t.recycles>=1?(Fo(e,t),!1):(Fo(e,t),!0)}function Mo(e){if(!e)return;let t=Po(e);t.recycles+=1,Fo(e,t)}function No(e,n){return p({level:`warn`,phase:`ios_runner_recycle_budget_exhausted`,data:{command:e.command,commandId:e.commandId,requestId:n.requestId,maxRecycles:1}}),new t(`COMMAND_FAILED`,`iOS runner was already restarted during this request and "${e.command}" still failed, so agent-device stopped instead of paying for another runner boot.`,{command:e.command,commandId:e.commandId,recovery:`runner_recycle_budget_exhausted`,hint:"The current screen is overwhelming the iOS accessibility capture (usually heavy or animating content). The app session is preserved: run `screenshot` for visual truth and interact with coordinate commands, or navigate to another screen and retry. Re-running the same command immediately will likely wedge again.",logPath:n.logPath})}function Po(e){return Io(),$.get(e)??{touchedSession:!1,recycles:0,lastAtMs:Date.now()}}function Fo(e,t){t.lastAtMs=Date.now(),$.delete(e),$.set(e,t)}function Io(){let e=Date.now()-6e5;for(let[t,n]of $)n.lastAtMs<e&&$.delete(t);for(;$.size>512;){let e=$.keys().next().value;if(e===void 0)break;$.delete(e)}}async function Lo(e,n){O(n.requestId);let r=Fe(n.requestId),i=D({command:`uptime`}),a;for(let t=1;t<=2;t+=1){let o=await Ro({device:e,command:i,options:n,signal:r,attempt:t,recoveryReason:a});if(o.kind===`prepared`)return o.result;a=o.recoveryReason}throw new t(`COMMAND_FAILED`,`iOS runner prepare failed`)}async function Ro(e){let{device:t,command:n,options:r,signal:i,attempt:a,recoveryReason:o}=e,s=Date.now(),c=await J(t,{...r,cleanStaleBundles:a>1?!0:r.cleanStaleBundles,...Ko(r,`runner_session`)}),l=Date.now()-s;try{return{kind:`prepared`,result:Qo(t,await Go(t,c,n,r,i,l,{recoveryReason:o}))}}catch(e){return await zo({device:t,session:c,command:n,options:r,signal:i,attempt:a,error:e})}}async function zo(e){let{device:t,session:n,command:i,options:a,signal:o,attempt:s,error:c}=e,l=r(c,`COMMAND_FAILED`);if(s===1&&Jo(l,n))return{kind:`prepared`,result:await Bo({device:t,session:n,command:i,options:a,signal:o,error:l})};if(!Ho(l))throw c;let u=l.message||`runner_health_failed`;if(s>=2)throw await Vo(n,`prepare_runner_health_failed`),c;return O(a.requestId),await Y(n,`prepare_runner_health_retry`),p({level:`warn`,phase:`ios_runner_prepare_health_retry`,data:{command:i.command,commandId:i.commandId,sessionId:n.sessionId,attempt:s,maxAttempts:2,reason:u}}),{kind:`retry`,recoveryReason:u}}async function Bo(e){let{device:t,session:n,command:r,options:i,signal:a,error:o}=e,s=o.message||`runner_health_failed`;await Y(n,`prepare_cached_runner_health_failed`),await En(n.xctestrunArtifact,s);let c=Date.now(),l=await J(t,{...i,cleanStaleBundles:!0,forceRunnerXctestrunRebuild:!0,...Ko(i,`runner_rebuild`)}),u=Date.now()-c;try{let e=await Go(t,l,r,i,a,u,{recoveryReason:s});return p({level:`info`,phase:`ios_runner_prepare_bad_cache_recovered`,data:{command:r.command,commandId:r.commandId,sessionId:l.sessionId,xctestrunPath:l.xctestrunArtifact?.xctestrunPath,reason:s}}),Qo(t,e)}catch(e){await Vo(l,`prepare_rebuilt_runner_health_failed`);let n=Xo(e,l,s);throw $o(t,{cache:l.xctestrunArtifact?.cache,artifact:l.xctestrunArtifact?.artifact,buildMs:l.xctestrunArtifact?.buildMs,connectMs:u,healthCheckMs:0,xctestrunPath:l.xctestrunArtifact?.xctestrunPath,failureReason:n.message}),n}}async function Vo(e,t){try{await Y(e,t)}catch{}}function Ho(e){return T(e)?!1:E(e)||Ke(e)||Yo(e)}async function Uo(e,t,n){O(n.requestId);let i=Fe(n.requestId),a=Oo(n,t),o,s=!1;try{if(!Ea(e.id)?.alive&&Ao(a)){if(!jo(a))throw No(t,n);s=!0}o=await J(e,n),s&&Mo(a),ko(a);let r=o.ready?et:no(o);return await Ra(e,o,t,n.logPath,r,i)}catch(a){let s=r(a,`COMMAND_FAILED`);if(s.code===`COMMAND_FAILED`&&typeof s.message==`string`&&s.message.includes(`Runner did not accept connection`)&&Ke(s)&&o)return O(n.requestId),await Wo({device:e,session:o,command:t,options:n,signal:i,restartReason:`runner_connect_failed_before_command_send`});if(o&&ts(s))return O(n.requestId),await Wo({device:e,session:o,command:t,options:n,signal:i,restartReason:`runner_readiness_preflight_failed_before_command_send`,recoveredDiagnosticPhase:`ios_runner_readiness_preflight_recovered`});if(o&&E(s))return await ao({device:e,session:o,command:t,transportError:s,options:n,signal:i,invalidationReason:`transport_error_after_command_send`,invalidateSession:Y});throw a}}async function Wo(e){let{device:t,command:n,options:i,signal:a,restartReason:o}=e,s=Oo(i,n);if(!jo(s))throw No(n,i);await Y(e.session,o);let c=await J(t,{...i,cleanStaleBundles:!0});Mo(s);try{let r=await Ra(t,c,n,i.logPath,$e,a);return e.recoveredDiagnosticPhase&&p({level:`debug`,phase:e.recoveredDiagnosticPhase,data:{command:n.command,commandId:n.commandId,recovery:`session_restarted`,sessionId:c.sessionId}}),r}catch(e){let o=r(e,`COMMAND_FAILED`);if(E(o))return await ao({device:t,session:c,command:n,transportError:o,options:i,signal:a,invalidationReason:`transport_error_after_retry_command_send`,invalidateSession:Y});throw e}}async function Go(e,t,n,r,i,a,o){let s=Date.now(),c=qo(r.prepareDeadline,r.healthTimeoutMs,`runner_health`);return Zo(await Ra(e,t,n,r.logPath,c,i),t,a,Date.now()-s,o)}function Ko(e,t){if(!e.prepareDeadline)return{};let n=qo(e.prepareDeadline,e.buildTimeoutMs,t);return{buildTimeoutMs:n,startupTimeoutMs:n}}function qo(e,n,r){if(!e)return n??45e3;let i=Math.floor(e.remainingMs());if(i<=0)throw new t(`COMMAND_FAILED`,`prepare ios-runner timed out`,{phase:r,reason:`prepare_deadline_expired`});return i}function Jo(e,t){let n=t.xctestrunArtifact;return!n||n.cache===`miss`?!1:Ho(e)}function Yo(e){let t=e.message.toLowerCase();return t.includes(`timeout`)||t.includes(`timed out`)||t.includes(`deadline`)}function Xo(e,n,i){let a=r(e,`COMMAND_FAILED`);return new t(a.code,`artifact restored but runner did not connect`,{...a.details??{},restoredFailureReason:i,xctestrunPath:n.xctestrunArtifact?.xctestrunPath,artifact:n.xctestrunArtifact?.artifact,cache:n.xctestrunArtifact?.cache,reason:a.message},a)}function Zo(e,t,n,r,i){let a=t.xctestrunArtifact,o={...i?.recoveryReason?{recoveryReason:i.recoveryReason}:{},...i?.failureReason?{failureReason:i.failureReason}:{}};return a?{runner:e,cache:a.cache,artifact:a.artifact,buildMs:a.buildMs,connectMs:Math.max(0,n),healthCheckMs:Math.max(0,r),xctestrunPath:a.xctestrunPath,...o}:{runner:e,connectMs:Math.max(0,n),healthCheckMs:Math.max(0,r),...o}}function Qo(e,t){return $o(e,t),t}function $o(e,t){p({level:t.failureReason?`warn`:`info`,phase:`apple_runner_prepare`,data:{platform:e.platform,target:e.target,deviceId:e.id,cache:t.cache,artifact:t.artifact,buildMs:t.buildMs,connectMs:t.connectMs,healthCheckMs:t.healthCheckMs,timingContainment:t.buildMs===void 0?{healthCheckMs:[]}:{connectMs:[`buildMs`],healthCheckMs:[]},xctestrunPath:t.xctestrunPath,recoveryReason:t.recoveryReason,failureReason:t.failureReason}})}function es(e){return e.details?.runnerReadinessPreflightFailed===!0}function ts(e){return es(e)&&(E(e)||ns(e))}function ns(e){let t=e.message.toLowerCase();return t.includes(`timeout`)||t.includes(`timed out`)}var rs=e({abortAllIosRunnerSessions:()=>ja,detachIosSimulatorRunnerSessionsForShutdown:()=>Ma,prepareIosRunner:()=>cs,prewarmAppleRunnerCache:()=>as,prewarmIosRunnerSession:()=>os,runAppleRunnerCommand:()=>is,stopAllIosRunnerSessions:()=>Na});async function is(e,t,n={}){La(e),O(n.requestId);let r=D(t),i=ls(e,n);return z(r.command)?fe(()=>(O(n.requestId),i.runCommand(e,r,n)),{shouldRetry:e=>(O(n.requestId),E(e))}):i.runCommand(e,r,n)}function as(e,t={}){if(o(e))return ss({device:e,options:t,failurePhase:`ios_runner_cache_prewarm_failed`,task:async t=>{await Ir(e,t)}})}function os(e,t={}){if(!o(e))return;let n=ls(e,t).prewarm;if(!n){p({level:`debug`,phase:`ios_runner_session_prewarm_unavailable`,data:{deviceId:e.id}});return}return ss({device:e,options:t,failurePhase:`ios_runner_session_prewarm_failed`,task:async t=>{await n(e,t)}})}function ss(e){let{device:t,options:n,failurePhase:r,task:i}=e,{propagateError:a=!1,...o}=n;return i(o).catch(e=>{if(p({level:`warn`,phase:r,data:{deviceId:t.id,error:e instanceof Error?e.message:String(e)}}),a)throw e})}async function cs(e,t){La(e),O(t.requestId);let n=D({command:`uptime`}),r=ls(e,t);if(r.prepare)return await r.prepare(e,t);let i=Date.now();return{runner:await r.runCommand(e,n,t),connectMs:0,healthCheckMs:Math.max(0,Date.now()-i)}}function ls(e,t){return ye(e,us,void 0,{requestId:t.requestId})}const us=be(Uo,{prepare:Lo,prewarm:async(e,t)=>{await Lo(e,{...t,healthTimeoutMs:et})}});export{je as C,Me as S,Ie as T,ze as _,rs as a,Fe as b,Aa as c,nn as d,P as f,Ve as g,He as h,is as i,fi as l,Be as m,as as n,Ea as o,We as p,os as r,Da as s,cs as t,Ur as u,Ne as v,Ee as w,Pe as x,w as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime.js";import{AsyncLocalStorage as t}from"node:async_hooks";var n=e({createLocalAppleRunnerProvider:()=>i,resolveAppleRunnerProvider:()=>a,withAppleRunnerProvider:()=>s});const r=new t;function i(e,t={}){return{runCommand:e,...t}}function a(e,t,n,r={}){if(n)return c(n);let i=o(e,r);return c(i?i.provider:t)}function o(e,t={}){let n=r.getStore();return n&&n.deviceId===e.id&&(n.requestId?n.requestId===t.requestId:!t.requestId)?n:void 0}async function s(e,t,n){if(!e)return await n();let i={provider:c(e),deviceId:t.deviceId,requestId:t.requestId};return await r.run(i,n)}function c(e){return typeof e==`function`?{runCommand:e}:e}export{a as n,n as r,i as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{t as e}from"./rolldown-runtime.js";import{F as t,H as n}from"./sdk-contracts.js";var r=e({MAX_RUNNER_SEQUENCE_STEPS:()=>20,SEQUENCEABLE_RUNNER_STEP_KINDS:()=>i,buildRunnerSequenceCommand:()=>u,parseRunnerSequenceResult:()=>d,validateRunnerSequenceSteps:()=>s});const i=[`tap`,`doubleTap`,`longPress`,`drag`];function a(e){return typeof e==`string`&&i.includes(e)}function o(e,n,r){return new t(`INVALID_ARGS`,r,{stepIndex:e,kind:typeof n==`string`?n:void 0})}function s(e){if(!Array.isArray(e)||e.length===0)throw new t(`INVALID_ARGS`,`sequence requires at least one step`,{stepCount:Array.isArray(e)?e.length:0});if(e.length>20)throw new t(`INVALID_ARGS`,`sequence accepts at most 20 steps, received ${e.length}`,{stepCount:e.length,maxSteps:20});e.forEach((e,t)=>c(e,t))}function c(e,t){if(!a(e.kind))throw o(t,e.kind,`sequence step ${t} has unsupported kind "${String(e.kind)}"; allowed: ${i.join(`, `)}`);if(!Number.isFinite(e.x)||!Number.isFinite(e.y))throw o(t,e.kind,`sequence step ${t} (${e.kind}) requires finite x and y`);if(e.kind===`drag`&&(!Number.isFinite(e.x2)||!Number.isFinite(e.y2)))throw o(t,e.kind,`sequence step ${t} (drag) requires finite x2 and y2`);e.durationMs!==void 0&&l(e.durationMs,0,1e4,t,e.kind,`durationMs`),e.pauseMs!==void 0&&l(e.pauseMs,0,1e4,t,e.kind,`pauseMs`)}function l(e,t,n,r,i,a){if(!Number.isFinite(e)||e<t||e>n)throw o(r,i,`sequence step ${r} (${i}) ${a} must be between ${t} and ${n}`)}function u(e,t){return s(e),{command:`sequence`,steps:e,appBundleId:t}}function d(e){let t=p(e.sequenceResults),n=typeof e.completedSteps==`number`&&Number.isFinite(e.completedSteps)?e.completedSteps:t.filter(e=>e.ok).length,r=typeof e.failedStepIndex==`number`&&Number.isFinite(e.failedStepIndex)?e.failedStepIndex:t.findIndex(e=>!e.ok)>=0?t.findIndex(e=>!e.ok):void 0;if(r!==void 0)throw f(t,n,r);return{results:t,completedSteps:n,failedStepIndex:r}}function f(e,r,i){let a=e[i],o=a?.kind??`step`,s=a?.errorMessage??`sequence step ${i} (${o}) failed`;return new t(n(a?.errorCode),s,{failedStepIndex:i,failedStepKind:o,completedSteps:r,sequenceResults:e,hint:`Run snapshot -i to inspect the current UI, then continue from the observed state.`})}function p(e){return Array.isArray(e)?e.map(e=>{let t=e??{};return{ok:t.ok===!0,kind:typeof t.kind==`string`?t.kind:`unknown`,errorCode:typeof t.errorCode==`string`?t.errorCode:void 0,errorMessage:typeof t.errorMessage==`string`?t.errorMessage:void 0,gestureStartUptimeMs:typeof t.gestureStartUptimeMs==`number`?t.gestureStartUptimeMs:void 0,gestureEndUptimeMs:typeof t.gestureEndUptimeMs==`number`?t.gestureEndUptimeMs:void 0}}):[]}export{d as n,r,u as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{F as e}from"./sdk-contracts.js";import{URL as t}from"node:url";function n(n){if(!n)return;let o=r(n.metroHost),s=i(n.metroPort),c=`http`,l=r(n.bundleUrl);if(l){let n;try{n=new t(l)}catch(t){throw new e(`INVALID_ARGS`,`Invalid runtime bundle URL: ${l}`,{},t)}(n.protocol===`http:`||n.protocol===`https:`)&&(o??=r(n.hostname),s??=i(n.port.length>0?Number(n.port):a(n.protocol)),c=n.protocol===`https:`?`https`:`http`)}if(!(!o||!s))return{host:o,port:s,scheme:c}}function r(e){let t=e?.trim();return t&&t.length>0?t:void 0}function i(e){if(Number.isInteger(e)&&!(e<=0||e>65535))return e}function a(e){if(e===`https:`)return 443;if(e===`http:`)return 80}export{r as n,n as t};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime.js";import{D as t,F as n,H as r,I as i,O as a,P as o,j as s,k as c}from"./sdk-contracts.js";import{j as l,v as u,w as d}from"./sdk-android-adb.js";import{_ as f}from"./sdk-batch.js";import{C as p,D as m,E as h,F as g,G as _,I as ee,K as v,L as te,M as ne,N as re,O as ie,P as ae,S as oe,T as se,U as y,W as b,X as x,_ as ce,a as le,an as ue,b as S,d as de,f as fe,g as pe,gn as C,h as me,j as he,m as ge,p as _e,sn as ve,v as ye,w as be,x as xe,y as Se}from"./device-rotation.js";import{_ as Ce,a as we,b as Te,i as Ee,m as De,n as Oe,y as ke}from"./sdk-selectors.js";import{r as Ae,t as je}from"./snapshot-quality.js";import{o as Me,r as Ne}from"./sdk-finders.js";import{a as Pe,i as Fe,o as Ie,r as Le,t as Re}from"./selectors2.js";import{n as ze,r as Be}from"./sdk-app-inventory.js";import{i as Ve,n as He,r as Ue,t as We}from"./png-worker-contract.js";import Ge,{promises as w}from"node:fs";import T from"node:path";import{fileURLToPath as Ke}from"node:url";import{Worker as qe}from"node:worker_threads";const Je=/\b(logbox|redbox|reload js|copy stack|component stack|call stack|runtime error|open debugger to view warnings)\b/,Ye=/\b(redbox|runtime error|reload js|copy stack|component stack|call stack)\b/,Xe=[/\b[\w.$<>/-]+\.(?:tsx?|jsx?):\d+(?::\d+)?\b/,/\b[\w.$<>/-]+\.(?:tsx?|jsx?)\s+\(\d+:\d+\)/],Ze=[/^!,\s+/,/^(warn|warning|error):\s+/,/\b(?:possible\s+)?unhandled (?:promise )?rejection\b/],Qe=[`open debugger to view warnings`,`getsnapshot should be cached to avoid an infinite loop`,`unique "key" prop`,`unique 'key' prop`,`virtualizedlists should never be nested`,`failed prop type`],$e=new Set([`x`,`×`,`✕`,`✖`,`⨯`]);function et(e){if(nt(e).detected)return[`Hint: React Native warning/error overlay detected. It overlays part of the app and should be handled before interacting.`,`Run: agent-device react-native dismiss-overlay`,`The command verifies the overlay is gone. Run agent-device snapshot -i afterward only when you need fresh refs for the next action.`].join(`
|
|
2
|
+
`)}function tt(e){return nt(e)}function nt(e){let t=ot(e),n=t.detected?st(t):null;return{detected:t.detected,redBox:t.redBox,dismissNodes:t.dismissNodes,minimizeNodes:t.minimizeNodes,collapsedNodes:t.collapsedNodes,primaryAction:n}}function rt(e){return[...e.dismissNodes,...e.minimizeNodes,...e.collapsedNodes]}function it(e){return ht(e.label?.trim())&&Tt(e.rect)}function at(e,t){let n=e.label?.trim();return!n||!it(e)?!1:t.some(e=>e.label?.trim()===n&&Et(e))}function ot(e){let t=e.map(ct).join(`
|
|
3
|
+
`).toLowerCase(),n=E(e,_t),r=E(e,xt),i=E(e,ht,Ct),a=E(e,gt),o=ut(t),s=dt(t),c=ft(t,n,r);return{dismissNodes:n,minimizeNodes:r,collapsedNodes:i,redBox:pt(t,o,c),detected:mt({text:t,hasReactNativeStackFrame:o,hasOverlayControl:c,hasControllessRedBoxText:s,collapsedNodes:i,openDebuggerWarningNodes:a})}}function st(e){let t=Dt(e.dismissNodes);if(t)return jt(t,Mt(t));let n=Nt(e.collapsedNodes.filter(wt));return n?.rect?{action:`close-collapsed-banner`,point:Rt(n),rect:n.rect,ref:n.ref,label:Bt(n)}:null}function ct(e){return[e.label,e.value,e.identifier,e.type,e.role].filter(Boolean).join(` `)}function lt(e){return Je.test(e)}function ut(e){return Xe.some(t=>t.test(e))}function dt(e){return/\buncaught\b/.test(e)&&/unable to download asset/.test(e)}function ft(e,t,n){return t.length>0||n.length>0||/\b(reload js|copy stack)\b/.test(e)}function pt(e,t,n){return Ye.test(e)||dt(e)||t&&n}function mt(e){return e.collapsedNodes.length>0||e.openDebuggerWarningNodes.length>0||e.hasControllessRedBoxText||e.hasOverlayControl&&(lt(e.text)||e.hasReactNativeStackFrame)}function ht(e){let t=e?.trim().toLowerCase();return t?Qe.some(e=>t.includes(e))||Ze.some(e=>e.test(t)):!1}function gt(e){return e.includes(`open debugger to view warnings`)||/^!,\s+open debugger\b/.test(e)}function _t(e){return vt(e)||yt(e)||bt(e)}function vt(e){return/^dismiss(?:\s*\([^)]*\))?$/i.test(e)}function yt(e){return/^close(?:\s*\([^)]*\))?$/i.test(e)}function bt(e){return $e.has(e)}function xt(e){return/^minimi[sz]e(?:\b|\s|\()/i.test(e)}function St(e){return/^!,\s+/.test(e)}function Ct(e){return!e.rect||e.rect.height<=180}function wt(e){let t=Bt(e)?.trim().toLowerCase()??``;return(gt(t)||St(t))&&Et(e)}function Tt(e){return e?e.x<=1&&e.y<=1&&e.width>=300&&e.height>=600:!1}function Et(e){return e.rect?e.rect.width>=120&&e.rect.height>=36&&e.rect.height<=180:!1}function E(e,t,n=()=>!0){let r=[];for(let i of e)i.ref&&n(i)&&[i.label,i.value,i.identifier].map(e=>e?.trim().toLowerCase()).filter(e=>!!e).some(e=>t(e))&&r.push(i);return r}function Dt(e){return Pt(e,At)}function Ot(e){let t=[e.type,e.role,e.subrole].join(` `).toLowerCase();return/\b(button|menuitem|link)\b/.test(t)}function kt(e){return e?e.width*e.height:1/0}function At(e){return[It(Ot(e)),It(e.hittable),-kt(e.rect)]}function jt(e,t){if(!e.rect)throw Error(`React Native overlay target node must have rect`);return{action:t,point:a(e.rect),rect:e.rect,ref:e.ref,label:Bt(e)}}function Mt(e){let t=Bt(e)?.trim().toLowerCase();return t&&vt(t)?`dismiss`:`close`}function Nt(e){return Pt(e,Ft)}function Pt(e,t){let n=e.filter(e=>e.rect);return n.length===0?null:n.sort((e,n)=>Lt(t(n),t(e)))[0]??null}function Ft(e){return[It(e.hittable),e.rect?.width??0,e.rect?.y??0]}function It(e){return+(e===!0)}function Lt(e,t){for(let n=0;n<e.length;n+=1){let r=e[n]-t[n];if(r!==0)return r}return 0}function Rt(e){if(!e.rect)throw Error(`Collapsed React Native warning node must have rect`);let t=Math.min(e.rect.height,52),n=Math.min(36,Math.max(18,t*.45));return{x:Math.round(zt(e.rect.x+e.rect.width-n,e.rect.x+1,e.rect.x+e.rect.width-1)),y:Math.round(e.rect.y+t/2)}}function zt(e,t,n){return Math.min(n,Math.max(t,e))}function Bt(e){return e.label??e.value??e.identifier}const Vt=[`status`,`get`,`dismiss`,`enter`,`return`];function Ht(e){return Vt.includes(e)}function Ut(e){let t=e?.trim().split(/\s+/,1)[0];if(!t||!t.startsWith(`@`)||t.length<3)return null;let n=t.slice(1);return/^[A-Za-z_-]*\d[\w-]*$/i.test(n)||/^(?:ref|node|element|el)[\w-]*$/i.test(n)?t:null}function Wt(e){let{nodes:t,backend:n,snapshotRaw:r}=e;if(r||!o(n))return{partial:!1,visibleNodeCount:t.length,totalNodeCount:t.length,reasons:[]};let i=Te(t),a=new Set;return i.hiddenCount>0&&a.add(`offscreen-nodes`),i.nodes.some(e=>e.hiddenContentAbove)&&a.add(`scroll-hidden-above`),i.nodes.some(e=>e.hiddenContentBelow)&&a.add(`scroll-hidden-below`),{partial:a.size>0,visibleNodeCount:i.nodes.length,totalNodeCount:t.length,reasons:[...a]}}function Gt(e,t){try{let n=Ke(e),r=T.extname(n)||`.js`;return[T.join(T.dirname(n),`${t}${r}`),T.join(T.dirname(n),`internal`,`${t}${r}`)].find(e=>Ge.existsSync(e))??null}catch{return null}}var D=class extends Error{};let O=null,Kt=!1,qt=!1,Jt=0;const k=new Map;function Yt(e){Kt=!0,!qt&&(qt=!0,l({level:`warn`,phase:`png_worker_unavailable`,data:{reason:e}}),process.emitWarning(`PNG worker unavailable, falling back to in-process PNG processing: ${e}`))}function Xt(e){let t=k.get(e.id);t&&(k.delete(e.id),$t(),e.ok?t.resolve(e.result):t.reject(new n(r(e.error.code),e.error.message,e.error.details)))}function Zt(e,t){O===e&&(Yt(t.message),O=null,e.terminate().catch(()=>{}),Qt(new D(`PNG worker failed: ${t.message}`)))}function Qt(e){let t=[...k.values()];k.clear();for(let n of t)n.reject(e)}function $t(){O&&(k.size>0?O.ref():O.unref())}function en(){if(Kt)return null;if(O)return O;let e=Gt(import.meta.url,`png-worker`);if(!e)return Yt(`worker entry module not found next to the current module`),null;try{let t=new qe(e,{execArgv:e.endsWith(`.ts`)?[`--experimental-strip-types`]:[]});return t.on(`message`,Xt),t.on(`error`,e=>{Zt(t,e)}),t.on(`exit`,e=>{Zt(t,Error(`PNG worker exited with code ${e}`))}),t.unref(),O=t,t}catch(e){return Yt(`failed to spawn worker: ${e instanceof Error?e.message:String(e)}`),null}}function tn(e){let t=en();if(!t)return Promise.reject(new D(`PNG worker is unavailable`));Jt+=1;let n=Jt;return new Promise((r,i)=>{k.set(n,{resolve:r,reject:i}),$t();try{t.postMessage({...e,id:n})}catch(e){k.delete(n),$t(),i(new D(`failed to post job to PNG worker: ${e instanceof Error?e.message:String(e)}`))}})}async function nn(e,t){try{return await tn(e)}catch(e){if(e instanceof D)return t();throw e}}function rn(){en()}async function an(){let e=O;O=null,Qt(new D(`PNG worker terminated`)),e&&await e.terminate()}async function A(e,t){let n=await nn({kind:`decode`,png:e,label:t},()=>{let n=Ue(e,t);return{kind:`decode`,width:n.width,height:n.height,data:n.data}});return new Ve({width:n.width,height:n.height,data:We(n.data)})}async function on(e){return We((await nn({kind:`encode`,width:e.width,height:e.height,data:e.data},()=>({kind:`encode`,png:Ve.sync.write(e)}))).png)}async function sn(e){let{kind:t,...n}=await nn({kind:`diff-pixels`,...e},()=>({kind:`diff-pixels`,...He(e)}));return{...n,diffData:We(n.diffData)}}const j=[0,187,255,255];function cn(e,t){for(let n of t)n.rect.width<4||n.rect.height<4||ln(e,n.rect)}function ln(e,t){let n=M(t.x,0,e.width-1),r=M(t.y,0,e.height-1),i=M(t.x+t.width-1,0,e.width-1),a=M(t.y+t.height-1,0,e.height-1);for(let t=0;t<2;t+=1){for(let o=n;o<=i;o+=1)un(e,o,r+t,j),un(e,o,a-t,j);for(let o=r;o<=a;o+=1)un(e,n+t,o,j),un(e,i-t,o,j)}}function un(e,t,n,r){if(t<0||t>=e.width||n<0||n>=e.height)return;let i=(n*e.width+t)*4;e.data[i]=r[0],e.data[i+1]=r[1],e.data[i+2]=r[2],e.data[i+3]=r[3]}function M(e,t,n){return Math.min(Math.max(e,t),n)}const dn=[{x:-1,y:-1},{x:0,y:-1},{x:1,y:-1},{x:-1,y:0},{x:1,y:0},{x:-1,y:1},{x:0,y:1},{x:1,y:1}];function fn(e){let{mask:t,width:n,height:r,hooks:i}=e,a=new Uint8Array(t.length),o=new Int32Array(t.length),s=[];for(let e=0;e<t.length;e+=1){if(!hn(t,a,e))continue;let c=0,l=mn(o,a,0,e),u=i.create(e);for(;c<l;){let e=o[c];c+=1,i.visit(u,e),l=pn({mask:t,visited:a,queue:o,queueEnd:l,width:n,height:r,pixelIndex:e})}s.push(u)}return s}function pn(e){let{mask:t,visited:n,queue:r,width:i,height:a,pixelIndex:o}=e,s=o%i,c=Math.floor(o/i),l=e.queueEnd;for(let e of dn){let o=s+e.x,u=c+e.y;if(!gn(o,u,i,a))continue;let d=u*i+o;hn(t,n,d)&&(l=mn(r,n,l,d))}return l}function mn(e,t,n,r){return t[r]=1,e[n]=r,n+1}function hn(e,t,n){return e[n]===1&&t[n]!==1}function gn(e,t,n,r){return e>=0&&e<n&&t>=0&&t<r}const _n=.4,vn={icon:90,toggle:90,chevron:75,separator:45,visual:35,background:10},yn={leading:20,trailing:20,separator:10,unknown:0,background:-30};function bn(e){let t=Tn(Sn(xn(e.diffMask,e.width,e.height,e.ocr),e.width,e.height),10),n=In(e.ocr?.currentBlocksRaw??[]),r=In(e.ocr?.baselineBlocksRaw??[]);return t.filter(Bn).map(t=>En(t,e,n,r)).filter(t=>t.rect.y>=e.height*.08).filter(An).sort((e,t)=>t.score-e.score).slice(0,Math.max(0,e.maxDeltas??12)).map((e,t)=>Dn(e,t+1))}function xn(e,t,n,r){let i=new Uint8Array(e);if(!r)return i;for(let e of[...r.baselineBlocksRaw,...r.currentBlocksRaw])Hn(i,t,n,ne(e.rect,8));return i}function Sn(e,t,n){return fn({mask:e,width:t,height:n,hooks:{create:e=>Cn(e,t),visit:(e,n)=>wn(e,n,t)}})}function Cn(e,t){let n=e%t,r=Math.floor(e/t);return{minX:n,minY:r,maxX:n,maxY:r,differentPixels:0}}function wn(e,t,n){let r=t%n,i=Math.floor(t/n);e.minX=Math.min(e.minX,r),e.minY=Math.min(e.minY,i),e.maxX=Math.max(e.maxX,r),e.maxY=Math.max(e.maxY,i),e.differentPixels+=1}function Tn(e,t){let n=[];for(let r of e.sort((e,t)=>e.minY-t.minY||e.minX-t.minX)){let e=n.find(e=>Un(e,r,t));if(!e){n.push({...r});continue}e.minX=Math.min(e.minX,r.minX),e.minY=Math.min(e.minY,r.minY),e.maxX=Math.max(e.maxX,r.maxX),e.maxY=Math.max(e.maxY,r.maxY),e.differentPixels+=r.differentPixels}return n}function En(e,t,n,r){let i=Vn(e),a=Nn(i,t.regions),o=Pn(i,n,r),s=On(i,o?.block.rect,t.width),c=kn(i,s,e.differentPixels,t),l={...a?{regionIndex:a}:{},slot:s,likelyKind:c,rect:i};return{...a?{regionIndex:a}:{},slot:s,likelyKind:c,rect:i,...o?{nearestText:zn(o.block.text)}:{},score:jn(l,e.differentPixels,t)}}function Dn(e,t){return{index:t,...e.regionIndex?{regionIndex:e.regionIndex}:{},slot:e.slot,likelyKind:e.likelyKind,rect:e.rect,...e.nearestText?{nearestText:e.nearestText}:{}}}function On(e,t,n){if(e.height<=3&&e.width>=n*.12)return`separator`;if(!t)return e.width>=n*_n?`background`:`unknown`;if(e.width>=n*_n)return`background`;let r=e.x+e.width/2,i=t.x+t.width/2;return r<i-t.width/2?`leading`:r>i+t.width/2?`trailing`:e.width>=n*.35?`background`:`unknown`}function kn(e,t,n,r){let i=e.width/e.height,a=n/(e.width*e.height);return t===`separator`?`separator`:t===`background`?`background`:t===`trailing`&&i>=1.5&&i<=3.8&&a>=.35?`toggle`:t===`trailing`&&e.width<=r.width*.06&&e.height<=r.height*.04?`chevron`:t===`leading`&&i>=.55&&i<=1.8?`icon`:Mn(e,r)?`background`:`visual`}function An(e){return e.likelyKind!==`background`}function jn(e,t,n){let r=Mn(e.rect,n)?-35:0,i=e.regionIndex?20:0;return vn[e.likelyKind]+yn[e.slot]+i+r+Math.min(20,t/200)}function Mn(e,t){return e.width>=t.width*.25||e.height>=t.height*.06}function Nn(e,t){let n,r=0;for(let i of t){let t=re(e,i.rect);t<=r||(r=t,n=i)}return n?.index}function Pn(e,t,n){let r=Fn(e,t);if(r)return Rn(e,r.blocks);let i=Fn(e,n);return i?Rn(e,i.blocks):void 0}function Fn(e,t){let n,r=0;for(let i of t){let t=Wn(e,i.rect);t<=r||(r=t,n=i)}return n}function In(e){let t=[];for(let n of[...e].sort((e,t)=>e.rect.y-t.rect.y)){let e=t.find(e=>Ln(e.rect,n.rect));if(!e){t.push({rect:n.rect,blocks:[n]});continue}e.blocks.push(n),e.blocks.sort((e,t)=>e.rect.x-t.rect.x),e.rect=te([e.rect,n.rect])}return t}function Ln(e,t){return Wn(e,t)>0?!0:Math.abs(g(e).y-g(t).y)<=Math.max(e.height,t.height)*.5}function Rn(e,t){let n,r=g(e);for(let e of t){let t=Math.sqrt(ee(r,g(e.rect)));n&&t>=n.distance||(n={block:e,distance:t})}return n}function zn(e){return e.trim().replace(/^[^\p{L}\p{N}]+/u,``).replace(/^\p{L}\s+/u,``)}function Bn(e){let t=Vn(e);return e.differentPixels>=24&&t.width>=3&&t.height>=3}function Vn(e){return{x:e.minX,y:e.minY,width:e.maxX-e.minX+1,height:e.maxY-e.minY+1}}function Hn(e,t,n,r){let i=he(Math.floor(r.x),0,t-1),a=he(Math.floor(r.y),0,n-1),o=he(Math.ceil(r.x+r.width),0,t),s=he(Math.ceil(r.y+r.height),0,n);for(let n=a;n<s;n+=1)for(let r=i;r<o;r+=1)e[n*t+r]=0}function Un(e,t,n){return e.minX-n<=t.maxX&&t.minX-n<=e.maxX&&e.minY-n<=t.maxY&&t.minY-n<=e.maxY}function Wn(e,t){return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}async function Gn(e){if(await d(`tesseract`))try{let[t,n]=await Promise.all([Jn(e.baselinePath),Jn(e.currentPath)]);if(t.exitCode!==0||n.exitCode!==0)return;let r=Kn(t.stdout,e.width,e.height),i=Kn(n.stdout,e.width,e.height),a=qn(r,i),o=tr(a);return r.length===0&&i.length===0?void 0:{provider:`tesseract`,baselineBlocks:r.length,currentBlocks:i.length,baselineBlocksRaw:r,currentBlocksRaw:i,matches:a,...o.length>0?{movementClusters:o}:{}}}catch{return}}function Kn(e,t,n){let[r,...i]=e.split(/\r?\n/);if(!r)return[];let a=r.split(` `),o=new Map(a.map((e,t)=>[e,t])),s=[];for(let e of i){if(!e.trim())continue;let t=e.split(` `),n=P(t,o,`level`),r=N(t,o,`text`).trim(),i=P(t,o,`conf`);if(n!==5||!ir(r)||i<0)continue;let a=P(t,o,`left`),c=P(t,o,`top`),l=P(t,o,`width`),u=P(t,o,`height`);l<=0||u<=0||s.push({key:[N(t,o,`page_num`),N(t,o,`block_num`),N(t,o,`par_num`),N(t,o,`line_num`)].join(`:`),text:r,confidence:i,rect:{x:a,y:c,width:l,height:u}})}let c=new Map;for(let e of s){let t=c.get(e.key);t?t.push(e):c.set(e.key,[e])}return Array.from(c.values()).flatMap(e=>Xn(e)).map(e=>Yn(e,t,n)).filter(e=>e!==null)}function qn(e,t){let n=new Set,r=[];for(let i of e){let e=Zn(i,ar(i.text),t,n);if(e===null)continue;n.add(e);let a=t[e],o=Qn(i,a);$n(o)&&r.push(o)}return r.sort((e,t)=>er(t)-er(e)).slice(0,12)}function Jn(e){return u(`tesseract`,[e,`stdout`,`-l`,`eng`,`tsv`],{allowFailure:!0,timeoutMs:1e4})}function Yn(e,t,n){if(e.length===0)return null;let r=[...e].sort((e,t)=>e.rect.x-t.rect.x),i=te(r.map(e=>e.rect)),a=Math.round(or(r.map(e=>e.confidence))*100)/100;return{text:r.map(e=>e.text).join(` `),confidence:a,rect:i,normalizedRect:ae({x:F(i.x/t),y:F(i.y/n),width:F(i.width/t),height:F(i.height/n)})}}function Xn(e){let t=[...e].sort((e,t)=>e.rect.x-t.rect.x),n=[],r=[];for(let e of t){let t=r.at(-1);if(!t){r.push(e);continue}let i=e.rect.x-(t.rect.x+t.rect.width),a=Math.max(t.rect.height,e.rect.height);if(i>Math.max(48,a*2.5)){n.push(r),r=[e];continue}r.push(e)}return r.length>0&&n.push(r),n}function Zn(e,t,n,r){let i=null,a=1/0;for(let o=0;o<n.length;o+=1){if(r.has(o))continue;let s=n[o];if(ar(s.text)!==t)continue;let c=ee(g(e.normalizedRect),g(s.normalizedRect));c>=a||(i=o,a=c)}return i}function Qn(e,t){let n={x:t.rect.x-e.rect.x,y:t.rect.y-e.rect.y,width:t.rect.width-e.rect.width,height:t.rect.height-e.rect.height},r=sr(t.rect.width/e.rect.width),i=sr(t.rect.height/e.rect.height),a=Math.abs(r-1)>=.08||Math.abs(i-1)>=.12;return{text:e.text,baselineRect:e.rect,currentRect:t.rect,delta:n,confidence:Math.round(Math.min(e.confidence,t.confidence)*100)/100,possibleTextMetricMismatch:a}}function $n(e){return Math.abs(e.delta.x)>=2||Math.abs(e.delta.y)>=2||Math.abs(e.delta.width)>=2||Math.abs(e.delta.height)>=2||e.possibleTextMetricMismatch}function er(e){return Math.abs(e.delta.x)+Math.abs(e.delta.y)+Math.abs(e.delta.width)+Math.abs(e.delta.height)+(e.possibleTextMetricMismatch?25:0)}function tr(e){let t=[];for(let n of[...e].sort((e,t)=>e.currentRect.y-t.currentRect.y)){let e=t.find(e=>Math.abs(n.delta.x-or(e.map(e=>e.delta.x)))<=32);e?e.push(n):t.push([n])}return t.filter(e=>e.length>=2).map(nr).filter(e=>e.yRange.max-e.yRange.min<=60).sort((e,t)=>rr(t)-rr(e)).slice(0,4)}function nr(e){let t=e.map(e=>e.delta.x),n=e.map(e=>e.delta.y);return{texts:e.map(e=>e.text),xRange:{min:Math.min(...t),max:Math.max(...t)},yRange:{min:Math.min(...n),max:Math.max(...n)}}}function rr(e){let t=(e.xRange.min+e.xRange.max)/2,n=(e.yRange.min+e.yRange.max)/2;return Math.abs(t)*2+Math.abs(n)}function N(e,t,n){let r=t.get(n);return r===void 0?``:e[r]??``}function P(e,t,n){let r=Number(N(e,t,n));return Number.isFinite(r)?r:0}function ir(e){return/[\p{L}\p{N}]/u.test(e)}function ar(e){return e.trim().replace(/\s+/g,` `).toLowerCase()}function or(e){return e.reduce((e,t)=>e+t,0)/e.length}function F(e){return Math.round(e*100*100)/100}function sr(e){return Math.round(e*1e3)/1e3}function cr(e,t){return e.flatMap(e=>lr(e,t.baseline.width,t.baseline.height)?ur(e,t,gr(t.baseline.height)):[e])}function lr(e,t,n){let r=e.maxX-e.minX+1;return e.maxY-e.minY+1>=hr(n)&&r>=t*.35}function ur(e,t,n){let r=mr(e,pr(fr(dr(e,t.diffMask,t.baseline.width)),Math.max(1,Math.round((e.maxX-e.minX+1)*.08))),n);if(r.length<=1)return[e];let i=r.map(([n,r])=>_r(e,n,r,t)).filter(e=>e!==null);return i.length>1?i:[e]}function dr(e,t,n){let r=[];for(let i=e.minY;i<=e.maxY;i+=1){let a=0;for(let r=e.minX;r<=e.maxX;r+=1)t[i*n+r]===1&&(a+=1);r.push(a)}return r}function fr(e){return e.map((t,n)=>{let r=0,i=0,a=Math.max(0,n-3),o=Math.min(e.length-1,n+3);for(let t=a;t<=o;t+=1)r+=e[t],i+=1;return Math.round(r/i)})}function pr(e,t){let n=[],r=null;for(let i=0;i<e.length;i+=1){if(e[i]<=t){r??=i;continue}r!==null&&(i-r>=6&&n.push([r,i-1]),r=null)}return r!==null&&e.length-r>=6&&n.push([r,e.length-1]),n}function mr(e,t,n){let r=[],i=e.minY;for(let[a,o]of t){let t=e.minY+Math.round((a+o)/2);t-i+1<n||e.maxY-t<n||(r.push([i,t]),i=t+1)}return r.push([i,e.maxY]),r}function hr(e){return Math.max(48,Math.round(e*.07))}function gr(e){return Math.max(24,Math.round(e*.03))}function _r(e,t,n,r){let i=null;for(let a=t;a<=n;a+=1)for(let t=e.minX;t<=e.maxX;t+=1){let e=a*r.baseline.width+t;r.diffMask[e]===1&&(i??=vr(t,a),yr(i,e,t,a,r.baseline,r.current))}return i}function vr(e,t){return{minX:e,minY:t,maxX:e,maxY:t,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0}}function yr(e,t,n,r,i,a){let o=t*4;e.minX=Math.min(e.minX,n),e.minY=Math.min(e.minY,r),e.maxX=Math.max(e.maxX,n),e.maxY=Math.max(e.maxY,r),e.differentPixels+=1,e.baselineRed+=i.data[o],e.baselineGreen+=i.data[o+1],e.baselineBlue+=i.data[o+2],e.currentRed+=a.data[o],e.currentGreen+=a.data[o+1],e.currentBlue+=a.data[o+2]}const br=2.5;function xr(e){let t=Sr(e);return cr(t.length<=2e3?Tr(t,12):t,e).sort((e,t)=>{let n=t.differentPixels-e.differentPixels;if(n!==0)return n;let r=e.minY-t.minY;return r===0?e.minX-t.minX:r}).slice(0,Math.max(0,e.maxRegions??8)).map((t,n)=>Or(t,n+1,{width:e.baseline.width,height:e.baseline.height,totalPixels:e.totalPixels,differentPixels:e.differentPixels}))}function Sr(e){let{diffMask:t,baseline:n,current:r}=e,{width:i,height:a}=n;return fn({mask:t,width:i,height:a,hooks:{create:e=>Cr(e,i),visit:(e,t)=>wr(e,t,i,n,r)}})}function Cr(e,t){let n=e%t,r=Math.floor(e/t);return{minX:n,minY:r,maxX:n,maxY:r,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0}}function wr(e,t,n,r,i){let a=t%n,o=Math.floor(t/n),s=t*4;e.minX=Math.min(e.minX,a),e.minY=Math.min(e.minY,o),e.maxX=Math.max(e.maxX,a),e.maxY=Math.max(e.maxY,o),e.differentPixels+=1,e.baselineRed+=r.data[s],e.baselineGreen+=r.data[s+1],e.baselineBlue+=r.data[s+2],e.currentRed+=i.data[s],e.currentGreen+=i.data[s+1],e.currentBlue+=i.data[s+2]}function Tr(e,t){let n=[];for(let r of e.sort((e,t)=>{let n=e.minY-t.minY;return n===0?e.minX-t.minX:n})){let e=n.find(e=>Er(e,r,t));if(!e){n.push({...r});continue}Dr(e,r)}return n}function Er(e,t,n){return e.minX-n<=t.maxX&&t.minX-n<=e.maxX&&e.minY-n<=t.maxY&&t.minY-n<=e.maxY}function Dr(e,t){e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e.differentPixels+=t.differentPixels,e.baselineRed+=t.baselineRed,e.baselineGreen+=t.baselineGreen,e.baselineBlue+=t.baselineBlue,e.currentRed+=t.currentRed,e.currentGreen+=t.currentGreen,e.currentBlue+=t.currentBlue}function Or(e,t,n){let r={x:e.minX,y:e.minY,width:e.maxX-e.minX+1,height:e.maxY-e.minY+1},i={x:Math.round(e.minX+r.width/2),y:Math.round(e.minY+r.height/2)},a=kr(e.baselineRed,e.baselineGreen,e.baselineBlue,e.differentPixels),o=kr(e.currentRed,e.currentGreen,e.currentBlue,e.differentPixels),s=r.width*r.height,c=L(e.differentPixels/s),l=Math.round(I(a)),u=Math.round(I(o)),d=Mr(r,n.width,n.height),f=Nr(s,n.totalPixels),p=jr(a,o),m=Ar(i,n.width,n.height);return{index:t,rect:r,normalizedRect:ae({x:L(r.x/n.width),y:L(r.y/n.height),width:L(r.width/n.width),height:L(r.height/n.height)}),differentPixels:e.differentPixels,shareOfDiffPercentage:L(e.differentPixels/n.differentPixels),densityPercentage:c,shape:d,size:f,location:m,averageBaselineColorHex:Pr(a),averageCurrentColorHex:Pr(o),baselineLuminance:l,currentLuminance:u,dominantChange:p}}function kr(e,t,n,r){return{r:Math.round(e/r),g:Math.round(t/r),b:Math.round(n/r)}}function Ar(e,t,n){let r=e.x<t/3?`left`:e.x>t*2/3?`right`:`center`,i=e.y<n/3?`top`:e.y>n*2/3?`bottom`:`middle`;return r===`center`&&i===`middle`?`center`:`${i}-${r}`}function jr(e,t){let n=I(e),r=I(t)-n;return Math.abs(r)>=12?r>0?`brighter`:`darker`:Math.max(Math.abs(t.r-e.r),Math.abs(t.g-e.g),Math.abs(t.b-e.b))>=12?`color-shift`:`mixed`}function Mr(e,t,n){return e.width>=t*.55&&e.height>=n*.12?`large-area`:e.width>=e.height*br?`horizontal-band`:e.height>=e.width*br?`vertical-band`:`compact`}function Nr(e,t){let n=e/t;return n>=.04?`large`:n>=.01?`medium`:`small`}function I(e){return e.r*.2126+e.g*.7152+e.b*.0722}function Pr(e){return`#${Fr(e.r)}${Fr(e.g)}${Fr(e.b)}`}function Fr(e){return e.toString(16).padStart(2,`0`)}function L(e){return Math.round(e*100*100)/100}const Ir=255*Math.sqrt(3);async function Lr(e,t,n={}){await Rr(e,`Baseline image not found`),await Rr(t,`Current screenshot not found`);let r=n.outputPath,[i,a]=await Promise.all([w.readFile(e),w.readFile(t)]),[o,s]=await Promise.all([A(i,`baseline screenshot`),A(a,`current screenshot`)]);zr(o.width,o.height,`baseline screenshot`,n.maxPixels),zr(s.width,s.height,`current screenshot`,n.maxPixels);let c=n.threshold??.1;if(o.width!==s.width||o.height!==s.height){let e=o.width*o.height;return await Br(n.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:o.width,height:o.height},actual:{width:s.width,height:s.height}}}}let l=o.width*o.height,u=c*Ir,{diffData:d,diffMask:f,differentPixels:p}=await sn({width:o.width,height:o.height,baselineData:o.data,currentData:s.data,maxColorDistance:u}),m=p>0?xr({diffMask:f,baseline:o,current:s,totalPixels:l,differentPixels:p,maxRegions:n.maxRegions}):[];if(p>0&&r){let e=new Ve({width:o.width,height:o.height,data:d});cn(e,m),await w.mkdir(T.dirname(r),{recursive:!0}),await w.writeFile(r,await on(e))}else await Br(n.outputPath);let h=p>0?await Gn({baselinePath:e,currentPath:t,width:o.width,height:o.height}):void 0,g=h&&(h.matches.length>0||(h.movementClusters?.length??0)>0)?{provider:h.provider,baselineBlocks:h.baselineBlocks,currentBlocks:h.currentBlocks,matches:h.matches,...h.movementClusters?{movementClusters:h.movementClusters}:{}}:void 0,_=p>0&&h?bn({diffMask:f,width:o.width,height:o.height,regions:m,ocr:h}):[],ee=l>0?Math.round(p/l*100*100)/100:0;return{...p>0&&r?{diffPath:r}:{},...m.length>0?{regions:m}:{},...g?{ocr:g}:{},..._.length>0?{nonTextDeltas:_}:{},totalPixels:l,differentPixels:p,mismatchPercentage:ee,match:p===0}}async function Rr(e,t){try{await w.access(e)}catch{throw new n(`INVALID_ARGS`,`${t}: ${e}`)}}function zr(e,t,r,i){if(i==null||i<=0)return;let a=e*t;if(!(a<=i))throw new n(`INVALID_ARGS`,`${r} is ${a} pixels, which exceeds the configured maxImagePixels limit of ${i}`)}async function Br(e){if(e)try{await w.unlink(e)}catch(e){if(!Vr(e,`ENOENT`))throw e}}function Vr(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}function Hr(e,t){return e.map(e=>{let n=Ur(e,t);return n.length>0?{...e,currentOverlayMatches:n}:e})}function Ur(e,t){let n=Wr(e.rect);return t.map(t=>{let r=t.overlayRect,i=re(e.rect,r);return i<=0?null:{ref:t.ref,...t.label?{label:t.label}:{},rect:r,overlayCoveragePercentage:Gr(i/Wr(r)),regionCoveragePercentage:Gr(i/n)}}).filter(e=>e!==null).sort((e,t)=>{let n=t.regionCoveragePercentage-e.regionCoveragePercentage;return n===0?t.overlayCoveragePercentage-e.overlayCoveragePercentage:n}).slice(0,3).map(e=>({ref:e.ref,...e.label?{label:e.label}:{},rect:e.rect,regionCoveragePercentage:e.regionCoveragePercentage}))}function Wr(e){return e.width*e.height}function Gr(e){return Math.round(e*100*100)/100}async function R(e,t,r){if(t.kind===`path`&&!e.policy.allowLocalInputPaths)throw new n(`INVALID_ARGS`,`Local ${r.field??`input`} paths are not allowed by command policy`);try{return await e.artifacts.resolveInput(t,r)}catch(e){throw i(e)}}async function z(e,t,r){if(t?.kind===`path`&&!e.policy.allowLocalOutputPaths)throw new n(`INVALID_ARGS`,`Local output paths are not allowed by command policy`);try{return await e.artifacts.reserveOutput(t,{...r,visibility:r.visibility??`client-visible`,requestedClientPath:t?.kind===`downloadableArtifact`?t.clientPath??r.requestedClientPath:r.requestedClientPath})}catch(e){throw i(e)}}async function Kr(e,t){try{return await e.artifacts.createTempFile(t)}catch(e){throw i(e)}}const qr=async(e,t)=>{if(!t.baseline)throw new n(`INVALID_ARGS`,`diff screenshot requires a baseline image`);let r=Jr(t.threshold),i=t.current??{kind:`live`};if(t.overlayRefs&&!ti(i))throw new n(`INVALID_ARGS`,`diff screenshot <current.png> cannot use --overlay-refs because saved-image comparisons have no live accessibility refs`);let a=await R(e,t.baseline,{usage:`diff screenshot baseline`,field:`baseline`}),o,s,c,l=[];try{let n;ti(i)?(s=await Yr(e,t),n=s.path):(o=await R(e,i,{usage:`diff screenshot current`,field:`current`}),n=o.path),c=t.out?await z(e,t.out,{field:`diffPath`,ext:`.png`,artifactType:`screenshot-diff`}):void 0;let u=await Lr(a.path,n,{threshold:r,outputPath:c?.path,maxPixels:e.policy.maxImagePixels});ti(i)&&(u=await Xr(e,t,c?.path,u,l));let d=u.diffPath?await c?.publish():void 0;return d&&l.push(d),u.diffPath||await c?.cleanup?.(),{...u,...l.length>0?{artifacts:l}:{}}}catch(e){throw await c?.cleanup?.(),e}finally{await a.cleanup?.(),await o?.cleanup?.(),await s?.cleanup?.()}};function Jr(e){if(e==null||e===``)return .1;let t=Number(e);if(Number.isNaN(t)||t<0||t>1)throw new n(`INVALID_ARGS`,`--threshold must be a number between 0 and 1`);return t}async function Yr(e,t){let n=await Kr(e,{prefix:`agent-device-diff-current`,ext:`.png`});try{await Zr(e,t,n.path,Qr(t))}catch(e){throw await n.cleanup(),e}return n}async function Xr(e,t,n,r,i){if(!t.overlayRefs)return r;if(r.match||r.dimensionMismatch)return n&&await ei(n),r;let a=await z(e,$r(t,n),{field:`currentOverlayPath`,ext:`.png`,artifactType:`screenshot`});try{let n=await Zr(e,t,a.path,{overlayRefs:!0,...Qr(t)}),o=await a.publish();return o&&i.push(o),{...r,currentOverlayPath:n.path??a.path,...n.overlayRefs?{currentOverlayRefCount:n.overlayRefs.length}:{},...r.regions&&n.overlayRefs?{regions:Hr(r.regions,n.overlayRefs)}:{}}}catch(e){throw await a.cleanup?.(),e}}async function Zr(e,t,r,i={}){if(!e.backend.captureScreenshot)throw new n(`UNSUPPORTED_OPERATION`,`screenshot is not supported by this backend`);return await e.backend.captureScreenshot({session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata},r,i)??{}}function Qr(e){return{normalizeStatusBar:e.normalizeStatusBar??!0,...e.surface?{surface:e.surface}:{}}}function $r(e,t){if(e.currentOverlayOut)return e.currentOverlayOut;if(e.out?.kind===`path`)return{kind:`path`,path:B(t??e.out.path)};if(e.out?.kind===`downloadableArtifact`)return{kind:`downloadableArtifact`,...e.out.clientPath?{clientPath:B(e.out.clientPath)}:{},...e.out.fileName?{fileName:B(e.out.fileName)}:{}}}function B(e){let t=T.extname(e);return`${t?e.slice(0,-t.length):e}.current-overlay${t||`.png`}`}async function ei(e){try{await w.unlink(B(e))}catch(e){if(!ni(e,`ENOENT`))throw e}}function ti(e){return e.kind===`live`}function ni(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}async function ri(e,t){if(!Number.isInteger(t)||t<1)throw new n(`INVALID_ARGS`,`Screenshot max size must be a positive integer`);let r=await A(await w.readFile(e),`screenshot`),i=Math.max(r.width,r.height);if(i<=t)return;let a=t/i,o=ii(r,Math.max(1,Math.round(r.width*a)),Math.max(1,Math.round(r.height*a)));await w.writeFile(e,await on(o))}function ii(e,t,n){let r=new Ve({width:t,height:n});for(let i=0;i<n;i+=1){let a=i*e.height/n,o=(i+1)*e.height/n;for(let n=0;n<t;n+=1){let s=n*e.width/t,c=(n+1)*e.width/t,l=0,u=0,d=0,f=0,p=0;for(let t=Math.floor(a);t<Math.ceil(o);t+=1){let n=Math.min(t+1,o)-Math.max(t,a);for(let r=Math.floor(s);r<Math.ceil(c);r+=1){let i=n*(Math.min(r+1,c)-Math.max(r,s)),a=(t*e.width+r)*4;l+=(e.data[a]??0)*i,u+=(e.data[a+1]??0)*i,d+=(e.data[a+2]??0)*i,f+=(e.data[a+3]??0)*i,p+=i}}let m=(i*r.width+n)*4;r.data[m]=Math.round(l/p),r.data[m+1]=Math.round(u/p),r.data[m+2]=Math.round(d/p),r.data[m+3]=Math.round(f/p)}}return r}const ai=async(e,t)=>{if(!e.backend.captureScreenshot)throw new n(`UNSUPPORTED_OPERATION`,`screenshot is not supported by this backend`);let r=await z(e,t.out,{field:`path`,ext:`.png`,artifactType:`screenshot`}),i;try{await e.backend.captureScreenshot({session:t.session,requestId:t.requestId,appId:t.appId,appBundleId:t.appBundleId,signal:t.signal??e.signal,metadata:t.metadata},r.path,{fullscreen:t.fullscreen,overlayRefs:t.overlayRefs,stabilize:t.stabilize,normalizeStatusBar:t.normalizeStatusBar,surface:t.surface}),t.maxSize!==void 0&&await ri(r.path,t.maxSize),i=await r.publish()}catch(e){throw await r.cleanup?.(),e}return{path:r.path,...i?{artifacts:[i]}:{},...C(`Saved screenshot: ${r.path}`)}};function oi(e,n){return e.presentationKey?e:{...e,presentationKey:t(n)}}function si(e){let{previous:t,current:n,options:r,identity:i}=e;if(r.forceFull===!0||r.raw===!0||!t||t.comparisonSafe===!1||n.comparisonSafe===!1||!ci(t,n,i)||!t.presentationKey||t.presentationKey!==n.presentationKey||!li(t,n))return;let a=r.scope?.trim();return{ageMs:Math.max(0,n.createdAt-t.createdAt),nodeCount:n.nodes.length,...r.interactiveOnly===!0?{interactiveOnly:!0}:{},...a?{scope:a}:{}}}function ci(e,t,n){return!(e.backend&&t.backend&&e.backend!==t.backend||n?.previousAppBundleId&&n.currentAppBundleId&&n.previousAppBundleId!==n.currentAppBundleId)}function li(e,t){return e.truncated===t.truncated?JSON.stringify(ui(e.nodes))===JSON.stringify(ui(t.nodes)):!1}function ui(e){return e.map(e=>({index:e.index,depth:e.depth,parentIndex:e.parentIndex,type:e.type,role:e.role,subrole:e.subrole,label:e.label,value:e.value,identifier:e.identifier,enabled:e.enabled,selected:e.selected,focused:e.focused,hittable:e.hittable,rect:e.rect,bundleId:e.bundleId,appName:e.appName,windowTitle:e.windowTitle,surface:e.surface,hiddenContentAbove:e.hiddenContentAbove,hiddenContentBelow:e.hiddenContentBelow,interactionBlocked:e.interactionBlocked,presentationHints:e.presentationHints}))}const di=async(e,t)=>{let n=await pi(e,t),r=si({previous:n.session?.snapshot,current:n.snapshot,options:t,identity:{previousAppBundleId:n.session?.appBundleId,currentAppBundleId:n.result.appBundleId??n.session?.appBundleId}});return await e.sessions.set(hi(t.session,n)),{nodes:n.snapshot.nodes,truncated:n.snapshot.truncated??!1,visibility:Wt({nodes:n.snapshot.nodes,backend:n.snapshot.backend,snapshotRaw:t.raw}),...ue({...n.annotations,warnings:n.warnings}),...r?{unchanged:r}:{},...n.result.snapshotDiagnostics?{snapshotDiagnostics:n.result.snapshotDiagnostics}:{},...gi(n)}},fi=async(e,t)=>{let n=await pi(e,t),r=t.interactiveOnly===!0,i=n.session?.snapshot,a=hi(t.session,n);if(!i){let t=h(n.snapshot.nodes,{flatten:r});return await e.sessions.set(a),{mode:`snapshot`,baselineInitialized:!0,summary:{additions:0,removals:0,unchanged:t},lines:[],...n.warnings.length>0?{warnings:n.warnings}:{}}}let o=se(i.nodes,n.snapshot.nodes,{flatten:r});return await e.sessions.set(a),{mode:`snapshot`,baselineInitialized:!1,summary:o.summary,lines:o.lines,...n.warnings.length>0?{warnings:n.warnings}:{}}};async function pi(e,t){if(!e.backend.captureSnapshot)throw new n(`UNSUPPORTED_OPERATION`,`snapshot is not supported by this backend`);let r=t.session??`default`,i=await e.sessions.get(r),a=await e.backend.captureSnapshot({session:r,requestId:t.requestId,appId:i?.appId,appBundleId:i?.appBundleId,signal:t.signal??e.signal,metadata:t.metadata},{interactiveOnly:t.interactiveOnly,depth:t.depth,scope:t.scope,raw:t.raw}),o=oi(mi(a,e),t),s=ve(a),c=b(e);return{snapshot:o,result:a,session:i,annotations:s,warnings:_i({result:a,annotations:s,snapshot:o,options:t,session:i,capturedAt:o.createdAt??c,runtimeNow:c})}}function mi(e,t){return e.snapshot?e.snapshot:{nodes:e.nodes??[],truncated:e.truncated,backend:e.backend,createdAt:b(t)}}function hi(e,t){let n=t.session?.name??e??`default`;return{...t.session??{name:n},name:n,snapshot:t.snapshot,appName:t.result.appName??t.session?.appName,appBundleId:t.result.appBundleId??t.session?.appBundleId}}function gi(e){let t=e.result.appName??e.session?.appName,n=e.result.appBundleId??e.session?.appBundleId;return{...t||n?{appName:t??n}:{},...n?{appBundleId:n}:{}}}function _i(e){let t=[...e.annotations.warnings??[]];e.annotations.quality&&t.push(...Ae(e.annotations.quality,e.snapshot.nodes)),t.push(...bi(e)),e.annotations.quality||(t.push(...vi(e)),t.push(...yi(e.snapshot.nodes)));let n=xi(e.annotations.androidSnapshot);n&&t.push(n);let r=et(e.snapshot.nodes);r&&t.push(r);let i=Si(e);return i&&t.push(i),t.push(...Ei(e.annotations.freshness,e.snapshot.backend)),Array.from(new Set(t))}function vi(e){return e.snapshot.backend!==`xctest`||e.options.interactiveOnly!==!0||e.snapshot.nodes.length!==1||e.snapshot.nodes[0]?.type!==`Application`?[]:[`iOS interactive snapshot exposed only the application root. XCTest accessibility queries can fail to enumerate some simulator UI trees even when screenshots and direct gestures still work. Use screenshot as visual truth, try a scoped/full snapshot for diagnostics, and prefer direct selectors when known.`]}function yi(e){let t=new Set(e.map(e=>e.parentIndex).filter(e=>e!==void 0));return e.filter(e=>t.has(e.index)||(e.type?.toLowerCase()??``).includes(`text`)?!1:(e.label??``).split(`, `).length>10).map(e=>{let t=(e.label??``).split(`, `).length,n=e.identifier?` (${e.identifier})`:``;return`@${e.ref} [${e.type??`element`}]${n} merges ~${t} labels into a single accessibility element. The app likely marks a container as accessible, which hides every descendant from assistive tech and automation — the children cannot be addressed individually. Fix the app's accessibility (mark the rows, not the container); until then use screenshot as visual truth and coordinate taps.`})}function bi(e){let t=e.annotations.analysis;if(e.snapshot.backend!==`android`||e.options.interactiveOnly!==!0||e.snapshot.nodes.length>0||!t||(t.rawNodeCount??0)<12)return[];let n=[`Interactive snapshot is empty after filtering ${t.rawNodeCount} raw Android nodes. Likely causes: the app content is not accessibility-visible yet, a transient route change, or depth/filter options hid the target.`];return typeof e.options.depth==`number`&&typeof t.maxDepth==`number`&&t.maxDepth>=e.options.depth+2&&n.push(`Interactive output is empty at depth ${e.options.depth}; retry without -d.`),n}function xi(e){if(e?.backend===`uiautomator-dump`)return`Android snapshot helper unavailable; using stock UIAutomator dump, which can time out on busy React Native UIs.${e.fallbackReason?` Reason: ${e.fallbackReason}`:``}`}function Si(e){let t=e.session?.snapshot;if(!e.annotations.freshness&&t&&Ci(t,e.snapshot)&&wi(t,e.capturedAt,e.runtimeNow)&&Di(t.nodes.length,e.snapshot.nodes.length))return Ti}function Ci(e,t){return e.presentationKey===void 0||t.presentationKey===void 0?!0:e.presentationKey===t.presentationKey}function wi(e,t,n){return[t,n].some(t=>{let n=t-e.createdAt;return n>=0&&n<=2e3})}const Ti=`Recent snapshots dropped sharply in node count, which suggests stale or mid-transition UI. Use screenshot as visual truth, wait briefly, then re-snapshot once.`;function Ei(e,t){return!e?.staleAfterRetries||t!==`android`?[]:e.reason===`stuck-route`?[`Recent ${e.action} was followed by a nearly identical snapshot after ${e.retryCount} automatic retr${e.retryCount===1?`y`:`ies`}. If you expected navigation or submit, the tree may still be stale. Use screenshot as visual truth, wait briefly, then re-snapshot once.`]:e.reason===`sharp-drop`?[Ti]:[]}function Di(e,t){return e<12?!1:t<=Math.floor(e*.2)}const V={screenshot:ai,diffScreenshot:qr,snapshot:di,diffSnapshot:fi};function Oi(e){return{screenshot:t=>V.screenshot(e,t),diffScreenshot:t=>V.diffScreenshot(e,t),snapshot:t=>V.snapshot(e,t),diffSnapshot:t=>V.diffSnapshot(e,t)}}const ki=async(e,t)=>await Ni(e,t,`press`),Ai=async(e,t)=>await Ni(e,t,`click`),ji=async(e,t)=>{if(!t.text)throw new n(`INVALID_ARGS`,`fill requires text`);let r=ce(t),i=r.needsPreActionBaseline?null:await Ii(e,t);if(i)return i;let a=await ie(e,t,{action:`fill`,requireInteractive:!0,promoteToHittableAncestor:!1,captureEvidenceBaseline:r.needsPreActionBaseline});if(!e.backend.fill)throw new n(`UNSUPPORTED_OPERATION`,`fill is not supported by this backend`);let o=Pi(a),s=y(await e.backend.fill(v(e,t),o,t.text,{delayMs:t.delayMs})),c=`node`in a?a.node?.type??``:``,l=c&&!Ce(c,e.backend.platform)?`fill target ${Ri(a)} resolved to "${c}", attempting fill anyway.`:void 0;return await pe(e,t,a,{...a,text:t.text,...l?{warning:l}:{},...s?{backendResult:s}:{}},r)},Mi=async(e,t)=>{let r=t.text;if(!r)throw new n(`INVALID_ARGS`,`type requires text`);let i=zi(r);if(i)throw new n(`INVALID_ARGS`,`type does not accept a target ref like "${i}"`,{hint:`Use fill ${i} "text" to target that field, or press ${i} then type "text" to append.`});if(!e.backend.typeText)throw new n(`UNSUPPORTED_OPERATION`,`type is not supported by this backend`);let a=x(t.delayMs??0,`delay-ms`,0,1e4),o=y(await e.backend.typeText(v(e,t),r,{delayMs:a}));return{kind:`text`,text:r,delayMs:a,...o?{backendResult:o}:{},...C(`Typed ${Array.from(r).length} chars`)}};async function Ni(e,t,r){let i=ce(t),a=i.needsPreActionBaseline?null:await Fi(e,t,r);if(a)return a;let o=await ie(e,t,{action:r,requireInteractive:!0,promoteToHittableAncestor:!0,captureEvidenceBaseline:i.needsPreActionBaseline});if(!e.backend.tap)throw new n(`UNSUPPORTED_OPERATION`,`tap is not supported by this backend`);let s=Pi(o),c=y(await e.backend.tap(v(e,t),s,{button:t.button,count:t.count,intervalMs:t.intervalMs,holdMs:t.holdMs,jitterPx:t.jitterPx,doubleTap:t.doubleTap}));return await pe(e,t,o,{...o,...c?{backendResult:c}:{}},i)}function Pi(e){if(!e.point)throw new n(`COMMAND_FAILED`,`Interaction target resolved without coordinates`);return e.point}async function Fi(e,t,n){if(n!==`click`||t.target.kind!==`ref`||!e.backend.tapTarget||Li(t))return null;let r=await m(e,t,t.target,n),i=y(await e.backend.tapTarget(v(e,t),{kind:`ref`,ref:t.target.ref,...t.target.fallbackLabel?{fallbackLabel:t.target.fallbackLabel}:{}}));return{kind:`ref`,target:{kind:`ref`,ref:t.target.ref},...r,...i?{backendResult:i}:{}}}async function Ii(e,t){if(t.target.kind!==`ref`||!e.backend.fillTarget)return null;let n=await m(e,t,t.target,`fill`),r=y(await e.backend.fillTarget(v(e,t),{kind:`ref`,ref:t.target.ref,...t.target.fallbackLabel?{fallbackLabel:t.target.fallbackLabel}:{}},t.text,{delayMs:t.delayMs}));return{kind:`ref`,target:{kind:`ref`,ref:t.target.ref},text:t.text,...n,...r?{backendResult:r}:{}}}function Li(e){return e.count!==void 0||e.intervalMs!==void 0||e.holdMs!==void 0||e.jitterPx!==void 0||e.doubleTap!==void 0||e.button!==void 0&&e.button!==`primary`}function Ri(e){return e.target?.kind===`ref`?e.target.ref:e.target?.kind===`selector`?e.target.selector:`point`}function zi(e){return Ut(e)}const H=1e4,Bi=async(e,t)=>{let r=t.locator??`any`;if(!t.query)throw new n(`INVALID_ARGS`,`find requires a value`);if(t.action===`wait`)return await Yi(e,t,r);let{capture:i,match:a}=await Xi(e,t,r);if(!a)throw new n(`COMMAND_FAILED`,`find did not match any element`);if(t.action===`exists`)return{kind:`found`,found:!0};let o=`@${a.ref}`;return t.action===`get_attrs`?{kind:`attrs`,ref:o,node:a}:{kind:`text`,ref:o,text:await xe(e,i,a),node:a}},Vi=async(e,t)=>{if(t.target.kind===`ref`){let n=await oe(e,t.session),r=p(n.snapshot.nodes,t.target.ref,{fallbackLabel:t.target.fallbackLabel??``,invalidRefMessage:`get text requires a ref like @e2`,notFoundMessage:`Ref ${t.target.ref} not found`}),i=Re(r.node,e.backend.platform,{action:`get`}),a={kind:`ref`,ref:`@${r.ref}`};return t.property===`attrs`?{kind:`attrs`,target:a,node:r.node,selectorChain:i}:{kind:`text`,target:a,text:await xe(e,n,r.node),node:r.node,selectorChain:i}}let n=await ia(e,t,t.session??`default`,{selector:t.target.selector,disambiguateAmbiguous:t.property===`text`}),r=Re(n.node,e.backend.platform,{action:`get`});if(t.property===`attrs`)return{kind:`attrs`,target:{kind:`selector`,selector:n.selector},node:n.node,selectorChain:r};let i=await xe(e,n.capture,n.node);return{kind:`text`,target:{kind:`selector`,selector:n.selector},text:i,node:n.node,selectorChain:r}},Hi=async(e,t)=>{let r=await Vi(e,{...t,property:`text`,target:t.target});if(r.kind!==`text`)throw new n(`COMMAND_FAILED`,`getText returned non-text result`);return r},Ui=async(e,t)=>{let r=await Vi(e,{...t,property:`attrs`,target:t.target});if(r.kind!==`attrs`)throw new n(`COMMAND_FAILED`,`getAttrs returned non-attrs result`);return r},Wi=async(e,t)=>{if(!we(t.predicate))throw new n(`INVALID_ARGS`,Oe);if(t.predicate===`text`&&!t.expectedText)throw new n(`INVALID_ARGS`,`is text requires expected text value`);let r=await S(e,t,{updateSession:!0,includeRects:$i(t.predicate)}),i=f(t.selector);if(t.predicate===`exists`){let a=Le(r.snapshot.nodes,i,{platform:e.backend.platform});if(!a)throw new n(`COMMAND_FAILED`,Fe(i,[],{unique:!1}),{hint:Ie([])});return{predicate:t.predicate,pass:!0,selector:a.selector.raw,matches:a.matches,selectorChain:i.selectors.map(e=>e.raw)}}let a=Pe(r.snapshot.nodes,i,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:!1});if(!a)throw new n(`COMMAND_FAILED`,Fe(i,[],{unique:!0}),{command:`is`,reason:`selector_not_found`,predicate:t.predicate,selector:i.raw,hint:Ie([])});let o=Ee({predicate:t.predicate,node:a.node,nodes:r.snapshot.nodes,expectedText:t.expectedText,platform:e.backend.platform});if(!o.pass)throw new n(`COMMAND_FAILED`,`is ${t.predicate} failed for selector ${a.selector.raw}: ${o.details}`,{command:`is`,reason:`predicate_failed`,predicate:t.predicate,selector:a.selector.raw,predicateDetails:o.details});return{predicate:t.predicate,pass:!0,selector:a.selector.raw,...t.predicate===`text`?{text:o.actualText}:{},selectorChain:i.selectors.map(e=>e.raw)}},Gi=async(e,t)=>await Wi(e,{...t,predicate:`visible`,selector:t.target.selector}),Ki=async(e,t)=>await Wi(e,{...t,predicate:`hidden`,selector:t.target.selector}),qi=async(e,t)=>{if(t.target.kind===`sleep`)return await _(e,t.target.durationMs),{kind:`sleep`,waitedMs:t.target.durationMs};if(t.target.kind===`ref`){let r=await oe(e,t.session),i=s(t.target.ref);if(!i)throw new n(`INVALID_ARGS`,`Invalid ref: ${t.target.ref}`);let a=c(r.snapshot.nodes,i),o=a?ke(a,r.snapshot.nodes):void 0;if(!o)throw new n(`COMMAND_FAILED`,`Ref ${t.target.ref} not found or has no label`);return await ta(e,t,o,t.target.timeoutMs)}if(t.target.kind===`selector`)return await ea(e,t,t.target.selector,t.target.timeoutMs);if(t.target.kind===`stable`)return await ra(e,t,t.target.quietMs,t.target.timeoutMs);if(!t.target.text)throw new n(`INVALID_ARGS`,`wait requires text`);return await ta(e,t,t.target.text,t.target.timeoutMs)},Ji=async(e,t)=>{let r=await qi(e,{...t,target:{kind:`text`,text:t.text,timeoutMs:t.timeoutMs}});if(r.kind!==`text`)throw new n(`COMMAND_FAILED`,`waitForText returned non-text result`);return r};async function Yi(e,t,r){let i=t.timeoutMs??H,a=b(e);for(;b(e)-a<i;){let{match:n}=await Xi(e,t,r);if(n)return{kind:`found`,found:!0,waitedMs:b(e)-a};await _(e,300)}throw new n(`COMMAND_FAILED`,`find wait timed out`)}async function Xi(e,t,n){let r=Me(n,t.query),i=await S(e,t,{updateSession:!0,scope:Zi(e,n,t.query,r)});if(je(i.snapshot.snapshotQuality))throw Qi(i.snapshot.snapshotQuality);return r?{capture:i,match:Pe(i.snapshot.nodes,r,{platform:e.backend.platform,requireRect:!1,requireUnique:!1})?.node}:{capture:i,match:Ne(i.snapshot.nodes,n,t.query,{requireRect:!1}).matches[0]}}function Zi(e,t,n,r){if(!r&&e.backend.platform!==`web`)return be(t)?n:void 0}function Qi(e){return new n(`COMMAND_FAILED`,`find could not read the current accessibility tree`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth, navigate with coordinates if needed, then retry find after reaching a readable screen.`})}function $i(e){return e===`visible`||e===`hidden`}async function ea(e,t,r,i){let a=i??H,o=b(e),s=f(r);for(;b(e)-o<a;){let n=Le((await S(e,t,{updateSession:!0})).snapshot.nodes,s,{platform:e.backend.platform});if(n)return{kind:`selector`,selector:n.selector.raw,waitedMs:b(e)-o};await _(e,300)}throw new n(`COMMAND_FAILED`,`wait timed out for selector: ${r}`)}async function ta(e,t,r,i){let a=i??H,o=b(e);for(;b(e)-o<a;){if(e.backend.findText?(await e.backend.findText(v(e,t),r)).found:await na(e,t,r))return{kind:`text`,text:r,waitedMs:b(e)-o};await _(e,300)}throw new n(`COMMAND_FAILED`,`wait timed out for text: ${r}`)}async function na(e,t,n){return!!De((await S(e,t,{updateSession:!0})).snapshot.nodes,n)}async function ra(e,t,r,i){let a=i??H,o=r??500,s=await Se(e,t,{quietMs:o,timeoutMs:a});if(!s.settled)throw new n(`COMMAND_FAILED`,`wait timed out waiting for a stable UI`,{reason:`wait_stable_timeout`,...s.stalled?{captureStalled:!0}:{},quietMs:o,timeoutMs:a,captures:s.captures,nodeCount:s.nodeCount,...s.stalled?{hint:`A snapshot capture stalled past the wait timeout, so no settle verdict is available. The UI may still be readable: retry, or use screenshot to inspect the surface.`}:{}});return{kind:`stable`,waitedMs:s.waitedMs,captures:s.captures,nodeCount:s.nodeCount,...s.nodeCount<5?{hint:ye}:{}}}async function ia(e,t,r,i){let a=await S(e,{...t,session:r},{updateSession:!0}),o=f(i.selector),s=Pe(a.snapshot.nodes,o,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:i.disambiguateAmbiguous});if(!s)throw new n(`COMMAND_FAILED`,Fe(o,[],{unique:!0}),{hint:Ie([])});return{capture:a,node:s.node,selector:s.selector.raw,ref:`@${s.node.ref}`}}const U={find:Bi,get:Vi,getText:Hi,getAttrs:Ui,is:Wi,isVisible:Gi,isHidden:Ki,wait:qi,waitForText:Ji},W={click:Ai,press:ki,fill:ji,typeText:Mi,focus:de,longPress:fe,swipe:me,scroll:ge,pinch:_e};function aa(e){return{find:t=>U.find(e,t),get:t=>U.get(e,t),getText:(t,n={})=>U.getText(e,{...n,target:t}),getAttrs:(t,n={})=>U.getAttrs(e,{...n,target:t}),is:t=>U.is(e,t),isVisible:(t,n={})=>U.isVisible(e,{...n,target:t}),isHidden:(t,n={})=>U.isHidden(e,{...n,target:t}),wait:t=>U.wait(e,t),waitForText:(t,n={})=>U.waitForText(e,{...n,text:t})}}function oa(e){return{click:(t,n={})=>W.click(e,{...n,target:t}),press:(t,n={})=>W.press(e,{...n,target:t}),fill:(t,n,r={})=>W.fill(e,{...r,target:t,text:n}),typeText:(t,n={})=>W.typeText(e,{...n,text:t}),focus:(t,n={})=>W.focus(e,{...n,target:t}),longPress:(t,n={})=>W.longPress(e,{...n,target:t}),swipe:t=>W.swipe(e,t),scroll:t=>W.scroll(e,t),pinch:t=>W.pinch(e,t)}}function G(e,t){if(e!==void 0)return K(e,t)}function K(e,t){let r=e?.trim();if(!r)throw new n(`INVALID_ARGS`,`${t} must be a non-empty string`);return r}const sa=async(e,t={})=>{if(!e.backend.listDevices)throw new n(`UNSUPPORTED_OPERATION`,`admin.devices is not supported by this backend`);return{kind:`adminDevices`,devices:await e.backend.listDevices(v(e,t),t.filter)}},ca=async(e,t={})=>{if(!e.backend.bootDevice)throw new n(`UNSUPPORTED_OPERATION`,`admin.boot is not supported by this backend`);let r=va(t.target),i=y(await e.backend.bootDevice(v(e,t),r));return{kind:`deviceBooted`,...r?{target:r}:{},...i?{backendResult:i}:{},...C(`Booted device`)}},la=async(e,t={})=>{if(!e.backend.shutdownDevice)throw new n(`UNSUPPORTED_OPERATION`,`admin.shutdown is not supported by this backend`);let r=va(t.target),i=y(await e.backend.shutdownDevice(v(e,t),r));return{kind:`deviceShutdown`,...r?{target:r}:{},...i?{backendResult:i}:{},...C(`Shutdown device`)}},ua=async(e,t)=>await pa(e,t,`install`),da=async(e,t)=>await pa(e,t,`reinstall`),fa=async(e,t)=>await pa(e,t,`installFromSource`);async function pa(e,t,r){let i=r===`reinstall`?`reinstallApp`:`installApp`,a=e.backend[i];if(!a)throw new n(`UNSUPPORTED_OPERATION`,`admin.${r} is not supported by this backend`);let o=`app`in t&&t.app!==void 0?K(t.app,`app`):void 0;if(r!==`installFromSource`&&!o)throw new n(`INVALID_ARGS`,`admin.${r} requires app`);let s=v(e,t),c=await ma(e,s,t.source);try{let t=await a.call(e.backend,s,{...o?{app:o}:{},source:c.source});return ya(r,o,c.source,t)}finally{await c.cleanup?.()}}async function ma(e,t,n){let r=await ha(e,ga(n));try{return{source:ga(e.backend.resolveInstallSource?await e.backend.resolveInstallSource(t,r.source):r.source),...r.cleanup?{cleanup:r.cleanup}:{}}}catch(e){if(r.cleanup)try{await r.cleanup()}catch{}throw e}}async function ha(e,t){if(t.kind===`url`)return{source:t};let n=await R(e,t,{usage:`admin.install`,field:`source`});return{source:{kind:`path`,path:n.path},...n.cleanup?{cleanup:n.cleanup}:{}}}function ga(e){if(!e||typeof e!=`object`)throw new n(`INVALID_ARGS`,`install source is required`);if(e.kind===`path`)return{kind:`path`,path:K(e.path,`source.path`)};if(e.kind===`uploadedArtifact`)return{kind:`uploadedArtifact`,id:K(e.id,`source.id`)};if(e.kind===`url`){let t=K(e.url,`source.url`);return _a(t),{kind:`url`,url:t}}throw new n(`INVALID_ARGS`,`install source kind must be path, uploadedArtifact, or url`)}function _a(e){let t;try{t=new URL(e)}catch{throw new n(`INVALID_ARGS`,`Invalid install source URL: ${e}`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new n(`INVALID_ARGS`,`Install source URL must use http or https`)}function va(e){if(!e)return;let t=G(e.id,`target.id`),n=G(e.name,`target.name`),r={...t?{id:t}:{},...n?{name:n}:{},...e.platform?{platform:e.platform}:{},...e.target?{target:e.target}:{},...e.headless===void 0?{}:{headless:e.headless}};return Object.keys(r).length>0?r:void 0}function ya(e,t,n,r){let i=y(r),a=e===`reinstall`?`appReinstalled`:e===`installFromSource`?`appInstalledFromSource`:`appInstalled`,o=q(r,`appName`),s=q(r,`appId`),c=q(r,`bundleId`),l=q(r,`packageName`),u=q(r,`launchTarget`),d=q(r,`installablePath`),f=q(r,`archivePath`);return{kind:a,...t?{app:t}:{},source:n,...s?{appId:s}:{},...o?{appName:o}:{},...c?{bundleId:c}:{},...l?{packageName:l}:{},...u?{launchTarget:u}:{},...d?{installablePath:d}:{},...f?{archivePath:f}:{},...i?{backendResult:i}:{},...C(`${e===`reinstall`?`Reinstalled`:`Installed`}: ${o??u??t??ba(n)}`)}}function q(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function ba(e){return e.kind===`path`?e.path:e.kind===`uploadedArtifact`?e.id:e.url}const xa=/^[A-Za-z0-9_.:-]{1,64}$/,Sa=async(e,t)=>{if(!e.backend.openApp)throw new n(`UNSUPPORTED_OPERATION`,`apps.open is not supported by this backend`);let r=Oa(t),i=y(await e.backend.openApp(J(e,t),r,{launchArgs:t.launchArgs,relaunch:t.relaunch}));return{kind:`appOpened`,target:r,relaunch:t.relaunch===!0,...i?{backendResult:i}:{},...C(`Opened: ${Aa(r)}`)}},Ca=async(e,t={})=>{if(!e.backend.closeApp)throw new n(`UNSUPPORTED_OPERATION`,`apps.close is not supported by this backend`);let r=G(t.app,`app`),i=y(await e.backend.closeApp(J(e,t),r));return{kind:`appClosed`,...r?{app:r}:{},...i?{backendResult:i}:{},...C(r?`Closed: ${r}`:`Closed app`)}},wa=async(e,t={})=>{if(!e.backend.listApps)throw new n(`UNSUPPORTED_OPERATION`,`apps.list is not supported by this backend`);return{kind:`appsList`,apps:await e.backend.listApps(J(e,t),ze(t.filter))}},Ta=async(e,t)=>{if(!e.backend.getAppState)throw new n(`UNSUPPORTED_OPERATION`,`apps.state is not supported by this backend`);let r=K(t.app,`app`);return{kind:`appState`,app:r,state:await e.backend.getAppState(J(e,t),r)}},Ea=async(e,t)=>{if(!e.backend.pushFile)throw new n(`UNSUPPORTED_OPERATION`,`apps.push is not supported by this backend`);let r=K(t.app,`app`),i=await ja(e,t.input);try{let n=y(await e.backend.pushFile(J(e,t),i.backendInput,r));return{kind:`appPushed`,app:r,inputKind:i.inputKind,...n?{backendResult:n}:{},...C(`Pushed to ${r}`)}}finally{await i.cleanup?.()}},Da=async(e,t)=>{if(!e.backend.triggerAppEvent)throw new n(`UNSUPPORTED_OPERATION`,`apps.triggerEvent is not supported by this backend`);let r=Ma(t.name);Na(t.payload,`apps.triggerEvent payload for "${r}"`);let i=y(await e.backend.triggerAppEvent(J(e,t),{name:r,...t.payload?{payload:t.payload}:{}}));return{kind:`appEventTriggered`,name:r,...t.payload?{payload:t.payload}:{},...i?{backendResult:i}:{},...C(`Triggered app event: ${r}`)}};function Oa(e){let t=G(e.app,`app`),r=G(e.appId,`appId`),i=G(e.bundleId,`bundleId`),a=G(e.packageName,`packageName`),o=G(e.url,`url`),s=G(e.activity,`activity`),c={...t?{app:t}:{},...r?{appId:r}:{},...i?{bundleId:i}:{},...a?{packageName:a}:{},...o?{url:o}:{},...s?{activity:s}:{}};if(!ka(c))throw new n(`INVALID_ARGS`,`apps.open requires app, appId, bundleId, packageName, url, or activity`);return c}function ka(e){return!!(e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity)}function Aa(e){return e.app??e.appId??e.bundleId??e.packageName??e.url??e.activity??`app`}async function ja(e,t){if(!t||typeof t!=`object`)throw new n(`INVALID_ARGS`,`apps.push requires an input`);if(t.kind===`json`)return Pa(t.payload,`apps.push JSON payload`,8192),{backendInput:{kind:`json`,payload:t.payload},inputKind:`json`};let r=await R(e,t,{usage:`apps.push`,field:`input`});return{backendInput:{kind:`file`,path:r.path},inputKind:`file`,...r.cleanup?{cleanup:r.cleanup}:{}}}function Ma(e){let t=K(e,`name`);if(!xa.test(t))throw new n(`INVALID_ARGS`,`Invalid apps.triggerEvent name: ${t}`,{hint:`Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash.`});return t}function Na(e,t){e!==void 0&&Pa(e,t,8192)}function Pa(e,t,r){if(Fa(e,t),Buffer.byteLength(Ia(e,t),`utf8`)>r)throw new n(`INVALID_ARGS`,`${t} exceeds ${r} bytes`)}function Fa(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw new n(`INVALID_ARGS`,`${t} must be a JSON object`)}function Ia(e,t){try{let r=JSON.stringify(e);if(typeof r!=`string`)throw new n(`INVALID_ARGS`,`${t} must be JSON-serializable`);return r}catch{throw new n(`INVALID_ARGS`,`${t} must be JSON-serializable`)}}function J(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}const Y={open:Sa,close:Ca,list:wa,state:Ta,push:Ea,triggerEvent:Da},X={devices:sa,boot:ca,shutdown:la,install:ua,reinstall:da,installFromSource:fa};function La(e){return{open:t=>Y.open(e,t),close:t=>Y.close(e,t),list:(t={})=>Y.list(e,{...t,filter:Be(t.filter)}),state:t=>Y.state(e,t),push:t=>Y.push(e,t),triggerEvent:t=>Y.triggerEvent(e,t)}}function Ra(e){return{devices:t=>X.devices(e,t),boot:t=>X.boot(e,t),shutdown:t=>X.shutdown(e,t),install:t=>X.install(e,t),reinstall:t=>X.reinstall(e,t),installFromSource:t=>X.installFromSource(e,t)}}const za=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i,Ba=/\b[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g;function Va(e){let t=!1,n=e;return n=n.replaceAll(/(authorization|token|secret|password|passwd|api[-_]?key)=([^&\s]+)/gi,(e,n)=>(t=!0,`${String(n)}=[REDACTED]`)),n=n.replaceAll(/("(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)"\s*:\s*")([^"]*)(")/gi,(e,n,r,i)=>(t=!0,`${String(n)}[REDACTED]${String(i)}`)),n=n.replaceAll(/\b(Bearer\s+)([^\s",;]+)/gi,(e,n)=>(t=!0,`${String(n)}[REDACTED]`)),n=n.replaceAll(/((?:authorization|cookie|token|secret|password|passwd|api[-_]?key)\s*[:=]\s*)([^\s,;&]+)/gi,(e,n)=>(t=!0,`${String(n)}[REDACTED]`)),n=n.replaceAll(Ba,()=>(t=!0,`[REDACTED]`)),n=Ua(n,()=>{t=!0}),{value:n,redacted:t}}function Ha(e){try{let t=new URL(e),n=Wa(t);return(t.username||t.password)&&(t.username=`REDACTED`,t.password=`REDACTED`,n=!0),{value:t.toString(),redacted:n}}catch{return}}function Ua(e,t){return/(https?:\/\/|token|secret|password|authorization|cookie|api[-_]?key)/i.test(e)?e.replaceAll(/https?:\/\/[^\s"'<>)]+/gi,e=>{let n=Ha(e);return n?(n.redacted&&t(),n.value):e}):e}function Wa(e){let t=!1;for(let n of Array.from(e.searchParams.keys()))za.test(n)&&(e.searchParams.set(n,`[REDACTED]`),t=!0);return t}const Z=2048,Ga=4096,Ka=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i;function qa(e){let t=e.redacted===!0;return{kind:`diagnosticsLogs`,entries:e.entries.map(e=>{let n=Q(e.message,Ga),r=eo(e.metadata);return t||=n.redacted||r.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.level?{level:e.level}:{},message:n.value??``,...e.source?{source:e.source}:{},...r.value?{metadata:r.value}:{}}}),...e.nextCursor?{nextCursor:e.nextCursor}:{},...e.timeWindow?{timeWindow:e.timeWindow}:{},...e.backend?{backend:e.backend}:{},redacted:t,...e.notes?{notes:e.notes}:{}}}function Ja(e,t){let n=e.redacted===!0;return{kind:`diagnosticsNetwork`,entries:e.entries.map(e=>{let r=e.url?Za(e.url):void 0,i=t===`headers`||t===`all`?Xa(e.requestHeaders):void 0,a=t===`headers`||t===`all`?Xa(e.responseHeaders):void 0,o=t===`body`||t===`all`?Qa(e.requestBody):void 0,s=t===`body`||t===`all`?Qa(e.responseBody):void 0,c=eo(e.metadata);return n||=(r?.redacted??!1)||(i?.redacted??!1)||(a?.redacted??!1)||(o?.redacted??!1)||(s?.redacted??!1)||c.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.method?{method:e.method}:{},...r?{url:r.value}:{},...e.status===void 0?{}:{status:e.status},...e.durationMs===void 0?{}:{durationMs:e.durationMs},...i?.value?{requestHeaders:i.value}:{},...a?.value?{responseHeaders:a.value}:{},...o?.value===void 0?{}:{requestBody:o.value},...s?.value===void 0?{}:{responseBody:s.value},...c.value?{metadata:c.value}:{}}}),...e.nextCursor?{nextCursor:e.nextCursor}:{},...e.timeWindow?{timeWindow:e.timeWindow}:{},...e.backend?{backend:e.backend}:{},redacted:n,...e.notes?{notes:e.notes}:{}}}function Ya(e){let t=e.redacted===!0;return{kind:`diagnosticsPerf`,metrics:e.metrics.map(e=>{let n=Q(e.message,Ga),r=eo(e.metadata);return t||=n.redacted||r.redacted,{name:e.name,...e.value===void 0?{}:{value:e.value},...e.unit?{unit:e.unit}:{},...e.status?{status:e.status}:{},...n.value===void 0?{}:{message:n.value},...r.value?{metadata:r.value}:{}}}),...e.startedAt?{startedAt:e.startedAt}:{},...e.endedAt?{endedAt:e.endedAt}:{},...e.backend?{backend:e.backend}:{},redacted:t,...e.notes?{notes:e.notes}:{}}}function Xa(e){if(!e)return{redacted:!1};let t=!1,n={};for(let[r,i]of Object.entries(e))if(Ka.test(r))n[r]=`[REDACTED]`,t=!0;else{let e=Q(i,Z);n[r]=e.value??``,t||=e.redacted}return{value:n,redacted:t}}function Za(e){return Ha(e)??Q(e,Z)}function Qa(e){return e===void 0?{redacted:!1}:$a(e)??Q(e,Z)}function $a(e){try{let t=to(JSON.parse(e),Va);return no(JSON.stringify(t.value),Z,t.redacted)}catch{return}}function eo(e){return to(e,e=>Q(e,Z))}function to(e,t){if(e===void 0)return{redacted:!1};if(typeof e==`string`)return t(e);if(!e||typeof e!=`object`)return{value:e,redacted:!1};if(Array.isArray(e)){let n=!1;return{value:e.map(e=>{let r=to(e,t);return n||=r.redacted,r.value}),redacted:n}}let n=!1,r={};for(let[i,a]of Object.entries(e)){if(Ka.test(i)){r[i]=`[REDACTED]`,n=!0;continue}let e=to(a,t);r[i]=e.value,n||=e.redacted}return{value:r,redacted:n}}function Q(e,t){if(e===void 0)return{redacted:!1};let n=Va(e);return no(n.value,t,n.redacted)}function no(e,t,n){if(e===void 0)return{redacted:n};let r=e;return r.length>t&&(r=`${r.slice(0,t)}...[truncated]`,n=!0),{value:r,redacted:n}}const ro=async(e,t={})=>{if(!e.backend.readLogs)throw new n(`UNSUPPORTED_OPERATION`,`diagnostics.logs is not supported by this backend`);return qa(await e.backend.readLogs(await oo(e,t),so(t)))},io=async(e,t={})=>{if(!e.backend.dumpNetwork)throw new n(`UNSUPPORTED_OPERATION`,`diagnostics.network is not supported by this backend`);let r=co(t);return Ja(await e.backend.dumpNetwork(await oo(e,t),r),r.include??`summary`)},ao=async(e,t={})=>{if(!e.backend.measurePerf)throw new n(`UNSUPPORTED_OPERATION`,`diagnostics.perf is not supported by this backend`);return Ya(await e.backend.measurePerf(await oo(e,t),lo(t)))};async function oo(e,t){let n=v(e,t),r=t.session?await e.sessions.get(t.session):void 0;return{...n,...t.appId??r?.appId?{appId:t.appId??r?.appId}:{},...t.appBundleId??r?.appBundleId?{appBundleId:t.appBundleId??r?.appBundleId}:{}}}function so(e){return{...uo(e,100,500,`logs limit`),...e.levels===void 0?{}:{levels:mo(e.levels,`levels`)},...e.search===void 0?{}:{search:K(e.search,`search`)},...e.source===void 0?{}:{source:K(e.source,`source`)}}}function co(e){return{...uo(e,25,200,`network limit`),include:po(e.include)}}function lo(e){return{...fo(e),...e.sampleMs===void 0?{}:{sampleMs:x(e.sampleMs,`sampleMs`,100,6e4)},...e.metrics===void 0?{}:{metrics:mo(e.metrics,`metrics`,20)}}}function uo(e,t,n,r){return{...fo(e),...e.cursor===void 0?{}:{cursor:K(e.cursor,`cursor`)},limit:e.limit===void 0?t:x(e.limit,r,1,n)}}function fo(e){return{...e.since===void 0?{}:{since:K(e.since,`since`)},...e.until===void 0?{}:{until:K(e.until,`until`)}}}function po(e){if(e===void 0)return`summary`;if(e===`summary`||e===`headers`||e===`body`||e===`all`)return e;throw new n(`INVALID_ARGS`,`network include must be summary, headers, body, or all`)}function mo(e,t,r=50){if(!Array.isArray(e))throw new n(`INVALID_ARGS`,`${t} must be an array of strings`);if(e.length>r)throw new n(`INVALID_ARGS`,`${t} must contain at most ${r} entries`);return e.map((e,n)=>K(e,`${t}[${n}]`))}const ho={logs:ro,network:io,perf:ao};function go(e){return{logs:t=>ho.logs(e,t),network:t=>ho.network(e,t),perf:t=>ho.perf(e,t)}}const _o=async(e,t)=>{let r=Co(t.action,`record`),i=r===`start`?e.backend.startRecording:e.backend.stopRecording;if(!i)throw new n(`UNSUPPORTED_OPERATION`,`record ${r} is not supported by this backend`);let a=t.out?await z(e,t.out,{field:`path`,ext:`.mp4`,artifactType:`screen-recording`}):void 0;try{let n=yo(t,a?.path);return wo(r,await i.call(e.backend,v(e,t),n),await a?.publish())}catch(e){throw await a?.cleanup?.(),e}},vo=async(e,t)=>{let r=Co(t.action,`trace`),i=r===`start`?e.backend.startTrace:e.backend.stopTrace;if(!i)throw new n(`UNSUPPORTED_OPERATION`,`trace ${r} is not supported by this backend`);let a=t.out?await z(e,t.out,{field:`outPath`,ext:`.trace`,artifactType:`trace-log`}):void 0;try{let n={...a?.path?{outPath:a.path}:{}};return To(r,await i.call(e.backend,v(e,t),n),await a?.publish())}catch(e){throw await a?.cleanup?.(),e}};function yo(e,t){let n={};t&&(n.outPath=t);let r=bo(e.fps);r!==void 0&&(n.fps=r);let i=xo(e.maxSize);i!==void 0&&(n.maxSize=i);let a=So(e.quality);return a!==void 0&&(n.quality=a),e.hideTouches!==void 0&&(n.showTouches=e.hideTouches!==!0),n}function bo(e){return e===void 0?void 0:x(e,`fps`,1,60)}function xo(e){return e===void 0?void 0:x(e,`maxSize`,1,2**53-1)}function So(e){if(e===void 0)return;let t=le(e);if(t===void 0)throw new n(`INVALID_ARGS`,`quality must be one of: medium, high (legacy numeric values 5-10 are accepted)`);return t}function Co(e,t){if(e===`start`||e===`stop`)return e;throw new n(`INVALID_ARGS`,`${t} action must be start or stop`)}function wo(e,t,n){return{...typeof t.path==`string`?{path:t.path}:{},...typeof t.telemetryPath==`string`?{telemetryPath:t.telemetryPath}:{},...typeof t.warning==`string`?{warning:t.warning}:{},...Eo(e,t,n,{startKind:`recordingStarted`,stopKind:`recordingStopped`,startMessage:`Recording started`,stopMessage:`Recording stopped`})}}function To(e,t,n){return{...typeof t.outPath==`string`?{outPath:t.outPath}:{},...Eo(e,t,n,{startKind:`traceStarted`,stopKind:`traceStopped`,startMessage:`Trace started`,stopMessage:`Trace stopped`})}}function Eo(e,t,n,r){return{kind:e===`start`?r.startKind:r.stopKind,action:e,...n?{artifact:n}:{},backendResult:t,...C(e===`start`?r.startMessage:r.stopMessage)}}const Do={record:_o,trace:vo};function Oo(e){return{record:t=>Do.record(e,t),trace:t=>Do.trace(e,t)}}const ko=async(e,t={})=>{if(!e.backend.pressBack)throw new n(`UNSUPPORTED_OPERATION`,`system.back is not supported by this backend`);let r=t.mode??`in-app`;if(r!==`in-app`&&r!==`system`)throw new n(`INVALID_ARGS`,`system.back mode must be in-app or system`);let i=y(await e.backend.pressBack(v(e,t),{mode:r}));return{kind:`systemBack`,mode:r,...i?{backendResult:i}:{},...C(`Back`)}},Ao=async(e,t={})=>{if(!e.backend.pressHome)throw new n(`UNSUPPORTED_OPERATION`,`system.home is not supported by this backend`);let r=y(await e.backend.pressHome(v(e,t)));return{kind:`systemHome`,...r?{backendResult:r}:{},...C(`Home`)}},jo=async(e,t)=>{if(!e.backend.rotate)throw new n(`UNSUPPORTED_OPERATION`,`system.rotate is not supported by this backend`);let r=Lo(t.orientation),i=y(await e.backend.rotate(v(e,t),r));return{kind:`systemRotated`,orientation:r,...i?{backendResult:i}:{},...C(`Rotated to ${r}`)}},Mo=async(e,t={})=>{if(!e.backend.setKeyboard)throw new n(`UNSUPPORTED_OPERATION`,`system.keyboard is not supported by this backend`);let r=t.action??`status`;if(!Ht(r))throw new n(`INVALID_ARGS`,`system.keyboard action must be status, get, dismiss, enter, or return`);let i=await e.backend.setKeyboard(v(e,t),{action:r}),a=y(i),o=Go(i)?i:{};return r===`enter`||r===`return`?zo(o,a):r===`dismiss`?Bo(r,o,a):Vo(r,o,a)},No=async(e,t)=>{if(t.action===`read`){if(!e.backend.getClipboard)throw new n(`UNSUPPORTED_OPERATION`,`system.clipboard read is not supported by this backend`);let r=await e.backend.getClipboard(v(e,t));return{kind:`clipboardText`,action:`read`,text:typeof r==`string`?r:r.text}}if(t.action!==`write`)throw new n(`INVALID_ARGS`,`system.clipboard action must be read or write`);if(!e.backend.setClipboard)throw new n(`UNSUPPORTED_OPERATION`,`system.clipboard write is not supported by this backend`);if(typeof t.text!=`string`)throw new n(`INVALID_ARGS`,`system.clipboard write requires text`);let r=y(await e.backend.setClipboard(v(e,t),t.text));return{kind:`clipboardUpdated`,action:`write`,textLength:Array.from(t.text).length,...r?{backendResult:r}:{},...C(`Clipboard updated`)}},Po=async(e,t={})=>{if(!e.backend.openSettings)throw new n(`UNSUPPORTED_OPERATION`,`system.settings is not supported by this backend`);let r=G(t.target,`target`),i=y(await e.backend.openSettings(v(e,t),r));return{kind:`settingsOpened`,...r?{target:r}:{},...i?{backendResult:i}:{},...C(r?`Opened settings: ${r}`:`Opened settings`)}},Fo=async(e,t={})=>{if(!e.backend.handleAlert)throw new n(`UNSUPPORTED_OPERATION`,`system.alert is not supported by this backend`);let r=t.action??`get`;if(r!==`get`&&r!==`accept`&&r!==`dismiss`&&r!==`wait`)throw new n(`INVALID_ARGS`,`system.alert action must be get, accept, dismiss, or wait`);let i=t.timeoutMs===void 0?void 0:x(t.timeoutMs,`timeoutMs`,0,12e4);return Ro(r,await e.backend.handleAlert(v(e,t),r,{timeoutMs:i}))},Io=async(e,t={})=>{if(!e.backend.openAppSwitcher)throw new n(`UNSUPPORTED_OPERATION`,`system.appSwitcher is not supported by this backend`);let r=y(await e.backend.openAppSwitcher(v(e,t)));return{kind:`appSwitcherOpened`,...r?{backendResult:r}:{},...C(`Opened app switcher`)}};function Lo(e){switch(e){case`portrait`:case`portrait-upside-down`:case`landscape-left`:case`landscape-right`:return e;default:throw new n(`INVALID_ARGS`,`system.rotate orientation must be portrait, portrait-upside-down, landscape-left, or landscape-right`)}}function Ro(e,t){return e===`get`?Ho(t):e===`wait`?Uo(t):Wo(e,t)}function zo(e,t){return{kind:`keyboardEnterPressed`,action:`enter`,state:e,...t?{backendResult:t}:{},...C(`Keyboard enter pressed`)}}function Bo(e,t,n){return{kind:`keyboardDismissed`,action:e,state:t,...n?{backendResult:n}:{},...C(t.dismissed===!1?`Keyboard already hidden`:`Keyboard dismissed`)}}function Vo(e,t,n){return{kind:`keyboardState`,action:e,state:t,...n?{backendResult:n}:{}}}function Ho(e){if(e.kind!==`alertStatus`)throw new n(`COMMAND_FAILED`,`system.alert get returned an invalid backend result`);return{kind:`alertStatus`,action:`get`,alert:e.alert}}function Uo(e){if(e.kind!==`alertWait`)throw new n(`COMMAND_FAILED`,`system.alert wait returned an invalid backend result`);return{kind:`alertWait`,action:`wait`,alert:e.alert,...e.waitedMs===void 0?{}:{waitedMs:e.waitedMs},...e.timedOut===void 0?{}:{timedOut:e.timedOut},...C(e.alert?`Alert visible`:`Alert wait timed out`)}}function Wo(e,t){if(t.kind!==`alertHandled`)throw new n(`COMMAND_FAILED`,`system.alert ${e} returned an invalid backend result`);return{kind:`alertHandled`,action:e,handled:t.handled,...t.alert?{alert:t.alert}:{},...t.button?{button:t.button}:{},...C(t.handled?`Alert ${e}ed`:`No alert handled`)}}function Go(e){return!!(e&&typeof e==`object`)}const $={back:ko,home:Ao,rotate:jo,keyboard:Mo,clipboard:No,settings:Po,alert:Fo,appSwitcher:Io};function Ko(e){return{back:t=>$.back(e,t),home:t=>$.home(e,t),rotate:t=>$.rotate(e,t),keyboard:t=>$.keyboard(e,t),clipboard:t=>$.clipboard(e,t),settings:t=>$.settings(e,t),alert:t=>$.alert(e,t),appSwitcher:t=>$.appSwitcher(e,t)}}function qo(e){return{capture:Oi(e),selectors:aa(e),interactions:oa(e),system:Ko(e),apps:La(e),admin:Ra(e),recording:Oo(e),observability:go(e)}}var Jo=e({createAgentDevice:()=>Yo,createMemorySessionStore:()=>Xo,localCommandPolicy:()=>$o,restrictedCommandPolicy:()=>es});function Yo(e){let t={backend:e.backend,artifacts:e.artifacts,sessions:e.sessions??Xo(),policy:e.policy??es(),diagnostics:e.diagnostics,clock:e.clock,signal:e.signal};return{...t,...qo(t)}}function Xo(e=[]){let t=new Map(e.map(e=>[e.name,Zo(e)]));return{get:e=>Zo(t.get(e)),set:e=>{t.set(e.name,Zo(e))},delete:e=>{t.delete(e)},list:()=>Array.from(t.values(),e=>Zo(e))}}function Zo(e){if(e)return{...e,...e.snapshot?{snapshot:structuredClone(e.snapshot)}:{},...e.metadata?{metadata:Qo(e.metadata)}:{}}}function Qo(e){try{return structuredClone(e)}catch{return{...e}}}function $o(e={}){return{allowLocalInputPaths:!0,allowLocalOutputPaths:!0,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}function es(e={}){return{allowLocalInputPaths:!1,allowLocalOutputPaths:!1,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}export{on as a,Ut as c,tt as d,it as f,A as i,Ht as l,rt as m,$o as n,rn as o,at as p,Jo as r,an as s,Yo as t,nt as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AsyncLocalStorage as e}from"node:async_hooks";function t(t,n=e=>e){let r=new e;return{resolve(e){return e?n(e):r.getStore()??t},async run(e,t){return e?await r.run(n(e),t):await t()},hasScope(){return!!r.getStore()}}}export{t};
|