agent-device 0.21.18 → 0.21.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.18.apk → agent-device-android-ime-helper-0.21.20.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.20.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.18.manifest.json → agent-device-android-ime-helper-0.21.20.manifest.json} +4 -4
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.18.apk → agent-device-android-snapshot-helper-0.21.20.apk} +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.20.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.18.manifest.json → agent-device-android-snapshot-helper-0.21.20.manifest.json} +6 -6
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +12 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +1 -14
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +14 -16
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +40 -14
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +20 -5
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationProjection.swift +2 -15
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFold.swift +10 -25
- package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFoldProjection.swift +1 -18
- package/dist/src/adapter.js +1 -1
- package/dist/src/adb-executor.js +2 -2
- package/dist/src/adb-failure.js +2 -1
- package/dist/src/agent-browser-lifecycle.js +1 -1
- package/dist/src/agent-browser-process-record.js +1 -1
- package/dist/src/agent-browser-provider.js +1 -1
- package/dist/src/agent-browser-tool.js +1 -1
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/ai-sdk.js +1 -1
- package/dist/src/alert-runtime.js +1 -1
- package/dist/src/alert.js +1 -0
- package/dist/src/android-input-ownership.js +1 -1
- package/dist/src/android.js +1 -1
- package/dist/src/app-launch.js +2 -2
- package/dist/src/app-lifecycle.js +1 -1
- package/dist/src/app-log-runtime2.js +1 -1
- package/dist/src/app-resolution.js +2 -2
- package/dist/src/apple-runner-platform.js +1 -1
- package/dist/src/archive.js +2 -2
- package/dist/src/browser-launch.js +1 -1
- package/dist/src/cache.js +1 -1
- package/dist/src/catalog.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +287 -301
- package/dist/src/cli-runner.js +1 -1
- package/dist/src/cli.js +4 -4
- package/dist/src/client-metro-companion.js +1 -1
- package/dist/src/client-metro.js +1 -1
- package/dist/src/client-types.d.ts +25 -6
- package/dist/src/{scroll-command.d.ts → cloud-artifacts.d.ts} +242 -238
- package/dist/src/command-metadata.js +1 -1
- package/dist/src/command-schema.js +3 -3
- package/dist/src/command-tools.js +2 -2
- package/dist/src/command.js +1 -1
- package/dist/src/config.js +1 -1
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/contracts.js +1 -1
- package/dist/src/daemon-client-lease-beat.js +1 -1
- package/dist/src/daemon-client-lifecycle.js +1 -1
- package/dist/src/daemon-client-transport.js +1 -1
- package/dist/src/daemon-policy-file.js +1 -1
- package/dist/src/daemon-registration.js +1 -1
- package/dist/src/debug-symbols-facade.js +3 -3
- package/dist/src/device-claim-inspection.js +1 -1
- package/dist/src/device-claim-rule.js +1 -1
- package/dist/src/device-inventory-context.js +1 -1
- package/dist/src/device-rotation.js +1 -1
- package/dist/src/device-session.js +1 -1
- package/dist/src/devicectl.js +1 -1
- package/dist/src/diagnostics.js +1 -1
- package/dist/src/diagnostics2.js +1 -1
- package/dist/src/display-inventory.js +1 -1
- package/dist/src/durable-resource.js +1 -1
- package/dist/src/engine-eval-script.js +1 -1
- package/dist/src/error.js +1 -1
- package/dist/src/exec.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/generic-settle.js +1 -1
- package/dist/src/gesture-runtime.js +1 -1
- package/dist/src/hdc.js +1 -1
- package/dist/src/helper.js +2 -2
- package/dist/src/host.js +1 -1
- package/dist/src/index.d.ts +3 -3
- package/dist/src/index.js +1 -1
- package/dist/src/input-actions2.js +2 -2
- package/dist/src/install-source-network-transport.js +1 -1
- package/dist/src/interaction-positionals.js +1 -1
- package/dist/src/interaction-ref-policy.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interaction2.js +1 -1
- package/dist/src/interactor.js +5 -5
- package/dist/src/interactor2.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +2 -2
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/ios-snapshot-acquisition.js +1 -1
- package/dist/src/ios-snapshot-engine.js +1 -1
- package/dist/src/launch-confirmation.js +1 -0
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun-runtime-dependencies.js +1 -1
- package/dist/src/limrun.d.ts +50 -42
- package/dist/src/local-interactor-operation-set.js +1 -1
- package/dist/src/mechanics.js +16 -17
- package/dist/src/mobile-snapshot-semantics.js +1 -1
- package/dist/src/observe-until.js +1 -0
- package/dist/src/overlay.js +2 -2
- package/dist/src/owner-identity.js +1 -1
- package/dist/src/parameterized-recorded-fill.js +1 -1
- package/dist/src/perf-facade.js +1 -1
- package/dist/src/perf-runtime-operation-builder.js +1 -1
- package/dist/src/perf-runtime-plan.js +1 -1
- package/dist/src/perf-target.js +1 -1
- package/dist/src/physical-device-control.js +1 -1
- package/dist/src/platform-request-scope.js +1 -1
- package/dist/src/platform-runtime-android-adb-host.js +1 -1
- package/dist/src/platform-runtime-app-log-process.js +1 -1
- package/dist/src/platform-runtime-host.js +1 -1
- package/dist/src/platform-runtime-managed-owner.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +2 -2
- package/dist/src/platform-runtime-runtime-hints.js +1 -1
- package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/platform-runtime2.js +1 -1
- package/dist/src/png-worker-client.js +1 -1
- package/dist/src/provider-device-admission.js +1 -0
- package/dist/src/provider-session-ownership.js +1 -1
- package/dist/src/provider-webdriver.js +1 -1
- package/dist/src/proxy.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/registry.js +52 -36
- package/dist/src/replay-divergence.js +1 -1
- package/dist/src/replay.js +1 -1
- package/dist/src/request-admission.js +1 -1
- package/dist/src/request-runtime-binding.js +1 -1
- package/dist/src/result-serialization.js +1 -1
- package/dist/src/runner-cache-metadata.js +3 -3
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-dev-tools-security.js +1 -1
- package/dist/src/runner-device-readiness.js +1 -1
- package/dist/src/runner-disposal.js +1 -1
- package/dist/src/runner-error-classification.js +3 -3
- package/dist/src/runner-exchange.js +1 -1
- package/dist/src/runner-operations-facade.js +1 -1
- package/dist/src/runner-session-types.js +1 -1
- package/dist/src/runner-start-budget.js +1 -1
- package/dist/src/runner-startup-transport.js +1 -1
- package/dist/src/runner-xctestrun.js +1 -1
- package/dist/src/runner.js +1 -1
- package/dist/src/runtime-admission.js +1 -0
- package/dist/src/runtime.js +1 -1
- package/dist/src/runtime10.js +2 -2
- package/dist/src/runtime2.js +2 -2
- package/dist/src/runtime3.js +1 -1
- package/dist/src/runtime4.js +5 -5
- package/dist/src/runtime5.js +1 -1
- package/dist/src/runtime6.js +1 -1
- package/dist/src/runtime7.js +1 -1
- package/dist/src/runtime8.js +1 -1
- package/dist/src/runtime9.js +1 -1
- package/dist/src/screen-recording-resource-recovery.js +1 -1
- package/dist/src/screenshot-result.js +1 -1
- package/dist/src/screenshot-runtime.js +1 -1
- package/dist/src/screenshot3.js +1 -1
- package/dist/src/script.js +1 -1
- package/dist/src/scroll-gesture.js +1 -1
- package/dist/src/sdk-batch-runner.js +2 -2
- package/dist/src/sdk-batch.js +1 -1
- package/dist/src/sdk-contracts.d.ts +18 -2
- package/dist/src/sdk-contracts.js +2 -2
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-selectors.d.ts +13 -4
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selection.js +0 -0
- package/dist/src/selector-pipeline-policy.js +1 -0
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +1 -1
- package/dist/src/session-runtime-admission.js +1 -1
- package/dist/src/session-snapshot.js +1 -1
- package/dist/src/session-store.js +3 -3
- package/dist/src/session2.js +5 -5
- package/dist/src/simulator-boot.js +1 -1
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot-desktop-projection.js +1 -1
- package/dist/src/snapshot-runtime-binding.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot-state.js +1 -1
- package/dist/src/snapshot4.js +1 -1
- package/dist/src/src.js +1 -1
- package/dist/src/src7.js +1 -1
- package/dist/src/target-evidence.js +1 -1
- package/dist/src/text-entry-focus.js +1 -1
- package/dist/src/tool-provider.js +3 -3
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/tool-provider3.js +1 -1
- package/dist/src/toolchain-probe.js +1 -1
- package/dist/src/touch-runtime.js +1 -1
- package/dist/src/touch-runtime2.js +1 -0
- package/dist/src/tree.js +1 -1
- package/dist/src/type-text-runtime.js +1 -1
- package/dist/src/update-check.js +1 -1
- package/dist/src/video.js +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.18.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.18.apk.sha256 +0 -1
- package/dist/src/runner-command-traits.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{N as e,P as t,S as n,d as r,j as i,k as a,m as o,o as s,v as c}from"./sdk-contracts.js";import{C as l,p as u}from"./sdk-device.js";import{Lt as d,Mn as f,Pn as p,dr as m,fr as h,ur as ee}from"./sdk-batch.js";import{s as te}from"./session-store.js";import{c as g,i as ne,s as _,u as v}from"./target-evidence.js";import{d as y}from"./parameterized-recorded-fill.js";import{_ as re,g as ie,l as ae,r as oe,s as se}from"./overlay.js";import{r as ce}from"./diagnostics.js";import"./diagnostics2.js";import{i as le}from"./rect-center.js";import{a as b}from"./android-system-chrome.js";import{r as ue}from"./request-cancel.js";import"./request.js";import{i as de}from"./request-runtime-binding.js";import{F as fe,I as pe,M as x,f as me,i as S,j as he,m as ge,n as _e,o as C,p as w,r as T,s as E,x as D}from"./session-snapshot.js";import{n as O}from"./dispatch-resolve.js";import{s as k}from"./quality-warnings.js";import{t as A}from"./backend-snapshot-options.js";import{t as j}from"./snapshot-runtime-binding.js";function M(e){let t=i(e);return t?{ok:!0,ref:t.base,generation:t.generation}:{ok:!1,response:s(`INVALID_ARGS`,`Invalid ref "${e}" — malformed generation suffix.`,{hint:o})}}function N(e,t){if(t===`exists`)return{found:!0};if(t===`wait`)return{found:!0,waitedMs:e.waitedMs};if(t===`list`)return{action:`list`,matches:Array.isArray(e.matches)?e.matches.length:0};let n=typeof e.ref==`string`?e.ref:void 0;return t===`get_attrs`?{ref:n,action:`get attrs`}:{ref:n,action:`get text`,text:typeof e.text==`string`?e.text:``}}function P(e){return e.kind===`found`?{found:!0,...typeof e.waitedMs==`number`?{waitedMs:e.waitedMs}:{}}:e.kind===`list`?{matches:e.matches.map(e=>({ref:e.ref,node:b(e.node)}))}:{ref:e.ref,...e.kind===`text`?{text:e.text}:{},node:b(e.node)}}function F(e,t){let n=Array.isArray(e.selectorChain)?e.selectorChain:void 0,r=xe(e),i=r?.kind===`ref`?z(r.ref):void 0,a=r?.kind===`selector`?r.selector:void 0,o={...i?{ref:i}:{},...a?{selector:a}:{},...n?{selectorChain:n}:{}};if(t===`attrs`)return o;let s=typeof e.text==`string`?e.text:``;return{...o,text:s,refLabel:be(s)}}function I(e){let{target:t}=e;return{...t.kind===`ref`?{ref:z(t.ref)}:{},...t.kind===`selector`?{selector:t.selector}:{},...typeof e.text==`string`?{text:e.text}:{},node:b(e.node)}}function L(e){let{node:t,preActionNodes:n,...r}=e;return r}function ve(e){return{waitedMs:e.waitedMs,...typeof e.text==`string`?{text:e.text}:{},...typeof e.selector==`string`?{selector:e.selector}:{},...typeof e.captures==`number`?{captures:e.captures}:{},...typeof e.nodeCount==`number`?{nodeCount:e.nodeCount}:{},...typeof e.hint==`string`?{hint:e.hint}:{}}}function ye(e){let{selectorChain:t,...n}=e;return n}function R(e,t,n,r,i,a){let o=e.get(t);if(!o)return;let s=y(o)&&i?ne(i,{mode:a}):void 0;e.recordAction(o,{command:n.command,positionals:n.positionals??[],flags:n.flags??{},result:r,interactiveObservation:te(n),...s?{targetEvidence:s,targetEvidenceMode:a??`action`}:{}})}function be(e){let t=e.trim();if(!(!t||t.length>80||/[\r\n]/.test(t)))return t}function xe(e){let t=e.target;if(!t||typeof t!=`object`)return;let n=t;if(n.kind===`ref`&&typeof n.ref==`string`)return{kind:`ref`,ref:n.ref};if(n.kind===`selector`&&typeof n.selector==`string`)return{kind:`selector`,selector:n.selector}}function z(e){return e.startsWith(`@`)?e.slice(1):e}async function B(e){let t=await j({...e,plan:d({hasActiveApp:e.session?.appBundleId!==void 0,intent:Se(e.command)}),readiness:!e.session});return t.ok?{ok:!0,operations:{capture:t.capture,...t.readTextAtPoint?{readText:t.readTextAtPoint}:{},...t.findText?{findText:t.findText}:{}}}:t}function Se(e){switch(e){case`is`:return`capture-only`;case`find`:case`get`:return`element-text`;case`wait`:return`wait-observation`}}const Ce=[[`snapshotDepth`,`--depth`],[`snapshotScope`,`--scope`],[`snapshotRaw`,`--raw`]];function V(e,t){let n=Ce.filter(([e])=>t?.[e]!==void 0).map(([,e])=>e);return n.length===0?null:s(`INVALID_ARGS`,`${e} @ref does not support ${n.join(`, `)}.`)}async function H(t,n){if(t.device.platform!==`android`||!t.appBundleId||t.lease?.leaseProvider||de(t.device))return null;if(!n)throw new e(`INTERNAL_ERROR`,`Android observation was not supplied by root runtime composition`);let r=await n.readAppState(t.device),i=r.package?.trim();if(!i||i===t.appBundleId)return null;let a=await n.isPermissionPackage(i);return!Ee(i)&&!a?null:{expectedPackage:t.appBundleId,foregroundPackage:i,activity:r.activity,hint:Te(a),...a?{permissionDialog:!0}:{}}}function we(e){return e.permissionDialog?`Android permission dialog is blocking ${e.expectedPackage}`:`${e.foregroundPackage} is foreground instead of ${e.expectedPackage}`}function Te(e){return e?`Use "alert get" to inspect it, then "alert accept" or "alert dismiss" to respond.`:`Use screenshot as visual truth, then take a fresh snapshot -i before retrying.`}function Ee(e){return e===`com.android.settings`||e===`com.android.systemui`||e.includes(`launcher`)}async function De(e){let{device:t,node:n,flags:r,appBundleId:i,traceOutPath:a,surface:o,contextFromFlags:s}=e,c=ie(n),l=e.readTextAtPoint;if(!l)return c;let d=le(n.rect);if(!d||u(t)&&c&&!re(n.type??``))return c;let f=s(r,i,a),p=await l({point:d,options:{appBundleId:i,surface:o},execution:ge(f)});return p.status===`read`?p.text:(ce({level:`warn`,phase:`interaction_read_fallback`,data:{reason:Oe(p.reason),nodeRef:n.ref,surface:o,platform:t.platform}}),c)}function Oe(e){switch(e){case`no-text-at-point`:return`no_text_at_point`;default:return e}}function U(e){let{session:t,sessionStore:n,sessionName:r}=e,i=0,a,o,s=t=>(e.consumedSnapshot&&(e.consumedSnapshot.state=t.snapshot),t);return{capture:async c=>{let l=Date.now(),u=Ie(c,e.req.flags?.out),d=Me({timestamp:l,lastSnapshotAt:i,lastSnapshotResult:a,lastSnapshotCacheKey:o,session:t,request:c,cacheKey:u});if(d)return s(d);let f=Ne({session:t,timestamp:l,request:c});if(f)return i=f.createdAt,a={snapshot:f},o=u,s(a);let p=await ke({params:e,request:c});c.signal?.throwIfAborted();let m={snapshot:p};return Re({session:t,sessionStore:n,sessionName:r,snapshot:p}),i=l,a=m,o=u,s(m)}}}async function ke(e){let{params:t,request:r}=e,i=await W(t,r,r.snapshotScope);return r.recovery?.legacyIosSparse&&ae(i)?n(i,await Ae({runtimeParams:t,request:r,policy:r.recovery.legacyIosSparse})):r.recovery?.sparseVerdictQueryScope?.shouldScope&&k(i.snapshotQuality)?n(i,await je({runtimeParams:t,request:r,policy:r.recovery.sparseVerdictQueryScope,snapshot:i})):i}async function Ae(e){let{runtimeParams:t,request:n,policy:r}=e;try{return await W(t,n,void 0,!1)}catch(e){if(!r.shouldScope)throw e;return await W(t,n,r.query,!1)}}async function je(e){let{runtimeParams:t,request:n,policy:r,snapshot:i}=e;try{return await W(t,n,r.query,!1)}catch{return i}}async function W(e,t,n,r=t.flags?.snapshotInteractiveOnly){let i={...t.flags,snapshotInteractiveOnly:r},a=e.capture,o=await E({device:e.device,session:e.session,flags:i,outPath:t.outPath??e.req.flags?.out,logPath:e.logPath??``,snapshotScope:n,includeRects:t.includeRects,signal:t.signal,captureData:async()=>await a(w({flags:i,logPath:e.logPath??``,meta:e.req.meta,session:e.session,snapshotScope:n,includeRects:t.includeRects,signal:t.signal}))});return _(e.captureProof,o.snapshot)}function Me(e){let{timestamp:t,lastSnapshotAt:n,lastSnapshotResult:r,lastSnapshotCacheKey:i,session:a,request:o,cacheKey:s}=e;if(o.cache?.forceFresh!==!0&&r&&i===s&&!(t-n>=750)&&!x(a)&&!G(a,o))return r}function Ne(e){let{session:t,timestamp:n,request:r}=e,i=t?.snapshot;if(!(!i||fe(i))&&Pe(t,r)&&Fe(i,n)&&i.presentationKey===K(r))return i}function Pe(e,t){return t.cache?.forceFresh===!0||t.cache?.useSessionSnapshot!==!0||x(e)||G(e,t)?!1:e.snapshot?.postGestureOutcome?.kind!==`unsettled`}function Fe(e,t){return t-e.createdAt<750}function G(e,t){return t.cache?.bypassForPostGestureStabilization===!0&&D(e)}function K(e){return c(a(Le(e)))}function Ie(e,t){return JSON.stringify({presentationKey:K(e),includeRects:e.includeRects===!0,outPath:e.outPath??t??null})}function Le(e){return e.snapshotScope===void 0?e.flags:{...e.flags,snapshotScope:e.snapshotScope}}function Re(e){let{session:t,sessionStore:n,sessionName:r,snapshot:i}=e;!t||k(i.snapshotQuality)||(S(t,i),n.set(r,t))}function q(e){return me({backend:Be(e),...v(`selector commands`,{plural:!0}),sessions:C({sessionName:e.sessionName,getSession:()=>e.session,recordOptions:{includeSnapshot:!0},setRecord:t=>{!e.session||!t.snapshot||(S(e.session,t.snapshot),e.sessionStore.set(e.sessionName,e.session))}}),signal:e.signal??ue(e.req.meta?.requestId)})}async function ze(e,t){e.consumedSnapshot??={},e.captureProof??={};let n=e.sessionStore.get(e.sessionName);return!n&&t?{ok:!1,response:r()}:{ok:!0,session:n,device:n?.device??await O(e.req.flags??{})}}async function J(e,t){let n=await ze(e,t.requireSession);if(!n.ok)return n;let r=await B({command:t.command,device:n.device,session:n.session,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});return r.ok?{ok:!0,runtime:q({...e,session:n.session,device:n.device,bound:r.operations})}:{ok:!1,response:r.response}}function Be(e){let{req:t,session:n,device:r,logPath:i,sessionName:a,sessionStore:o}=e,s=e.contextFromFlags??((e,t,n)=>he(i??``,e,t,n)),c=e.bound?.readText,u=e.bound?.findText,d=w({flags:t.flags,logPath:i??``,meta:t.meta,session:n,snapshotScope:void 0}).execution,f=e.bound,p=f===void 0?void 0:U({device:r,session:n,sessionStore:o,sessionName:a,req:t,consumedSnapshot:e.consumedSnapshot,captureProof:e.captureProof,logPath:i,capture:f.capture});return{platform:l(r),captureSnapshot:p&&(async(e,n)=>{let i={...t.flags,...A(n)},a=n?.includeRects===!0,o=n?.scope??t.flags?.snapshotScope,s=t.command===`wait`||t.command===`find`||Ve(t)||a&&r.platform===`web`;return await p.capture({flags:i,signal:e.signal,snapshotScope:o,includeRects:a,cache:{forceFresh:s,useSessionSnapshot:!0,bypassForPostGestureStabilization:!0}})}),readText:async(e,i)=>({text:await De({readTextAtPoint:c,device:r,node:i,flags:t.flags,appBundleId:n?.appBundleId,traceOutPath:n?.trace?.outPath,surface:n?.surface,contextFromFlags:s})}),...u?{findText:async(e,t)=>{let{found:r}=await u({text:t,options:{appBundleId:n?.appBundleId,surface:n?.surface},execution:d,...e.signal?{signal:e.signal}:{}});return n&&pe(n),{found:r}}}:{}}}function Ve(e){if(e.command!==`is`)return!1;let t=h(e.positionals??[]);return t.ok&&t.predicate===`absent`}async function Y(e){let{req:t}=e;if(t.command!==`find`)return null;let n=t.positionals??[],r=f(n,t.flags);if(!r.ok)return s(r.code,r.message);let i=r.parsed,a=i.action;if(!p(a))return null;let o=await J(e,{requireSession:!1,command:`find`});if(!o.ok)return o.response;let c=await Q(async()=>{let n=await o.runtime.selectors.find({session:e.sessionName,requestId:t.meta?.requestId,locator:i.locator,query:i.query,action:a,timeoutMs:i.timeoutMs});R(e.sessionStore,e.sessionName,t,N(n,a));let r=P(n),s=typeof r.ref==`string`?[r.ref]:Array.isArray(r.matches)?r.matches.map(e=>e.ref).filter(e=>typeof e==`string`):[];if(s.length>0){let t=e.sessionStore.get(e.sessionName);if(t&&(_e(t,s),e.sessionStore.set(e.sessionName,t),t.snapshotGeneration!==void 0))return{...r,refsGeneration:t.snapshotGeneration}}return r});return g({response:c,consumedTree:X(e),captureProof:e.captureProof})}function X(e){return e.consumedSnapshot?.state??e.sessionStore.get(e.sessionName)?.snapshot}async function He(e){let{req:t}=e;if(t.command!==`get`)return null;let n=m(t.positionals?.[0]);if(!n.ok)return s(n.code,n.message);let r=n.format,i=We(t);if(!i.ok)return i.response;if(i.target.kind===`ref`){let e=V(`get`,t.flags);if(e)return e}let a=t.internal?.replayTargetGuard,o=await J(e,{requireSession:!0,command:`get`});if(!o.ok)return o.response;let c=o.runtime,l=i.target.kind===`ref`?T({session:e.sessionStore.get(e.sessionName),ref:i.target.ref,mintedGeneration:i.refGeneration}):void 0,u=await Q(async()=>{let n=await c.selectors.get({session:e.sessionName,requestId:t.meta?.requestId,property:r,target:i.target,expectedResolvedTarget:a});R(e.sessionStore,e.sessionName,t,F(n,r),{node:n.node,preActionNodes:n.preActionNodes});let o=I(n);return l?{...o,warning:l}:o});return g({response:u,consumedTree:X(e),captureProof:e.captureProof})}async function Ue(e){let{req:t}=e;if(t.command!==`is`)return null;let n=h(t.positionals??[]);if(!n.ok)return s(n.code,n.message,n.hint?{hint:n.hint}:void 0);let{predicate:r,selectorExpression:i,expectedText:a}=n;if(r===`absent`){let e=se({depth:t.flags?.snapshotDepth,scope:t.flags?.snapshotScope});if(e){let t=oe(e);return s(t.code,t.message,t.details)}}let o=t.internal?.replayTargetGuard,c=await J(e,{requireSession:!0,command:`is`});if(!c.ok)return c.response;let l=await Q(async()=>{let n=await c.runtime.selectors.is({session:e.sessionName,requestId:t.meta?.requestId,predicate:r,selector:i,expectedText:a,expectedResolvedTarget:o}),s=Z(n),l=L(n);return R(e.sessionStore,e.sessionName,t,l,s),ye(l)});return g({response:await $(e,l,`is ${r}`),consumedTree:X(e),captureProof:e.captureProof})}function Z(e){let t=e.node,n=e.preActionNodes;if(!(!t||typeof t!=`object`||!Array.isArray(n)))return{node:t,preActionNodes:n}}function We(e){let t=e.positionals?.[1]??``;if(t.startsWith(`@`)){let n=M(t);return n.ok?{ok:!0,target:{kind:`ref`,ref:n.ref,fallbackLabel:e.positionals.length>2?e.positionals.slice(2).join(` `).trim():``},refGeneration:n.generation}:{ok:!1,response:n.response}}let n=ee(e.positionals?.slice(1)??[]);return n.ok?{ok:!0,target:{kind:`selector`,selector:`selector`in n?n.selector:``}}:{ok:!1,response:s(n.code,n.message)}}async function Q(e){try{return{ok:!0,data:await e()}}catch(e){let n=t(e);return s(n.code,n.message,n.details)}}async function $(e,t,n){if(t.ok)return t;let r=e.sessionStore.get(e.sessionName);if(!r)return t;let i;try{if(!e.androidObservation)return t;i=await H(r,e.androidObservation)}catch{return t}return i?s(t.error.code,`${n} failed because ${we(i)}.`,{...t.error.details??{},...i,blockedBy:`android_foreground_surface`,originalMessage:t.error.message}):t}export{$ as a,q as c,V as d,B as f,M as g,ve as h,Ue as i,U as l,L as m,Y as n,Z as o,R as p,He as r,Q as s,X as t,H as u};
|
|
1
|
+
import{N as e,P as t,S as n,d as r,j as i,k as a,m as o,o as s,v as c}from"./sdk-contracts.js";import{C as l,p as u}from"./sdk-device.js";import{Fn as d,Nn as f,Rt as p,dr as m,fr as ee,pr as h}from"./sdk-batch.js";import{s as te}from"./session-store.js";import{c as g,i as ne,s as re,u as _}from"./target-evidence.js";import{d as v}from"./parameterized-recorded-fill.js";import{_ as ie,g as ae,l as oe,r as se,s as ce}from"./overlay.js";import{r as le}from"./diagnostics.js";import"./diagnostics2.js";import{i as ue}from"./rect-center.js";import{a as y}from"./android-system-chrome.js";import{r as de}from"./request-cancel.js";import"./request.js";import{n as fe}from"./provider-device-admission.js";import{A as pe,E as b,d as x,f as me,g as he,h as ge,i as S,k as _e,n as C,o as w,r as T,s as E,u as D}from"./session-snapshot.js";import{n as O}from"./dispatch-resolve.js";import{s as k}from"./quality-warnings.js";import{t as A}from"./backend-snapshot-options.js";import{t as j}from"./snapshot-runtime-binding.js";function M(e){let t=i(e);return t?{ok:!0,ref:t.base,generation:t.generation}:{ok:!1,response:s(`INVALID_ARGS`,`Invalid ref "${e}" — malformed generation suffix.`,{hint:o})}}function N(e,t){if(t===`exists`)return{found:!0};if(t===`wait`)return{found:!0,waitedMs:e.waitedMs};if(t===`list`)return{action:`list`,matches:Array.isArray(e.matches)?e.matches.length:0};let n=typeof e.ref==`string`?e.ref:void 0;return t===`get_attrs`?{ref:n,action:`get attrs`}:{ref:n,action:`get text`,text:typeof e.text==`string`?e.text:``}}function P(e){return e.kind===`found`?{found:!0,...typeof e.waitedMs==`number`?{waitedMs:e.waitedMs}:{}}:e.kind===`list`?{matches:e.matches.map(e=>({ref:e.ref,node:y(e.node)}))}:{ref:e.ref,...e.kind===`text`?{text:e.text}:{},node:y(e.node)}}function F(e,t){let n=Array.isArray(e.selectorChain)?e.selectorChain:void 0,r=xe(e),i=r?.kind===`ref`?z(r.ref):void 0,a=r?.kind===`selector`?r.selector:void 0,o={...i?{ref:i}:{},...a?{selector:a}:{},...n?{selectorChain:n}:{}};if(t===`attrs`)return o;let s=typeof e.text==`string`?e.text:``;return{...o,text:s,refLabel:be(s)}}function I(e){let{target:t}=e;return{...t.kind===`ref`?{ref:z(t.ref)}:{},...t.kind===`selector`?{selector:t.selector}:{},...typeof e.text==`string`?{text:e.text}:{},node:y(e.node)}}function L(e){let{node:t,preActionNodes:n,...r}=e;return r}function ve(e){return{waitedMs:e.waitedMs,...typeof e.text==`string`?{text:e.text}:{},...typeof e.selector==`string`?{selector:e.selector}:{},...typeof e.captures==`number`?{captures:e.captures}:{},...typeof e.nodeCount==`number`?{nodeCount:e.nodeCount}:{},...typeof e.hint==`string`?{hint:e.hint}:{}}}function ye(e){let{selectorChain:t,...n}=e;return n}function R(e,t,n,r,i,a){let o=e.get(t);if(!o)return;let s=v(o)&&i?ne(i,{mode:a}):void 0;e.recordAction(o,{command:n.command,positionals:n.positionals??[],flags:n.flags??{},result:r,interactiveObservation:te(n),...s?{targetEvidence:s,targetEvidenceMode:a??`action`}:{}})}function be(e){let t=e.trim();if(!(!t||t.length>80||/[\r\n]/.test(t)))return t}function xe(e){let t=e.target;if(!t||typeof t!=`object`)return;let n=t;if(n.kind===`ref`&&typeof n.ref==`string`)return{kind:`ref`,ref:n.ref};if(n.kind===`selector`&&typeof n.selector==`string`)return{kind:`selector`,selector:n.selector}}function z(e){return e.startsWith(`@`)?e.slice(1):e}async function B(e){let t=await j({...e,plan:p({hasActiveApp:e.session?.appBundleId!==void 0,intent:Se(e.command)}),readiness:!e.session});return t.ok?{ok:!0,operations:{capture:t.capture,...t.readTextAtPoint?{readText:t.readTextAtPoint}:{},...t.findText?{findText:t.findText}:{}}}:t}function Se(e){switch(e){case`is`:return`capture-only`;case`find`:case`get`:return`element-text`;case`wait`:return`wait-observation`}}const Ce=[[`snapshotDepth`,`--depth`],[`snapshotScope`,`--scope`],[`snapshotRaw`,`--raw`]];function V(e,t){let n=Ce.filter(([e])=>t?.[e]!==void 0).map(([,e])=>e);return n.length===0?null:s(`INVALID_ARGS`,`${e} @ref does not support ${n.join(`, `)}.`)}async function H(t,n){if(t.device.platform!==`android`||!t.appBundleId||t.lease?.leaseProvider||fe(t.device))return null;if(!n)throw new e(`INTERNAL_ERROR`,`Android observation was not supplied by root runtime composition`);let r=await n.readAppState(t.device),i=r.package?.trim();if(!i||i===t.appBundleId)return null;let a=await n.isPermissionPackage(i);return!Ee(i)&&!a?null:{expectedPackage:t.appBundleId,foregroundPackage:i,activity:r.activity,hint:Te(a),...a?{permissionDialog:!0}:{}}}function we(e){return e.permissionDialog?`Android permission dialog is blocking ${e.expectedPackage}`:`${e.foregroundPackage} is foreground instead of ${e.expectedPackage}`}function Te(e){return e?`Use "alert get" to inspect it, then "alert accept" or "alert dismiss" to respond.`:`Use screenshot as visual truth, then take a fresh snapshot -i before retrying.`}function Ee(e){return e===`com.android.settings`||e===`com.android.systemui`||e.includes(`launcher`)}async function De(e){let{device:t,node:n,flags:r,appBundleId:i,traceOutPath:a,surface:o,contextFromFlags:s}=e,c=ae(n),l=e.readTextAtPoint;if(!l)return c;let d=ue(n.rect);if(!d||u(t)&&c&&!ie(n.type??``))return c;let f=s(r,i,a),p=await l({point:d,options:{appBundleId:i,surface:o},execution:me(f)});return p.status===`read`?p.text:(le({level:`warn`,phase:`interaction_read_fallback`,data:{reason:Oe(p.reason),nodeRef:n.ref,surface:o,platform:t.platform}}),c)}function Oe(e){switch(e){case`no-text-at-point`:return`no_text_at_point`;default:return e}}function U(e){let{session:t,sessionStore:n,sessionName:r}=e,i=0,a,o,s=t=>(e.consumedSnapshot&&(e.consumedSnapshot.state=t.snapshot),t);return{capture:async c=>{let l=Date.now(),u=Ie(c,e.req.flags?.out),d=Me({timestamp:l,lastSnapshotAt:i,lastSnapshotResult:a,lastSnapshotCacheKey:o,session:t,request:c,cacheKey:u});if(d)return s(d);let f=Ne({session:t,timestamp:l,request:c});if(f)return i=f.createdAt,a={snapshot:f},o=u,s(a);let p=await ke({params:e,request:c});c.signal?.throwIfAborted();let m={snapshot:p};return Re({session:t,sessionStore:n,sessionName:r,snapshot:p}),i=l,a=m,o=u,s(m)}}}async function ke(e){let{params:t,request:r}=e,i=await W(t,r,r.snapshotScope);return r.recovery?.legacyIosSparse&&oe(i)?n(i,await Ae({runtimeParams:t,request:r,policy:r.recovery.legacyIosSparse})):r.recovery?.sparseVerdictQueryScope?.shouldScope&&k(i.snapshotQuality)?n(i,await je({runtimeParams:t,request:r,policy:r.recovery.sparseVerdictQueryScope,snapshot:i})):i}async function Ae(e){let{runtimeParams:t,request:n,policy:r}=e;try{return await W(t,n,void 0,!1)}catch(e){if(!r.shouldScope)throw e;return await W(t,n,r.query,!1)}}async function je(e){let{runtimeParams:t,request:n,policy:r,snapshot:i}=e;try{return await W(t,n,r.query,!1)}catch{return i}}async function W(e,t,n,r=t.flags?.snapshotInteractiveOnly){let i={...t.flags,snapshotInteractiveOnly:r},a=e.capture,o=await E({device:e.device,session:e.session,flags:i,outPath:t.outPath??e.req.flags?.out,logPath:e.logPath??``,snapshotScope:n,includeRects:t.includeRects,signal:t.signal,captureData:async()=>await a(x({flags:i,logPath:e.logPath??``,meta:e.req.meta,session:e.session,snapshotScope:n,includeRects:t.includeRects,signal:t.signal}))});return re(e.captureProof,o.snapshot)}function Me(e){let{timestamp:t,lastSnapshotAt:n,lastSnapshotResult:r,lastSnapshotCacheKey:i,session:a,request:o,cacheKey:s}=e;if(o.cache?.forceFresh!==!0&&r&&i===s&&!(t-n>=750)&&!b(a)&&!G(a,o))return r}function Ne(e){let{session:t,timestamp:n,request:r}=e,i=t?.snapshot;if(!(!i||_e(i))&&Pe(t,r)&&Fe(i,n)&&i.presentationKey===K(r))return i}function Pe(e,t){return t.cache?.forceFresh===!0||t.cache?.useSessionSnapshot!==!0||b(e)||G(e,t)?!1:e.snapshot?.postGestureOutcome?.kind!==`unsettled`}function Fe(e,t){return t-e.createdAt<750}function G(e,t){return t.cache?.bypassForPostGestureStabilization===!0&&he(e)}function K(e){return c(a(Le(e)))}function Ie(e,t){return JSON.stringify({presentationKey:K(e),includeRects:e.includeRects===!0,outPath:e.outPath??t??null})}function Le(e){return e.snapshotScope===void 0?e.flags:{...e.flags,snapshotScope:e.snapshotScope}}function Re(e){let{session:t,sessionStore:n,sessionName:r,snapshot:i}=e;!t||k(i.snapshotQuality)||(S(t,i),n.set(r,t))}function q(e){return D({backend:Be(e),..._(`selector commands`,{plural:!0}),sessions:w({sessionName:e.sessionName,getSession:()=>e.session,recordOptions:{includeSnapshot:!0},setRecord:t=>{!e.session||!t.snapshot||(S(e.session,t.snapshot),e.sessionStore.set(e.sessionName,e.session))}}),signal:e.signal??de(e.req.meta?.requestId)})}async function ze(e,t){e.consumedSnapshot??={},e.captureProof??={};let n=e.sessionStore.get(e.sessionName);return!n&&t?{ok:!1,response:r()}:{ok:!0,session:n,device:n?.device??await O(e.req.flags??{})}}async function J(e,t){let n=await ze(e,t.requireSession);if(!n.ok)return n;let r=await B({command:t.command,device:n.device,session:n.session,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});return r.ok?{ok:!0,runtime:q({...e,session:n.session,device:n.device,bound:r.operations})}:{ok:!1,response:r.response}}function Be(e){let{req:t,session:n,device:r,logPath:i,sessionName:a,sessionStore:o}=e,s=e.contextFromFlags??((e,t,n)=>ge(i??``,e,t,n)),c=e.bound?.readText,u=e.bound?.findText,d=x({flags:t.flags,logPath:i??``,meta:t.meta,session:n,snapshotScope:void 0}).execution,f=e.bound,p=f===void 0?void 0:U({device:r,session:n,sessionStore:o,sessionName:a,req:t,consumedSnapshot:e.consumedSnapshot,captureProof:e.captureProof,logPath:i,capture:f.capture});return{platform:l(r),captureSnapshot:p&&(async(e,n)=>{let i={...t.flags,...A(n)},a=n?.includeRects===!0,o=n?.scope??t.flags?.snapshotScope,s=t.command===`wait`||t.command===`find`||Ve(t)||a&&r.platform===`web`;return await p.capture({flags:i,signal:e.signal,snapshotScope:o,includeRects:a,cache:{forceFresh:s,useSessionSnapshot:!0,bypassForPostGestureStabilization:!0}})}),readText:async(e,i)=>({text:await De({readTextAtPoint:c,device:r,node:i,flags:t.flags,appBundleId:n?.appBundleId,traceOutPath:n?.trace?.outPath,surface:n?.surface,contextFromFlags:s})}),...u?{findText:async(e,t)=>{let{found:r}=await u({text:t,options:{appBundleId:n?.appBundleId,surface:n?.surface},execution:d,...e.signal?{signal:e.signal}:{}});return n&&pe(n),{found:r}}}:{}}}function Ve(e){if(e.command!==`is`)return!1;let t=h(e.positionals??[]);return t.ok&&t.predicate===`absent`}async function Y(e){let{req:t}=e;if(t.command!==`find`)return null;let n=t.positionals??[],r=f(n,t.flags);if(!r.ok)return s(r.code,r.message);let i=r.parsed,a=i.action;if(!d(a))return null;let o=await J(e,{requireSession:!1,command:`find`});if(!o.ok)return o.response;let c=await Q(async()=>{let n=await o.runtime.selectors.find({session:e.sessionName,requestId:t.meta?.requestId,locator:i.locator,query:i.query,action:a,timeoutMs:i.timeoutMs});R(e.sessionStore,e.sessionName,t,N(n,a));let r=P(n),s=typeof r.ref==`string`?[r.ref]:Array.isArray(r.matches)?r.matches.map(e=>e.ref).filter(e=>typeof e==`string`):[];if(s.length>0){let t=e.sessionStore.get(e.sessionName);if(t&&(C(t,s),e.sessionStore.set(e.sessionName,t),t.snapshotGeneration!==void 0))return{...r,refsGeneration:t.snapshotGeneration}}return r});return g({response:c,consumedTree:X(e),captureProof:e.captureProof})}function X(e){return e.consumedSnapshot?.state??e.sessionStore.get(e.sessionName)?.snapshot}async function He(e){let{req:t}=e;if(t.command!==`get`)return null;let n=ee(t.positionals?.[0]);if(!n.ok)return s(n.code,n.message);let r=n.format,i=We(t);if(!i.ok)return i.response;if(i.target.kind===`ref`){let e=V(`get`,t.flags);if(e)return e}let a=t.internal?.replayTargetGuard,o=await J(e,{requireSession:!0,command:`get`});if(!o.ok)return o.response;let c=o.runtime,l=i.target.kind===`ref`?T({session:e.sessionStore.get(e.sessionName),ref:i.target.ref,mintedGeneration:i.refGeneration}):void 0,u=await Q(async()=>{let n=await c.selectors.get({session:e.sessionName,requestId:t.meta?.requestId,property:r,target:i.target,expectedResolvedTarget:a});R(e.sessionStore,e.sessionName,t,F(n,r),{node:n.node,preActionNodes:n.preActionNodes});let o=I(n);return l?{...o,warning:l}:o});return g({response:u,consumedTree:X(e),captureProof:e.captureProof})}async function Ue(e){let{req:t}=e;if(t.command!==`is`)return null;let n=h(t.positionals??[]);if(!n.ok)return s(n.code,n.message,n.hint?{hint:n.hint}:void 0);let{predicate:r,selectorExpression:i,expectedText:a}=n;if(r===`absent`){let e=ce({depth:t.flags?.snapshotDepth,scope:t.flags?.snapshotScope});if(e){let t=se(e);return s(t.code,t.message,t.details)}}let o=t.internal?.replayTargetGuard,c=await J(e,{requireSession:!0,command:`is`});if(!c.ok)return c.response;let l=await Q(async()=>{let n=await c.runtime.selectors.is({session:e.sessionName,requestId:t.meta?.requestId,predicate:r,selector:i,expectedText:a,expectedResolvedTarget:o}),s=Z(n),l=L(n);return R(e.sessionStore,e.sessionName,t,l,s),ye(l)});return g({response:await $(e,l,`is ${r}`),consumedTree:X(e),captureProof:e.captureProof})}function Z(e){let t=e.node,n=e.preActionNodes;if(!(!t||typeof t!=`object`||!Array.isArray(n)))return{node:t,preActionNodes:n}}function We(e){let t=e.positionals?.[1]??``;if(t.startsWith(`@`)){let n=M(t);return n.ok?{ok:!0,target:{kind:`ref`,ref:n.ref,fallbackLabel:e.positionals.length>2?e.positionals.slice(2).join(` `).trim():``},refGeneration:n.generation}:{ok:!1,response:n.response}}let n=m(e.positionals?.slice(1)??[]);return n.ok?{ok:!0,target:{kind:`selector`,selector:`selector`in n?n.selector:``}}:{ok:!1,response:s(n.code,n.message)}}async function Q(e){try{return{ok:!0,data:await e()}}catch(e){let n=t(e);return s(n.code,n.message,n.details)}}async function $(e,t,n){if(t.ok)return t;let r=e.sessionStore.get(e.sessionName);if(!r)return t;let i;try{if(!e.androidObservation)return t;i=await H(r,e.androidObservation)}catch{return t}return i?s(t.error.code,`${n} failed because ${we(i)}.`,{...t.error.details??{},...i,blockedBy:`android_foreground_surface`,originalMessage:t.error.message}):t}export{$ as a,q as c,V as d,B as f,M as g,ve as h,Ue as i,U as l,L as m,Y as n,Z as o,R as p,He as r,Q as s,X as t,H as u};
|
package/dist/src/selectors.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Dn as e,Er as t,Sr as n,Tr as r,wn as i,wr as a,xr as o}from"./sdk-batch.js";import{t as s}from"./sdk-selectors.js";export{i as findSelectorChainMatch,s as formatSelectorFailure,r as isNodeEditable,t as isNodeVisible,o as isSelectorToken,n as parseSelectorChain,e as resolveSelectorChain,a as tryParseSelectorChain};
|
package/dist/src/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{N as e,l as t}from"./sdk-contracts.js";import{
|
|
1
|
+
import{N as e,l as t}from"./sdk-contracts.js";import{v as n}from"./sdk-batch.js";import{i as r}from"./catalog.js";import{a as i}from"./version.js";import{a,i as ee,r as o,t as te}from"./command-tools.js";import{i as s,r as c,t as l}from"./cli-help.js";const u=`agent-device drives iOS, Android, tvOS, Android TV, macOS, Linux, and web apps. Tools mirror CLI commands of the same name; CLI flags are camelCase properties (--settle -> settle: true).
|
|
2
2
|
|
|
3
3
|
Start: known app -> call open {app, foreground: true} at once; do not probe with devices, apps, appstate, snapshot, or screenshot first. open returns the initial interactive snapshot with @refs. Unknown app id: devices, then apps, then open the discovered id; never invent ids. Existing session: continue from its state, do not reopen.
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{N as e}from"./sdk-contracts.js";import{
|
|
1
|
+
import{N as e}from"./sdk-contracts.js";import{i as t}from"./runtime-admission.js";function n(e,n){return n.available?void 0:t(e,n)}function r(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Device runtime facts inspection is unavailable.`)}const i=new WeakMap;let a;(class e{static{a=(t,n)=>{let r=new e;return i.set(r,{device:Object.freeze({...t}),plan:n}),Object.freeze(r),r}}#e;constructor(){this.#e=void 0}get admitted(){return this.#e,!0}});function o(t){let n=i.get(t);if(n===void 0)throw new e(`COMMAND_FAILED`,`Runtime plan admission is not one minted by admitRuntimePlan; refusing to bind.`);return n}async function s(e){let t=await r(e.inspectFacts)(e.device);for(let n of e.plan.use.required){let e=t.operations[n];if(!e.available)return{admitted:!1,operation:n,fact:e}}return a(e.device,e.plan)}function c(t){if(t)return t;throw new e(`COMMAND_FAILED`,`Device runtime binding is unavailable.`)}export{o as a,n as i,c as n,r,s as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{E as e,N as t,O as n,b as r,h as i,o as a}from"./sdk-contracts.js";import{u as o}from"./capture.js";import{r as s}from"./snapshot-capture-annotations.js";import{r as c}from"./snapshot-diagnostics.js";import{f as l}from"./android-input-ownership.js";import{C as u,d,h as f}from"./sdk-device.js";import{Ar as ee,Bt as te,Sn as ne,Tt as re,Wt as ie,ct as ae,dt as oe,ht as se,lt as ce,ut as le,xt as ue}from"./sdk-batch.js";import{M as de,a as fe,d as pe,j as me,k as he,o as ge,t as _e,w as ve}from"./runtime.js";import{r as p}from"./success-text.js";import{h as ye,o as m}from"./overlay.js";import{i as h}from"./click-button.js";import{a as be,r as g}from"./diagnostics.js";import{t as _}from"./timeouts.js";import"./diagnostics2.js";import"./retry.js";import{t as xe}from"./snapshot-state.js";import{n as Se}from"./request-runtime-binding.js";import{i as Ce}from"./lease-context.js";import{t as we}from"./interactor-types.js";import{randomInt as Te}from"node:crypto";let v={resolve:async()=>{throw new t(`COMMAND_FAILED`,`Interactor resolution is not composed for this process.`,{reason:`interactor-resolution-missing`})}};function Ee(e){v=e}function De(){return v}var y=class e{#e;constructor(e){this.#e=e}get state(){return this.#e.state}get scope(){return this.#e.scope}get tree(){return this.#e.tree}get generation(){return this.#e.generation}static expire(t){return t.#e.state===`expired`?t:new e({...t.#e,state:`expired`})}};const Oe=new y({state:`active`,scope:`all`,tree:void 0,generation:void 0});function ke(e){return new y({state:`active`,...e})}function Ae(e){return y.expire(e)}const b=new WeakMap,x=new WeakSet;function S(e){return e.refFrame??Oe}function C(e){return S(e).generation??e.snapshotGeneration}function je(e){return S(e).tree}function Me(e){Pe(e),w(e),e.refFrame=Ae(S(e)),e.snapshotScopeSource=void 0}function w(e){e.snapshot&&x.add(e.snapshot)}function Ne(e){return x.has(e)}function Pe(e){let t=T(e)+1;return b.set(e,t),t}function T(e){return b.get(e)??0}function Fe(e){E(e,`all`)}function Ie(e,t){E(e,t)}function E(e,t){e.refFrame=ke({scope:t,tree:e.snapshot,generation:e.snapshotGeneration})}function D(e){return S(e).state}function O(e){return S(e).scope}function Le(e){let t=e.ref.startsWith(`@`)?e.ref.slice(1):e.ref;return{admission:Re({session:e.session,refBody:t,mintedGeneration:e.mintedGeneration}),scope:O(e.session),currentGeneration:C(e.session)}}function Re(e){let{session:t,refBody:n,mintedGeneration:r}=e;if(D(t)===`expired`)return{admitted:!1,reason:`ref_frame_expired`};if(r!==void 0&&r!==C(t))return{admitted:!1,reason:`ref_generation_mismatch`};let i=O(t);if(i!==`all`){if(r===void 0)return{admitted:!1,reason:`plain_ref_requires_complete_frame`};if(!i.has(n))return{admitted:!1,reason:`ref_not_issued`}}return{admitted:!0}}const ze=[250,400,600];function k(e){return e===`press`||e===`click`||e===`back`||e===`open`}function A(e){return e.map(e=>[e.depth??0,e.type??``,e.label??``,e.value??``,e.identifier??``,e.enabled===!1?`disabled`:`enabled`,e.hittable===!0?`hittable`:`not-hittable`].join(`|`))}function Be(e,t){return e<12?!1:t<=Math.floor(e*.2)}function Ve(e,t,n){return n.interactiveOnly&&e.snapshot.nodes.length===0&&e.rawNodeCount!==void 0&&e.rawNodeCount>=12?`empty-interactive`:n.mode===`ref-refresh`?null:Be(t.baselineCount,e.snapshot.nodes.length)?He(e.snapshot)?null:`sharp-drop`:t.routeComparable&&k(t.action)&&Ue(t.baselineSignatures,e.snapshot.nodes)?`stuck-route`:null}function He(e){return e.nodes.some(e=>e.hittable===!0||!!e.label?.trim()||!!e.value?.trim()||!!e.identifier?.trim())}function Ue(e,t){if(!e||e.length===0)return!1;let n=Math.max(e.length,t.length);if(n<12)return!1;let r=A(t),i=Math.min(e.length,r.length),a=0;for(let t=0;t<i;t+=1)e[t]===r[t]&&(a+=1);let o=Math.max(0,r.length-e.length),s=Math.max(0,e.length-r.length),c=Math.max(3,Math.floor(n*.15));return a>=Math.floor(n*.9)&&o<=c&&s<=c}async function We(e){let t=e.window.markedAt+e.retry.retryBudgetMs,n=await e.capture(),r=e.classify(n),i=0;for(let a of e.retry.delaysMs){if(!r)break;let o=t-Date.now();if(o<=0)break;await _(Math.min(a,o)),n=await e.capture(),i+=1,r=e.classify(n)}r||e.onTrustworthyCapture?.();let a=i>0||r?{action:e.window.action,retryCount:i,staleAfterRetries:!!r,reason:r??void 0}:void 0;return{...n,annotations:{...n.annotations,...s({freshness:a})}}}function Ge(e,t,n=e.snapshot){if(e.device.platform!==`android`)return;let r=Ke(e,n),i=r?.comparisonSafe===!0;e.androidSnapshotFreshness={action:t,markedAt:Date.now(),baselineCount:(r??n)?.nodes.length??0,baselineSignatures:i?A(r?.nodes??[]):void 0,routeComparable:i}}function Ke(e,t){if(t?.comparisonSafe===!0)return t;let n=e.lastComparisonSafeSnapshot;return!n||n.comparisonSafe!==!0?t:Date.now()-n.createdAt<=5e3?n:t}function j(e){if(!e||e.device.platform!==`android`)return;let t=e.androidSnapshotFreshness;if(t){if(Date.now()-t.markedAt>2500){delete e.androidSnapshotFreshness;return}return t}}function M(e){!e||e.device.platform!==`android`||delete e.androidSnapshotFreshness}async function N(e,t){return We({capture:e.capture,classify:n=>Ve({snapshot:n.snapshot,rawNodeCount:n.annotations.analysis?.rawNodeCount},t,{interactiveOnly:e.interactiveOnly,mode:e.androidFreshnessMode}),window:t,retry:{retryBudgetMs:1500,delaysMs:ze},onTrustworthyCapture:()=>M(e.session)})}const qe=`activity.launchConsole.launchArgs.clearAppState.verbose.iosXctestrunFile.iosXctestDerivedDataPath.iosXctestEnvDir.snapshotInteractiveOnly.snapshotPreferredBackend.snapshotDepth.snapshotScope.snapshotRaw.snapshotCustomActions.snapshotIncludeHiddenContentHints.count.intervalMs.delayMs.durationMs.holdMs.jitterPx.pixels.until.doubleTap.backMode.pauseMs.pattern`.split(`.`);function Je(e){return Object.fromEntries(qe.map(t=>[t,e?.[t]]))}function P(e,t,n,r,i,a){return{requestId:i??be().requestId,appBundleId:n,runnerLeaseContext:Ce({meta:a}),logPath:e,traceLogPath:r,...Je(t),screenshotCaptureBackend:t?.maestro?.screenshotCaptureBackend,...o(t),clickButton:h(t)}}function Ye(e){return e?.interactionOutcome?.retryOnNoChange===!0}function Xe(e){let{session:t,command:n,positionals:r,flags:i,preSnapshot:a}=e;if(!Ye(i)||!it(t))return;let o=ot(n);if(!o||!ft(r))return;let s=z(a?.nodes??[]);s.length!==0&&(t.pendingInteractionOutcome={action:n,command:o,positionals:r,flags:R(i),markedAt:Date.now(),attemptsRemaining:2,preSignature:s})}function Ze(e){let t=e?.pendingInteractionOutcome;if(!(!e||!t)){if(!it(e)){F(e);return}if(Date.now()-t.markedAt>3e4){F(e);return}return t}}function F(e){e?.pendingInteractionOutcome&&(e.pendingInteractionOutcome=void 0)}async function I(e){let{pending:t,snapshot:n}=e,r=V(t.preSignature,z(n.nodes));if(r!==`unchanged`||t.attemptsRemaining<=0)return{retried:!1,change:r};let i=e.retryTap,a=i?at(t.positionals):void 0;if(!i||!a)return L(t,i?`unreadable-retry-point`:`device-runtime-unavailable`),{retried:!1,change:r};let o=Date.now();return--t.attemptsRemaining,await Qe(i,e)?(g({level:`info`,phase:`interaction_no_change_retry`,data:{action:t.action,attemptsRemaining:t.attemptsRemaining,durationMs:Date.now()-o}}),{retried:!0,change:r}):(L(t,`retry-tap-unavailable`),{retried:!1,change:r})}async function Qe(e,t){let{session:n,pending:r}=t,i=at(r.positionals);if(!i)return!1;try{return await e({device:n.device,point:i,context:{...P(t.logPath,r.flags,n.appBundleId,n.trace?.outPath),surface:n.surface}})}catch{return!1}}function L(e,t){g({level:`info`,phase:`interaction_no_change_retry_skipped`,data:{action:e.action,attemptsRemaining:e.attemptsRemaining,reason:t}})}function $e(e){g({level:e.attempts>0?`info`:`debug`,phase:`interaction_settled`,data:{action:e.pending.action,change:e.change,attempts:e.attempts,durationMs:Date.now()-e.startedAt}})}function et(e){g({level:`warn`,phase:`interaction_settle_timeout`,data:{action:e.pending.action,attempts:e.attempts,durationMs:Date.now()-e.startedAt}})}function R(e){if(!e?.interactionOutcome&&!e?.postGestureStabilization)return e;let{interactionOutcome:t,postGestureStabilization:n,...r}=e;return r}function z(e){let t=new Map,n=[],r=de(e);for(let i of e){let e=st(i,t,r);e&&n.push(e)}return n}function B(e){return e?.comparisonKey??e?.snapshotQuality?.backend}function V(e,t){return e.length===0||t.length===0?`ambiguous`:U(e,t)?`unchanged`:`changed`}function H(e,t){return Math.abs(e.x-t.x)<=1&&Math.abs(e.y-t.y)<=1&&Math.abs(e.width-t.width)<=1&&Math.abs(e.height-t.height)<=1}function U(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.key!==i.key||!H(r,i))return!1}return!0}function tt(e,t){let n=W(e),r=W(t);if(n.size===0||r.size===0)return`ambiguous`;let i=0,a=!1;for(let[e,t]of n){let n=r.get(e);if(!n){a=!0;continue}if(i+=1,!H(t,n))return`changed`}if(i===0)return`ambiguous`;let o=r.size>i;return a&&o?`changed`:`unchanged`}function W(e){let t=new Map;for(let n of e)!n.identity||!n.discriminating||t.has(n.identity)||t.set(n.identity,n);return t}function G(e,t){let n=e.filter(e=>e.discriminating),r=t.filter(e=>e.discriminating);if(n.length===0||n.length!==r.length)return!1;let i=new Map(r.map(e=>[e.key,e]));for(let e of n){let t=i.get(e.key);if(!t||!H(e,t))return!1}return!0}function K(e,t){let n=new Map(t.filter(e=>e.discriminating).map(e=>[e.key,e])),r=0,i=0,a=0;for(let t of e){if(!t.discriminating)continue;let e=n.get(t.key);if(!e){r+=1;continue}n.delete(t.key),a+=1,H(t,e)||(i+=1)}return{onlyInBaseline:r,onlyInCurrent:n.size,rectMismatched:i,shared:a}}function nt(e,t,n){let r=q(rt(e,n)),i=q(rt(t,n));for(let[e,t]of r){let n=i.get(e);if(!n||!H(t,n))return!0;i.delete(e)}return i.size>0}function q(e){let t=new Map,n=new Map;for(let r of e){let e=t.get(r.content)??0;t.set(r.content,e+1),n.set(`${r.content}|#${e}`,r)}return n}function rt(e,t){return e.filter(e=>e.discriminating&&e.x<t.x+t.width&&t.x<e.x+e.width&&e.y<t.y+t.height&&t.y<e.y+e.height)}function it(e){return f(e.device)}function at(e){let t=Number(e[0]),n=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(n)?{x:t,y:n}:void 0}function ot(e){if(e===`click`||e===`press`)return`press`}function st(e,t,n){if(!e.rect||!pt(e.rect)||mt(e))return;let r=dt(e);if(!r)return;let i=t.get(r)??0;t.set(r,i+1);let a=lt(e);return{key:`${r}|#${i}`,...a?{identity:a}:{},content:ct(e,a),x:Math.round(e.rect.x),y:Math.round(e.rect.y),width:Math.round(e.rect.width),height:Math.round(e.rect.height),discriminating:!ut(e,n)}}function ct(e,t){return t??`${e.type??``}|${e.role??``}`}function lt(e){let t=[e.identifier,e.label,e.value].map(e=>typeof e==`string`?e.trim():``).join(`|`);if(t.replaceAll(`|`,``))return`${t}|${e.type??``}`}function ut(e,t){return ee(e)||e.ref!==void 0&&t.has(e.ref)}function dt(e){let t=[e.identifier,e.label,e.value,e.type,e.role,...ye(e),e.hittable===!0?`hittable`:`not-hittable`].map(e=>typeof e==`string`?e.trim():``).join(`|`);return t.replaceAll(`|`,``)?t:void 0}function ft(e){return e.length===2&&e.every(e=>Number.isFinite(Number(e)))}function pt(e){return[e.x,e.y,e.width,e.height].every(e=>Number.isFinite(e))&&e.width>0&&e.height>0}function mt(e){return`${e.label??``} ${e.identifier??``}`.toLowerCase().includes(`scroll bar`)}function ht(e){let{session:t,command:n,action:r=n,positionals:i,flags:a,scheduleOutcomeRetry:o=!1,androidFreshnessBaseline:s}=e;o&&Xe({session:t,command:n,positionals:i,flags:a,preSnapshot:t.snapshot}),k(r)&&Ge(t,r,s??t.snapshot),gt(t,r,i,a)}function gt(e,t,n=[],r){if(!Et(e.device)||!Tt(t,n,r))return;let i=Dt(e.device)?z(e.snapshot?.nodes??[]):void 0;e.postGestureStabilization={action:t,positionals:n,markedAt:Date.now(),...i?.length?{baselineSignature:i,baselineBackend:B(e.snapshot)}:{}}}function _t(e){e?.postGestureStabilization&&(e.postGestureStabilization=void 0)}function vt(e){return!!e?.postGestureStabilization}async function yt(e){let t=Ze(e.session);if(t&&e.session)return await bt({...e,session:e.session},t);if(f(e.device)&&e.session&&vt(e.session))return await St({...e,session:e.session});let n=j(e.session);if(n&&e.device.platform===`android`){let t=await N(e,n);return{snapshot:t.snapshot,...t.annotations}}}async function bt(e,t){let n=e.session,r=Date.now(),i=0,a=await xt(e,t,await J(e)),o=await I({session:n,pending:t,logPath:e.logPath,snapshot:a.snapshot,retryTap:e.retryTap});for(;o.retried;)i+=1,a=await xt(e,t,await J(e)),o=await I({session:n,pending:t,logPath:e.logPath,snapshot:a.snapshot,retryTap:e.retryTap});F(n);let s=await Ct({session:n,initial:a,capture:async()=>await J(e),readSnapshot:e=>e.snapshot});return a=s.value,o.change!==`ambiguous`&&a.annotations.freshness?.staleAfterRetries!==!0&&M(n),o.change===`unchanged`?et({pending:t,attempts:i,startedAt:r}):$e({pending:t,change:o.change,attempts:i,startedAt:r}),wt(s)}async function xt(e,t,n){let r=n;return V(t.preSignature,z(r.snapshot.nodes))===`unchanged`?(await _(500),r=await J(e),r):r}async function St(e){return wt(await Ct({session:e.session,capture:async()=>await J(e),readSnapshot:e=>e.snapshot}))}async function J(e){let t=j(e.session);return t&&e.device.platform===`android`?await N(e,t):await e.capture()}async function Ct(e){let{session:t,capture:n,readSnapshot:r}=e,i=t?.postGestureStabilization;if(!t||!Et(t.device)||!i)return{value:e.initial??await n()};try{return await me({pending:{action:i.action,positionals:i.positionals??[],baselineSignature:i.baselineSignature,baselineBackend:i.baselineBackend},needsBaselineDistrust:Dt(t.device),initial:e.initial,hooks:{capture:n,readSurface:e=>{let t=r(e);return{signature:z(t.nodes),backend:B(t)}},signaturesStable:U,classifyBaselineEvidence:tt,surfacesIdentical:G,summarizeDivergence:K}})}finally{_t(t)}}function wt(e){let{snapshot:t,annotations:n}=e.value;return e.postGestureOutcome&&(t.postGestureOutcome=e.postGestureOutcome),{snapshot:t,...n}}function Tt(e,t,n){return n?.postGestureStabilization===!1?!1:n?.postGestureStabilization===!0||e===`swipe`||e===`scroll`||e===`gesture`&&t[0]===`swipe`}function Et(e){return f(e)}function Dt(e){return d(e.platform)}let Y;async function Ot(){if(Y)return Y;let{createAppleSessionObservation:e}=await import(`./session-observation.js`),{listLocalDeviceInventory:t,shouldPropagateDeviceInventoryProbeError:n}=await import(`./device-inventory-context.js`).then(e=>e.t);return Y??=e({listLocalDevices:t,shouldPropagateProbeError:n}),Y}const kt=Object.freeze({async observeRunnerSession(e){return(await Ot()).observeRunnerSession(e)},async resolveSoleForegroundApp(e){return(await Ot()).resolveSoleForegroundApp(e)}});async function At(e,t,n,r){let{queryAppleRunnerSelector:i}=await import(`./runner-operations-facade.js`);return await i(e,t,n,r)}function jt(e,t){return a(`UNSUPPORTED_OPERATION`,`${e} is not supported on this device`,{reason:t.reason},t.hint?{hint:t.hint}:void 0)}async function X(e){let t=await Pt(e.inspectFacts)(e.device);for(let n of e.required){let r=t.operations[n];if(!r.available)return{type:`response`,response:e.unavailableResponse?e.unavailableResponse(r):jt(e.command,r)}}return{type:`admitted`,bind:Ft(e.bindDevice)}}async function Mt(e){let t=await X({...e,required:e.use.required});if(t.type===`response`)return t;let n=await t.bind(e.device,e.use);return e.readiness&&await Se(n),{type:`runtime`,runtime:n}}async function Nt(e,t){let n=await Mt(e);if(n.type===`response`)return{ok:!1,response:n.response};let r=n.runtime;return{ok:!0,execute:async({dispatchContext:e})=>await t(r,e)}}function Pt(e){if(e)return e;throw new t(`COMMAND_FAILED`,`Device runtime facts inspection is unavailable.`,{reason:`runtime-gateway-missing`})}function Ft(e){if(e)return e;throw new t(`COMMAND_FAILED`,`Device runtime binding is unavailable.`,{reason:`runtime-gateway-missing`})}function It(e){let{flags:t,logPath:r,meta:a,session:o,snapshotScope:s}=e,{appBundleId:c,trace:l,surface:u}=o??{},d=e.context??P(r??``,t,c,l?.outPath,a?.requestId,a);return{options:{appBundleId:c,...n(t,i),scope:s,includeRects:e.includeRects,surface:u},execution:Z(d),...e.signal===void 0?{}:{signal:e.signal}}}function Z(e){return{requestId:e.requestId,verbose:e.verbose,logPath:e.logPath,traceLogPath:e.traceLogPath,iosXctestrunFile:e.iosXctestrunFile,iosXctestDerivedDataPath:e.iosXctestDerivedDataPath,iosXctestEnvDir:e.iosXctestEnvDir,runnerLeaseContext:e.runnerLeaseContext}}function Lt(e){let t=ve(e);return{...t,capture:_e(t),selectors:ge(t),interactions:fe(t)}}async function Rt(e){let t=await(await De().resolve(e.device,e.runnerContext)).snapshot(e.options);if(!(`stage`in t))return t;let{presentIosSnapshotAcquisition:n}=await import(`./ios-snapshot-runtime.js`);return await n(t,e.options)}function zt(e){let t=e?e.textEntryReadiness:void 0,n=Wt(t)?{textEntryReadiness:t}:{},r=Bt(e);return r?{...n,...r}:n}function Bt(e){if(!Vt(e))return null;let t=Ht(e.target);return t?{verification:`unconfirmed`,requested:e.requested,before:e.before,after:e.after,target:t}:null}function Vt(e){return!!(e&&e.verification===`unconfirmed`&&typeof e.requested==`string`&&Q(e.before)&&Q(e.after))}function Ht(e){if(!Kt(e)||!Ut(e))return null;let t=Gt(e.rect);return t?{resourceId:e.resourceId,className:e.className,packageName:e.packageName,rect:t}:null}function Ut(e){return Q(e.resourceId)&&Q(e.className)&&Q(e.packageName)}function Wt(e){return typeof e==`string`&&we.includes(e)}function Q(e){return e===null||typeof e==`string`}function Gt(e){return!Kt(e)||![e.x,e.y,e.width,e.height].every(e=>typeof e==`number`)?null:e}function Kt(e){return!!e&&typeof e==`object`}async function qt(e){let t={device:e.device,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice},n=te(e.command,e.requiresCapture),r=await X({command:e.command,required:n.use.required,...e.unavailableResponse?{unavailableResponse:e.unavailableResponse}:{},...t});if(r.type===`response`)return{ok:!1,response:r.response};let i=r.bind;switch(n.kind){case`tap-point`:return{ok:!0,runtime:{kind:`tap`,captured:!1,runtime:await i(e.device,ie)}};case`captured-tap`:return{ok:!0,runtime:{kind:`tap`,captured:!0,runtime:await i(e.device,oe)}};case`long-press-point`:return{ok:!0,runtime:{kind:`long-press`,captured:!1,runtime:await i(e.device,re)}};case`captured-long-press`:return{ok:!0,runtime:{kind:`long-press`,captured:!0,runtime:await i(e.device,le)}};case`hover-point`:return{ok:!0,runtime:{kind:`hover`,captured:!1,runtime:await i(e.device,ue)}};case`captured-hover`:return{ok:!0,runtime:{kind:`hover`,captured:!0,runtime:await i(e.device,ce)}};case`fill-point`:return{ok:!0,runtime:{kind:`fill`,captured:!1,runtime:await i(e.device,se)}};case`captured-fill`:return{ok:!0,runtime:{kind:`fill`,captured:!0,runtime:await i(e.device,ae)}}}}function Jt(e,t){let n={execution:Z(t),appBundleId:t.appBundleId},r=e.captured?en(e.runtime):void 0;switch(e.kind){case`tap`:return Yt(e,t,n,r);case`long-press`:return Xt(e,n,r);case`hover`:return Zt(e,n,r);case`fill`:return Qt(e,t,n,r)}}function Yt(e,t,n,r){let i=e.captured?e.runtime.operations.tapRef:void 0,a=e.captured?e.runtime.operations.tapElementSelector:void 0;return Object.freeze({captureSnapshot:r,tapPoint:async(r,i={})=>{let a=tn(i,t),o=await e.runtime.operations.tapPoint({point:r,options:a,...n});return{x:r.x,y:r.y,count:a.count,intervalMs:a.intervalMs,holdMs:a.holdMs,jitterPx:a.jitterPx,doubleTap:a.doubleTap,...a.button===`primary`?{}:{button:a.button},...o??{},...p(an(r,a.button))}},tapRef:i?async e=>await i({ref:e,...n}):void 0,tapElementSelector:e.captured&&a?async t=>{let r=await e.runtime.operations.tapElementSelector?.({selector:t,...n}),i=r?.maestroNonHittableCoordinateFallbackUsed===!0;return{selector:t.raw,...r??{},...p(i?`tapped via non-hittable coordinate fallback`:`Tapped ${t.raw}`)}}:void 0})}function Xt(e,t,n){return Object.freeze({captureSnapshot:n,longPressPoint:async(n,r)=>{let i=await e.runtime.operations.longPressPoint({point:n,durationMs:r,...t});return{x:n.x,y:n.y,durationMs:r,...i??{},...p(`Long pressed (${n.x}, ${n.y})`)}}})}function Zt(e,t,n){let r=e.captured?e.runtime.operations.hoverRef:void 0;return Object.freeze({captureSnapshot:n,hoverPoint:async n=>{let r=await e.runtime.operations.hoverPoint({point:n,...t});return{x:n.x,y:n.y,...r??{},...p(`Hovered (${n.x}, ${n.y})`)}},hoverRef:r?async e=>await r({ref:e,...t}):void 0})}function Qt(e,t,n,r){let i=e.captured?e.runtime.operations.fillRef:void 0,a=e=>he(e??t.delayMs??0,`delay-ms`,0,1e4);return Object.freeze({captureSnapshot:r,fillPoint:async(t,r,i={})=>{let o=a(i.delayMs),s=await e.runtime.operations.fillPoint({point:t,text:r,delayMs:o,allowNonHittableCoordinateFallback:i.allowNonHittableCoordinateFallback===!0,...n});return{x:t.x,y:t.y,text:r,delayMs:o,...$t(s)?{maestroNonHittableCoordinateFallbackUsed:!0}:{},...zt(s),...p(`Filled ${Array.from(r).length} chars`)}},fillRef:i?async(e,t,r={})=>await i({ref:e,text:t,delayMs:a(r.delayMs),...n}):void 0})}function $t(e){return typeof e==`object`&&!!e&&`maestroNonHittableCoordinateFallbackUsed`in e&&e.maestroNonHittableCoordinateFallbackUsed===!0}function en(e){return async t=>await e.operations.captureSnapshot(t)}function tn(e,t){let n=nn(e,t);return rn(n),{button:e.button??h(t),...n,surface:e.surface??t.surface}}function nn(e,t){return{count:$(e.count,t.count,1,`count`,1,200),intervalMs:$(e.intervalMs,t.intervalMs,0,`interval-ms`,0,1e4),holdMs:$(e.holdMs,t.holdMs,0,`hold-ms`,0,1e4),jitterPx:$(e.jitterPx,t.jitterPx,0,`jitter-px`,0,100),doubleTap:e.doubleTap??t.doubleTap??!1}}function $(e,t,n,r,i,a){return he(e??t??n,r,i,a)}function rn(e){if(e.doubleTap&&e.holdMs>0)throw new t(`INVALID_ARGS`,`double-tap cannot be combined with hold-ms`);if(e.doubleTap&&e.jitterPx>0)throw new t(`INVALID_ARGS`,`double-tap cannot be combined with jitter-px`)}function an(e,t){return t===`primary`?`Pressed (${e.x}, ${e.y})`:`${t===`secondary`?`Right`:`Middle`} clicked (${e.x}, ${e.y})`}function on(e){let{inspectFacts:t,bindDevice:n}=e;if(!t||!n)return;let r=new Map;return async({device:e,point:i,context:a})=>{let o=r.get(e.id);o||(o=qt({device:e,command:`press`,requiresCapture:!1,inspectFacts:t,bindDevice:n}),r.set(e.id,o));let s=await o;if(!s.ok)return!1;let c=Jt(s.runtime,a);return c.tapPoint?(await c.tapPoint(i),!0):!1}}async function sn(e){let t=await yt({session:e.session,device:e.device,logPath:e.logPath,interactiveOnly:e.flags?.snapshotInteractiveOnly===!0,androidFreshnessMode:e.androidFreshnessMode,capture:()=>ln(e),retryTap:on(e)});if(t)return t;let n=await ln(e);return M(e.session),{snapshot:n.snapshot,...n.annotations}}async function cn(e){if(e.captureData)return await e.captureData();let{device:t,session:r,logPath:a}=e,o=P(a,un(e),r?.appBundleId,r?.trace?.outPath);return await Rt({device:t,runnerContext:{requestId:o.requestId,signal:e.signal,appBundleId:o.appBundleId,verbose:o.verbose,logPath:o.logPath,traceLogPath:o.traceLogPath,iosXctestrunFile:o.iosXctestrunFile,iosXctestDerivedDataPath:o.iosXctestDerivedDataPath,iosXctestEnvDir:o.iosXctestEnvDir,runnerLeaseContext:o.runnerLeaseContext},options:{appBundleId:o.appBundleId,signal:e.signal,...n(o,i),includeRects:e.includeRects,surface:r?.surface}})}async function ln(e){let t=Date.now(),n=await cn(e);c(e.session,{durationMs:Date.now()-t,backend:n.backend,platform:u(e.device)});let r=s(n),i=l(n,xe(n,un(e)));return r.androidSnapshot?.systemSurfaceOnly===!0&&(i.systemSurfaceOnly=!0),{data:n,snapshot:i,annotations:r}}function un(e){return e.snapshotScope===void 0?e.flags:{...e.flags,snapshotScope:e.snapshotScope}}function dn(t,n){if(!t||!t.trim().startsWith(`@`))return{ok:!0,scope:t};if(!n?.snapshot)return a(`INVALID_ARGS`,`Ref scope requires an existing snapshot in session.`);let i=e(t.trim());if(!i)return a(`INVALID_ARGS`,`Invalid ref scope: ${t}`);let o=[n.snapshot,...n.snapshotScopeSource?[n.snapshotScopeSource]:[]],s=!1,c;for(let e of o){let t=r(e.nodes,i);if(t&&(s=!0,c=pe(t,e.nodes),c))break}return s?c?{ok:!0,scope:c}:a(`COMMAND_FAILED`,`Ref ${t} has no label to scope by`,{reason:m.refUnlabeled,ref:i}):a(`COMMAND_FAILED`,`Ref ${t} not found`,{reason:m.refNotFound,ref:i},{hint:ne})}function fn(e,t,n={}){if(!e)return;let r=je(e);return{name:t,appBundleId:e.appBundleId,appName:e.appName,...n.includeSnapshot===!0?{snapshot:e.snapshot,...r&&n.omitRefFrameSnapshot!==!0?{refFrameSnapshot:r}:{}}:{},metadata:{surface:e.surface,...n.metadata??{}}}}function pn(e){return{get:t=>t===e.sessionName?fn(e.getSession(),e.sessionName,e.recordOptions):void 0,set:t=>{if(t.name!==e.sessionName){g({level:`warn`,phase:`runtime_session_write_skipped`,data:{expected:e.sessionName,received:t.name}});return}e.setRecord(t)}}}function mn(e,t){e.snapshot!==t&&(e.snapshotGeneration=gn(e.snapshotGeneration)),e.snapshot=t,e.snapshotScopeSource=void 0,t.comparisonSafe===!0&&(e.lastComparisonSafeSnapshot=t)}function hn(e,t){e.snapshotScopeSource=t.scopeSource,e.snapshotGeneration=t.keptCurrentSnapshot?t.previousGeneration:gn(t.previousGeneration)}function gn(e){return e===void 0?Te(1e5,1e6):e+1}function _n(e){let t=e.startsWith(`@`)?e.slice(1):e,n=t.indexOf(`~`);return n===-1?t:t.slice(0,n)}function vn(e,t){let n=new Set;for(let e of t){let t=_n(e);t.length>0&&n.add(t)}n.size!==0&&Ie(e,n)}function yn(e,t){if(t?.diff)return vn(e,bn(t)),e.snapshotGeneration}function bn(e){let t=[];for(let n of e.diff?.lines??[])n.ref&&t.push(n.ref);for(let n of e.refs??[])t.push(n.ref);for(let n of e.tail??[])t.push(n.ref);return t}function xn(e){return`Ref @${e.ref.startsWith(`@`)?e.ref.slice(1):e.ref} was minted from snapshot s${e.mintedGeneration} but the session's ref frame is now s${e.currentFrameEpoch} — re-run snapshot -i.`}function Sn(e){let{session:t,ref:n,mintedGeneration:r}=e;if(t&&D(t)===`expired`)return`The UI may have changed since these refs were issued, so they no longer represent current device state. Take a new snapshot before relying on or interacting with them.`;if(r!==void 0){let e=t?C(t)??0:0;if(r!==e)return xn({ref:n,mintedGeneration:r,currentFrameEpoch:e})}}export{K as A,D as B,U as C,G as D,nt as E,Ne as F,w as I,Le as L,j as M,Fe as N,B as O,Me as P,T as R,ht as S,tt as T,Ee as V,Nt as _,hn as a,At as b,cn as c,qt as d,Lt as f,Mt as g,X as h,mn as i,P as j,R as k,dn as l,Z as m,vn as n,pn as o,It as p,Sn as r,sn as s,yn as t,Jt as u,jt as v,z as w,vt as x,kt as y,S as z};
|
|
1
|
+
import{E as e,N as t,O as n,b as r,h as i,o as a}from"./sdk-contracts.js";import{u as o}from"./capture.js";import{r as s}from"./snapshot-capture-annotations.js";import{r as c}from"./snapshot-diagnostics.js";import{f as l}from"./android-input-ownership.js";import{C as u,d,h as f}from"./sdk-device.js";import{Cn as ee,jr as te}from"./sdk-batch.js";import{A as ne,C as re,a as ie,g as ae,j as oe,o as se,t as ce}from"./runtime.js";import{h as le,o as p}from"./overlay.js";import{i as ue}from"./click-button.js";import{a as de,r as fe}from"./diagnostics.js";import{t as pe}from"./timeouts.js";import"./diagnostics2.js";import"./retry.js";import{t as me}from"./snapshot-state.js";import{i as he}from"./lease-context.js";import{randomInt as ge}from"node:crypto";let m={resolve:async()=>{throw new t(`COMMAND_FAILED`,`Interactor resolution is not composed for this process.`,{reason:`interactor-resolution-missing`})}};function _e(e){m=e}function ve(){return m}var h=class e{#e;constructor(e){this.#e=e}get state(){return this.#e.state}get scope(){return this.#e.scope}get tree(){return this.#e.tree}get generation(){return this.#e.generation}static expire(t){return t.#e.state===`expired`?t:new e({...t.#e,state:`expired`})}};const ye=new h({state:`active`,scope:`all`,tree:void 0,generation:void 0});function be(e){return new h({state:`active`,...e})}function xe(e){return h.expire(e)}const g=new WeakMap,_=new WeakSet;function v(e){return e.refFrame??ye}function y(e){return v(e).generation??e.snapshotGeneration}function Se(e){return v(e).tree}function Ce(e){Te(e),b(e),e.refFrame=xe(v(e)),e.snapshotScopeSource=void 0}function b(e){e.snapshot&&_.add(e.snapshot)}function we(e){return _.has(e)}function Te(e){let t=x(e)+1;return g.set(e,t),t}function x(e){return g.get(e)??0}function Ee(e){S(e,`all`)}function De(e,t){S(e,t)}function S(e,t){e.refFrame=be({scope:t,tree:e.snapshot,generation:e.snapshotGeneration})}function C(e){return v(e).state}function w(e){return v(e).scope}function Oe(e){let t=e.ref.startsWith(`@`)?e.ref.slice(1):e.ref;return{admission:T({session:e.session,refBody:t,mintedGeneration:e.mintedGeneration}),scope:w(e.session),currentGeneration:y(e.session)}}function T(e){let{session:t,refBody:n,mintedGeneration:r}=e;if(C(t)===`expired`)return{admitted:!1,reason:`ref_frame_expired`};if(r!==void 0&&r!==y(t))return{admitted:!1,reason:`ref_generation_mismatch`};let i=w(t);if(i!==`all`){if(r===void 0)return{admitted:!1,reason:`plain_ref_requires_complete_frame`};if(!i.has(n))return{admitted:!1,reason:`ref_not_issued`}}return{admitted:!0}}const ke=[250,400,600];function E(e){return e===`press`||e===`click`||e===`back`||e===`open`}function D(e){return e.map(e=>[e.depth??0,e.type??``,e.label??``,e.value??``,e.identifier??``,e.enabled===!1?`disabled`:`enabled`,e.hittable===!0?`hittable`:`not-hittable`].join(`|`))}function Ae(e,t){return e<12?!1:t<=Math.floor(e*.2)}function je(e,t,n){return n.interactiveOnly&&e.snapshot.nodes.length===0&&e.rawNodeCount!==void 0&&e.rawNodeCount>=12?`empty-interactive`:n.mode===`ref-refresh`?null:Ae(t.baselineCount,e.snapshot.nodes.length)?Me(e.snapshot)?null:`sharp-drop`:t.routeComparable&&E(t.action)&&Ne(t.baselineSignatures,e.snapshot.nodes)?`stuck-route`:null}function Me(e){return e.nodes.some(e=>e.hittable===!0||!!e.label?.trim()||!!e.value?.trim()||!!e.identifier?.trim())}function Ne(e,t){if(!e||e.length===0)return!1;let n=Math.max(e.length,t.length);if(n<12)return!1;let r=D(t),i=Math.min(e.length,r.length),a=0;for(let t=0;t<i;t+=1)e[t]===r[t]&&(a+=1);let o=Math.max(0,r.length-e.length),s=Math.max(0,e.length-r.length),c=Math.max(3,Math.floor(n*.15));return a>=Math.floor(n*.9)&&o<=c&&s<=c}async function Pe(e){let t=e.window.markedAt+e.retry.retryBudgetMs,n=await e.capture(),r=e.classify(n),i=0;for(let a of e.retry.delaysMs){if(!r)break;let o=t-Date.now();if(o<=0)break;await pe(Math.min(a,o)),n=await e.capture(),i+=1,r=e.classify(n)}r||e.onTrustworthyCapture?.();let a=i>0||r?{action:e.window.action,retryCount:i,staleAfterRetries:!!r,reason:r??void 0}:void 0;return{...n,annotations:{...n.annotations,...s({freshness:a})}}}function Fe(e,t,n=e.snapshot){if(e.device.platform!==`android`)return;let r=Ie(e,n),i=r?.comparisonSafe===!0;e.androidSnapshotFreshness={action:t,markedAt:Date.now(),baselineCount:(r??n)?.nodes.length??0,baselineSignatures:i?D(r?.nodes??[]):void 0,routeComparable:i}}function Ie(e,t){if(t?.comparisonSafe===!0)return t;let n=e.lastComparisonSafeSnapshot;return!n||n.comparisonSafe!==!0?t:Date.now()-n.createdAt<=5e3?n:t}function O(e){if(!e||e.device.platform!==`android`)return;let t=e.androidSnapshotFreshness;if(t){if(Date.now()-t.markedAt>2500){delete e.androidSnapshotFreshness;return}return t}}function k(e){!e||e.device.platform!==`android`||delete e.androidSnapshotFreshness}async function A(e,t){return Pe({capture:e.capture,classify:n=>je({snapshot:n.snapshot,rawNodeCount:n.annotations.analysis?.rawNodeCount},t,{interactiveOnly:e.interactiveOnly,mode:e.androidFreshnessMode}),window:t,retry:{retryBudgetMs:1500,delaysMs:ke},onTrustworthyCapture:()=>k(e.session)})}function j(e){let t=new Map,n=[],r=oe(e);for(let i of e){let e=Re(i,t,r);e&&n.push(e)}return n}function M(e){return e?.comparisonKey??e?.snapshotQuality?.backend}function N(e,t){return Math.abs(e.x-t.x)<=1&&Math.abs(e.y-t.y)<=1&&Math.abs(e.width-t.width)<=1&&Math.abs(e.height-t.height)<=1}function P(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.key!==i.key||!N(r,i))return!1}return!0}function F(e,t){let n=I(e),r=I(t);if(n.size===0||r.size===0)return`ambiguous`;let i=0,a=!1;for(let[e,t]of n){let n=r.get(e);if(!n){a=!0;continue}if(i+=1,!N(t,n))return`changed`}if(i===0)return`ambiguous`;let o=r.size>i;return a&&o?`changed`:`unchanged`}function I(e){let t=new Map;for(let n of e)!n.identity||!n.discriminating||t.has(n.identity)||t.set(n.identity,n);return t}function L(e,t){let n=e.filter(e=>e.discriminating),r=t.filter(e=>e.discriminating);if(n.length===0||n.length!==r.length)return!1;let i=new Map(r.map(e=>[e.key,e]));for(let e of n){let t=i.get(e.key);if(!t||!N(e,t))return!1}return!0}function R(e,t){let n=new Map(t.filter(e=>e.discriminating).map(e=>[e.key,e])),r=0,i=0,a=0;for(let t of e){if(!t.discriminating)continue;let e=n.get(t.key);if(!e){r+=1;continue}n.delete(t.key),a+=1,N(t,e)||(i+=1)}return{onlyInBaseline:r,onlyInCurrent:n.size,rectMismatched:i,shared:a}}function Le(e,t,n){let r=z(B(e,n)),i=z(B(t,n));for(let[e,t]of r){let n=i.get(e);if(!n||!N(t,n))return!0;i.delete(e)}return i.size>0}function z(e){let t=new Map,n=new Map;for(let r of e){let e=t.get(r.content)??0;t.set(r.content,e+1),n.set(`${r.content}|#${e}`,r)}return n}function B(e,t){return e.filter(e=>e.discriminating&&e.x<t.x+t.width&&t.x<e.x+e.width&&e.y<t.y+t.height&&t.y<e.y+e.height)}function Re(e,t,n){if(!e.rect||!Ue(e.rect)||We(e))return;let r=He(e);if(!r)return;let i=t.get(r)??0;t.set(r,i+1);let a=Be(e);return{key:`${r}|#${i}`,...a?{identity:a}:{},content:ze(e,a),x:Math.round(e.rect.x),y:Math.round(e.rect.y),width:Math.round(e.rect.width),height:Math.round(e.rect.height),discriminating:!Ve(e,n)}}function ze(e,t){return t??`${e.type??``}|${e.role??``}`}function Be(e){let t=[e.identifier,e.label,e.value].map(e=>typeof e==`string`?e.trim():``).join(`|`);if(t.replaceAll(`|`,``))return`${t}|${e.type??``}`}function Ve(e,t){return te(e)||e.ref!==void 0&&t.has(e.ref)}function He(e){let t=[e.identifier,e.label,e.value,e.type,e.role,...le(e),e.hittable===!0?`hittable`:`not-hittable`].map(e=>typeof e==`string`?e.trim():``).join(`|`);return t.replaceAll(`|`,``)?t:void 0}function Ue(e){return[e.x,e.y,e.width,e.height].every(e=>Number.isFinite(e))&&e.width>0&&e.height>0}function We(e){return`${e.label??``} ${e.identifier??``}`.toLowerCase().includes(`scroll bar`)}function Ge(e){let{session:t,command:n,action:r=n,positionals:i,flags:a,androidFreshnessBaseline:o}=e;E(r)&&Fe(t,r,o??t.snapshot),Ke(t,r,i,a)}function Ke(e,t,n=[],r){if(!H(e.device)||!et(t,n,r))return;let i=U(e.device)?j(e.snapshot?.nodes??[]):void 0;e.postGestureStabilization={action:t,positionals:n,markedAt:Date.now(),...i?.length?{baselineSignature:i,baselineBackend:M(e.snapshot)}:{}}}function qe(e){e?.postGestureStabilization&&(e.postGestureStabilization=void 0)}function V(e){return!!e?.postGestureStabilization}async function Je(e){if(f(e.device)&&e.session&&V(e.session))return await Ye({...e,session:e.session});let t=O(e.session);if(t&&e.device.platform===`android`){let n=await A(e,t);return{snapshot:n.snapshot,...n.annotations}}}async function Ye(e){return Qe(await Ze({session:e.session,capture:async()=>await Xe(e),readSnapshot:e=>e.snapshot}))}async function Xe(e){let t=O(e.session);return t&&e.device.platform===`android`?await A(e,t):await e.capture()}async function Ze(e){let{session:t,capture:n,readSnapshot:r}=e,i=t?.postGestureStabilization;if(!t||!H(t.device)||!i)return{value:e.initial??await n()};try{return await ne({pending:{action:i.action,positionals:i.positionals??[],baselineSignature:i.baselineSignature,baselineBackend:i.baselineBackend},needsBaselineDistrust:U(t.device),initial:e.initial,hooks:{capture:n,readSurface:e=>{let t=r(e);return{signature:j(t.nodes),backend:M(t)}},signaturesStable:P,classifyBaselineEvidence:F,surfacesIdentical:L,summarizeDivergence:R}})}finally{qe(t)}}function Qe(e){let{snapshot:t,annotations:n}=e.value;return e.postGestureOutcome&&(t.postGestureOutcome=e.postGestureOutcome),{snapshot:t,...n}}function $e(e){if(!e?.postGestureStabilization)return e;let{postGestureStabilization:t,...n}=e;return n}function et(e,t,n){return n?.postGestureStabilization===!1?!1:n?.postGestureStabilization===!0||e===`swipe`||e===`scroll`||e===`gesture`&&t[0]===`swipe`}function H(e){return f(e)}function U(e){return d(e.platform)}const tt=`activity.launchConsole.launchArgs.clearAppState.verbose.iosXctestrunFile.iosXctestDerivedDataPath.iosXctestEnvDir.snapshotInteractiveOnly.snapshotPreferredBackend.snapshotDepth.snapshotScope.snapshotRaw.snapshotCustomActions.snapshotIncludeHiddenContentHints.count.intervalMs.delayMs.durationMs.holdMs.jitterPx.pixels.until.doubleTap.backMode.pauseMs.pattern`.split(`.`);function nt(e){return Object.fromEntries(tt.map(t=>[t,e?.[t]]))}function W(e,t,n,r,i,a){return{requestId:i??de().requestId,appBundleId:n,runnerLeaseContext:he({meta:a}),logPath:e,traceLogPath:r,...nt(t),screenshotCaptureBackend:t?.maestro?.screenshotCaptureBackend,...o(t),clickButton:ue(t)}}let G;async function K(){if(G)return G;let{createAppleSessionObservation:e}=await import(`./session-observation.js`),{listLocalDeviceInventory:t,shouldPropagateDeviceInventoryProbeError:n}=await import(`./device-inventory-context.js`).then(e=>e.t);return G??=e({listLocalDevices:t,shouldPropagateProbeError:n}),G}const rt=Object.freeze({async observeRunnerSession(e){return(await K()).observeRunnerSession(e)},async resolveSoleForegroundApp(e){return(await K()).resolveSoleForegroundApp(e)}});async function it(e,t,n,r){let{queryAppleRunnerSelector:i}=await import(`./runner-operations-facade.js`);return await i(e,t,n,r)}function at(e){let{flags:t,logPath:r,meta:a,session:o,snapshotScope:s}=e,{appBundleId:c,trace:l,surface:u}=o??{},d=e.context??W(r??``,t,c,l?.outPath,a?.requestId,a);return{options:{appBundleId:c,...n(t,i),scope:s,includeRects:e.includeRects,surface:u},execution:q(d),...e.signal===void 0?{}:{signal:e.signal}}}function q(e){return{requestId:e.requestId,verbose:e.verbose,logPath:e.logPath,traceLogPath:e.traceLogPath,iosXctestrunFile:e.iosXctestrunFile,iosXctestDerivedDataPath:e.iosXctestDerivedDataPath,iosXctestEnvDir:e.iosXctestEnvDir,runnerLeaseContext:e.runnerLeaseContext}}function ot(e){let t=re(e);return{...t,capture:ce(t),selectors:se(t),interactions:ie(t)}}async function J(e){let t=await(await ve().resolve(e.device,e.runnerContext)).snapshot(e.options);if(!(`stage`in t))return t;let{presentIosSnapshotAcquisition:n}=await import(`./ios-snapshot-runtime.js`);return await n(t,e.options)}async function st(e){let t=await Je({session:e.session,device:e.device,interactiveOnly:e.flags?.snapshotInteractiveOnly===!0,androidFreshnessMode:e.androidFreshnessMode,capture:()=>X(e)});if(t)return t;let n=await X(e);return k(e.session),{snapshot:n.snapshot,...n.annotations}}async function Y(e){if(e.captureData)return await e.captureData();let{device:t,session:r,logPath:a}=e,o=W(a,Z(e),r?.appBundleId,r?.trace?.outPath);return await J({device:t,runnerContext:{requestId:o.requestId,signal:e.signal,appBundleId:o.appBundleId,verbose:o.verbose,logPath:o.logPath,traceLogPath:o.traceLogPath,iosXctestrunFile:o.iosXctestrunFile,iosXctestDerivedDataPath:o.iosXctestDerivedDataPath,iosXctestEnvDir:o.iosXctestEnvDir,runnerLeaseContext:o.runnerLeaseContext},options:{appBundleId:o.appBundleId,signal:e.signal,...n(o,i),includeRects:e.includeRects,surface:r?.surface}})}async function X(e){let t=Date.now(),n=await Y(e);c(e.session,{durationMs:Date.now()-t,backend:n.backend,platform:u(e.device)});let r=s(n),i=l(n,me(n,Z(e)));return r.androidSnapshot?.systemSurfaceOnly===!0&&(i.systemSurfaceOnly=!0),{data:n,snapshot:i,annotations:r}}function Z(e){return e.snapshotScope===void 0?e.flags:{...e.flags,snapshotScope:e.snapshotScope}}function ct(t,n){if(!t||!t.trim().startsWith(`@`))return{ok:!0,scope:t};if(!n?.snapshot)return a(`INVALID_ARGS`,`Ref scope requires an existing snapshot in session.`);let i=e(t.trim());if(!i)return a(`INVALID_ARGS`,`Invalid ref scope: ${t}`);let o=[n.snapshot,...n.snapshotScopeSource?[n.snapshotScopeSource]:[]],s=!1,c;for(let e of o){let t=r(e.nodes,i);if(t&&(s=!0,c=ae(t,e.nodes),c))break}return s?c?{ok:!0,scope:c}:a(`COMMAND_FAILED`,`Ref ${t} has no label to scope by`,{reason:p.refUnlabeled,ref:i}):a(`COMMAND_FAILED`,`Ref ${t} not found`,{reason:p.refNotFound,ref:i},{hint:ee})}function lt(e,t,n={}){if(!e)return;let r=Se(e);return{name:t,appBundleId:e.appBundleId,appName:e.appName,...n.includeSnapshot===!0?{snapshot:e.snapshot,...r&&n.omitRefFrameSnapshot!==!0?{refFrameSnapshot:r}:{}}:{},metadata:{surface:e.surface,...n.metadata??{}}}}function ut(e){return{get:t=>t===e.sessionName?lt(e.getSession(),e.sessionName,e.recordOptions):void 0,set:t=>{if(t.name!==e.sessionName){fe({level:`warn`,phase:`runtime_session_write_skipped`,data:{expected:e.sessionName,received:t.name}});return}e.setRecord(t)}}}function dt(e,t){e.snapshot!==t&&(e.snapshotGeneration=Q(e.snapshotGeneration)),e.snapshot=t,e.snapshotScopeSource=void 0,t.comparisonSafe===!0&&(e.lastComparisonSafeSnapshot=t)}function ft(e,t){e.snapshotScopeSource=t.scopeSource,e.snapshotGeneration=t.keptCurrentSnapshot?t.previousGeneration:Q(t.previousGeneration)}function Q(e){return e===void 0?ge(1e5,1e6):e+1}function pt(e){let t=e.startsWith(`@`)?e.slice(1):e,n=t.indexOf(`~`);return n===-1?t:t.slice(0,n)}function $(e,t){let n=new Set;for(let e of t){let t=pt(e);t.length>0&&n.add(t)}n.size!==0&&De(e,n)}function mt(e,t){if(t?.diff)return $(e,ht(t)),e.snapshotGeneration}function ht(e){let t=[];for(let n of e.diff?.lines??[])n.ref&&t.push(n.ref);for(let n of e.refs??[])t.push(n.ref);for(let n of e.tail??[])t.push(n.ref);return t}function gt(e){return`Ref @${e.ref.startsWith(`@`)?e.ref.slice(1):e.ref} was minted from snapshot s${e.mintedGeneration} but the session's ref frame is now s${e.currentFrameEpoch} — re-run snapshot -i.`}function _t(e){let{session:t,ref:n,mintedGeneration:r}=e;if(t&&C(t)===`expired`)return`The UI may have changed since these refs were issued, so they no longer represent current device state. Take a new snapshot before relying on or interacting with them.`;if(r!==void 0){let e=t?y(t)??0:0;if(r!==e)return gt({ref:n,mintedGeneration:r,currentFrameEpoch:e})}}export{b as A,L as C,Ee as D,O as E,_e as F,x as M,v as N,Ce as O,C as P,Le as S,R as T,Ge as _,ft as a,j as b,Y as c,at as d,q as f,V as g,W as h,dt as i,Oe as j,we as k,ct as l,it as m,$ as n,ut as o,rt as p,_t as r,st as s,mt as t,ot as u,$e as v,M as w,F as x,P as y};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{N as e,Z as t}from"./sdk-contracts.js";import{_ as n}from"./sdk-batch-runner.js";import{C as r,a as i,i as a,n as o}from"./sdk-device.js";import{$n as s,Qn as c,cn as l,on as ee,p as te,x as ne}from"./sdk-batch.js";import{t as re}from"./recording-scope.js";import{a as ie}from"./scroll-gesture.js";import{_ as u,c as ae,d as oe,g as se,h as ce,i as le,l as ue,m as de,o as fe,p as d,s as pe,u as f,y as me}from"./script.js";import{A as p,C as he,D as ge,E as _e,M as ve,N as ye,S as be,T as xe,_ as Se,a as Ce,b as we,g as m,i as Te,k as Ee,l as De,n as Oe,r as ke,s as Ae,t as je,v as Me,w as Ne,x as Pe,y as Fe}from"./parameterized-recorded-fill.js";import{n as h,t as Ie}from"./catalog.js";import{o as Le,t as g}from"./back-mode.js";import{t as Re}from"./session.js";import{r as ze}from"./success-text.js";import{t as Be}from"./click-button.js";import"./device.js";import{r as _,t as Ve}from"./device-rotation.js";import{a as v,r as y}from"./diagnostics.js";import{k as He}from"./owner-identity.js";import"./file.js";import{t as Ue}from"./tv-remote.js";import"./diagnostics2.js";import{n as We,r as Ge}from"./session-repair-tombstone.js";import{n as Ke,r as b,t as x}from"./session-paths.js";import{t as qe}from"./keyboard-actions.js";import S from"node:path";import C from"node:fs";import{createHash as Je}from"node:crypto";import{StringDecoder as Ye}from"node:string_decoder";function Xe(e,t={}){let n=[e.command];return e.command===`snapshot`?oe(n,e):e.command===`open`?le(n,e):e.command===`runtime`?ae(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?pe(n,e):e.command===`screenshot`?ue(n,e):fe(n,e),n.join(` `)}function Ze(e){return e.targetEvidences?[c(e.targetEvidences)]:e.targetEvidence?[s(e.targetEvidence)]:[]}function w(e){return e?.scriptPublication??m}function Qe(e,t){let n=w(e),r=typeof t.saveScript==`string`?x(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath;e.scriptPublication=Me(n,{requested:{path:r,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function $e(e){e.scriptPublication=we(w(e))}function et(e){e.scriptPublication=Ne(w(e))}function tt(e,t){e.scriptPublication=xe(w(e),t)}function nt(e){e.scriptPublication=Se(w(e))}function rt(e,t){let n=w(e);return n.kind===`repair`&&n.closeReceipt===t}function it(e){return w(e).kind===`repair`}function at(e){return he(w(e))}function T(e){return _e(w(e))}function ot(e){return ge(w(e))}function st(e,t){if(t.flags?.noRecord||_t(e,t))return;t.flags&&Ae(e,t.flags);let n=lt(t),r=ft(e,ut(t,n));n&&dt(e,n);let i={ts:Date.now(),command:r.command,positionals:r.positionals,runtime:r.runtime,flags:yt(r.flags),result:r.result,...r.targetEvidence?{targetEvidence:r.targetEvidence}:{},...r.targetEvidences?{targetEvidences:r.targetEvidences}:{}};return e.actions.push(i),y({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),i}function ct(e,t,n,r,i,a){t&&e.recordAction(t,{command:r,positionals:a?.positionals??n.positionals??[],flags:a?.flags??n.flags??{},result:i??{}})}function lt(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return;let t=ye(e.flags.recordAs),n=ve(t);return{literal:p({ts:0,command:e.command,positionals:e.positionals,flags:e.flags}),placeholder:n}}function ut(e,t){if(!t)return e;let{literal:n,placeholder:r}=t;return{...e,positionals:mt(e.positionals,r),result:je(e.result,n,r),targetEvidence:Oe(e.targetEvidence,n,r)}}function dt(e,t){t.literal.trim()&&(e.recordedFillLiterals??=new Map,!e.recordedFillLiterals.has(t.literal)&&e.recordedFillLiterals.set(t.literal,t.placeholder))}function ft(e,t){let n=e.recordedFillLiterals;if(!n||n.size===0)return t;let r=ke(t.result,n),i=(t.targetEvidenceMode??`action`)===`landmark`?pt(t.targetEvidence,n):E(t.targetEvidence,n),a=t.targetEvidences?{source:E(t.targetEvidences.source,n),destination:E(t.targetEvidences.destination,n)}:t.targetEvidences;return{...t,result:r,targetEvidence:i,targetEvidences:a}}function pt(e,t){return e&&(Ce(e,t)?void 0:e)}function E(e,t){return!e||!Ce(e,t)?e:{...Te(e,t),verification:`unverifiable`}}function mt(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const ht=new Set([`snapshot`,`get`,`is`,`find`]);function gt(e){return e.internal?.replayPlanStep!==!0&&ht.has(e.command)}function _t(e,t){return!t.interactiveObservation||T(e)===void 0?!1:t.flags?.record!==!0}const vt=Le();function yt(e){if(!e)return{};let t={};for(let n of vt){let r=e[n];r!==void 0&&(t[n]=r)}return t}function D(e){return S.join(e,`idle-expiry.json`)}function bt(e){let t;try{t=C.readFileSync(e,`utf8`)}catch{return}let n;try{n=JSON.parse(t)}catch{return}if(!(typeof n?.expiresAt!=`number`||!Number.isFinite(n.expiresAt))&&!(n.expiresAt<=Date.now())&&typeof n.owner==`string`&&!(!xt(n.expiredAtMs)||!xt(n.idleExpiryMs))&&(n.deviceKey===void 0||typeof n.deviceKey==`string`))return n}function xt(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0}function St(t){let n=t.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new e(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(t.some(e=>e.command===`close`))throw new e(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[e,n]of t.entries())ne({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=e);if(!t.slice(r+1).some(Ot))throw new e(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function Ct(t){for(let n of t){if(wt(n)){Tt(n);continue}let t=kt(n),r=t??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&ne(n)===`mutates-app`)throw new e(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=t;if(!(!i||!l(i)||n.targetEvidence))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function wt(e){return Et(e)!==void 0}function Tt(t){let n=Et(t);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!l(n))&&!t.targetEvidences)throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function Et(e){return e.command===`gesture`?me(e.positionals):void 0}function Dt(t,n){if(t instanceof e){if(t.details?.reason===`script_target_exists`)return new e(t.code,`A file already exists at ${String(t.details.path)}.`,{...t.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=t.details?.retriable===!0;return new e(t.code,t.message,{...t.details,retriable:n,hint:t.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Ot(e){if(e.command!==`wait`)return!1;let t=ee(e.positionals);return t?.kind!==`selector`||!l(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function kt(e){if(e.command===`get`)return e.positionals[1];if(se(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&At(t)&&At(n)?void 0:t}}function At(e){return e.trim().length>0&&Number.isFinite(Number(e))}function jt(e){let t=e.scriptPublication??m;return t.kind===`repair`?t.status===`committed`||!be(t):!1}function Mt(e){return!Pe(e.scriptPublication??m)||jt(e)}var Nt=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=it(e),r=t?.publication===`active`,i;try{if(Mt(e))return{written:!1};let a=Pt(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=S.dirname(i);return C.existsSync(o)||C.mkdirSync(o,{recursive:!0}),Lt({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=Fe(e.scriptPublication??m)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return Ft({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=Ee(e.scriptPublication??m);if(t)return x(t);let n=b(e.name),r=new Date(e.createdAt).toISOString().replaceAll(/[:.]/g,`-`);return S.join(this.sessionsDir,`${n}-${r}.ad`)}};function Pt(e,t){let n=Rt(e,{strictPortableRefs:t.activePublication});return t.activePublication&&St(n),{script:Jt(e,n,t.appendCompleteSentinel),actionCount:n.length}}function Ft(t){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=t;if(y({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:It(r,i)};if(o)return{written:!1,error:Dt(r,i)};if(r instanceof e)throw r;return{written:!1}}function It(t,n){if(t instanceof e)return t;let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to write the healed script${n?` to ${n}`:``}: ${r}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function Lt(t){let{scriptPath:n,script:r,force:i}=t;try{He({destination:n,contents:r,publish:i?`replace`:`link-exclusive`})}catch(t){throw t.code===`EEXIST`?new e(`COMMAND_FAILED`,`A file already exists at ${n}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:n}):t}}function Rt(e,t={}){let n=T(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=Vt(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&zt(n);let o=qt(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&Ct(a),a}function zt(t){let n=t.command===`gesture`?me(t.positionals??[]):void 0;if(n){Bt(n);return}if(!O(t.command))return;let r=t.command===`get`?t.positionals?.[1]:t.positionals?.[0];if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot write recorded step "${t.command} ${r}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function Bt(t){let n=[t.source,t.destination].find(e=>e.startsWith(`@`));if(n)throw new e(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function Vt(e){let t=Ht(e);if(!(!t||!O(e.command)))return ce(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?Wt(e,t):e.command===`fill`?Ut(e,t):Gt(e,t)}function Ht(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function O(e){return se(e)||e===`fill`||e===`get`}function Ut(e,t){let n=p(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function Wt(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):Kt(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Gt(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function Kt(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function qt(e,t){if(!O(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r}}}function Jt(e,t,n){let i=[],a=e.device.kind?` kind=${e.device.kind}`:``;i.push(`context platform=${r(e.device)} device=${de(e.device.name)}${a} theme=unknown`);for(let e of t)e.flags?.noRecord||(i.push(...Ze(e)),i.push(Yt(e)));return n&&i.push(`# agent-device:heal-complete`),`${i.join(`
|
|
2
|
-
`)}\n`}function Yt(e){return Xt([e.command],e)||Xe(e)}function Xt(e,t){if(ce(t.command))return Zt(e,t);if(t.command===`fill`)return Qt(e,t);if(t.command===`get`)return $t(e,t)}function Zt(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(d(u(n))),k(e,t),f(e,t),e.join(` `);if(t.positionals.length===1)return e.push(d(n)),f(e,t),e.join(` `)}}function Qt(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(d(u(n))),k(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(d(r)),f(e,t),e.join(` `)}function $t(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(d(n)),e.push(d(u(r))),r.startsWith(`@`)&&k(e,t),e.join(` `)}function k(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(d(n))}const en=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],tn={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function nn(e,t){let n=t??{};switch(e.command){case h.devices:return rn(n.devices);case h.apps:return an(n.apps,e.flags?.appsFilter);case h.boot:return on(`Booted`,n,!0);case h.shutdown:return on(`Shut down`,n,!1);case h.install:return sn(`Installed`,n);case h.reinstall:return sn(`Reinstalled`,n);case h.screenshot:return cn(e,n);default:return{}}}function rn(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=un(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:yn(`Found ${t.length} ${bn(`device`,t.length)}`,i.map(e=>_n(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function an(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=M(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:yn(`Found ${n.length} ${bn(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function on(e,t,n){let r=dn(t);if(!r)return{};let i={device:r,...gn(t),booted:n};return{summary:`${e} ${_n(i,!1)}`,details:i}}function sn(e,t){let n=M(t.appName),r=M(t.bundleId),i=A(t,[`packageName`,`package`]),a=M(t.platform),o=M(t.launchTarget),s=A(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=vn(n,s);if(!c)return{};let l={};return j(l,`appName`,n),j(l,`bundleId`,r),j(l,`packageName`,i),j(l,`platform`,a),o!==s&&j(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function cn(e,t){let n=ln(e,t);return n?{details:{requestedFileName:n}}:{}}function ln(e,t){let n=R(e.meta?.clientArtifactPaths?.path)??R(t.path);if(n)return L(n)}function un(e){if(!n(e))return;let t=dn(e);if(t)return{name:t,...gn(e)}}function dn(e){let t=A(e,[`name`,`deviceName`,`device`]);return!t||!fn(e,t)?t:mn(e)}function fn(e,t){let n=pn(t);return en.some(t=>{let r=M(e[t]);return r!==void 0&&pn(r)===n})}function pn(e){return e.toLowerCase()}function mn(e){let t=M(e.appleOs),n=M(e.platform),r=M(e.kind),i=hn(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function hn(e,t){let n=e??t;if(!(!n||!Object.hasOwn(tn,n)))return tn[n]}function gn(e){let t=M(e.platform),n=M(e.appleOs),r=M(e.kind),i=M(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function _n(e,t){let n=M(e.name)??M(e.device)??`device`,r=M(e.platform),i=M(e.appleOs),a=[r,i===r?void 0:i,M(e.kind),M(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function vn(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function A(e,t){for(let n of t){let t=M(e[n]);if(t)return t}}function j(e,t,n){n&&(e[t]=n)}function yn(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function bn(e,t){return t===1?e:`${e}s`}function M(e){let t=R(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function N(e){return M(e)}function P(e){return typeof e==`boolean`?e:void 0}function F(e,t){let n=N(e);return n&&t.includes(n)?n:void 0}function I(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function L(e){let t=R(e);return t?M(t.split(/[\\/]/).at(-1)):void 0}function R(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function z(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const xn=[`up`,`down`,`left`,`right`],Sn=[`top`,`bottom`];function Cn(e){return`${e.command===h.reinstall?`Reinstalled`:`Installed`} ${Dn(e.result??{})??`app`}`}function wn(e){let t=e.result??{};switch(e.command){case h.scroll:return kn(t);case h.screenshot:return Mn(t);case h.home:return`Went home`;case h.back:return Pn(t);case h.appSwitcher:return`Opened app switcher`;case h.actionButton:return`Pressed Action Button`;case h.orientation:return In(t);case h.fold:return Fn(t);case h.viewport:return Ln(t);case h.clipboard:return Rn(t);case h.keyboard:return zn(t);case h.tvRemote:return Hn(t);case h.gesture:return Un(t);case h.swipe:return Wn(t);case h.trace:return Kn(`trace`,e);case h.record:return Kn(`recording`,e);default:return}}function Tn(e){let t=e.result??{};switch(e.command){case h.scroll:return I({direction:F(t.direction,xn),edge:F(t.edge,Sn),passes:z(t.passes),amount:z(t.amount),pixels:z(t.pixels),durationMs:z(t.durationMs),x1:z(t.x1),y1:z(t.y1),x2:z(t.x2),y2:z(t.y2)});case h.screenshot:return I({requestedFileName:Nn(t)});case h.back:return I({mode:F(t.mode,g)});case h.orientation:return I({orientation:F(t.orientation,Ve)});case h.fold:return I({pose:F(t.pose,_)});case h.viewport:return I({width:z(t.width),height:z(t.height)});case h.clipboard:return I({action:F(t.action,[`read`,`write`])});case h.keyboard:return Vn(t);case h.tvRemote:return I({button:F(t.button,Ue),durationMs:z(t.durationMs)});case h.gesture:case h.swipe:return Gn(t);case h.trace:case h.record:return I({action:F(t.action,[`start`,`stop`]),fileName:Jn(e),showTouches:P(t.showTouches)});default:return{}}}function En(e,t){if(e.command!==h.screenshot)return t;let n=ln(e,t);return n?{...t,requestedFileName:n}:t}function Dn(e){let t=N(e.appName),n=Yn(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??On(e)}function On(e){let t=N(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function kn(e){let t=F(e.direction,xn),n=F(e.edge,Sn),r=z(e.passes);return n?An(n,r):t?jn(t,e):`Scrolled`}function An(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function jn(e,t){let n=z(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=z(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function Mn(e){let t=Nn(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function Nn(e){return L(e.requestedFileName)??L(e.path)}function Pn(e){return F(e.mode,g)===`system`?`Went back using system navigation`:`Went back`}function Fn(e){let t=F(e.pose,_);return t?`Folded to ${t}`:`Changed fold pose`}function In(e){let t=F(e.orientation,Ve);return t?P(e.confirmed)===!1?`Requested ${t} (unconfirmed)`:`Rotated to ${t}`:`Changed orientation`}function Ln(e){let t=z(e.width),n=z(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function Rn(e){let t=F(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function zn(e){let t=R(e.action);if(!t||!qe(t))return`Used keyboard`;if(t===`dismiss`)return Bn(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=P(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function Bn(e){return P(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function Vn(e){let t=R(e.action);return I({action:t&&qe(t)?t:void 0,platform:F(e.platform,[`ios`,`android`]),visible:P(e.visible),wasVisible:P(e.wasVisible),dismissed:P(e.dismissed),attempts:z(e.attempts),mechanism:F(e.mechanism,[`dismissKey`])})}function Hn(e){let t=F(e.button,Ue);return t?`Pressed TV remote ${t}`:`Used TV remote`}function Un(e){let t=F(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function Wn(e){let t=z(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function Gn(e){return I({kind:F(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:z(e.durationMs),pointerCount:z(e.pointerCount),x1:z(e.x1),y1:z(e.y1),x2:z(e.x2),y2:z(e.y2),count:z(e.count),pauseMs:z(e.pauseMs),pattern:F(e.pattern,[`one-way`,`ping-pong`]),scale:z(e.scale)})}function Kn(e,t){let n=qn(e,F(t.result?.action,[`start`,`stop`])),r=Jn(t);return r?`${n} ${r}`:n}function qn(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function Jn(e){let t=e.result??{};return L(t.requestedFileName)??L(t.outPath)??L(t.path)??L(e.positionals[1])}function Yn(e,t){for(let n of t){let t=N(e[n]);if(t)return t}}function Xn(e){switch(e.command){case h.open:return`Opened ${B(e)??`session`}`;case h.close:return`Closed ${N(e.result?.session)??`session`}`;case h.click:case h.press:return`Tapped ${B(e)??`target`}`;case h.longPress:return`Long pressed ${B(e)??`target`}`;case h.hover:return`Hovered ${B(e)??`target`}`;case h.fill:return`Filled ${B(e)??`target`}`;case h.type:return`Typed text`;case h.install:case h.reinstall:case Ie.installSource:return Cn(e);default:return wn(e)??`Ran ${e.command}`}}function Zn(e){return I({command:e.command,positionals:or(e),flags:vr(e),...Qn(e),...$n(e),...er(e),...Tn(e)})}function Qn(e){if(!tr(e.command))return{};let t=e.result??{};return I({ref:G(t),targetLabel:B(e),selectorChainLength:mr(t.selectorChain)?.length,x:z(t.x),y:z(t.y),x2:z(t.x2),y2:z(t.y2),durationMs:z(t.durationMs)})}function $n(e){if(!nr(e.command))return{};let t=e.result??{};return I({platform:F(t.platform,i),target:F(t.target,o),appName:N(t.appName),appBundleId:N(t.appBundleId),bundleId:N(t.bundleId),packageName:N(t.packageName),launchTarget:N(t.launchTarget)})}function er(e){let t=e.result??{};return e.command===h.snapshot?Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}:e.command!==h.wait&&e.command!==h.find&&e.command!==h.get&&e.command!==h.is?{}:I({waitedMs:z(t.waitedMs),found:P(t.found)})}function tr(e){return e===h.click||e===h.press||e===h.longPress||e===h.hover||e===h.focus||e===h.fill}function nr(e){return e===h.open||e===h.install||e===h.reinstall||e===Ie.installSource}function B(e){let t=e.result??{};return rr(t)??ir(t)??ar(t)??fr(e.positionals[0])}function rr(e){let t=G(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function ir(e){let t=z(e.x),n=z(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function ar(e){return N(e.appName)??N(e.appBundleId)??N(e.bundleId)??N(e.packageName)}function or(e){if(e.positionals.length!==0)return e.command===h.type?[H(`text`)]:e.command===h.fill?sr(e):e.command===h.find?cr(e):e.command===h.clipboard?lr(e):e.command===h.push?ur(e,`app`,`payload`):e.command===h.triggerAppEvent?ur(e,`event`,`payload`):e.positionals.map(V)}function sr(e){let t=H(`text`),n=e.result??{},r=G(n);if(r)return[`@${r}`,t];if(N(n.selector))return[H(`target`),t];let i=z(n.x),a=z(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function cr(e){let t=+!!pr(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],H(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,H(`text`)]:[...r,...e.positionals.slice(n).map(dr)]:r}function lr(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,H(`text`)]:e.positionals.map(V)}function ur(e,t,n){let[r,i,...a]=e.positionals;return[...r?[H(t)]:[],...i?[H(n)]:[],...a.map(V)]}function dr(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:V(e)}function V(e){return fr(e)??H(`arg`)}function fr(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function H(e){return`<${e}>`}function pr(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function mr(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const hr={enums:[{source:`platform`,values:a},{source:`target`,values:o}]},gr={booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}]},_r={[h.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:Re}]},[h.click]:U(),[h.press]:U(),[h.longPress]:U(),[h.hover]:U(),[h.fill]:br(),[h.type]:br(),[h.scroll]:{numbers:[{source:`pixels`},{source:`durationMs`}]},[h.gesture]:xr(),[h.swipe]:xr(),[h.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[h.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[h.back]:{enums:[{source:`backMode`,output:`mode`,values:g}]},[h.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:re}]},[h.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[h.boot]:{booleans:[{source:`headless`}]},[h.close]:{booleans:[{source:`shutdown`}]}};function vr(e){let t=e.flags??{},n={},r=Object.hasOwn(_r,e.command)?_r[e.command]:void 0;return W(n,t,hr),W(n,t,r),W(n,t,yr(e.command)),Object.keys(n).length>0?n:void 0}function yr(e){return te(e)?gr:void 0}function U(){return{booleans:[{source:`doubleTap`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`}],enums:[{source:`clickButton`,values:Be}]}}function br(){return{numbers:[{source:`delayMs`}]}}function xr(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:ie}]}}function W(e,t,n){n&&(Sr(e,t,n.booleans??[]),Cr(e,t,n.numbers??[]),wr(e,t,n.enums??[]))}function Sr(e,t,n){for(let r of n)Tr(e,r.output??r.source,t[r.source])}function Cr(e,t,n){for(let r of n)Er(e,r.output??r.source,t[r.source])}function wr(e,t,n){for(let r of n)Dr(e,r.output??r.source,t[r.source],r.values)}function G(e){let t=N(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function Tr(e,t,n){typeof n==`boolean`&&(e[t]=n)}function Er(e,t,n){let r=z(n);r!==void 0&&(e[t]=r)}function Dr(e,t,n,r){let i=F(n,r);i!==void 0&&(e[t]=i)}const Or=65536;function kr(e){return Je(`sha256`).update(e,`utf8`).digest(`hex`).slice(0,32)}function K(e,t){let n=Nr(e);if(n===void 0)return!1;try{let e=jr(t),r=Buffer.allocUnsafe(Or),i=0;do if(i=C.readSync(n,r,0,r.length,null),!e.push(r.subarray(0,i)))return!0;while(i>0);return e.end(),!0}finally{C.closeSync(n)}}async function Ar(e){let t=await Pr(e);if(t===void 0)return{lineCount:0,firstLineDigest:void 0};let n={lineCount:0,firstLineDigest:void 0};try{let e=jr(e=>{n.lineCount===0&&(n.firstLineDigest=kr(e)),n.lineCount+=1}),r=Buffer.allocUnsafe(Or);for(;;){let{bytesRead:n}=await t.read(r,0,r.length,null);if(e.push(r.subarray(0,n)),n===0)break}return e.end(),n}finally{await t.close()}}function q(e){let t;return K(e,e=>(t=kr(e),!1)),t}function jr(e){let t=new Ye(`utf8`),n=``,r=!1;return{push(i){if(r)return!1;let a=`${n}${t.write(i)}`,o=0;for(let t=a.indexOf(`
|
|
1
|
+
import{N as e,tt as t}from"./sdk-contracts.js";import{_ as n}from"./sdk-batch-runner.js";import{C as r,a as i,i as a,n as o}from"./sdk-device.js";import{$n as s,S as c,er as l,ln as u,m as ee,sn as te}from"./sdk-batch.js";import{t as ne}from"./recording-scope.js";import{a as re}from"./scroll-gesture.js";import{_ as d,c as ie,d as ae,g as oe,h as se,i as ce,l as le,m as ue,o as de,p as f,s as fe,u as p,y as pe}from"./script.js";import{A as m,C as me,D as he,E as ge,M as _e,N as ve,S as ye,T as be,_ as xe,a as Se,b as Ce,g as h,i as we,k as Te,l as Ee,n as De,r as Oe,s as ke,t as Ae,v as je,w as Me,x as Ne,y as Pe}from"./parameterized-recorded-fill.js";import{n as g,t as Fe}from"./catalog.js";import{o as Ie,t as _}from"./back-mode.js";import{t as Le}from"./session.js";import{r as Re}from"./success-text.js";import{t as ze}from"./click-button.js";import"./device.js";import{r as Be,t as Ve}from"./device-rotation.js";import{a as v,r as y}from"./diagnostics.js";import{k as He}from"./owner-identity.js";import"./file.js";import{t as Ue}from"./tv-remote.js";import"./diagnostics2.js";import{n as We,r as Ge}from"./session-repair-tombstone.js";import{n as Ke,r as b,t as x}from"./session-paths.js";import{t as qe}from"./keyboard-actions.js";import S from"node:path";import C from"node:fs";import{createHash as Je}from"node:crypto";import{StringDecoder as Ye}from"node:string_decoder";function Xe(e,t={}){let n=[e.command];return e.command===`snapshot`?ae(n,e):e.command===`open`?ce(n,e):e.command===`runtime`?ie(n,e,{includeAllPositionals:t.runtimeIncludeAllPositionals}):e.command===`record`?fe(n,e):e.command===`screenshot`?le(n,e):de(n,e),n.join(` `)}function Ze(e){return e.targetEvidences?[s(e.targetEvidences)]:e.targetEvidence?[l(e.targetEvidence)]:[]}function w(e){return e?.scriptPublication??h}function Qe(e,t){let n=w(e),r=typeof t.saveScript==`string`?x(t.saveScript):n.kind===`repair`?void 0:t.healedSiblingPath;e.scriptPublication=je(n,{requested:{path:r,force:t.force===!0},boundary:t.firstArm?e.actions.length:0,sourcePath:t.sourcePath})}function $e(e){e.scriptPublication=Ce(w(e))}function et(e){e.scriptPublication=Me(w(e))}function tt(e,t){e.scriptPublication=be(w(e),t)}function nt(e){e.scriptPublication=xe(w(e))}function rt(e,t){let n=w(e);return n.kind===`repair`&&n.closeReceipt===t}function it(e){return w(e).kind===`repair`}function at(e){return me(w(e))}function T(e){return ge(w(e))}function ot(e){return he(w(e))}function st(e,t){if(t.flags?.noRecord||_t(e,t))return;t.flags&&ke(e,t.flags);let n=lt(t),r=ft(e,ut(t,n));n&&dt(e,n);let i={ts:Date.now(),command:r.command,positionals:r.positionals,runtime:r.runtime,flags:yt(r.flags),result:r.result,...r.targetEvidence?{targetEvidence:r.targetEvidence}:{},...r.targetEvidences?{targetEvidences:r.targetEvidences}:{}};return e.actions.push(i),y({level:`debug`,phase:`record_action`,data:{command:t.command,session:e.name}}),i}function ct(e,t,n,r,i,a){t&&e.recordAction(t,{command:r,positionals:a?.positionals??n.positionals??[],flags:a?.flags??n.flags??{},result:i??{}})}function lt(e){if(e.command!==`fill`||typeof e.flags.recordAs!=`string`)return;let t=ve(e.flags.recordAs),n=_e(t);return{literal:m({ts:0,command:e.command,positionals:e.positionals,flags:e.flags}),placeholder:n}}function ut(e,t){if(!t)return e;let{literal:n,placeholder:r}=t;return{...e,positionals:mt(e.positionals,r),result:Ae(e.result,n,r),targetEvidence:De(e.targetEvidence,n,r)}}function dt(e,t){t.literal.trim()&&(e.recordedFillLiterals??=new Map,!e.recordedFillLiterals.has(t.literal)&&e.recordedFillLiterals.set(t.literal,t.placeholder))}function ft(e,t){let n=e.recordedFillLiterals;if(!n||n.size===0)return t;let r=Oe(t.result,n),i=(t.targetEvidenceMode??`action`)===`landmark`?pt(t.targetEvidence,n):E(t.targetEvidence,n),a=t.targetEvidences?{source:E(t.targetEvidences.source,n),destination:E(t.targetEvidences.destination,n)}:t.targetEvidences;return{...t,result:r,targetEvidence:i,targetEvidences:a}}function pt(e,t){return e&&(Se(e,t)?void 0:e)}function E(e,t){return!e||!Se(e,t)?e:{...we(e,t),verification:`unverifiable`}}function mt(e,t){let n=e[0];return n?.startsWith(`@`)?e.length>=3?[n,e[1],t]:[n,t]:e.length>=3&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))?[e[0],e[1],t]:n===void 0?[t]:[n,t]}const ht=new Set([`snapshot`,`get`,`is`,`find`]);function gt(e){return e.internal?.replayPlanStep!==!0&&ht.has(e.command)}function _t(e,t){return!t.interactiveObservation||T(e)===void 0?!1:t.flags?.record!==!0}const vt=Ie();function yt(e){if(!e)return{};let t={};for(let n of vt){let r=e[n];r!==void 0&&(t[n]=r)}return t}function D(e){return S.join(e,`idle-expiry.json`)}function bt(e){let t;try{t=C.readFileSync(e,`utf8`)}catch{return}let n;try{n=JSON.parse(t)}catch{return}if(!(typeof n?.expiresAt!=`number`||!Number.isFinite(n.expiresAt))&&!(n.expiresAt<=Date.now())&&typeof n.owner==`string`&&!(!xt(n.expiredAtMs)||!xt(n.idleExpiryMs))&&(n.deviceKey===void 0||typeof n.deviceKey==`string`))return n}function xt(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0}function St(t){let n=t.flatMap((e,t)=>e.command===`open`?[t]:[]);if(n.length!==1||n[0]!==0)throw new e(`COMMAND_FAILED`,`Cannot publish this session: an open-to-destination script requires exactly one initial recorded open.`,{retriable:!1,hint:`Close this session and start a fresh one with open <app> --save-script[=<path>].`});if(t.some(e=>e.command===`close`))throw new e(`COMMAND_FAILED`,`Cannot publish an active-session script containing close.`,{retriable:!1,hint:`Close this session and record the journey again from a fresh open --save-script session.`});let r=-1;for(let[e,n]of t.entries())c({command:n.command,positionals:n.positionals,flags:n.flags})===`mutates-app`&&(r=e);if(!t.slice(r+1).some(Ot))throw new e(`COMMAND_FAILED`,`Cannot publish this session without a portable destination guard after the final mutating action.`,{retriable:!0,hint:`Record a selector-targeted wait on a labeled or id-bearing landmark, for example wait 'role="heading" label="Screen X"', so its recorded identity is captured, then retry session save-script.`})}function Ct(t){for(let n of t){if(wt(n)){Tt(n);continue}let t=kt(n),r=t??(n.command===`wait`?n.positionals[0]:void 0);if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${r}": the session-local ref was not converted to a portable selector.`,{retriable:!1,hint:`Close this session and record the journey again using selectors or resolvable refs.`});if(n.command===`find`&&c(n)===`mutates-app`)throw new e(`COMMAND_FAILED`,`Cannot publish a recorded mutating find step because its target identity is not replay-verifiable.`,{retriable:!1,hint:`Close this session and record the journey again with an explicit selector-targeted click, press, fill, or focus action.`});let i=t;if(!(!i||!u(i)||n.targetEvidence))throw new e(`COMMAND_FAILED`,`Cannot publish recorded step "${n.command} ${i}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again from open --save-script so target-v1 evidence is captured before each interaction.`})}}function wt(e){return Et(e)!==void 0}function Tt(t){let n=Et(t);if(!n)return;let r=[n.source,n.destination];for(let n of r){if(n?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": the session-local ref was not converted to a portable selector.`,{retriable:!1});if(!(!n||!u(n))&&!t.targetEvidences)throw new e(`COMMAND_FAILED`,`Cannot publish recorded drag endpoint "${n}": recording-time target identity evidence is missing.`,{retriable:!1,hint:`Close this session and record the journey again so targets-v1 evidence is captured for both drag endpoints.`})}}function Et(e){return e.command===`gesture`?pe(e.positionals):void 0}function Dt(t,n){if(t instanceof e){if(t.details?.reason===`script_target_exists`)return new e(t.code,`A file already exists at ${String(t.details.path)}.`,{...t.details,retriable:!0,hint:`Retry session save-script with another path, or pass --force to replace the existing file. The session remains armed.`});let n=t.details?.retriable===!0;return new e(t.code,t.message,{...t.details,retriable:n,hint:t.details?.hint??(n?`Fix the recorded journey or target, then retry session save-script. The session remains armed.`:`Close this session and start a fresh one with open <app> --save-script[=<path>].`)})}let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to publish the active session script${n?` to ${n}`:``}: ${r}`,{retriable:!0,hint:`Check the target path and permissions, then retry session save-script. The session remains armed.`})}function Ot(e){if(e.command!==`wait`)return!1;let t=te(e.positionals);return t?.kind!==`selector`||!u(t.selectorExpression)?!1:e.targetEvidence?.verification===`verified`}function kt(e){if(e.command===`get`)return e.positionals[1];if(oe(e.command)||e.command===`fill`){let[t,n]=e.positionals;return t!==void 0&&n!==void 0&&At(t)&&At(n)?void 0:t}}function At(e){return e.trim().length>0&&Number.isFinite(Number(e))}function jt(e){let t=e.scriptPublication??h;return t.kind===`repair`?t.status===`committed`||!ye(t):!1}function Mt(e){return!Ne(e.scriptPublication??h)||jt(e)}var Nt=class{sessionsDir;constructor(e){this.sessionsDir=e}write(e,t){let n=it(e),r=t?.publication===`active`,i;try{if(Mt(e))return{written:!1};let a=Pt(e,{appendCompleteSentinel:n,activePublication:r});i=this.resolveScriptPath(e);let o=S.dirname(i);return C.existsSync(o)||C.mkdirSync(o,{recursive:!0}),Lt({scriptPath:i,script:a.script,force:t?.force}),n&&(e.scriptPublication=Pe(e.scriptPublication??h)),{written:!0,path:i,actionCount:a.actionCount}}catch(t){return Ft({session:e,error:t,scriptPath:i,repairArmed:n,activePublication:r})}}resolveScriptPath(e){let t=Te(e.scriptPublication??h);if(t)return x(t);let n=b(e.name),r=new Date(e.createdAt).toISOString().replaceAll(/[:.]/g,`-`);return S.join(this.sessionsDir,`${n}-${r}.ad`)}};function Pt(e,t){let n=Rt(e,{strictPortableRefs:t.activePublication});return t.activePublication&&St(n),{script:Jt(e,n,t.appendCompleteSentinel),actionCount:n.length}}function Ft(t){let{session:n,error:r,scriptPath:i,repairArmed:a,activePublication:o}=t;if(y({level:`warn`,phase:`session_script_write_failed`,data:{session:n.name,path:i,error:r instanceof Error?r.message:String(r)}}),a)return{written:!1,error:It(r,i)};if(o)return{written:!1,error:Dt(r,i)};if(r instanceof e)throw r;return{written:!1}}function It(t,n){if(t instanceof e)return t;let r=t instanceof Error?t.message:String(t);return new e(`COMMAND_FAILED`,`Failed to write the healed script${n?` to ${n}`:``}: ${r}`,{hint:`The repair transaction completed but the healed .ad could not be published; check the target path and permissions, then retry close --save-script.`})}function Lt(t){let{scriptPath:n,script:r,force:i}=t;try{He({destination:n,contents:r,publish:i?`replace`:`link-exclusive`})}catch(t){throw t.code===`EEXIST`?new e(`COMMAND_FAILED`,`A file already exists at ${n}; remove it, pass replay --save-script=<other-path>, or pass --force/--overwrite to replace it.`,{reason:`script_target_exists`,path:n}):t}}function Rt(e,t={}){let n=T(e),r=n!==void 0,i=e.actions.slice(n??0),a=[];for(let n of i){if(n.command===`snapshot`)continue;let i=Vt(n);if(i){a.push(i);continue}(r||t.strictPortableRefs)&&zt(n);let o=qt(e,n);o&&a.push(o),a.push(n)}return t.strictPortableRefs&&Ct(a),a}function zt(t){let n=t.command===`gesture`?pe(t.positionals??[]):void 0;if(n){Bt(n);return}if(!O(t.command))return;let r=t.command===`get`?t.positionals?.[1]:t.positionals?.[0];if(r?.startsWith(`@`))throw new e(`COMMAND_FAILED`,`Cannot write recorded step "${t.command} ${r}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function Bt(t){let n=[t.source,t.destination].find(e=>e.startsWith(`@`));if(n)throw new e(`COMMAND_FAILED`,`Cannot write recorded drag endpoint "${n}" to a script: it never resolved to a selector, so the ref would not resolve in a fresh replay session.`)}function Vt(e){let t=Ht(e);if(!(!t||!O(e.command)))return se(e.command)||e.command===`hover`?{...e,positionals:[t]}:e.command===`longpress`?Wt(e,t):e.command===`fill`?Ut(e,t):Gt(e,t)}function Ht(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>typeof e==`string`)?e.result.selectorChain:[];return t.length>0?t.join(` || `):void 0}function O(e){return oe(e)||e===`fill`||e===`get`}function Ut(e,t){let n=m(e);return n.length>0?{...e,positionals:[t,n]}:void 0}function Wt(e,t){let n=typeof e.result?.durationMs==`number`?String(e.result.durationMs):Kt(e.positionals??[]);return{...e,positionals:n?[t,n]:[t]}}function Gt(e,t){let n=e.positionals?.[0];return n===`text`||n===`attrs`?{...e,positionals:[n,t]}:void 0}function Kt(e){let t=e.at(-1);if(!(e.length<=1||t===void 0||t.trim()===``))return Number.isFinite(Number(t))?t:void 0}function qt(e,t){if(!O(t.command))return;let n=t.result?.refLabel;if(typeof n!=`string`||n.trim().length===0)return;let r=n.trim();return{ts:t.ts,command:`snapshot`,positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotScope:r},result:{scope:r}}}function Jt(e,t,n){let i=[],a=e.device.kind?` kind=${e.device.kind}`:``;i.push(`context platform=${r(e.device)} device=${ue(e.device.name)}${a} theme=unknown`);for(let e of t)e.flags?.noRecord||(i.push(...Ze(e)),i.push(Yt(e)));return n&&i.push(`# agent-device:heal-complete`),`${i.join(`
|
|
2
|
+
`)}\n`}function Yt(e){return Xt([e.command],e)||Xe(e)}function Xt(e,t){if(se(t.command))return Zt(e,t);if(t.command===`fill`)return Qt(e,t);if(t.command===`get`)return $t(e,t)}function Zt(e,t){let n=t.positionals?.[0];if(n){if(n.startsWith(`@`))return e.push(f(d(n))),k(e,t),p(e,t),e.join(` `);if(t.positionals.length===1)return e.push(f(n)),p(e,t),e.join(` `)}}function Qt(e,t){let n=t.positionals?.[0];if(!n?.startsWith(`@`))return;e.push(f(d(n))),k(e,t);let r=t.positionals.slice(1).join(` `);return t.positionals.length>1&&e.push(f(r)),p(e,t),e.join(` `)}function $t(e,t){let n=t.positionals?.[0],r=t.positionals?.[1];if(!(!n||!r))return e.push(f(n)),e.push(f(d(r))),r.startsWith(`@`)&&k(e,t),e.join(` `)}function k(e,t){let n=t.result?.refLabel;typeof n==`string`&&n.trim().length>0&&e.push(f(n))}const en=[`id`,`deviceId`,`device_id`,`serial`,`udid`,`device_udid`,`identifier`],tn={ios:`iOS`,ipados:`iPadOS`,tvos:`tvOS`,watchos:`watchOS`,visionos:`visionOS`,macos:`macOS`,apple:`Apple`,android:`Android`,linux:`Linux`,web:`Web`};function nn(e,t){let n=t??{};switch(e.command){case g.devices:return rn(n.devices);case g.apps:return an(n.apps,e.flags?.appsFilter);case g.boot:return on(`Booted`,n,!0);case g.shutdown:return on(`Shut down`,n,!1);case g.install:return sn(`Installed`,n);case g.reinstall:return sn(`Reinstalled`,n);case g.screenshot:return cn(e,n);default:return{}}}function rn(e){if(!Array.isArray(e))return{};let t=e.flatMap(e=>{let t=un(e);return t?[t]:[]}),n=t.slice(0,5),r=Math.max(0,t.length-n.length),i=t.slice(0,3);return{summary:yn(`Found ${t.length} ${bn(`device`,t.length)}`,i.map(e=>_n(e,!0)),Math.max(0,t.length-i.length)),details:{deviceCount:t.length,devices:n,...r>0?{omittedDeviceCount:r}:{}}}}function an(e,t){if(!Array.isArray(e))return{};let n=e.flatMap(e=>{let t=M(e);return t?[t]:[]}),r=n.slice(0,5),i=Math.max(0,n.length-r.length),a=n.slice(0,3);return{summary:yn(`Found ${n.length} ${bn(`app`,n.length)}`,a,Math.max(0,n.length-a.length)),details:{appCount:n.length,apps:r,...i>0?{omittedAppCount:i}:{},...t===`all`||t===`user-installed`?{filter:t}:{}}}}function on(e,t,n){let r=dn(t);if(!r)return{};let i={device:r,...gn(t),booted:n};return{summary:`${e} ${_n(i,!1)}`,details:i}}function sn(e,t){let n=M(t.appName),r=M(t.bundleId),i=A(t,[`packageName`,`package`]),a=M(t.platform),o=M(t.launchTarget),s=A(t,[`bundleId`,`packageName`,`package`,`appId`,`launchTarget`]),c=vn(n,s);if(!c)return{};let l={};return j(l,`appName`,n),j(l,`bundleId`,r),j(l,`packageName`,i),j(l,`platform`,a),o!==s&&j(l,`launchTarget`,o),{summary:`${e} ${c}`,details:l}}function cn(e,t){let n=ln(e,t);return n?{details:{requestedFileName:n}}:{}}function ln(e,t){let n=R(e.meta?.clientArtifactPaths?.path)??R(t.path);if(n)return L(n)}function un(e){if(!n(e))return;let t=dn(e);if(t)return{name:t,...gn(e)}}function dn(e){let t=A(e,[`name`,`deviceName`,`device`]);return!t||!fn(e,t)?t:mn(e)}function fn(e,t){let n=pn(t);return en.some(t=>{let r=M(e[t]);return r!==void 0&&pn(r)===n})}function pn(e){return e.toLowerCase()}function mn(e){let t=M(e.appleOs),n=M(e.platform),r=M(e.kind),i=hn(t,n);return i&&(r===`simulator`||r===`emulator`)?`${i} ${r}`:i?`${i} device`:r===`simulator`?`Simulator`:r===`emulator`?`Emulator`:`Unnamed device`}function hn(e,t){let n=e??t;if(!(!n||!Object.hasOwn(tn,n)))return tn[n]}function gn(e){let t=M(e.platform),n=M(e.appleOs),r=M(e.kind),i=M(e.target);return{...t?{platform:t}:{},...n?{appleOs:n}:{},...r?{kind:r}:{},...i?{target:i}:{},...typeof e.booted==`boolean`?{booted:e.booted}:{}}}function _n(e,t){let n=M(e.name)??M(e.device)??`device`,r=M(e.platform),i=M(e.appleOs),a=[r,i===r?void 0:i,M(e.kind),M(e.target),t&&typeof e.booted==`boolean`?e.booted?`booted`:`stopped`:void 0].filter(e=>!!e);return a.length>0?`${n} (${a.join(`, `)})`:n}function vn(e,t){return e&&t&&e!==t?`${e} (${t})`:e??t}function A(e,t){for(let n of t){let t=M(e[n]);if(t)return t}}function j(e,t,n){n&&(e[t]=n)}function yn(e,t,n){let r=[...t,...n>0?[`+${n} more`]:[]];return r.length>0?`${e}: ${r.join(`, `)}`:e}function bn(e,t){return t===1?e:`${e}s`}function M(e){let t=R(e);if(!t)return;let n=t.trim(),r=Array.from(n);return r.length<=120?n:`${r.slice(0,119).join(``)}…`}function N(e){return M(e)}function P(e){return typeof e==`boolean`?e:void 0}function F(e,t){let n=N(e);return n&&t.includes(n)?n:void 0}function I(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function L(e){let t=R(e);return t?M(t.split(/[\\/]/).at(-1)):void 0}function R(e){if(typeof e==`string`)return e.trim().length>0?e:void 0}function z(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}const xn=[`up`,`down`,`left`,`right`],Sn=[`top`,`bottom`];function Cn(e){return`${e.command===g.reinstall?`Reinstalled`:`Installed`} ${Dn(e.result??{})??`app`}`}function wn(e){let t=e.result??{};switch(e.command){case g.scroll:return kn(t);case g.screenshot:return Mn(t);case g.home:return`Went home`;case g.back:return Pn(t);case g.appSwitcher:return`Opened app switcher`;case g.actionButton:return`Pressed Action Button`;case g.orientation:return In(t);case g.fold:return Fn(t);case g.viewport:return Ln(t);case g.clipboard:return Rn(t);case g.keyboard:return zn(t);case g.tvRemote:return Hn(t);case g.gesture:return Un(t);case g.swipe:return Wn(t);case g.trace:return Kn(`trace`,e);case g.record:return Kn(`recording`,e);default:return}}function Tn(e){let t=e.result??{};switch(e.command){case g.scroll:return I({direction:F(t.direction,xn),edge:F(t.edge,Sn),passes:z(t.passes),amount:z(t.amount),pixels:z(t.pixels),durationMs:z(t.durationMs),x1:z(t.x1),y1:z(t.y1),x2:z(t.x2),y2:z(t.y2)});case g.screenshot:return I({requestedFileName:Nn(t)});case g.back:return I({mode:F(t.mode,_)});case g.orientation:return I({orientation:F(t.orientation,Ve)});case g.fold:return I({pose:F(t.pose,Be)});case g.viewport:return I({width:z(t.width),height:z(t.height)});case g.clipboard:return I({action:F(t.action,[`read`,`write`])});case g.keyboard:return Vn(t);case g.tvRemote:return I({button:F(t.button,Ue),durationMs:z(t.durationMs)});case g.gesture:case g.swipe:return Gn(t);case g.trace:case g.record:return I({action:F(t.action,[`start`,`stop`]),fileName:Jn(e),showTouches:P(t.showTouches)});default:return{}}}function En(e,t){if(e.command!==g.screenshot)return t;let n=ln(e,t);return n?{...t,requestedFileName:n}:t}function Dn(e){let t=N(e.appName),n=Yn(e,[`bundleId`,`packageName`,`appBundleId`,`launchTarget`]);return t&&n&&t!==n?`${t} (${n})`:t??n??On(e)}function On(e){let t=N(e.app);return t&&!t.includes(`/`)&&!t.includes(`\\`)?t:void 0}function kn(e){let t=F(e.direction,xn),n=F(e.edge,Sn),r=z(e.passes);return n?An(n,r):t?jn(t,e):`Scrolled`}function An(e,t){return t===0?`Already at ${e}`:t===void 0?`Scrolled to ${e}`:`Scrolled to ${e} in ${t} ${t===1?`pass`:`passes`}`}function jn(e,t){let n=z(t.pixels);if(n!==void 0)return`Scrolled ${e} by ${n}px`;let r=z(t.amount);return r===void 0?`Scrolled ${e}`:`Scrolled ${e} by ${r}`}function Mn(e){let t=Nn(e);return t?`Captured screenshot ${t}`:`Captured screenshot`}function Nn(e){return L(e.requestedFileName)??L(e.path)}function Pn(e){return F(e.mode,_)===`system`?`Went back using system navigation`:`Went back`}function Fn(e){let t=F(e.pose,Be);return t?`Folded to ${t}`:`Changed fold pose`}function In(e){let t=F(e.orientation,Ve);return t?P(e.confirmed)===!1?`Requested ${t} (unconfirmed)`:`Rotated to ${t}`:`Changed orientation`}function Ln(e){let t=z(e.width),n=z(e.height);return t!==void 0&&n!==void 0?`Set viewport to ${t}×${n}`:`Changed viewport`}function Rn(e){let t=F(e.action,[`read`,`write`]);return t===`read`?`Read clipboard`:t===`write`?`Updated clipboard`:`Used clipboard`}function zn(e){let t=R(e.action);if(!t||!qe(t))return`Used keyboard`;if(t===`dismiss`)return Bn(e);if(t===`enter`||t===`return`)return`Pressed keyboard return`;let n=P(e.visible);return n===void 0?`Inspected keyboard`:n?`Keyboard is visible`:`Keyboard is hidden`}function Bn(e){return P(e.dismissed)===!1?`Keyboard was already hidden`:`Dismissed keyboard`}function Vn(e){let t=R(e.action);return I({action:t&&qe(t)?t:void 0,platform:F(e.platform,[`ios`,`android`]),visible:P(e.visible),wasVisible:P(e.wasVisible),dismissed:P(e.dismissed),attempts:z(e.attempts),mechanism:F(e.mechanism,[`dismissKey`])})}function Hn(e){let t=F(e.button,Ue);return t?`Pressed TV remote ${t}`:`Used TV remote`}function Un(e){let t=F(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]);return t?`Ran ${t} gesture`:`Ran gesture`}function Wn(e){let t=z(e.count);return t!==void 0&&t>1?`Swiped ${t} times`:`Swiped`}function Gn(e){return I({kind:F(e.kind,[`fling`,`pan`,`pinch`,`rotate`,`transform`]),durationMs:z(e.durationMs),pointerCount:z(e.pointerCount),x1:z(e.x1),y1:z(e.y1),x2:z(e.x2),y2:z(e.y2),count:z(e.count),pauseMs:z(e.pauseMs),pattern:F(e.pattern,[`one-way`,`ping-pong`]),scale:z(e.scale)})}function Kn(e,t){let n=qn(e,F(t.result?.action,[`start`,`stop`])),r=Jn(t);return r?`${n} ${r}`:n}function qn(e,t){return t===`start`?e===`trace`?`Started trace`:`Started recording`:t===`stop`?e===`trace`?`Stopped trace`:`Stopped recording`:e===`trace`?`Updated trace`:`Updated recording`}function Jn(e){let t=e.result??{};return L(t.requestedFileName)??L(t.outPath)??L(t.path)??L(e.positionals[1])}function Yn(e,t){for(let n of t){let t=N(e[n]);if(t)return t}}function Xn(e){switch(e.command){case g.open:return`Opened ${B(e)??`session`}`;case g.close:return`Closed ${N(e.result?.session)??`session`}`;case g.click:case g.press:return`Tapped ${B(e)??`target`}`;case g.longPress:return`Long pressed ${B(e)??`target`}`;case g.hover:return`Hovered ${B(e)??`target`}`;case g.fill:return`Filled ${B(e)??`target`}`;case g.type:return`Typed text`;case g.install:case g.reinstall:case Fe.installSource:return Cn(e);default:return wn(e)??`Ran ${e.command}`}}function Zn(e){return I({command:e.command,positionals:or(e),flags:vr(e),...Qn(e),...$n(e),...er(e),...Tn(e)})}function Qn(e){if(!tr(e.command))return{};let t=e.result??{};return I({ref:G(t),targetLabel:B(e),selectorChainLength:mr(t.selectorChain)?.length,x:z(t.x),y:z(t.y),x2:z(t.x2),y2:z(t.y2),durationMs:z(t.durationMs)})}function $n(e){if(!nr(e.command))return{};let t=e.result??{};return I({platform:F(t.platform,i),target:F(t.target,o),appName:N(t.appName),appBundleId:N(t.appBundleId),bundleId:N(t.bundleId),packageName:N(t.packageName),launchTarget:N(t.launchTarget)})}function er(e){let t=e.result??{};return e.command===g.snapshot?Array.isArray(t.nodes)?{nodeCount:t.nodes.length}:{}:e.command!==g.wait&&e.command!==g.find&&e.command!==g.get&&e.command!==g.is?{}:I({waitedMs:z(t.waitedMs),found:P(t.found)})}function tr(e){return e===g.click||e===g.press||e===g.longPress||e===g.hover||e===g.focus||e===g.fill}function nr(e){return e===g.open||e===g.install||e===g.reinstall||e===Fe.installSource}function B(e){let t=e.result??{};return rr(t)??ir(t)??ar(t)??fr(e.positionals[0])}function rr(e){let t=G(e);if(t)return t.startsWith(`@`)?t:`@${t}`}function ir(e){let t=z(e.x),n=z(e.y);if(t!==void 0&&n!==void 0)return`(${t}, ${n})`}function ar(e){return N(e.appName)??N(e.appBundleId)??N(e.bundleId)??N(e.packageName)}function or(e){if(e.positionals.length!==0)return e.command===g.type?[H(`text`)]:e.command===g.fill?sr(e):e.command===g.find?cr(e):e.command===g.clipboard?lr(e):e.command===g.push?ur(e,`app`,`payload`):e.command===g.triggerAppEvent?ur(e,`event`,`payload`):e.positionals.map(V)}function sr(e){let t=H(`text`),n=e.result??{},r=G(n);if(r)return[`@${r}`,t];if(N(n.selector))return[H(`target`),t];let i=z(n.x),a=z(n.y);return i!==void 0&&a!==void 0?[String(i),String(a),t]:[t]}function cr(e){let t=+!!pr(e.positionals[0]);if(e.positionals[t]===void 0)return;let n=t+1,r=[...t===1?[String(e.positionals[0])]:[],H(`query`)],i=e.positionals[n];return i?i===`fill`||i===`type`?[...r,i,H(`text`)]:[...r,...e.positionals.slice(n).map(dr)]:r}function lr(e){let t=e.positionals[0]?.toLowerCase();return t===`read`?[`read`]:t===`write`?[`write`,H(`text`)]:e.positionals.map(V)}function ur(e,t,n){let[r,i,...a]=e.positionals;return[...r?[H(t)]:[],...i?[H(n)]:[],...a.map(V)]}function dr(e){return e===`click`||e===`focus`||e===`exists`||e===`get`||e===`text`||e===`attrs`||e===`wait`?e:V(e)}function V(e){return fr(e)??H(`arg`)}function fr(e){if(!e)return;let t=e.trim();if(/^@[a-zA-Z0-9:_-]+$/.test(t))return t}function H(e){return`<${e}>`}function pr(e){return e===`text`||e===`label`||e===`value`||e===`role`||e===`id`}function mr(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)?e:void 0}const hr={enums:[{source:`platform`,values:a},{source:`target`,values:o}]},gr={booleans:[{source:`settle`}],numbers:[{source:`settleQuietMs`}]},_r={[g.open]:{booleans:[{source:`relaunch`},{source:`testIme`}],enums:[{source:`surface`,values:Le}]},[g.click]:U(),[g.press]:U(),[g.longPress]:U(),[g.hover]:U(),[g.fill]:br(),[g.type]:br(),[g.scroll]:{numbers:[{source:`pixels`},{source:`durationMs`}]},[g.gesture]:xr(),[g.swipe]:xr(),[g.screenshot]:{booleans:[{source:`overlayRefs`},{source:`screenshotFullscreen`,output:`fullscreen`},{source:`screenshotNoStabilize`,output:`noStabilize`},{source:`screenshotNormalizeStatusBar`,output:`normalizeStatusBar`}],numbers:[{source:`screenshotPixelDensity`,output:`pixelDensity`},{source:`screenshotScale`,output:`scale`}]},[g.snapshot]:{booleans:[{source:`snapshotInteractiveOnly`,output:`interactiveOnly`},{source:`snapshotDiff`,output:`diff`},{source:`snapshotRaw`,output:`raw`},{source:`snapshotCustomActions`,output:`actions`},{source:`snapshotForceFull`,output:`forceFull`}],numbers:[{source:`snapshotDepth`,output:`depth`}]},[g.back]:{enums:[{source:`backMode`,output:`mode`,values:_}]},[g.record]:{booleans:[{source:`hideTouches`}],numbers:[{source:`fps`}],enums:[{source:`recordingScope`,output:`scope`,values:ne}]},[g.apps]:{enums:[{source:`appsFilter`,output:`filter`,values:[`user-installed`,`all`]}]},[g.boot]:{booleans:[{source:`headless`}]},[g.close]:{booleans:[{source:`shutdown`}]}};function vr(e){let t=e.flags??{},n={},r=Object.hasOwn(_r,e.command)?_r[e.command]:void 0;return W(n,t,hr),W(n,t,r),W(n,t,yr(e.command)),Object.keys(n).length>0?n:void 0}function yr(e){return ee(e)?gr:void 0}function U(){return{booleans:[{source:`doubleTap`}],numbers:[{source:`count`},{source:`intervalMs`},{source:`holdMs`},{source:`jitterPx`}],enums:[{source:`clickButton`,values:ze}]}}function br(){return{numbers:[{source:`delayMs`}]}}function xr(){return{numbers:[{source:`pointerCount`},{source:`count`},{source:`pauseMs`}],enums:[{source:`pattern`,values:re}]}}function W(e,t,n){n&&(Sr(e,t,n.booleans??[]),Cr(e,t,n.numbers??[]),wr(e,t,n.enums??[]))}function Sr(e,t,n){for(let r of n)Tr(e,r.output??r.source,t[r.source])}function Cr(e,t,n){for(let r of n)Er(e,r.output??r.source,t[r.source])}function wr(e,t,n){for(let r of n)Dr(e,r.output??r.source,t[r.source],r.values)}function G(e){let t=N(e.ref);if(!t)return;let n=t.startsWith(`@`)?t.slice(1):t;return/^[a-zA-Z0-9:_-]+$/.test(n)?n:void 0}function Tr(e,t,n){typeof n==`boolean`&&(e[t]=n)}function Er(e,t,n){let r=z(n);r!==void 0&&(e[t]=r)}function Dr(e,t,n,r){let i=F(n,r);i!==void 0&&(e[t]=i)}const Or=65536;function kr(e){return Je(`sha256`).update(e,`utf8`).digest(`hex`).slice(0,32)}function K(e,t){let n=Nr(e);if(n===void 0)return!1;try{let e=jr(t),r=Buffer.allocUnsafe(Or),i=0;do if(i=C.readSync(n,r,0,r.length,null),!e.push(r.subarray(0,i)))return!0;while(i>0);return e.end(),!0}finally{C.closeSync(n)}}async function Ar(e){let t=await Pr(e);if(t===void 0)return{lineCount:0,firstLineDigest:void 0};let n={lineCount:0,firstLineDigest:void 0};try{let e=jr(e=>{n.lineCount===0&&(n.firstLineDigest=kr(e)),n.lineCount+=1}),r=Buffer.allocUnsafe(Or);for(;;){let{bytesRead:n}=await t.read(r,0,r.length,null);if(e.push(r.subarray(0,n)),n===0)break}return e.end(),n}finally{await t.close()}}function q(e){let t;return K(e,e=>(t=kr(e),!1)),t}function jr(e){let t=new Ye(`utf8`),n=``,r=!1;return{push(i){if(r)return!1;let a=`${n}${t.write(i)}`,o=0;for(let t=a.indexOf(`
|
|
3
3
|
`);t!==-1;t=a.indexOf(`
|
|
4
|
-
`,o)){if(Mr(a.slice(o,t),e)===!1)return r=!0,!1;o=t+1}return n=a.slice(o),!0},end(){r||Mr(`${n}${t.end()}`,e)}}}function Mr(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0)return t(n)}function Nr(e){try{return C.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Pr(e){try{return await C.promises.open(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}const Fr=5242880;function Ir(e=process.env){let t=e.AGENT_DEVICE_EVENT_LOG_MAX_BYTES?.trim();if(t===void 0||!/^\d+$/.test(t))return Fr;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:Fr}function J(e){return`${e}.1`}function Y(e){return`${e}.window.json`}function Lr(e){let t;for(let n=0;n<3;n+=1){let n=Z(e);try{let t=Rr(e);if(Z(e)===n)return t}catch(r){if(t=r,Z(e)===n)throw r}}throw t??X(e,`the window did not settle while reading`)}function Rr(e){let t=J(e),n=Gr(e);if(n===`unverifiable`)throw X(e,`window file is invalid`);if(n===void 0)return zr(e,t);let r=n.at(-1);if(!r)throw X(e,`window file records no generation`);let i=Jr(e),a=Br(e,r),o=[],s=Vr({eventLogPath:e,rotatedPath:t,sidecar:n,activeStart:a,activeExists:i});return s!==void 0&&o.push({path:t,firstLineIndex:s}),i&&o.push({path:e,firstLineIndex:a}),{files:o,earliestCursor:o[0]?.firstLineIndex??a}}function zr(e,t){if(q(t)!==void 0)throw X(e,`a rotated event log exists with no window record`);return{files:Jr(e)?[{path:e,firstLineIndex:0}]:[],earliestCursor:0}}function Br(e,t){let n=q(e);return n!==void 0&&n===t.firstLineDigest?t.firstLineIndex:t.firstLineIndex+t.lineCount}function Vr(e){let{eventLogPath:t,rotatedPath:n,sidecar:r,activeStart:i,activeExists:a}=e,o=q(n);if(o===void 0)return;let s=r.find(e=>e.firstLineDigest===o);if(!s)throw X(t,`the rotated event log matches no window record`);let c=Wr(n);if(c!==s.lineCount)throw X(t,`the rotated event log holds ${c} lines, the window recorded ${s.lineCount}`);if(a&&s.firstLineIndex+s.lineCount!==i)throw X(t,`retained event log generations are not contiguous`);return s.firstLineIndex}async function Hr(e,t){let n=Yr(e);if(!n||n.size<t)return!1;let r=Gr(e);if(r===`unverifiable`)return await C.promises.rename(e,J(e)),!0;let i=await Ar(e);if(i.firstLineDigest!==void 0){let t=r??[],n=t.at(-1),a=n&&n.firstLineDigest===i.firstLineDigest?n:{firstLineIndex:n?n.firstLineIndex+n.lineCount:0,lineCount:i.lineCount,firstLineDigest:i.firstLineDigest};await qr(e,(a===n?t:[...t,a]).slice(-2))}return await C.promises.rename(e,J(e)),!0}function Ur(t,n){if(!(t>=n))throw new e(`COMMAND_FAILED`,`events cursor ${t} precedes the retained event log window; events before cursor ${n} were rotated out.`,{reason:`EVENT_LOG_CURSOR_EXPIRED`,cursor:t,earliestCursor:n,hint:`Resume with cursor ${n}, the oldest retained event; earlier events are no longer available.`})}function X(t,n){return new e(`COMMAND_FAILED`,`Session event log window cannot be verified: ${n}.`,{reason:`EVENT_LOG_WINDOW_UNVERIFIED`,path:t,hint:`Cursor positions for this session cannot be resolved. Delete ${t}, ${J(t)}, and ${Y(t)} to restart the timeline, or read the files directly.`})}function Wr(e){let t=0;return K(e,()=>{t+=1}),t}function Z(e){return[Q(Y(e)),Q(e),Q(J(e))].join(`|`)}function Q(e){try{let t=C.lstatSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return`absent`}}function Gr(e){let t;try{t=C.readFileSync(Y(e),`utf8`)}catch(e){return e.code===`ENOENT`?void 0:`unverifiable`}try{let e=JSON.parse(t);if(!n(e)||e.version!==2)return`unverifiable`;let{generations:r}=e;if(!Array.isArray(r)||r.length===0)return`unverifiable`;let i=r.map(Kr);return i.every(e=>e!==void 0)?i:`unverifiable`}catch{return`unverifiable`}}function Kr(e){if(!n(e))return;let{firstLineIndex:t,lineCount:r,firstLineDigest:i}=e;if(!(!Number.isSafeInteger(t)||t<0)&&!(!Number.isSafeInteger(r)||r<0)&&typeof i==`string`&&i.length!==0)return{firstLineIndex:t,lineCount:r,firstLineDigest:i}}async function qr(e,t){let n=Y(e),r=`${n}.${process.pid}.tmp`;await C.promises.writeFile(r,JSON.stringify({version:2,generations:t}),`utf8`),await C.promises.rename(r,n)}function Jr(e){return Yr(e)!==void 0}function Yr(t){try{let n=C.lstatSync(t);if(n.isSymbolicLink())throw new e(`COMMAND_FAILED`,`Session event log must not be a symbolic link: ${t}`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}const $=new Map,Xr=new Set;function Zr(e){return S.join(e,`events.ndjson`)}function Qr(e){return e.command!==h.events}function $r(e,n,r){let i=t({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});ti(e,`${JSON.stringify(i)}\n`)}async function ei(e){await(e?$.get(e):Promise.all($.values()))}function ti(e,t){let n=($.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await ni(e),await Hr(e,Ir()),await C.promises.appendFile(e,t,`utf8`)}).catch(t=>{y({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{$.get(e)===n&&$.delete(e)});$.set(e,n)}async function ni(e){let t=S.dirname(e);if(!Xr.has(t))try{await C.promises.mkdir(t,{recursive:!0}),Xr.add(t)}catch(t){throw y({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function ri(e,t,n){$r(e,t,{kind:`action.recorded`,requestId:v().requestId,command:n.command,summary:Xn(n),details:Zn(n)})}function ii(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??v().requestId,command:t.command,summary:`Started ${t.command}`}}function ai(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=nn(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??v().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??v().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function oi(e,t={}){let n=ci(t.cursor),r=li(t.limit),i=Lr(e);Ur(n,i.earliestCursor);let a=si(i.files,n,r),o=a.lines.flatMap(e=>{let t=ui(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:o,...a.nextCursor===void 0?{}:{nextCursor:String(a.nextCursor)}}}function si(e,t,n){let r=[],i;for(let a of e){let e=a.firstLineIndex;if(K(a.path,a=>{if(e>=t+n)return i=t+n,!1;e>=t&&r.push(a),e+=1}),i!==void 0)break}return{lines:r,...i===void 0?{}:{nextCursor:i}}}function ci(t){if(t===void 0||t.trim()===``)return 0;let n=Number(t);if(Number.isInteger(n)&&n>=0)return n;throw new e(`INVALID_ARGS`,`events cursor must be a non-negative integer string.`)}function li(t){if(t===void 0||typeof t==`string`&&t.trim()===``)return 100;let n=typeof t==`string`?Number(t):t;if(Number.isInteger(n)&&n>=1&&n<=500)return n;throw new e(`INVALID_ARGS`,`events limit must be between 1 and 500.`)}function ui(e){try{let t=di(JSON.parse(e));return t?fi(t):void 0}catch{return}}function di(e){if(n(e)&&e.version===1&&typeof e.ts==`string`&&typeof e.session==`string`&&pi(e.kind))return e}function fi(e){let t=n(e.details)?e.details:void 0;return{version:1,ts:e.ts,session:e.session,kind:e.kind,...typeof e.requestId==`string`?{requestId:e.requestId}:{},...typeof e.command==`string`?{command:e.command}:{},...mi(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function pi(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function mi(e){return e===`ok`||e===`error`}const hi=36e5;var gi=class{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new Nt(e)}get(e){return this.sessions.get(e)}set(e,t){let n=this.sessions.has(e);this.sessions.set(e,t),n||this.clearIdleExpiryTombstone(e)}delete(e){return this.runtimeHints.delete(e),this.sessions.delete(e)}values(){return this.sessions.values()}toArray(){return Array.from(this.sessions.values())}lookup(e){let t=this.sessions.get(e);return t?{address:e,session:t}:void 0}findByDevice(e){for(let[t,n]of this.sessions)if(n.device.id===e)return{address:t,session:n}}listRefs(){return Array.from(this.sessions,([e,t])=>({address:e,session:t}))}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){this.runtimeHints.set(e,t)}clearRuntimeHints(e){return this.runtimeHints.delete(e)}recordAction(e,t){let n=st(e,t);if(n){let t=this.resolveStoredSessionName(e);ri(this.resolveEventLogPath(t),t,n)}}recordEvent(e,t){$r(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return oi(this.resolveEventLogPath(e),t)}async flushEvents(e){await ei(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.scriptWriter.write(e,t);return n.written&&y({level:`info`,phase:`session_script_written`,data:{session:e.name,path:n.path}}),n}finalizeRepairTeardown(e){this.recordRepairFinalizeCloseIfCommitting(e);let t=this.writeSessionLog(e,{force:De(e,void 0)});at(e)&&(!t.written&&t.error?this.writeRepairTombstone(e,hi,{code:String(t.error.code),message:t.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){let t=e.scriptPublication??m;be(t)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:e.name,...ze(`Closed: ${e.name}`)}})}writeRepairTombstone(e,t=hi,n){try{let r=this.resolveSessionDir(e.name);C.mkdirSync(r,{recursive:!0});let i={owner:e.name,reapedAt:Date.now(),expiresAt:Date.now()+t,...ot(e)?{sourcePath:ot(e)}:{},...n?{commitFailure:n}:{}};C.writeFileSync(this.repairTombstonePath(e.name),`${JSON.stringify(i)}\n`)}catch(t){y({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.name,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return We(this.repairTombstonePath(e))}clearRepairTombstone(e){try{C.rmSync(this.repairTombstonePath(e),{force:!0})}catch{}}noteSessionActivity(e,t=Date.now()){let n=this.sessions.get(e);n&&(n.lastActivityAtMs=t)}writeIdleExpiryTombstone(e,t){try{C.mkdirSync(this.resolveSessionDir(e),{recursive:!0}),C.writeFileSync(D(this.resolveSessionDir(e)),`${JSON.stringify(t)}\n`)}catch(t){y({level:`warn`,phase:`idle_expiry_tombstone_write_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}readIdleExpiryTombstone(e){if(!Ke(e))return;let t=bt(D(this.resolveSessionDir(e)));return t?.owner===e?t:void 0}clearIdleExpiryTombstone(e){try{C.rmSync(D(this.resolveSessionDir(e)),{force:!0})}catch(t){y({level:`warn`,phase:`idle_expiry_tombstone_clear_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}repairTombstonePath(e){return Ge(this.resolveSessionDir(e))}defaultTracePath(e){let t=b(e.name),n=new Date().toISOString().replaceAll(/[:.]/g,`-`);return S.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(t){if(!Ke(t))throw new e(`INVALID_ARGS`,`Invalid session name ${JSON.stringify(t)}: a session name cannot be empty, ".", or "..".`);return S.join(this.sessionsDir,b(t))}resolveDaemonStateDir(){return S.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return C.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return S.join(this.resolveSessionDir(e),`app.log`)}resolveAppLogPidPath(e){return S.join(this.resolveSessionDir(e),`app-log.pid`)}resolveEventLogPath(e){return Zr(this.resolveSessionDir(e))}static expandHome(e,t){return x(e,t)}resolveStoredSessionName(e){for(let[t,n]of this.sessions)if(n===e)return t;return e.name}};export{$e as _,or as a,ct as c,rt as d,it as f,T as g,tt as h,Qr as i,nt as l,et as m,ai as n,En as o,at as p,ii as r,gt as s,gi as t,Qe as u};
|
|
4
|
+
`,o)){if(Mr(a.slice(o,t),e)===!1)return r=!0,!1;o=t+1}return n=a.slice(o),!0},end(){r||Mr(`${n}${t.end()}`,e)}}}function Mr(e,t){let n=e.endsWith(`\r`)?e.slice(0,-1):e;if(n.trim().length!==0)return t(n)}function Nr(e){try{return C.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Pr(e){try{return await C.promises.open(e,`r`)}catch(e){if(e.code===`ENOENT`)return;throw e}}const Fr=5242880;function Ir(e=process.env){let t=e.AGENT_DEVICE_EVENT_LOG_MAX_BYTES?.trim();if(t===void 0||!/^\d+$/.test(t))return Fr;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:Fr}function J(e){return`${e}.1`}function Y(e){return`${e}.window.json`}function Lr(e){let t;for(let n=0;n<3;n+=1){let n=Z(e);try{let t=Rr(e);if(Z(e)===n)return t}catch(r){if(t=r,Z(e)===n)throw r}}throw t??X(e,`the window did not settle while reading`)}function Rr(e){let t=J(e),n=Gr(e);if(n===`unverifiable`)throw X(e,`window file is invalid`);if(n===void 0)return zr(e,t);let r=n.at(-1);if(!r)throw X(e,`window file records no generation`);let i=Jr(e),a=Br(e,r),o=[],s=Vr({eventLogPath:e,rotatedPath:t,sidecar:n,activeStart:a,activeExists:i});return s!==void 0&&o.push({path:t,firstLineIndex:s}),i&&o.push({path:e,firstLineIndex:a}),{files:o,earliestCursor:o[0]?.firstLineIndex??a}}function zr(e,t){if(q(t)!==void 0)throw X(e,`a rotated event log exists with no window record`);return{files:Jr(e)?[{path:e,firstLineIndex:0}]:[],earliestCursor:0}}function Br(e,t){let n=q(e);return n!==void 0&&n===t.firstLineDigest?t.firstLineIndex:t.firstLineIndex+t.lineCount}function Vr(e){let{eventLogPath:t,rotatedPath:n,sidecar:r,activeStart:i,activeExists:a}=e,o=q(n);if(o===void 0)return;let s=r.find(e=>e.firstLineDigest===o);if(!s)throw X(t,`the rotated event log matches no window record`);let c=Wr(n);if(c!==s.lineCount)throw X(t,`the rotated event log holds ${c} lines, the window recorded ${s.lineCount}`);if(a&&s.firstLineIndex+s.lineCount!==i)throw X(t,`retained event log generations are not contiguous`);return s.firstLineIndex}async function Hr(e,t){let n=Yr(e);if(!n||n.size<t)return!1;let r=Gr(e);if(r===`unverifiable`)return await C.promises.rename(e,J(e)),!0;let i=await Ar(e);if(i.firstLineDigest!==void 0){let t=r??[],n=t.at(-1),a=n&&n.firstLineDigest===i.firstLineDigest?n:{firstLineIndex:n?n.firstLineIndex+n.lineCount:0,lineCount:i.lineCount,firstLineDigest:i.firstLineDigest};await qr(e,(a===n?t:[...t,a]).slice(-2))}return await C.promises.rename(e,J(e)),!0}function Ur(t,n){if(!(t>=n))throw new e(`COMMAND_FAILED`,`events cursor ${t} precedes the retained event log window; events before cursor ${n} were rotated out.`,{reason:`EVENT_LOG_CURSOR_EXPIRED`,cursor:t,earliestCursor:n,hint:`Resume with cursor ${n}, the oldest retained event; earlier events are no longer available.`})}function X(t,n){return new e(`COMMAND_FAILED`,`Session event log window cannot be verified: ${n}.`,{reason:`EVENT_LOG_WINDOW_UNVERIFIED`,path:t,hint:`Cursor positions for this session cannot be resolved. Delete ${t}, ${J(t)}, and ${Y(t)} to restart the timeline, or read the files directly.`})}function Wr(e){let t=0;return K(e,()=>{t+=1}),t}function Z(e){return[Q(Y(e)),Q(e),Q(J(e))].join(`|`)}function Q(e){try{let t=C.lstatSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch{return`absent`}}function Gr(e){let t;try{t=C.readFileSync(Y(e),`utf8`)}catch(e){return e.code===`ENOENT`?void 0:`unverifiable`}try{let e=JSON.parse(t);if(!n(e)||e.version!==2)return`unverifiable`;let{generations:r}=e;if(!Array.isArray(r)||r.length===0)return`unverifiable`;let i=r.map(Kr);return i.every(e=>e!==void 0)?i:`unverifiable`}catch{return`unverifiable`}}function Kr(e){if(!n(e))return;let{firstLineIndex:t,lineCount:r,firstLineDigest:i}=e;if(!(!Number.isSafeInteger(t)||t<0)&&!(!Number.isSafeInteger(r)||r<0)&&typeof i==`string`&&i.length!==0)return{firstLineIndex:t,lineCount:r,firstLineDigest:i}}async function qr(e,t){let n=Y(e),r=`${n}.${process.pid}.tmp`;await C.promises.writeFile(r,JSON.stringify({version:2,generations:t}),`utf8`),await C.promises.rename(r,n)}function Jr(e){return Yr(e)!==void 0}function Yr(t){try{let n=C.lstatSync(t);if(n.isSymbolicLink())throw new e(`COMMAND_FAILED`,`Session event log must not be a symbolic link: ${t}`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}const $=new Map,Xr=new Set;function Zr(e){return S.join(e,`events.ndjson`)}function Qr(e){return e.command!==g.events}function $r(e,n,r){let i=t({version:1,ts:r.ts??new Date().toISOString(),session:n,...r});ti(e,`${JSON.stringify(i)}\n`)}async function ei(e){await(e?$.get(e):Promise.all($.values()))}function ti(e,t){let n=($.get(e)??Promise.resolve()).catch(()=>void 0).then(async()=>{await ni(e),await Hr(e,Ir()),await C.promises.appendFile(e,t,`utf8`)}).catch(t=>{y({level:`warn`,phase:`session_event_log_write_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}})}).finally(()=>{$.get(e)===n&&$.delete(e)});$.set(e,n)}async function ni(e){let t=S.dirname(e);if(!Xr.has(t))try{await C.promises.mkdir(t,{recursive:!0}),Xr.add(t)}catch(t){throw y({level:`warn`,phase:`session_event_log_dir_failed`,data:{path:e,error:t instanceof Error?t.message:String(t)}}),t}}function ri(e,t,n){$r(e,t,{kind:`action.recorded`,requestId:v().requestId,command:n.command,summary:Xn(n),details:Zn(n)})}function ii(e){let{req:t}=e;return{kind:`request.started`,requestId:t.meta?.requestId??v().requestId,command:t.command,summary:`Started ${t.command}`}}function ai(e){let{req:t,response:n,durationMs:r}=e;if(n.ok){let e=nn(t,n.data);return{kind:`request.finished`,requestId:t.meta?.requestId??v().requestId,command:t.command,status:`ok`,summary:e.summary??`Finished ${t.command}`,details:{durationMs:r,...e.details}}}return{kind:`request.finished`,requestId:t.meta?.requestId??v().requestId,command:t.command,status:`error`,summary:`Failed ${t.command}: ${n.error.code}`,details:{durationMs:r,code:n.error.code,diagnosticId:n.error.diagnosticId}}}function oi(e,t={}){let n=ci(t.cursor),r=li(t.limit),i=Lr(e);Ur(n,i.earliestCursor);let a=si(i.files,n,r),o=a.lines.flatMap(e=>{let t=ui(e);return t?[t]:[]});return{path:e,cursor:String(n),limit:r,events:o,...a.nextCursor===void 0?{}:{nextCursor:String(a.nextCursor)}}}function si(e,t,n){let r=[],i;for(let a of e){let e=a.firstLineIndex;if(K(a.path,a=>{if(e>=t+n)return i=t+n,!1;e>=t&&r.push(a),e+=1}),i!==void 0)break}return{lines:r,...i===void 0?{}:{nextCursor:i}}}function ci(t){if(t===void 0||t.trim()===``)return 0;let n=Number(t);if(Number.isInteger(n)&&n>=0)return n;throw new e(`INVALID_ARGS`,`events cursor must be a non-negative integer string.`)}function li(t){if(t===void 0||typeof t==`string`&&t.trim()===``)return 100;let n=typeof t==`string`?Number(t):t;if(Number.isInteger(n)&&n>=1&&n<=500)return n;throw new e(`INVALID_ARGS`,`events limit must be between 1 and 500.`)}function ui(e){try{let t=di(JSON.parse(e));return t?fi(t):void 0}catch{return}}function di(e){if(n(e)&&e.version===1&&typeof e.ts==`string`&&typeof e.session==`string`&&pi(e.kind))return e}function fi(e){let t=n(e.details)?e.details:void 0;return{version:1,ts:e.ts,session:e.session,kind:e.kind,...typeof e.requestId==`string`?{requestId:e.requestId}:{},...typeof e.command==`string`?{command:e.command}:{},...mi(e.status)?{status:e.status}:{},...typeof e.summary==`string`?{summary:e.summary}:{},...t?{details:t}:{}}}function pi(e){return e===`request.started`||e===`request.finished`||e===`action.recorded`}function mi(e){return e===`ok`||e===`error`}const hi=36e5;var gi=class{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new Nt(e)}get(e){return this.sessions.get(e)}set(e,t){let n=this.sessions.has(e);this.sessions.set(e,t),n||this.clearIdleExpiryTombstone(e)}delete(e){return this.runtimeHints.delete(e),this.sessions.delete(e)}values(){return this.sessions.values()}toArray(){return Array.from(this.sessions.values())}lookup(e){let t=this.sessions.get(e);return t?{address:e,session:t}:void 0}findByDevice(e){for(let[t,n]of this.sessions)if(n.device.id===e)return{address:t,session:n}}listRefs(){return Array.from(this.sessions,([e,t])=>({address:e,session:t}))}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){this.runtimeHints.set(e,t)}clearRuntimeHints(e){return this.runtimeHints.delete(e)}recordAction(e,t){let n=st(e,t);if(n){let t=this.resolveStoredSessionName(e);ri(this.resolveEventLogPath(t),t,n)}}recordEvent(e,t){$r(this.resolveEventLogPath(e),e,t)}readEvents(e,t={}){return oi(this.resolveEventLogPath(e),t)}async flushEvents(e){await ei(e?this.resolveEventLogPath(e):void 0)}writeSessionLog(e,t){let n=this.scriptWriter.write(e,t);return n.written&&y({level:`info`,phase:`session_script_written`,data:{session:e.name,path:n.path}}),n}finalizeRepairTeardown(e){this.recordRepairFinalizeCloseIfCommitting(e);let t=this.writeSessionLog(e,{force:Ee(e,void 0)});at(e)&&(!t.written&&t.error?this.writeRepairTombstone(e,hi,{code:String(t.error.code),message:t.error.message}):this.writeRepairTombstone(e))}recordRepairFinalizeCloseIfCommitting(e){let t=e.scriptPublication??h;ye(t)&&this.recordAction(e,{command:`close`,positionals:[],flags:{},result:{session:e.name,...Re(`Closed: ${e.name}`)}})}writeRepairTombstone(e,t=hi,n){try{let r=this.resolveSessionDir(e.name);C.mkdirSync(r,{recursive:!0});let i={owner:e.name,reapedAt:Date.now(),expiresAt:Date.now()+t,...ot(e)?{sourcePath:ot(e)}:{},...n?{commitFailure:n}:{}};C.writeFileSync(this.repairTombstonePath(e.name),`${JSON.stringify(i)}\n`)}catch(t){y({level:`warn`,phase:`repair_tombstone_write_failed`,data:{session:e.name,error:t instanceof Error?t.message:String(t)}})}}readRepairTombstone(e){return We(this.repairTombstonePath(e))}clearRepairTombstone(e){try{C.rmSync(this.repairTombstonePath(e),{force:!0})}catch{}}noteSessionActivity(e,t=Date.now()){let n=this.sessions.get(e);n&&(n.lastActivityAtMs=t)}writeIdleExpiryTombstone(e,t){try{C.mkdirSync(this.resolveSessionDir(e),{recursive:!0}),C.writeFileSync(D(this.resolveSessionDir(e)),`${JSON.stringify(t)}\n`)}catch(t){y({level:`warn`,phase:`idle_expiry_tombstone_write_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}readIdleExpiryTombstone(e){if(!Ke(e))return;let t=bt(D(this.resolveSessionDir(e)));return t?.owner===e?t:void 0}clearIdleExpiryTombstone(e){try{C.rmSync(D(this.resolveSessionDir(e)),{force:!0})}catch(t){y({level:`warn`,phase:`idle_expiry_tombstone_clear_failed`,data:{session:e,error:t instanceof Error?t.message:String(t)}})}}repairTombstonePath(e){return Ge(this.resolveSessionDir(e))}defaultTracePath(e){let t=b(e.name),n=new Date().toISOString().replaceAll(/[:.]/g,`-`);return S.join(this.sessionsDir,`${t}-${n}.trace.log`)}resolveSessionDir(t){if(!Ke(t))throw new e(`INVALID_ARGS`,`Invalid session name ${JSON.stringify(t)}: a session name cannot be empty, ".", or "..".`);return S.join(this.sessionsDir,b(t))}resolveDaemonStateDir(){return S.dirname(this.sessionsDir)}ensureSessionDir(e){let t=this.resolveSessionDir(e);return C.mkdirSync(t,{recursive:!0}),t}resolveAppLogPath(e){return S.join(this.resolveSessionDir(e),`app.log`)}resolveAppLogPidPath(e){return S.join(this.resolveSessionDir(e),`app-log.pid`)}resolveEventLogPath(e){return Zr(this.resolveSessionDir(e))}static expandHome(e,t){return x(e,t)}resolveStoredSessionName(e){for(let[t,n]of this.sessions)if(n===e)return t;return e.name}};export{$e as _,or as a,ct as c,rt as d,it as f,T as g,tt as h,Qr as i,nt as l,et as m,ai as n,En as o,at as p,ii as r,gt as s,gi as t,Qe as u};
|