agent-device 0.21.2 → 0.21.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.2.apk → agent-device-android-ime-helper-0.21.4.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.4.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.2.manifest.json → agent-device-android-ime-helper-0.21.4.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.2.apk → agent-device-android-snapshot-helper-0.21.4.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.4.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.4.manifest.json +16 -0
  7. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +39 -0
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSystemSurfaceHostPolicy.swift +9 -1
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +2 -1
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +10 -1
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +26 -124
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +46 -0
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +36 -4
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+MainThreadWork.swift +229 -0
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +15 -0
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +4 -40
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +6 -40
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +30 -9
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +22 -6
  20. package/dist/src/adapter.js +1 -1
  21. package/dist/src/adb-executor.js +2 -2
  22. package/dist/src/adb-failure.js +1 -1
  23. package/dist/src/agent-browser-process-record.js +1 -1
  24. package/dist/src/agent-device-client.js +2 -2
  25. package/dist/src/api.js +3 -11
  26. package/dist/src/app-launch.js +1 -1
  27. package/dist/src/app-lifecycle.js +1 -1
  28. package/dist/src/app-log-reconnect.js +1 -1
  29. package/dist/src/archive.js +2 -2
  30. package/dist/src/auth.js +1 -1
  31. package/dist/src/back-mode.js +1 -1
  32. package/dist/src/cli-help.js +2 -2
  33. package/dist/src/cli.js +4 -4
  34. package/dist/src/client-metro-companion.js +1 -1
  35. package/dist/src/client-metro.js +1 -1
  36. package/dist/src/client-types.d.ts +70 -5
  37. package/dist/src/code-signature-cache.js +1 -1
  38. package/dist/src/command-schema.js +1 -1
  39. package/dist/src/command-tools.js +2 -2
  40. package/dist/src/command.js +1 -1
  41. package/dist/src/config.js +1 -1
  42. package/dist/src/connection-runtime.js +1 -1
  43. package/dist/src/connection.js +1 -1
  44. package/dist/src/contracts.js +1 -1
  45. package/dist/src/daemon-client-lifecycle.js +1 -1
  46. package/dist/src/daemon-registration.js +1 -1
  47. package/dist/src/daemon-resolution.js +1 -0
  48. package/dist/src/daemon-shutdown-report.js +1 -1
  49. package/dist/src/daemon.js +1 -1
  50. package/dist/src/device-claim-rule.js +1 -1
  51. package/dist/src/device-input-state.d.ts +10 -8
  52. package/dist/src/device-inventory-context.js +1 -1
  53. package/dist/src/device-session.js +1 -1
  54. package/dist/src/diagnostics.js +1 -1
  55. package/dist/src/error.js +2 -2
  56. package/dist/src/exec.js +1 -1
  57. package/dist/src/file.js +1 -1
  58. package/dist/src/find.js +1 -1
  59. package/dist/src/gesture-runtime.js +1 -1
  60. package/dist/src/harmonyos.js +1 -1
  61. package/dist/src/helper.js +1 -1
  62. package/dist/src/human-control-contract.js +1 -1
  63. package/dist/src/human-control.js +1 -1
  64. package/dist/src/index.js +1 -1
  65. package/dist/src/install-source-network-transport.js +1 -1
  66. package/dist/src/interaction.js +1 -1
  67. package/dist/src/interaction2.js +1 -1
  68. package/dist/src/interactor.js +4 -4
  69. package/dist/src/interactors.js +1 -1
  70. package/dist/src/internal/bin.js +1 -1
  71. package/dist/src/internal/daemon.js +2 -2
  72. package/dist/src/internal/png-worker.js +1 -1
  73. package/dist/src/ios-client.js +121 -7
  74. package/dist/src/ios-snapshot-adapter.js +1 -1
  75. package/dist/src/ios-system-surface.js +1 -1
  76. package/dist/src/lease-scope.js +1 -1
  77. package/dist/src/limrun-delta-sync-omitted.js +1 -0
  78. package/dist/src/limrun.d.ts +0 -1598
  79. package/dist/src/location-coordinates.js +1 -1
  80. package/dist/src/mechanics.js +16 -16
  81. package/dist/src/output-common.js +2 -0
  82. package/dist/src/owner-identity.js +1 -1
  83. package/dist/src/perf-runtime-operation-builder.js +1 -1
  84. package/dist/src/perf-runtime-plan.js +1 -1
  85. package/dist/src/physical-device-control.js +1 -1
  86. package/dist/src/platform-request-scope.js +1 -1
  87. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  88. package/dist/src/platform-runtime-app-log-android-transport.js +1 -1
  89. package/dist/src/platform-runtime-app-log-process.js +1 -1
  90. package/dist/src/platform-runtime-host.js +1 -1
  91. package/dist/src/platform-runtime-operation-host.js +2 -2
  92. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  93. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  94. package/dist/src/platform-runtime-screen-recording-harmony-host.js +1 -1
  95. package/dist/src/platform-runtime-screen-recording-output-host.js +1 -1
  96. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  97. package/dist/src/platform-runtime.js +1 -1
  98. package/dist/src/process.js +1 -1
  99. package/dist/src/provider-webdriver.js +1 -1
  100. package/dist/src/proxy.js +1 -1
  101. package/dist/src/quality-warnings.js +1 -1
  102. package/dist/src/react-native.js +1 -1
  103. package/dist/src/record-runtime.js +1 -1
  104. package/dist/src/recording-stop-observation.js +1 -0
  105. package/dist/src/register-builtins.js +1 -1
  106. package/dist/src/registry.js +35 -36
  107. package/dist/src/replay-divergence.js +1 -1
  108. package/dist/src/reporting.js +11 -9
  109. package/dist/src/request-providers.js +1 -1
  110. package/dist/src/result-serialization.js +1 -1
  111. package/dist/src/runner-cache-metadata.js +2 -2
  112. package/dist/src/runner-client.js +1 -1
  113. package/dist/src/runner-disposal.js +1 -1
  114. package/dist/src/runner-operations-facade.js +1 -1
  115. package/dist/src/runner.js +1 -1
  116. package/dist/src/runtime.js +3 -3
  117. package/dist/src/runtime10.js +1 -1
  118. package/dist/src/runtime2.js +4 -4
  119. package/dist/src/runtime3.js +1 -1
  120. package/dist/src/runtime4.js +5 -5
  121. package/dist/src/runtime5.js +1 -1
  122. package/dist/src/runtime6.js +1 -1
  123. package/dist/src/runtime9.js +1 -1
  124. package/dist/src/screen-recording-completion.js +1 -1
  125. package/dist/src/screen-recording-resource-recovery.js +1 -1
  126. package/dist/src/screen-recording-runtime.js +1 -1
  127. package/dist/src/screenshot-result.js +1 -1
  128. package/dist/src/screenshot-runtime.js +1 -1
  129. package/dist/src/sdk-batch.js +2 -2
  130. package/dist/src/sdk-contracts.js +2 -2
  131. package/dist/src/sdk-remote-config.d.ts +1 -0
  132. package/dist/src/sdk-remote-config.js +1 -1
  133. package/dist/src/sdk-selectors.d.ts +36 -24
  134. package/dist/src/selector-runtime.js +1 -1
  135. package/dist/src/session-observation.js +1 -1
  136. package/dist/src/session-routing.js +1 -1
  137. package/dist/src/session-snapshot.js +1 -1
  138. package/dist/src/session-store.js +2 -2
  139. package/dist/src/session2.js +5 -5
  140. package/dist/src/simulator.js +1 -1
  141. package/dist/src/snapshot-runtime-binding.js +1 -1
  142. package/dist/src/snapshot-runtime.js +1 -1
  143. package/dist/src/snapshot.js +1 -1
  144. package/dist/src/snapshot4.js +1 -1
  145. package/dist/src/src3.js +1 -1
  146. package/dist/src/src4.js +1 -1
  147. package/dist/src/stop-sequence.js +1 -0
  148. package/dist/src/success-text.js +1 -1
  149. package/dist/src/text-entry-focus.js +1 -0
  150. package/dist/src/tool-provider.js +1 -1
  151. package/dist/src/tool-provider2.js +1 -1
  152. package/dist/src/tool-provider3.js +1 -1
  153. package/dist/src/type-text-runtime.js +1 -1
  154. package/dist/src/video.js +2 -2
  155. package/dist/src/yauzl.js +1 -0
  156. package/package.json +2 -2
  157. package/server.json +2 -2
  158. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.2.apk.sha256 +0 -1
  159. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk.sha256 +0 -1
  160. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.manifest.json +0 -17
  161. package/dist/src/audio-probe-support.js +0 -1
  162. package/dist/src/config2.js +0 -1
  163. package/dist/src/provider-device-runtime.js +0 -1
  164. package/dist/src/screen-recording-live-handle.js +0 -1
@@ -1 +1 @@
1
- import{M as e}from"./sdk-contracts.js";import{l as t}from"./sdk-device.js";import{n,t as r}from"./simulator-state.js";const i=15e3;function a(e){return Object.freeze({canShutdownTarget:o,shutdownTarget:async(t,n)=>await s(e.appleTools,t,n)})}function o(e){return t(e)&&e.appleOs!==`watchos`&&e.kind===`simulator`}async function s(t,r,a){a.throwIfAborted();try{let e=await t.run({tool:`simctl`,args:n(r,[`shutdown`,r.id]),allowFailure:!0,timeoutMs:i},a);a.throwIfAborted();let o=l(e);return o.success?o:await c(t,r,a)===`Shutdown`?{...o,success:!0,exitCode:0}:o}catch(t){a.throwIfAborted();let n=e(t);return{success:!1,exitCode:-1,stdout:``,stderr:n.message,error:n}}}async function c(e,t,n){try{return await r(e,t,n,i)}catch{return n.throwIfAborted(),null}}function l(e){let t=e.exitCode??-1;return{success:t===0,exitCode:t,stdout:e.stdout,stderr:e.stderr}}export{a as createAppleShutdownRuntime};
1
+ import{N as e}from"./sdk-contracts.js";import{l as t}from"./sdk-device.js";import{n,t as r}from"./simulator-state.js";const i=15e3;function a(e){return Object.freeze({canShutdownTarget:o,shutdownTarget:async(t,n)=>await s(e.appleTools,t,n)})}function o(e){return t(e)&&e.appleOs!==`watchos`&&e.kind===`simulator`}async function s(t,r,a){a.throwIfAborted();try{let e=await t.run({tool:`simctl`,args:n(r,[`shutdown`,r.id]),allowFailure:!0,timeoutMs:i},a);a.throwIfAborted();let o=l(e);return o.success?o:await c(t,r,a)===`Shutdown`?{...o,success:!0,exitCode:0}:o}catch(t){a.throwIfAborted();let n=e(t);return{success:!1,exitCode:-1,stdout:``,stderr:n.message,error:n}}}async function c(e,t,n){try{return await r(e,t,n,i)}catch{return n.throwIfAborted(),null}}function l(e){let t=e.exitCode??-1;return{success:t===0,exitCode:t,stdout:e.stdout,stderr:e.stderr}}export{a as createAppleShutdownRuntime};
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";import{w as t}from"./sdk-device.js";import{Gt as n,Zt as r}from"./sdk-batch.js";import{n as i,t as a}from"./application-lifecycle-runtime.js";import{i as o,t as s}from"./touch-runtime.js";import{A as c,D as l,G as u,H as d,I as f,L as p,N as ee,O as te,P as m,R as h,T as g,U as ne,a as re,b as ie,d as ae,g as oe,i as se,j as ce,m as le,s as ue,t as de,v as fe,w as pe,x as me,z as he}from"./alert-runtime.js";import{n as ge}from"./audio-probe-runtime.js";import{n as _e}from"./perf-runtime.js";import{a as _,n as v}from"./durable-resource.js";import{n as ve}from"./async-lifecycle.js";import{i as ye,r as be}from"./src7.js";import{t as xe}from"./screen-recording-live-handle.js";import{t as y}from"./screen-recording-completion.js";import{t as b}from"./screen-recording-options.js";import{t as x}from"./screen-recording-runtime.js";import{i as S}from"./gesture-admission.js";import{t as C}from"./interactor-operation-catalog.js";import{i as w,n as T}from"./perf-runtime-operation-builder.js";import{t as E}from"./app-log-runtime.js";import{n as D,t as O}from"./application-lifecycle-interaction.js";import{randomUUID as k}from"node:crypto";import{setTimeout as A}from"node:timers/promises";const j=Object.freeze({resourceKind:E,version:1,encode:e=>({...e}),decode:e=>e.transport!==`harmony-hilog`||!N(e.outputPath)||!N(e.pidPath)?{status:`invalid`,message:`Invalid HarmonyOS app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:`harmony-hilog`,outputPath:e.outputPath,pidPath:e.pidPath})}});function M(e){return v({resourceKind:E,sessionId:e.sessionId,device:{id:e.device.id,family:`harmonyos`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:_(j,e.descriptor)})}function N(e){return typeof e==`string`&&e.trim().length>0}function Se(e){return be(e,{family:`harmonyos`,backend:`harmonyos`,label:`HarmonyOS`,codec:j,startUnavailableHint:`The selected HarmonyOS transport cannot start a background hilog stream.`,cleanupFailureMessage:`HarmonyOS app-log cleanup did not settle every owned resource`,doctor:async(e,t)=>({backend:`harmonyos`,checks:{},notes:t?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}),process:async({host:e,device:t,input:n,signal:r})=>{let i=await Ce(e,r);return{resolvePid:async r=>await ye(e,{executable:i,args:[`-t`,t.id,`shell`,`pidof`,n.appBundleId],allowFailure:!0,timeoutMs:5e3},r),command:e=>({kind:`host`,request:{executable:i,args:[`-t`,t.id,`shell`,`hilog`,`-P`,e],allowFailure:!0}})}},descriptor:({artifacts:e})=>({transport:`harmony-hilog`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>M({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function Ce(t,n){n.throwIfAborted(),await P(async()=>await t.toolchains.prepare(`harmonyos`),n),n.throwIfAborted();let r=await P(async()=>await t.commands.which(`hdc`),n);if(n.throwIfAborted(),!r)throw new e(`TOOL_MISSING`,`hdc not found in PATH`,{hint:`Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.`});return r}async function P(e,t){try{return await e()}catch(e){throw t.throwIfAborted(),e}}function we(e){let{resolveHost:t,device:n}=e,r={available:!1,reason:`Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions.`};return Object.freeze({perfFrames:async()=>({metric:r,sampling:r}),perfMemorySample:async({appId:e})=>({metric:e?await w(t().sampleMemory(n,e)):T(`HarmonyOS`,`bundle`),sampling:{method:`hdc-shell-proc-status`,description:`Resident memory snapshot from HarmonyOS /proc/<pid>/status. Values are reported in kilobytes.`,unit:`kB`,topConsumerLimit:1}}),perfMemorySnapshot:async({kind:e})=>({artifact:{available:!1,kind:e??`memgraph`,reason:`Memory snapshot artifacts are not supported on harmonyos.`,hint:`Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS.`,support:{platform:`harmonyos`,defaultKind:`memgraph`,androidHprof:!1,memgraph:!1,heapprofd:!1}},sampling:{method:`unsupported`,description:`HarmonyOS memory snapshot capture is not available through HDC.`,artifactOnly:!0}})})}const F=Object.freeze({resourceKind:x,version:1,encode:e=>({...e}),decode:e=>e.backend===`harmony-screen-recorder`&&typeof e.fileName==`string`&&De(e.fileName)&&e.remotePath===`/data/local/tmp/${e.fileName}`?{status:`decoded`,descriptor:Object.freeze({backend:`harmony-screen-recorder`,fileName:e.fileName,remotePath:e.remotePath})}:{status:`invalid`,message:`Invalid HarmonyOS screen-recording descriptor`}});function Te(e){let{device:n,owner:r,input:i,descriptor:a}=e;return v({resourceKind:x,sessionId:i.sessionId,device:t(n),owner:r,fence:i.fence,lifecycle:`open`,descriptor:_(F,a)})}function Ee(e){return F.decode(e).status===`decoded`?{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`HarmonyOS recorder ownership cannot be proven after daemon restart; no recorder was stopped.`}:{status:`cleanup-pending`,reason:`manual-recovery-required`}}function De(e){return/^agent-device-recording-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.mp4$/i.test(e)}function Oe(e){return e.kind===`device`?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS recording is supported on physical devices only.`})}function ke(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await Ae({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`HarmonyOS recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async e=>Ee(e.envelope.descriptor.body)})}async function Ae(t){let{host:n,device:r,owner:i,input:a,signal:o}=t;if(a.scope===`app`)throw new e(`INVALID_ARGS`,`HarmonyOS recording captures the whole physical-device screen; use --scope device or --scope system`);b(a,{scopes:[`device`,`system`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`HarmonyOS recordings do not support ${e.join(`, `)}`),o.throwIfAborted(),await n.screenRecording.outputs.prepare(a.outputPath);let s=`agent-device-recording-${k()}.mp4`,c={backend:`harmony-screen-recorder`,fileName:s,remotePath:`/data/local/tmp/${s}`},l;try{l=await n.screenRecording.harmony.start(r,s,o),o.throwIfAborted()}catch(e){throw o.aborted?(await L(n,r,c).catch(()=>{}),o.reason):e}z(l,`start`);try{o.throwIfAborted()}catch(e){throw await L(n,r,c).catch(()=>{}),e}let u=je(a),d=!1,f=async()=>{d||=(z(await n.screenRecording.harmony.stop(r),`stop`),!0)},p=xe(u,{finish:async e=>await Me(n,r,e,c,f),forceCleanup:async()=>await L(n,r,c,f)});return Object.freeze({pendingHandle:new ve(p),envelope:Te({device:r,owner:i,input:a,descriptor:c})})}function je(e){return Object.freeze({backend:`HarmonyOS ScreenRecorder`,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:Date.now(),scope:e.scope,showTouches:!1,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},gestureEvents:[]})}async function Me(e,t,n,r,i){await i();let a=await e.screenRecording.harmony.findMedia(t,r.fileName);if(!a)throw Error(`failed to find finalized HarmonyOS recording '${r.fileName}'`);if(!await Fe(e,t,r,a))throw Error(`failed to finalize HarmonyOS recording: ${r.fileName} did not produce a non-empty media file`);try{if((await e.screenRecording.harmony.pull(t,{remotePath:r.remotePath,outputPath:n.outPath})).exitCode!==0)throw Error(`failed to retrieve HarmonyOS recording`);let i=await e.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!1,gestureEvents:n.gestureEvents,targetLabel:`HarmonyOS recording`}),o=await Ne(e,t,r,a);return y(n,{...i,...Pe(i.warning,o)},!1)}catch(n){throw await e.screenRecording.harmony.remove(t,r.remotePath).catch(()=>{}),n}}async function Ne(e,t,n,r){let i=[];return await I(()=>e.screenRecording.harmony.remove(t,n.remotePath))||i.push(`staging artifact`),await I(()=>e.screenRecording.harmony.removeMedia(t,r))||i.push(`media-library artifact`),i.length===0?void 0:`HarmonyOS recording completed, but cleanup was not confirmed for the ${i.join(` and `)}.`}async function I(e){try{return await e()}catch{return!1}}function Pe(e,t){let n=[e,t].filter(e=>e!==void 0).join(` `);return n.length===0?{}:{warning:n}}async function Fe(e,t,n,r){let i;for(let a=0;a<40;a+=1){if(await e.screenRecording.harmony.remove(t,n.remotePath).catch(()=>{}),await e.screenRecording.harmony.stageMedia(t,{mediaUri:r,remotePath:n.remotePath})){let r=await e.screenRecording.harmony.stagedFileSize(t,n.remotePath);if(r!==void 0&&r>0&&r===i)return!0;i=r!==void 0&&r>0?r:void 0}else i=void 0;a<39&&await e.clock.sleep(250)}return!1}async function L(e,t,n,r=async()=>{z(await e.screenRecording.harmony.stop(t),`stop`)}){let i=[await R(r),await R(async()=>{if(!await e.screenRecording.harmony.remove(t,n.remotePath))throw Error(`HarmonyOS recording staging artifact removal was not confirmed`)}),await R(async()=>await Ie(e,t,n.fileName))].find(e=>e!==void 0);return i===void 0?{status:`cleaned`}:{status:`cleanup-pending`,reason:`transport-failed`,message:i instanceof Error?i.message:`HarmonyOS recording cleanup failed`}}async function Ie(e,t,n){let r=await e.screenRecording.harmony.findMedia(t,n);if(r&&!await e.screenRecording.harmony.removeMedia(t,r))throw Error(`HarmonyOS recording media removal was not confirmed`)}async function R(e){try{await e();return}catch(e){return e}}function z(e,t){if(e.exitCode===0&&e.stdout.includes(`start ability successfully`))return;let n=e.stdout.trim()||e.stderr.trim()||`hdc exit ${e.exitCode}`;throw Error(`failed to ${t} HarmonyOS screen recording: ${n}`)}async function Le(t,n){n.throwIfAborted();let{runHarmonyHdc:r}=await import(`./hdc.js`),i=await r(t,[`shell`,`aa`,`dump`,`-l`],{timeoutMs:15e3,signal:n});n.throwIfAborted();let a=Re(i.stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine the foreground HarmonyOS app`,{hint:`Open an app on the target, then retry appstate.`});return a}function Re(e){let t=e.split(/(?=^\s*Mission ID #)/m);for(let e of t){if(!/\bstate #FOREGROUND\b/.test(e))continue;let t=e.match(/mission name #\[#([^:]+):[^:]*:([^\]]+)]/);if(!t)continue;let[,n,r]=t;if(!(!n||!r))return{package:n,activity:r}}}function ze(e){return O({owner:`HarmonyOS`,openTargetIdentity:`bundle-id`,binding:D({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const Be=Object.freeze({available:!0}),Ve=Object.freeze({available:!1,reason:`unsupported-device-kind`}),B=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function V(e){let t=e.kind===`emulator`||e.kind===`device`?Be:Ve;return Object.freeze({deployApp:t,materializeAppSource:B,deployMaterializedApp:B,sendPushNotification:B})}function He(e){return V(e.device).deployApp.available?Object.freeze({deployApp:async t=>await Ue(e.commands,e.device,t,e.signal)}):Object.freeze({})}async function Ue(t,n,r,i){let a=await We(t,r.appPath,i)??r.app.trim();if(!a)throw new e(`INVALID_ARGS`,`Could not determine the bundle name from the HAP archive`,{hint:`Pass the HarmonyOS bundle name before the HAP path, or provide a valid HAP containing module.json.`});return await H(t,n,[`install`,`-r`,r.appPath],i,18e4),r.replaceExisting&&(await A(1e3,void 0,{signal:i}),await Ge(t,n,a,i)),{packageName:a,launchTarget:a}}async function We(e,t,n){let r=await e.run({executable:`unzip`,args:[`-p`,t,`module.json`],allowFailure:!0,timeoutMs:15e3},n);if(r.exitCode===0&&r.stdout.trim().length!==0)try{return JSON.parse(r.stdout).app?.bundleName?.trim()||void 0}catch{return}}async function Ge(t,n,r,i){let a=Ke((await H(t,n,[`shell`,`bm`,`dump`,`-n`,r],i)).stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine a launchable ability for ${r}`,{hint:`Check that the HarmonyOS bundle exposes a main ability.`});await H(t,n,[`shell`,`aa`,`start`,`-b`,r,...a.module?[`-m`,a.module]:[],`-a`,a.ability],i)}function Ke(e){let t=e.indexOf(`{`);if(t!==-1)try{let n=JSON.parse(e.slice(t)).hapModuleInfos?.find(e=>e.mainElementName);return n?.mainElementName?{ability:n.mainElementName,...n.moduleName?{module:n.moduleName}:{}}:void 0}catch{return}}async function H(e,t,n,r,i=15e3){return await e.run({executable:`hdc`,args:[`-t`,t.id,...n],timeoutMs:i},r)}const U=n(`harmonyos`),qe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`HarmonyOS reads element text from the captured tree only.`}),Je=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on HarmonyOS emulators and physical devices.`}),W=Object.freeze({available:!0}),G=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Ye=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS appstate is supported only for HarmonyOS emulators and devices.`}),Xe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple runner preparation is supported only for Apple targets.`}),K=Object.freeze({available:!0}),Ze=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`open is supported only for HarmonyOS emulators and devices.`}),Qe=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`close is supported only for HarmonyOS emulators and devices.`}),$e=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),q=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`snapshot is supported only for HarmonyOS emulators and devices.`}),J=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`screenshot is supported only for HarmonyOS emulators and devices.`}),et=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),tt=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`viewport resizes web targets only (--platform web).`});function nt(e){let t=rt(e),n=it(e);return a({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:G,clearRuntimeHints:G,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:Xe,configureProviderPortReverse:$e})}function rt(e){return e.kind===`emulator`||e.kind===`device`?K:Ze}function it(e){return e.kind===`emulator`||e.kind===`device`?K:Qe}const Y=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Gestures are supported on HarmonyOS emulators and physical devices.`}),at=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ot=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:S});function X(e){return e.kind===`emulator`||e.kind===`device`?W:Y}function Z(e){return e.kind===`emulator`||e.kind===`device`?W:Je}const Q=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),st=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`keyboard status/get is not available through the public HarmonyOS HDC API; use keyboard dismiss or enter`}),$=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`});function ct(e){let t=Se(e),n=async e=>{let n=await t.inspectFacts(e),r=V(e),i=Oe(e);return Object.freeze({device:n.device,operations:{...n.operations,...r,appState:e.kind===`simulator`?Ye:W,networkDump:G,screenRecordingStart:i,screenRecordingReattach:i,screenRecordingCleanup:i,...d({capture:e.kind===`emulator`||e.kind===`device`?W:q,customActions:et,withoutActiveApp:e.kind===`emulator`||e.kind===`device`?W:q}),...u({capture:e.kind===`emulator`||e.kind===`device`?W:J}),...h({findText:q}),...p({setViewport:tt}),...f({focus:Z(e)}),...ee({unsupported:Y,plan:X(e),directionalFling:X(e),multiTouch:at,targetAuthoredDrag:ot,viewport:X(e)}),...c({scroll:X(e)}),...l({type:Z(e)}),...o({unsupported:G,tap:Z(e),longPress:Z(e),fill:Z(e)}),...pe({readTextAtPoint:qe}),...me({back:Z(e)}),...ie({home:Z(e)}),...ue({appSwitcher:Z(e)}),...re({triggerAppEvent:Q}),...se({setSetting:Z(e)}),...de({read:Q,wait:Q,accept:Q,dismiss:Q}),...fe({orientation:Q}),...oe({tvRemote:Q}),...le({unsupported:Q,status:st,dismiss:Z(e),enter:Z(e)}),...ae({unsupported:Q}),...ge({capture:$,query:$}),..._e({frames:Z(e),memorySample:Z(e),memorySnapshot:Z(e),nativeCapture:Q,profileReport:Q}),ensureReady:W,bootTarget:G,bootTargetHeadless:G,listApps:W,...nt(e),shutdownTarget:G}})};return Object.freeze({owner:U,ownsDevice:e=>e.platform===`harmonyos`,inspectFacts:n,bind:async a=>{let o=await t.bind(a),c=await n(a.device),l=c.operations.screenRecordingStart;return Object.freeze({device:o.device,owner:U,facts:c,operations:Object.freeze({...o.operations,...He({commands:e.commands,device:a.device,signal:a.scope.signal}),...c.operations.appState.available?{appState:async()=>await Le(a.device,a.scope.signal)}:{},ensureReady:async()=>({...a.device,booted:!0}),...l.available?ke({host:e,device:a.device,owner:U,signal:a.scope.signal}):{},...c.operations.captureSnapshot.available?he({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...c.operations.captureScreenshot.available?ne({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...c.operations.focusPoint.available?m({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...c.operations.typeText.available?g({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...ce({device:a.device,signal:a.scope.signal,facts:c.operations,resolveInteractor:e.localInteractors.resolve}),...c.operations.scrollDirection.available?te({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...C({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:c.operations}),...r(c.operations.perfFrames,()=>we({resolveHost:()=>e.perf.harmony,device:a.device})),...r(c.operations.tapPoint,()=>s({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:c.operations,pause:async t=>await e.clock.sleep(t,a.scope.signal)})),listApps:async e=>{a.scope.signal.throwIfAborted();let{listHarmonyApps:t}=await import(`./app-lifecycle2.js`);return(await t(e.device,e.filter,{signal:a.scope.signal})).map(e=>({id:e.package,name:e.name}))},...i(ze({host:e.localInteractors,device:a.device,signal:a.scope.signal}),c.operations)}),[Symbol.asyncDispose]:async()=>await o[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}export{ct as createHarmonyPlatformRuntime};
1
+ import{C as e}from"./sdk-contracts.js";import{w as t}from"./sdk-device.js";import{Gt as n,Zt as r}from"./sdk-batch.js";import{n as i,t as a}from"./application-lifecycle-runtime.js";import{i as o,t as s}from"./touch-runtime.js";import{A as c,D as l,G as u,H as d,I as f,L as p,N as ee,O as te,P as m,R as h,T as g,U as ne,a as re,b as ie,d as ae,g as oe,i as se,j as ce,m as le,s as ue,t as de,v as fe,w as pe,x as me,z as he}from"./alert-runtime.js";import{n as ge}from"./audio-probe-runtime.js";import{n as _e}from"./perf-runtime.js";import{a as _,n as v}from"./durable-resource.js";import{n as ve}from"./async-lifecycle.js";import{i as ye,r as be}from"./src7.js";import{n as xe,t as y}from"./screen-recording-completion.js";import{t as b}from"./screen-recording-options.js";import{n as x}from"./screen-recording-runtime.js";import{i as S}from"./gesture-admission.js";import{t as C}from"./interactor-operation-catalog.js";import{i as w,n as T}from"./perf-runtime-operation-builder.js";import{t as E}from"./app-log-runtime.js";import{n as D,t as O}from"./application-lifecycle-interaction.js";import{randomUUID as k}from"node:crypto";import{setTimeout as A}from"node:timers/promises";const j=Object.freeze({resourceKind:E,version:1,encode:e=>({...e}),decode:e=>e.transport!==`harmony-hilog`||!N(e.outputPath)||!N(e.pidPath)?{status:`invalid`,message:`Invalid HarmonyOS app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:`harmony-hilog`,outputPath:e.outputPath,pidPath:e.pidPath})}});function M(e){return v({resourceKind:E,sessionId:e.sessionId,device:{id:e.device.id,family:`harmonyos`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:_(j,e.descriptor)})}function N(e){return typeof e==`string`&&e.trim().length>0}function Se(e){return be(e,{family:`harmonyos`,backend:`harmonyos`,label:`HarmonyOS`,codec:j,startUnavailableHint:`The selected HarmonyOS transport cannot start a background hilog stream.`,cleanupFailureMessage:`HarmonyOS app-log cleanup did not settle every owned resource`,doctor:async(e,t)=>({backend:`harmonyos`,checks:{},notes:t?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}),process:async({host:e,device:t,input:n,signal:r})=>{let i=await Ce(e,r);return{resolvePid:async r=>await ye(e,{executable:i,args:[`-t`,t.id,`shell`,`pidof`,n.appBundleId],allowFailure:!0,timeoutMs:5e3},r),command:e=>({kind:`host`,request:{executable:i,args:[`-t`,t.id,`shell`,`hilog`,`-P`,e],allowFailure:!0}})}},descriptor:({artifacts:e})=>({transport:`harmony-hilog`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>M({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function Ce(t,n){n.throwIfAborted(),await P(async()=>await t.toolchains.prepare(`harmonyos`),n),n.throwIfAborted();let r=await P(async()=>await t.commands.which(`hdc`),n);if(n.throwIfAborted(),!r)throw new e(`TOOL_MISSING`,`hdc not found in PATH`,{hint:`Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.`});return r}async function P(e,t){try{return await e()}catch(e){throw t.throwIfAborted(),e}}function we(e){let{resolveHost:t,device:n}=e,r={available:!1,reason:`Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions.`};return Object.freeze({perfFrames:async()=>({metric:r,sampling:r}),perfMemorySample:async({appId:e})=>({metric:e?await w(t().sampleMemory(n,e)):T(`HarmonyOS`,`bundle`),sampling:{method:`hdc-shell-proc-status`,description:`Resident memory snapshot from HarmonyOS /proc/<pid>/status. Values are reported in kilobytes.`,unit:`kB`,topConsumerLimit:1}}),perfMemorySnapshot:async({kind:e})=>({artifact:{available:!1,kind:e??`memgraph`,reason:`Memory snapshot artifacts are not supported on harmonyos.`,hint:`Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS.`,support:{platform:`harmonyos`,defaultKind:`memgraph`,androidHprof:!1,memgraph:!1,heapprofd:!1}},sampling:{method:`unsupported`,description:`HarmonyOS memory snapshot capture is not available through HDC.`,artifactOnly:!0}})})}const F=Object.freeze({resourceKind:x,version:1,encode:e=>({...e}),decode:e=>e.backend===`harmony-screen-recorder`&&typeof e.fileName==`string`&&De(e.fileName)&&e.remotePath===`/data/local/tmp/${e.fileName}`?{status:`decoded`,descriptor:Object.freeze({backend:`harmony-screen-recorder`,fileName:e.fileName,remotePath:e.remotePath})}:{status:`invalid`,message:`Invalid HarmonyOS screen-recording descriptor`}});function Te(e){let{device:n,owner:r,input:i,descriptor:a}=e;return v({resourceKind:x,sessionId:i.sessionId,device:t(n),owner:r,fence:i.fence,lifecycle:`open`,descriptor:_(F,a)})}function Ee(e){return F.decode(e).status===`decoded`?{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`HarmonyOS recorder ownership cannot be proven after daemon restart; no recorder was stopped.`}:{status:`cleanup-pending`,reason:`manual-recovery-required`}}function De(e){return/^agent-device-recording-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.mp4$/i.test(e)}function Oe(e){return e.kind===`device`?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS recording is supported on physical devices only.`})}function ke(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await Ae({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`HarmonyOS recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async e=>Ee(e.envelope.descriptor.body)})}async function Ae(t){let{host:n,device:r,owner:i,input:a,signal:o}=t;if(a.scope===`app`)throw new e(`INVALID_ARGS`,`HarmonyOS recording captures the whole physical-device screen; use --scope device or --scope system`);b(a,{scopes:[`device`,`system`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`HarmonyOS recordings do not support ${e.join(`, `)}`),o.throwIfAborted(),await n.screenRecording.outputs.prepare(a.outputPath);let s=`agent-device-recording-${k()}.mp4`,c={backend:`harmony-screen-recorder`,fileName:s,remotePath:`/data/local/tmp/${s}`},l;try{l=await n.screenRecording.harmony.start(r,s,o),o.throwIfAborted()}catch(e){throw o.aborted?(await L(n,r,c).catch(()=>{}),o.reason):e}z(l,`start`);try{o.throwIfAborted()}catch(e){throw await L(n,r,c).catch(()=>{}),e}let u=je(a),d=!1,f=async()=>{d||=(z(await n.screenRecording.harmony.stop(r),`stop`),!0)},p=xe(u,{finish:async e=>await Me(n,r,e,c,f),forceCleanup:async()=>await L(n,r,c,f)});return Object.freeze({pendingHandle:new ve(p),envelope:Te({device:r,owner:i,input:a,descriptor:c})})}function je(e){return Object.freeze({backend:`HarmonyOS ScreenRecorder`,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:Date.now(),scope:e.scope,showTouches:!1,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},gestureEvents:[]})}async function Me(e,t,n,r,i){await i();let a=await e.screenRecording.harmony.findMedia(t,r.fileName);if(!a)throw Error(`failed to find finalized HarmonyOS recording '${r.fileName}'`);if(!await Fe(e,t,r,a))throw Error(`failed to finalize HarmonyOS recording: ${r.fileName} did not produce a non-empty media file`);try{if((await e.screenRecording.harmony.pull(t,{remotePath:r.remotePath,outputPath:n.outPath})).exitCode!==0)throw Error(`failed to retrieve HarmonyOS recording`);let i=await e.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!1,gestureEvents:n.gestureEvents,targetLabel:`HarmonyOS recording`}),o=await Ne(e,t,r,a);return y(n,{...i,...Pe(i.warning,o)},{stopObservation:{recorder:`confirmed`},nativePathDisposition:o===void 0?`retired`:`retirable`,showTouches:!1})}catch(n){throw await e.screenRecording.harmony.remove(t,r.remotePath).catch(()=>{}),n}}async function Ne(e,t,n,r){let i=[];return await I(()=>e.screenRecording.harmony.remove(t,n.remotePath))||i.push(`staging artifact`),await I(()=>e.screenRecording.harmony.removeMedia(t,r))||i.push(`media-library artifact`),i.length===0?void 0:`HarmonyOS recording completed, but cleanup was not confirmed for the ${i.join(` and `)}.`}async function I(e){try{return await e()}catch{return!1}}function Pe(e,t){let n=[e,t].filter(e=>e!==void 0).join(` `);return n.length===0?{}:{warning:n}}async function Fe(e,t,n,r){let i;for(let a=0;a<40;a+=1){if(await e.screenRecording.harmony.remove(t,n.remotePath).catch(()=>{}),await e.screenRecording.harmony.stageMedia(t,{mediaUri:r,remotePath:n.remotePath})){let r=await e.screenRecording.harmony.stagedFileSize(t,n.remotePath);if(r!==void 0&&r>0&&r===i)return!0;i=r!==void 0&&r>0?r:void 0}else i=void 0;a<39&&await e.clock.sleep(250)}return!1}async function L(e,t,n,r=async()=>{z(await e.screenRecording.harmony.stop(t),`stop`)}){let i=[await R(r),await R(async()=>{if(!await e.screenRecording.harmony.remove(t,n.remotePath))throw Error(`HarmonyOS recording staging artifact removal was not confirmed`)}),await R(async()=>await Ie(e,t,n.fileName))].find(e=>e!==void 0);return i===void 0?{status:`cleaned`}:{status:`cleanup-pending`,reason:`transport-failed`,message:i instanceof Error?i.message:`HarmonyOS recording cleanup failed`}}async function Ie(e,t,n){let r=await e.screenRecording.harmony.findMedia(t,n);if(r&&!await e.screenRecording.harmony.removeMedia(t,r))throw Error(`HarmonyOS recording media removal was not confirmed`)}async function R(e){try{await e();return}catch(e){return e}}function z(e,t){if(e.exitCode===0&&e.stdout.includes(`start ability successfully`))return;let n=e.stdout.trim()||e.stderr.trim()||`hdc exit ${e.exitCode}`;throw Error(`failed to ${t} HarmonyOS screen recording: ${n}`)}async function Le(t,n){n.throwIfAborted();let{runHarmonyHdc:r}=await import(`./hdc.js`),i=await r(t,[`shell`,`aa`,`dump`,`-l`],{timeoutMs:15e3,signal:n});n.throwIfAborted();let a=Re(i.stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine the foreground HarmonyOS app`,{hint:`Open an app on the target, then retry appstate.`});return a}function Re(e){let t=e.split(/(?=^\s*Mission ID #)/m);for(let e of t){if(!/\bstate #FOREGROUND\b/.test(e))continue;let t=e.match(/mission name #\[#([^:]+):[^:]*:([^\]]+)]/);if(!t)continue;let[,n,r]=t;if(!(!n||!r))return{package:n,activity:r}}}function ze(e){return O({owner:`HarmonyOS`,openTargetIdentity:`bundle-id`,binding:D({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const Be=Object.freeze({available:!0}),Ve=Object.freeze({available:!1,reason:`unsupported-device-kind`}),B=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function V(e){let t=e.kind===`emulator`||e.kind===`device`?Be:Ve;return Object.freeze({deployApp:t,materializeAppSource:B,deployMaterializedApp:B,sendPushNotification:B})}function He(e){return V(e.device).deployApp.available?Object.freeze({deployApp:async t=>await Ue(e.commands,e.device,t,e.signal)}):Object.freeze({})}async function Ue(t,n,r,i){let a=await We(t,r.appPath,i)??r.app.trim();if(!a)throw new e(`INVALID_ARGS`,`Could not determine the bundle name from the HAP archive`,{hint:`Pass the HarmonyOS bundle name before the HAP path, or provide a valid HAP containing module.json.`});return await H(t,n,[`install`,`-r`,r.appPath],i,18e4),r.replaceExisting&&(await A(1e3,void 0,{signal:i}),await Ge(t,n,a,i)),{packageName:a,launchTarget:a}}async function We(e,t,n){let r=await e.run({executable:`unzip`,args:[`-p`,t,`module.json`],allowFailure:!0,timeoutMs:15e3},n);if(r.exitCode===0&&r.stdout.trim().length!==0)try{return JSON.parse(r.stdout).app?.bundleName?.trim()||void 0}catch{return}}async function Ge(t,n,r,i){let a=Ke((await H(t,n,[`shell`,`bm`,`dump`,`-n`,r],i)).stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine a launchable ability for ${r}`,{hint:`Check that the HarmonyOS bundle exposes a main ability.`});await H(t,n,[`shell`,`aa`,`start`,`-b`,r,...a.module?[`-m`,a.module]:[],`-a`,a.ability],i)}function Ke(e){let t=e.indexOf(`{`);if(t!==-1)try{let n=JSON.parse(e.slice(t)).hapModuleInfos?.find(e=>e.mainElementName);return n?.mainElementName?{ability:n.mainElementName,...n.moduleName?{module:n.moduleName}:{}}:void 0}catch{return}}async function H(e,t,n,r,i=15e3){return await e.run({executable:`hdc`,args:[`-t`,t.id,...n],timeoutMs:i},r)}const U=n(`harmonyos`),qe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`HarmonyOS reads element text from the captured tree only.`}),Je=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on HarmonyOS emulators and physical devices.`}),W=Object.freeze({available:!0}),G=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Ye=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS appstate is supported only for HarmonyOS emulators and devices.`}),Xe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple runner preparation is supported only for Apple targets.`}),K=Object.freeze({available:!0}),Ze=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`open is supported only for HarmonyOS emulators and devices.`}),Qe=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`close is supported only for HarmonyOS emulators and devices.`}),$e=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),q=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`snapshot is supported only for HarmonyOS emulators and devices.`}),J=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`screenshot is supported only for HarmonyOS emulators and devices.`}),et=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),tt=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`viewport resizes web targets only (--platform web).`});function nt(e){let t=rt(e),n=it(e);return a({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:G,clearRuntimeHints:G,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:Xe,configureProviderPortReverse:$e})}function rt(e){return e.kind===`emulator`||e.kind===`device`?K:Ze}function it(e){return e.kind===`emulator`||e.kind===`device`?K:Qe}const Y=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Gestures are supported on HarmonyOS emulators and physical devices.`}),at=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ot=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:S});function X(e){return e.kind===`emulator`||e.kind===`device`?W:Y}function Z(e){return e.kind===`emulator`||e.kind===`device`?W:Je}const Q=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),st=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`keyboard status/get is not available through the public HarmonyOS HDC API; use keyboard dismiss or enter`}),$=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`});function ct(e){let t=Se(e),n=async e=>{let n=await t.inspectFacts(e),r=V(e),i=Oe(e);return Object.freeze({device:n.device,operations:{...n.operations,...r,appState:e.kind===`simulator`?Ye:W,networkDump:G,screenRecordingStart:i,screenRecordingReattach:i,screenRecordingCleanup:i,...d({capture:e.kind===`emulator`||e.kind===`device`?W:q,customActions:et,withoutActiveApp:e.kind===`emulator`||e.kind===`device`?W:q}),...u({capture:e.kind===`emulator`||e.kind===`device`?W:J}),...h({findText:q}),...p({setViewport:tt}),...f({focus:Z(e)}),...ee({unsupported:Y,plan:X(e),directionalFling:X(e),multiTouch:at,targetAuthoredDrag:ot,viewport:X(e)}),...c({scroll:X(e)}),...l({type:Z(e)}),...o({unsupported:G,tap:Z(e),longPress:Z(e),fill:Z(e)}),...pe({readTextAtPoint:qe}),...me({back:Z(e)}),...ie({home:Z(e)}),...ue({appSwitcher:Z(e)}),...re({triggerAppEvent:Q}),...se({setSetting:Z(e)}),...de({read:Q,wait:Q,accept:Q,dismiss:Q}),...fe({orientation:Q}),...oe({tvRemote:Q}),...le({unsupported:Q,status:st,dismiss:Z(e),enter:Z(e)}),...ae({unsupported:Q}),...ge({capture:$,query:$}),..._e({frames:Z(e),memorySample:Z(e),memorySnapshot:Z(e),nativeCapture:Q,profileReport:Q}),ensureReady:W,bootTarget:G,bootTargetHeadless:G,listApps:W,...nt(e),shutdownTarget:G}})};return Object.freeze({owner:U,ownsDevice:e=>e.platform===`harmonyos`,inspectFacts:n,bind:async a=>{let o=await t.bind(a),c=await n(a.device),l=c.operations.screenRecordingStart;return Object.freeze({device:o.device,owner:U,facts:c,operations:Object.freeze({...o.operations,...He({commands:e.commands,device:a.device,signal:a.scope.signal}),...c.operations.appState.available?{appState:async()=>await Le(a.device,a.scope.signal)}:{},ensureReady:async()=>({...a.device,booted:!0}),...l.available?ke({host:e,device:a.device,owner:U,signal:a.scope.signal}):{},...c.operations.captureSnapshot.available?he({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...c.operations.captureScreenshot.available?ne({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...c.operations.focusPoint.available?m({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...c.operations.typeText.available?g({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...ce({device:a.device,signal:a.scope.signal,facts:c.operations,resolveInteractor:e.localInteractors.resolve}),...c.operations.scrollDirection.available?te({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...C({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:c.operations}),...r(c.operations.perfFrames,()=>we({resolveHost:()=>e.perf.harmony,device:a.device})),...r(c.operations.tapPoint,()=>s({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:c.operations,pause:async t=>await e.clock.sleep(t,a.scope.signal)})),listApps:async e=>{a.scope.signal.throwIfAborted();let{listHarmonyApps:t}=await import(`./app-lifecycle2.js`);return(await t(e.device,e.filter,{signal:a.scope.signal})).map(e=>({id:e.package,name:e.name}))},...i(ze({host:e.localInteractors,device:a.device,signal:a.scope.signal}),c.operations)}),[Symbol.asyncDispose]:async()=>await o[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}export{ct as createHarmonyPlatformRuntime};
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";import{w as t}from"./sdk-device.js";import{Gt as n,Xt as r,Zt as i}from"./sdk-batch.js";import{n as a,t as o}from"./application-lifecycle-runtime.js";import{i as s,t as c}from"./touch-runtime.js";import{A as l,D as u,G as d,H as f,I as p,L as m,N as ee,O as te,P as ne,R as re,T as ie,U as h,a as g,b as _,d as v,g as ae,i as y,m as oe,s as b,t as x,v as S,w as C,x as w,z as T}from"./alert-runtime.js";import{n as E}from"./audio-probe-runtime.js";import{n as D}from"./perf-runtime.js";import{a as O,n as k}from"./durable-resource.js";import{n as A}from"./async-lifecycle.js";import"./src7.js";import{t as j}from"./screen-recording-live-handle.js";import{t as M}from"./screen-recording-completion.js";import{t as N}from"./screen-recording-options.js";import{t as P}from"./screen-recording-runtime.js";import{i as F}from"./gesture-admission.js";import{n as I,t as L}from"./application-lifecycle-interaction.js";const R=Object.freeze({resourceKind:P,version:1,encode:e=>({...e}),decode:e=>e.backend===`agent-browser`&&typeof e.outputPath==`string`?{status:`decoded`,descriptor:Object.freeze({backend:`agent-browser`,outputPath:e.outputPath})}:{status:`invalid`,message:`Invalid web screen-recording descriptor`}});async function z(e){let{host:t,device:n,owner:r,signal:i}=e,a=await t.screenRecording.web.resolve(n);return a?{available:!0,operations:{screenRecordingStart:async e=>await B({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`Web recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async()=>V()}}:{available:!1,operations:{}}}async function B(n){let{host:r,transport:i,device:a,owner:o,input:s,signal:c}=n;if(s.recordOnlySession)throw new e(`INVALID_ARGS`,`record on web requires an active browser session; run open <url> --platform web first`);if(!s.outputPath.toLowerCase().endsWith(`.webm`))throw new e(`INVALID_ARGS`,`web recordings require a .webm output path; agent-browser records WebM directly`);N(s,{scopes:[`app`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`web recordings do not support ${e.join(`, `)}; agent-browser records WebM directly`),c.throwIfAborted(),await r.screenRecording.outputs.prepare(s.outputPath);let l=!1;try{await i.start(s.outputPath,c),l=!0,c.throwIfAborted()}catch(e){throw l&&await i.stop().catch(()=>{}),c.throwIfAborted(),e}let u=!1,d=async()=>{u||=(await i.stop(),!0)},f=j({backend:`agent-browser`,outPath:s.outputPath,...s.clientOutputPath===void 0?{}:{clientOutPath:s.clientOutputPath},startedAt:Date.now(),scope:s.scope,showTouches:!1,recordOnlySession:s.recordOnlySession,...s.activeSessionApp===void 0?{}:{activeSessionApp:s.activeSessionApp},gestureEvents:[]},{finish:async e=>{await d();let t=await r.screenRecording.finalize.complete({outputPath:e.outPath,showTouches:!1,gestureEvents:e.gestureEvents,targetLabel:`web recording`});return M(e,t,!1)},forceCleanup:async()=>{try{return await d(),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Web recording cleanup failed`}}}});return Object.freeze({pendingHandle:new A(f),envelope:k({resourceKind:P,sessionId:s.sessionId,device:t(a),owner:o,fence:s.fence,lifecycle:`open`,descriptor:O(R,{backend:`agent-browser`,outputPath:s.outputPath})})})}function V(){return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`Web recordings cannot be cleaned after daemon restart.`}}function H(e){return L({owner:`web`,openTargetIdentity:`app-name`,binding:I({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const U=n(`web`),W=Object.freeze({available:!0}),G=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Web targets read element text from the captured tree only.`}),K=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),q=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`record is not supported by this web provider`}),se=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),J=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ce=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`apps is not supported on web targets.`}),le=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Y=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ue=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple runner preparation is supported only for Apple targets.`}),de=Object.freeze({available:!1,reason:`owner-capability-missing`}),fe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`audio on web sessions is the stateless page probe; host capture is a macOS-host operation.`});function X(e,t){return typeof e==`function`?t:de}function Z(e,t){return e?W:t}const pe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),me=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:F}),Q=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`open is supported only for web browser devices.`}),he=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`close is supported only for web browser devices.`}),ge=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`});function _e(e){let t=ve(e),n=ye(e);return o({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:J,clearRuntimeHints:J,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:ue,configureProviderPortReverse:ge})}function ve(e){return e.kind===`device`?W:Q}function ye(e){return e.kind===`device`?W:he}function be(t){return Object.freeze({owner:U,ownsDevice:e=>e.platform===`web`,inspectFacts:async e=>{let n=await t.networkTransports.resolve(e),r=await z({host:t,device:e,owner:U,signal:new AbortController().signal}),i=e.kind===`device`?await t.localInteractors.resolve(e,{}):void 0;return $(e,n,r.available,i)},bind:async n=>{if(n.intent.kind===`exact-owner`&&!r(n.intent.owner,U))throw new e(`UNSUPPORTED_OPERATION`,`Web runtime owner identity does not match`);if(n.device.platform!==`web`)throw new e(`UNSUPPORTED_PLATFORM`,`Web runtime owner cannot bind ${n.device.platform}`);let i=await t.networkTransports.resolve(n.device),a=await z({host:t,device:n.device,owner:U,signal:n.scope.signal}),o=n.device.kind===`device`?await t.localInteractors.resolve(n.device,{signal:n.scope.signal}):void 0;return xe(t,n.device,n.scope.signal,i,a,$(n.device,i,a.available,o))},shutdown:async()=>void 0})}function xe(t,n,r,o,s,l){let u=o.dump,d={...u?{networkDump:async e=>{let t=await u({maxEntries:e.maxEntries,include:e.include},r);return Object.freeze({source:`provider`,...t})}}:{},...s.operations,...l.operations.captureSnapshot.available?T({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.captureScreenshot.available?h({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.focusPoint.available?ne({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.typeText.available?ie({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...i(l.operations.tapPoint,()=>c({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:l.operations,pause:async e=>await t.clock.sleep(e,r)})),...l.operations.scrollDirection.available?te({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.setViewport.available?{setViewport:async i=>{r.throwIfAborted();let a=await t.localInteractors.resolve(n,{signal:r});if(!a.setViewport)throw new e(`UNSUPPORTED_OPERATION`,`viewport is not supported by the bound web interactor`);await a.setViewport(i.width,i.height),r.throwIfAborted()}}:{},...i(l.operations.audioProbeQuery,()=>({audioProbeQuery:async r=>{let i=await t.audioProbe.web.resolve(n);if(i===void 0)throw new e(`UNSUPPORTED_OPERATION`,`audio is not supported by this web provider`);return await i.probe(r)}})),...a(H({host:t.localInteractors,device:n,signal:r}),l.operations)};return Object.freeze({device:n,owner:U,facts:l,operations:Object.freeze(d),[Symbol.asyncDispose]:async()=>void 0})}function $(e,t,n,r){let i=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`network is not supported by this web provider`}),a=Z(e.kind===`device`,Q);return Object.freeze({device:{family:`web`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:t.mode},operations:{appLogInspect:K,appLogDoctor:K,appLogStart:K,appLogReattach:K,appLogCleanup:K,appState:le,networkDump:Z(!!t.dump,i),screenRecordingStart:Z(n,q),screenRecordingReattach:Z(n,q),screenRecordingCleanup:Z(n,q),...f({capture:a,customActions:se,withoutActiveApp:a}),...re({findText:Q}),...d({capture:a}),...p({focus:a}),...u({type:a}),...s({unsupported:J,tap:a,tapRef:X(r?.tapRef,a),longPress:J,hover:X(r?.hover,a),hoverRef:X(r?.hoverRef,a),fill:a,fillRef:X(r?.fillRef,a)}),...l({scroll:a}),...ee({unsupported:pe,targetAuthoredDrag:me}),...m({setViewport:a}),...C({readTextAtPoint:G}),...w({back:Y}),..._({home:Y}),...S({orientation:Y}),...ae({tvRemote:Y}),...oe({unsupported:Y}),...v({unsupported:Y}),...E({capture:fe,query:W}),...D({frames:Y,memorySample:Y,memorySnapshot:Y,nativeCapture:Y,profileReport:Y}),...b({appSwitcher:Y}),...g({triggerAppEvent:Y}),...y({setSetting:Y}),...x({read:Y,wait:Y,accept:Y,dismiss:Y}),ensureReady:J,bootTarget:J,bootTargetHeadless:J,listApps:ce,deployApp:J,materializeAppSource:J,deployMaterializedApp:J,sendPushNotification:J,shutdownTarget:J,..._e(e)}})}export{be as createWebPlatformRuntime};
1
+ import{C as e}from"./sdk-contracts.js";import{w as t}from"./sdk-device.js";import{Gt as n,Xt as r,Zt as i}from"./sdk-batch.js";import{n as a,t as o}from"./application-lifecycle-runtime.js";import{i as s,t as c}from"./touch-runtime.js";import{A as l,D as u,G as d,H as f,I as p,L as m,N as ee,O as te,P as ne,R as re,T as ie,U as h,a as g,b as _,d as v,g as ae,i as y,m as oe,s as b,t as x,v as S,w as C,x as w,z as T}from"./alert-runtime.js";import{n as E}from"./audio-probe-runtime.js";import{n as D}from"./perf-runtime.js";import{a as O,n as k}from"./durable-resource.js";import{n as A}from"./async-lifecycle.js";import"./src7.js";import{n as j,t as M}from"./screen-recording-completion.js";import{t as N}from"./screen-recording-options.js";import{n as P}from"./screen-recording-runtime.js";import{i as F}from"./gesture-admission.js";import{n as I,t as L}from"./application-lifecycle-interaction.js";const R=Object.freeze({resourceKind:P,version:1,encode:e=>({...e}),decode:e=>e.backend===`agent-browser`&&typeof e.outputPath==`string`?{status:`decoded`,descriptor:Object.freeze({backend:`agent-browser`,outputPath:e.outputPath})}:{status:`invalid`,message:`Invalid web screen-recording descriptor`}});async function z(e){let{host:t,device:n,owner:r,signal:i}=e,a=await t.screenRecording.web.resolve(n);return a?{available:!0,operations:{screenRecordingStart:async e=>await B({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`Web recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async()=>V()}}:{available:!1,operations:{}}}async function B(n){let{host:r,transport:i,device:a,owner:o,input:s,signal:c}=n;if(s.recordOnlySession)throw new e(`INVALID_ARGS`,`record on web requires an active browser session; run open <url> --platform web first`);if(!s.outputPath.toLowerCase().endsWith(`.webm`))throw new e(`INVALID_ARGS`,`web recordings require a .webm output path; agent-browser records WebM directly`);N(s,{scopes:[`app`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`web recordings do not support ${e.join(`, `)}; agent-browser records WebM directly`),c.throwIfAborted(),await r.screenRecording.outputs.prepare(s.outputPath);let l=!1;try{await i.start(s.outputPath,c),l=!0,c.throwIfAborted()}catch(e){throw l&&await i.stop().catch(()=>{}),c.throwIfAborted(),e}let u=!1,d=async()=>{u||=(await i.stop(),!0)},f=j({backend:`agent-browser`,outPath:s.outputPath,...s.clientOutputPath===void 0?{}:{clientOutPath:s.clientOutputPath},startedAt:Date.now(),scope:s.scope,showTouches:!1,recordOnlySession:s.recordOnlySession,...s.activeSessionApp===void 0?{}:{activeSessionApp:s.activeSessionApp},gestureEvents:[]},{finish:async e=>{await d();let t=await r.screenRecording.finalize.complete({outputPath:e.outPath,showTouches:!1,gestureEvents:e.gestureEvents,targetLabel:`web recording`});return M(e,t,{stopObservation:{recorder:`confirmed`},showTouches:!1})},forceCleanup:async()=>{try{return await d(),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Web recording cleanup failed`}}}});return Object.freeze({pendingHandle:new A(f),envelope:k({resourceKind:P,sessionId:s.sessionId,device:t(a),owner:o,fence:s.fence,lifecycle:`open`,descriptor:O(R,{backend:`agent-browser`,outputPath:s.outputPath})})})}function V(){return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`Web recordings cannot be cleaned after daemon restart.`}}function H(e){return L({owner:`web`,openTargetIdentity:`app-name`,binding:I({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const U=n(`web`),W=Object.freeze({available:!0}),G=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Web targets read element text from the captured tree only.`}),K=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),q=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`record is not supported by this web provider`}),se=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),J=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ce=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`apps is not supported on web targets.`}),le=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Y=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ue=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple runner preparation is supported only for Apple targets.`}),de=Object.freeze({available:!1,reason:`owner-capability-missing`}),fe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`audio on web sessions is the stateless page probe; host capture is a macOS-host operation.`});function X(e,t){return typeof e==`function`?t:de}function Z(e,t){return e?W:t}const pe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),me=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:F}),Q=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`open is supported only for web browser devices.`}),he=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`close is supported only for web browser devices.`}),ge=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`});function _e(e){let t=ve(e),n=ye(e);return o({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:J,clearRuntimeHints:J,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:ue,configureProviderPortReverse:ge})}function ve(e){return e.kind===`device`?W:Q}function ye(e){return e.kind===`device`?W:he}function be(t){return Object.freeze({owner:U,ownsDevice:e=>e.platform===`web`,inspectFacts:async e=>{let n=await t.networkTransports.resolve(e),r=await z({host:t,device:e,owner:U,signal:new AbortController().signal}),i=e.kind===`device`?await t.localInteractors.resolve(e,{}):void 0;return $(e,n,r.available,i)},bind:async n=>{if(n.intent.kind===`exact-owner`&&!r(n.intent.owner,U))throw new e(`UNSUPPORTED_OPERATION`,`Web runtime owner identity does not match`);if(n.device.platform!==`web`)throw new e(`UNSUPPORTED_PLATFORM`,`Web runtime owner cannot bind ${n.device.platform}`);let i=await t.networkTransports.resolve(n.device),a=await z({host:t,device:n.device,owner:U,signal:n.scope.signal}),o=n.device.kind===`device`?await t.localInteractors.resolve(n.device,{signal:n.scope.signal}):void 0;return xe(t,n.device,n.scope.signal,i,a,$(n.device,i,a.available,o))},shutdown:async()=>void 0})}function xe(t,n,r,o,s,l){let u=o.dump,d={...u?{networkDump:async e=>{let t=await u({maxEntries:e.maxEntries,include:e.include},r);return Object.freeze({source:`provider`,...t})}}:{},...s.operations,...l.operations.captureSnapshot.available?T({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.captureScreenshot.available?h({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.focusPoint.available?ne({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.typeText.available?ie({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...i(l.operations.tapPoint,()=>c({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:l.operations,pause:async e=>await t.clock.sleep(e,r)})),...l.operations.scrollDirection.available?te({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.setViewport.available?{setViewport:async i=>{r.throwIfAborted();let a=await t.localInteractors.resolve(n,{signal:r});if(!a.setViewport)throw new e(`UNSUPPORTED_OPERATION`,`viewport is not supported by the bound web interactor`);await a.setViewport(i.width,i.height),r.throwIfAborted()}}:{},...i(l.operations.audioProbeQuery,()=>({audioProbeQuery:async r=>{let i=await t.audioProbe.web.resolve(n);if(i===void 0)throw new e(`UNSUPPORTED_OPERATION`,`audio is not supported by this web provider`);return await i.probe(r)}})),...a(H({host:t.localInteractors,device:n,signal:r}),l.operations)};return Object.freeze({device:n,owner:U,facts:l,operations:Object.freeze(d),[Symbol.asyncDispose]:async()=>void 0})}function $(e,t,n,r){let i=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`network is not supported by this web provider`}),a=Z(e.kind===`device`,Q);return Object.freeze({device:{family:`web`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:t.mode},operations:{appLogInspect:K,appLogDoctor:K,appLogStart:K,appLogReattach:K,appLogCleanup:K,appState:le,networkDump:Z(!!t.dump,i),screenRecordingStart:Z(n,q),screenRecordingReattach:Z(n,q),screenRecordingCleanup:Z(n,q),...f({capture:a,customActions:se,withoutActiveApp:a}),...re({findText:Q}),...d({capture:a}),...p({focus:a}),...u({type:a}),...s({unsupported:J,tap:a,tapRef:X(r?.tapRef,a),longPress:J,hover:X(r?.hover,a),hoverRef:X(r?.hoverRef,a),fill:a,fillRef:X(r?.fillRef,a)}),...l({scroll:a}),...ee({unsupported:pe,targetAuthoredDrag:me}),...m({setViewport:a}),...C({readTextAtPoint:G}),...w({back:Y}),..._({home:Y}),...S({orientation:Y}),...ae({tvRemote:Y}),...oe({unsupported:Y}),...v({unsupported:Y}),...E({capture:fe,query:W}),...D({frames:Y,memorySample:Y,memorySnapshot:Y,nativeCapture:Y,profileReport:Y}),...b({appSwitcher:Y}),...g({triggerAppEvent:Y}),...y({setSetting:Y}),...x({read:Y,wait:Y,accept:Y,dismiss:Y}),ensureReady:J,bootTarget:J,bootTargetHeadless:J,listApps:ce,deployApp:J,materializeAppSource:J,deployMaterializedApp:J,sendPushNotification:J,shutdownTarget:J,..._e(e)}})}export{be as createWebPlatformRuntime};
@@ -1 +1 @@
1
- function e(e,t,n=e.showTouches){return Object.freeze({status:`completed`,result:Object.freeze({backend:e.backend,outPath:e.outPath,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath},startedAt:e.startedAt,completedAt:Date.now(),scope:e.scope,showTouches:n,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...t})})}export{e as t};
1
+ import{C as e}from"./sdk-contracts.js";import{t}from"./durable-resource.js";function n(e,t){let n=r(e),a,o=!1,s,c,l=()=>o||s!==void 0,u=e=>(o=!0,a??=t.finish(n,e).catch(e=>{throw a=void 0,e}),a),d=()=>s??=a?a.then(async e=>e.status===`completed`?{status:`cleaned`}:await t.forceCleanup(n),async()=>await t.forceCleanup(n)):t.forceCleanup(n);return Object.freeze({inspect:()=>n,appendGestureEvents:e=>{e.length===0||l()||(n=r({...n,gestureEvents:[...n.gestureEvents,...e]}))},setTouchReferenceFrame:e=>{l()||(n=r({...n,...e?{touchReferenceFrame:e}:{}}))},setRunnerSessionId:e=>{l()||e.trim().length===0||(n=r({...n,runnerSessionId:e}))},invalidate:e=>{l()||n.invalidatedReason||(n=r({...n,invalidatedReason:e}))},finish:u,forceCleanup:d,[Symbol.asyncDispose]:async()=>{c??=d().then(i),await c}})}function r(e){return Object.freeze({...e,gestureEvents:Object.freeze([...e.gestureEvents])})}function i(n){if(!t(n))throw new e(`COMMAND_FAILED`,n.message??`Screen recording cleanup could not be confirmed`,{reason:n.reason,retriable:n.reason!==`ownership-fence-lost`,hint:n.reason===`ownership-fence-lost`?`Use the current recording owner or recovery record before retrying cleanup.`:`Keep the recovery record and retry cleanup through the exact runtime owner.`})}function a(e,t,n){let{stopObservation:r,nativePathDisposition:i,showTouches:a=e.showTouches}=n;return Object.freeze({status:`completed`,result:Object.freeze({backend:e.backend,outPath:e.outPath,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath},startedAt:e.startedAt,completedAt:Date.now(),stopObservation:r,...i===void 0?{}:{nativePathDisposition:i},scope:e.scope,showTouches:a,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...t})})}export{n,a as t};
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";import{D as t,T as n,w as r}from"./sdk-device.js";import{O as i,Yt as a,qt as o}from"./sdk-batch.js";import{r as s}from"./diagnostics.js";import{D as c}from"./owner-identity.js";import{i as l}from"./verified-file.js";import"./file.js";import"./diagnostics2.js";import{r as u}from"./session-paths.js";import{i as d,n as f,t as p}from"./durable-resource.js";import{t as ee}from"./screen-recording-runtime.js";import m from"node:path";import h from"node:fs";import te from"node:crypto";function g(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function _(e){return e.replaceAll(`-`,`_`)}async function v(e,t,n){let r={kind:`pending`};try{let i=ue(oe(e,t),`active`);e.store.write(n,i),r={kind:`persisted`},t.throwIfCanceled();let a=t.pendingHandle.transfer();r={kind:`transferred`,handle:a},t.sessionStore.set(t.sessionName,e.sessionSlot.replace(t.session,{handle:a,envelope:i}))}catch(i){throw await ne(e,t,n,r,i),i}}async function ne(e,t,n,r,i){let a=r.kind!==`pending`||ae(e,t,n),o=re(e,t,n,await ie(t,r));t.reportUndurableCleanup(t.device,!a&&o.cleanupError===void 0||o.confirmed?{confirmed:!0}:{confirmed:!1,reason:o.cleanupError instanceof Error?o.cleanupError.message:`The durable cleanup transition could not be confirmed`}),o.cleanupError!==void 0&&le(e,t,i,o.cleanupError)}function re(e,t,n,r){try{return{confirmed:ce(e,n,t.fence,r),cleanupError:r}}catch(n){return s({level:`error`,phase:`${_(e.resourceKind)}_pending_adoption_transition_failed`,data:{session:t.sessionName,transitionError:n instanceof Error?n.message:String(n)}}),{confirmed:!1,cleanupError:r??n}}}async function ie(e,t){try{t.kind===`transferred`?await t.handle[Symbol.asyncDispose]():await e.pendingHandle[Symbol.asyncDispose]();return}catch(e){return e}}function ae(e,t,n){try{return e.store.write(n,y(e,t,t.envelope.descriptor)),!0}catch(r){try{return e.store.write(n,y(e,t,{version:0,body:{reason:`runtime-contract-invalid`}})),!0}catch(n){return s({level:`error`,phase:`${_(e.resourceKind)}_runtime_contract_tombstone_failed`,data:{session:t.sessionName,descriptorError:r instanceof Error?r.message:String(r),persistenceError:n instanceof Error?n.message:String(n)}}),!1}}}function y(e,t,n){return f({resourceKind:e.resourceKind,sessionId:t.sessionName,device:r(t.device),owner:t.owner,fence:t.fence,lifecycle:`open`,descriptor:n,metadata:{phase:`runtime-contract-invalid`,runtimeContractInvalid:!0}})}function oe(t,n){let r=d(n.envelope);if(r.status===`decoded`&&se(r.envelope,n,t.resourceKind))return r.envelope;throw new e(`COMMAND_FAILED`,`${g(t.displayName)} runtime returned an incoherent durable envelope`,{reason:`runtime-contract-invalid`,hint:`Retain the runtime diagnostics and report the selected device and owner.`})}function se(e,n,i){return e.resourceKind===i&&e.sessionId===n.sessionName&&t(e.device,r(n.device))&&a(e.owner)===a(n.owner)&&e.fence.token===n.fence.token&&e.fence.generation===n.fence.generation&&e.lifecycle===`open`}function ce(e,t,n,r){let i=e.store.read(t);return i.status!==`decoded`||i.envelope.fence.token!==n.token||i.envelope.fence.generation!==n.generation?!1:(e.store.write(t,{...i.envelope,lifecycle:r===void 0?`completed`:`open`,metadata:{...i.envelope.metadata??{},phase:r===void 0?`completed`:`cleanup-pending`,cleanupStatus:r===void 0?`cleaned`:`cleanup-pending`}}),!0)}function le(e,t,n,r){s({level:`error`,phase:`${_(e.resourceKind)}_pending_adoption_cleanup_failed`,data:{session:t.sessionName,primaryError:n instanceof Error?n.message:String(n),cleanupError:r instanceof Error?r.message:String(r)}})}function ue(e,t){return Object.freeze({...e,lifecycle:`open`,metadata:{...e.metadata??{},phase:t}})}async function b(e){e.scope.signal.throwIfAborted();let t=new AbortController,n={...e.scope,signal:AbortSignal.any([e.scope.signal,t.signal])},r=()=>{},i=new Promise((e,t)=>{r=t}),a=()=>{},o=new Promise((t,n)=>{let r=()=>{try{e.scope.signal.throwIfAborted()}catch(e){n(e)}};if(e.scope.signal.aborted){r();return}e.scope.signal.addEventListener(`abort`,r,{once:!0}),a=()=>e.scope.signal.removeEventListener(`abort`,r)}),s=setTimeout(()=>{let n=new w(e.displayName,e.deadlineMs);t.abort(n),r(n)},e.deadlineMs);s.unref?.();let c=S(e,n),l,u=c.then(e=>(l??={kind:`acquisition`},e),e=>{throw l??={kind:`acquisition-error`},e}),d=i.catch(e=>{throw l??={kind:`deadline`,error:e},e}),f=o.catch(e=>{throw l??={kind:`cancellation`,error:e},e});try{return await Promise.race([u,d,f])}finally{if(clearTimeout(s),a(),l?.kind===`deadline`||l?.kind===`cancellation`){let t=l.error;c.then(n=>x(e,n,t),()=>{}).catch(()=>{})}else c.catch(()=>{})}}async function x(e,t,n){try{t.reattached.status===`active`&&await C(e,t.reattached.handle,`late_handle_cleanup_failed`,n)}finally{await C(e,t.control,`late_control_cleanup_failed`,n)}}async function S(e,t){let n,r;try{return n=await e.acquireControl(e.envelope,t),t.signal.throwIfAborted(),r=await n.reattach(e.envelope),t.signal.throwIfAborted(),{control:n,reattached:r}}catch(t){try{r?.status===`active`&&await C(e,r.handle,`late_handle_cleanup_failed`,t)}finally{n&&await C(e,n,`late_control_cleanup_failed`,t)}throw t}}async function C(e,t,n,r){try{await t[Symbol.asyncDispose]()}catch(t){e.onLateCleanupFailure(n,t,r)}}var w=class extends Error{deadlineMs;constructor(e,t){super(`${g(e)} recovery exceeded its ${t}ms deadline`),this.name=`DurableCaptureRecoveryDeadlineError`,this.deadlineMs=t}};const T=new Map;async function E(e){return await fe(e.resourcePath,async()=>{let t=e.store.read(e.resourcePath);if(t.status!==`decoded`)throw D(e.store,t.status===`missing`?`${e.store.displayName} resource record is missing`:`${e.store.displayName} resource record is unreattachable: ${t.message}`);if(!de(t.envelope.fence,e.expected))throw D(e.store,`${e.store.displayName} resource ownership fence was lost`);let n=t.envelope;return await e.run({get envelope(){return n},transition(t,r={}){return n=Object.freeze({...n,lifecycle:t,...r.descriptor===void 0?{}:{descriptor:r.descriptor},...r.metadata===void 0?{}:{metadata:r.metadata}}),e.store.write(e.resourcePath,n),n}})})}function de(e,t){return e.token===t.token&&e.generation===t.generation}async function fe(e,t){let n=T.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>i);T.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),T.get(e)===a&&T.delete(e)}}function D(t,n){return new e(`COMMAND_FAILED`,n,{reason:`ownership-fence-lost`,retriable:!1,hint:`Use the current ${t.displayName.toLowerCase()} resource owner or retain the recovery record for manual recovery.`})}async function pe(t,n,r){let i=t.sessionSlot.read(n.session);if(!i)throw new e(`INVALID_ARGS`,t.messages.noActive);try{let e=await O(t,{handle:i.handle,fence:i.envelope.fence,resourcePath:r});return j(t,n),e}catch(e){let i=t.store.read(r);throw i.status===`decoded`&&i.envelope.lifecycle===`completed`&&j(t,n),e}}async function O(e,t){return await E({store:e.store,resourcePath:t.resourcePath,expected:t.fence,run:async n=>{L(n);let r;try{r=await t.handle.finish()}catch(r){throw await k(e,n,t,r),r}if(r.status===`completed`)return I(e,n,r),r.result;I(e,n,r);let i=F(e,r);throw await k(e,n,t,i),i}})}async function k(e,t,n,r){let i;try{i=await n.handle.forceCleanup()}catch(i){A(e,n,r,i,me(t,i));return}try{N(t,i)}catch(t){A(e,n,r,i.status===`cleanup-pending`?i.message??i.reason:`cleanup returned ${i.status}`,t);return}p(i)||A(e,n,r,i.message)}function me(e,t){try{N(e,{status:`cleanup-pending`,reason:`cleanup-unconfirmed`,message:M(t)});return}catch(e){return e}}function A(e,t,n,r,i){s({level:`error`,phase:`${e.resourceKind.replaceAll(`-`,`_`)}_finish_cleanup_failed`,data:{resourcePath:t.resourcePath,finishError:M(n),cleanupError:r===void 0?`cleanup could not be confirmed`:M(r),...i===void 0?{}:{transitionError:M(i)}}})}function j(e,t){t.sessionStore.set(t.sessionName,e.sessionSlot.replace(t.session,void 0))}function M(e){return e instanceof Error?e.message:String(e)}async function he(e,t){let n=e.sessionSlot.read(t.session);n&&(P(e,await E({store:e.store,resourcePath:t.resourcePath,expected:n.envelope.fence,run:async e=>{L(e);let t=await n.handle.forceCleanup();return N(e,t),t}})),t.sessionStore&&t.sessionName&&t.sessionStore.set(t.sessionName,e.sessionSlot.replace(t.session,void 0)))}function N(e,t){e.transition(p(t)?`completed`:`open`,{metadata:{...e.envelope.metadata??{},phase:p(t)?`completed`:`cleanup-pending`,cleanupStatus:t.status,...t.status===`cleanup-pending`?{cleanupPendingReason:t.reason,...t.message?{cleanupPendingMessage:t.message}:{}}:{}}})}function P(e,t){if(!p(t))throw F(e,t)}function F(t,n){return new e(`COMMAND_FAILED`,n.message??`${g(t.displayName)} cleanup could not be confirmed`,{reason:n.reason,retriable:n.reason!==`ownership-fence-lost`,hint:t.messages.cleanupPendingHint})}function I(e,t,n){if(n.status===`completed`){t.transition(`completed`,{metadata:{...t.envelope.metadata??{},...e.completionMetadata(n.result),phase:`completed`}});return}N(t,n)}function L(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}async function R(e){let t=e.definition.store.list(e.sessionsDir),n=[];for(let r of t)n.push(await z(e,r));return{scanned:t.length,recovered:n.filter(e=>e===`recovered`).length,retained:n.filter(e=>e===`retained`).length}}async function z(e,t){let n=ge(e,t);if(n.status!==`recoverable`)return n.status;try{return await _e(e,t,n.envelope,e.perRecordDeadlineMs??5e3)?`recovered`:`retained`}catch(n){return H(e,n instanceof w?`timed_out`:`failed`,t,{error:n instanceof Error?n.message:String(n),...n instanceof w?{deadlineMs:n.deadlineMs}:{}}),`retained`}}function ge(e,t){let n=e.definition.store.read(t);if(n.status===`unreattachable`)return H(e,`record_unreattachable`,t,{reason:n.reason,message:n.message,version:n.version}),{status:`retained`};if(n.status===`missing`||n.envelope.lifecycle===`completed`)return{status:`ignored`};let r=e.definition.store.resolvePath(e.resolveSessionDir(n.envelope.sessionId));return m.resolve(t)===m.resolve(r)?{status:`recoverable`,envelope:n.envelope}:(H(e,`session_path_mismatch`,t,{envelopeSessionId:n.envelope.sessionId,canonicalPath:r}),{status:`retained`})}async function _e(e,t,n,r){return await ve(e,t,n,await b({displayName:e.definition.displayName,envelope:n,scope:e.scope,deadlineMs:r,acquireControl:e.acquireControl,onLateCleanupFailure:(n,r,i)=>H(e,n,t,{error:r instanceof Error?r.message:String(r),primaryError:i instanceof Error?i.message:String(i)})}))}async function ve(e,t,n,r){try{switch(r.reattached.status){case`active`:{let i=r.reattached.handle,a=await E({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{ye(e);let t=await i.forceCleanup();return N(e,t),t}});return p(a)}case`completed`:return await B(e,t,n,{...e.definition.completionMetadata(r.reattached.result)}),!0;case`missing`:return await B(e,t,n,{recoveryStatus:`already-missing`}),!0;case`unreattachable`:{if(!V(r.reattached.reason))return H(e,`retained`,t,{reason:r.reattached.reason,message:r.reattached.message}),!1;let i=await r.control.cleanup(n);return await E({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>N(e,i)}),p(i)}}}finally{await r.control[Symbol.asyncDispose]()}}async function B(e,t,n,r){await E({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{e.transition(`completed`,{metadata:{...e.envelope.metadata??{},phase:`completed`,...r}})}})}function ye(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}function V(e){switch(e){case`descriptor-invalid`:case`descriptor-version-unsupported`:case`ownership-fence-lost`:return!1;case`owner-unavailable`:case`transport-not-reattachable`:return!0}}function H(e,t,n,r){let i={phase:`${_(e.definition.resourceKind)}_recovery_${t}`,resourcePath:n,data:r};e.onDiagnostic?e.onDiagnostic(i):s({level:`warn`,phase:i.phase,data:{resourcePath:n,...r}})}async function be(t,n){let r=t.store.read(n.resourcePath);if(r.status!==`decoded`||r.envelope.lifecycle!==`open`)throw xe(t,r.status);let i=r.envelope,a=await b({displayName:t.displayName,envelope:i,scope:n.scope,deadlineMs:n.deadlineMs??5e3,acquireControl:n.acquireControl,onLateCleanupFailure:(e,r,i)=>n.scope.diagnostics.emit({level:`error`,phase:`${_(t.resourceKind)}_recovery_${e}`,data:{resourcePath:n.resourcePath,error:U(r),primaryError:U(i)}})});try{switch(a.reattached.status){case`active`:return await O(t,{handle:a.reattached.handle,fence:i.fence,resourcePath:n.resourcePath});case`completed`:{let e=a.reattached.result;return await E({store:t.store,resourcePath:n.resourcePath,expected:i.fence,run:async n=>{I(t,n,{status:`completed`,result:e,alreadyCompleted:!0})}}),e}case`missing`:throw new e(`COMMAND_FAILED`,`${g(t.displayName)} is missing`,{reason:`resource-missing`,hint:t.messages.cleanupPendingHint});case`unreattachable`:if(V(a.reattached.reason)){let e=await a.control.cleanup(i);await E({store:t.store,resourcePath:n.resourcePath,expected:i.fence,run:async t=>N(t,e)}),P(t,e)}throw new e(`COMMAND_FAILED`,a.reattached.message??`${g(t.displayName)} cannot be reattached`,{reason:a.reattached.reason,hint:t.messages.cleanupPendingHint})}}finally{await a.control[Symbol.asyncDispose]()}}function xe(t,n){return new e(`INVALID_ARGS`,n===`missing`?t.messages.noActive:`${g(t.displayName)} recovery record is not open`)}function U(e){return e instanceof Error?e.message:String(e)}function W(e){Ce(e.fileName);let t=t=>m.join(t,e.fileName);return Object.freeze({resourceKind:e.resourceKind,displayName:e.displayName,resolvePath:t,read(t){let n,r;try{if(n=l(t),n===void 0)return{status:`missing`};r=JSON.parse(h.readFileSync(n,`utf8`))}catch(t){return K(t)?{status:`missing`}:G(Te(t,e.displayName))}finally{n!==void 0&&h.closeSync(n)}return Se(d(r),e.resourceKind)},write(e,t){let n=m.dirname(e);h.mkdirSync(n,{recursive:!0}),c({destination:e,contents:`${JSON.stringify(t)}\n`})},list(e){let n;try{n=h.readdirSync(e,{withFileTypes:!0})}catch{return[]}return n.filter(e=>e.isDirectory()).map(n=>t(m.join(e,n.name))).filter(we).sort()}})}function Se(e,t){return e.status===`decoded`?e.envelope.resourceKind===t?{status:`decoded`,envelope:e.envelope}:G(`Expected ${t} resource record, received ${e.envelope.resourceKind}`):e}function Ce(e){if(e.length===0||m.basename(e)!==e)throw TypeError(`Durable capture resource fileName must be one file name`)}function we(e){try{return h.lstatSync(e),!0}catch(e){return!K(e)}}function G(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function K(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function Te(e,t){return e instanceof Error?e.message:`${t} resource record is invalid`}function Ee(e,t){t.admissionLedger.assertStartAllowed(t.device),De(e,t.resourcePath,t.device);let n=e.store.read(t.resourcePath);return Object.freeze({token:te.randomUUID(),generation:n.status===`decoded`?n.envelope.fence.generation+1:1})}function De(t,i,a){let o=n(r(a));for(let r of t.store.list(m.dirname(m.dirname(i)))){let a=t.store.read(r);if(a.status===`unreattachable`)throw new e(`COMMAND_FAILED`,`${g(q(t.displayName))} ${t.displayName} recovery record is unreattachable: ${a.message}`,{reason:a.reason,retriable:!1,hint:`Retain the corrupt or future-version ${t.displayName} manifest for manual recovery; no replacement capture is safe.`});if(a.status===`decoded`&&a.envelope.lifecycle!==`completed`&&(r===i||n(a.envelope.device)===o))throw new e(`COMMAND_FAILED`,`${g(q(t.displayName))} ${t.displayName} resource for this device has not reached a confirmed terminal state`,{reason:`cleanup-unconfirmed`,hint:`Retry exact-owner cleanup using the existing ${t.displayName} manifest before starting a replacement.`})}}function q(e){return/^[aeiou]/i.test(e)?`an`:`a`}function J(e){let t=(t,n)=>e.store.resolvePath(t.resolveSessionDir(n)),n=t=>({definition:e,resolveSessionDir:e=>m.join(t.sessionsDir,u(e)),...t});return Object.freeze({store:e.store,resourcePath:t,createNextFence(t){return Ee(e,t)},adoptStarted(n){return v(e,{...n,reportUndurableCleanup:(e,t)=>{t.confirmed?n.admissionLedger.clearUndurableCleanup(e):n.admissionLedger.blockUndurableCleanup(e,t.reason)}},t(n.sessionStore,n.sessionName))},finishLive(n){return pe(e,n,t(n.sessionStore,n.sessionName))},finishRecovered(t){return be(e,t)},forceCleanupLive(t){return he(e,t)},recoverAll(e){return R(n(e))},recoverOne(e,t){return z(n(e),t)}})}const Y=J({resourceKind:`screen-recording`,displayName:`screen recording`,store:W({resourceKind:ee,fileName:`screen-recording.resource.json`,displayName:`screen recording`}),sessionSlot:{read:e=>e.screenRecording,replace:(e,t)=>({...e,screenRecording:t})},completionMetadata:Ae,messages:{noActive:`no active recording`,cleanupPendingHint:`Keep screen-recording.resource.json and retry stop through its exact runtime owner.`}});function Oe(e){return Y.adoptStarted(e)}function ke(e){return Y.finishLive(e)}const X=`completion`;function Ae(e){return{[X]:{backend:e.backend,outPath:e.outPath,startedAt:e.startedAt,completedAt:e.completedAt,...e.capturedDurationMs===void 0?{}:{capturedDurationMs:e.capturedDurationMs},scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath},...e.telemetryPath===void 0?{}:{telemetryPath:e.telemetryPath},...e.warning===void 0?{}:{warning:e.warning},...e.overlayWarning===void 0?{}:{overlayWarning:e.overlayWarning},...e.activeSessionApp===void 0?{}:{activeSessionApp:je(e.activeSessionApp)},...e.chunks===void 0?{}:{chunks:e.chunks.map(Me)}}}}function je(e){return{bundleId:e.bundleId,...e.name===void 0?{}:{name:e.name}}}function Me(e){return{index:e.index,path:e.path,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath}}}function Z(e){return Y.finishRecovered(e)}async function Q(e){let t;try{return t=await e.gateway.bind({device:Ne(e.envelope),intent:{kind:`exact-owner`,owner:e.envelope.owner,fence:e.envelope.fence},scope:e.scope}),e.scope.signal.throwIfAborted(),e.create(t)}catch(e){throw t&&await t[Symbol.asyncDispose](),e}}function Ne(e){return{platform:e.device.family,id:e.device.id,name:e.device.id,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.appleOs===void 0?{}:{appleOs:e.device.appleOs},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}}}function Pe(e){return Y.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await Fe(e.gateway,t,n)},e.resourcePath)}async function Fe(e,t,n){return await Q({gateway:e,envelope:t,scope:n,create:e=>$({runtime:o(e,i),dispose:async()=>await e[Symbol.asyncDispose]()})})}function $(e){return Object.freeze({reattach:async t=>await e.runtime.operations.screenRecordingReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.screenRecordingCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}export{Oe as a,Y as c,X as i,J as l,Pe as n,ke as o,Q as r,Z as s,$ as t,W as u};
1
+ import{C as e}from"./sdk-contracts.js";import{D as t,T as n,w as r}from"./sdk-device.js";import{O as i,Yt as a,qt as o}from"./sdk-batch.js";import{r as s}from"./diagnostics.js";import{E as c}from"./owner-identity.js";import{i as l}from"./verified-file.js";import"./file.js";import"./diagnostics2.js";import{r as u}from"./session-paths.js";import{i as d,n as f,t as p}from"./durable-resource.js";import{n as m}from"./screen-recording-runtime.js";import h from"node:path";import g from"node:fs";import ee from"node:crypto";function _(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function v(e){return e.replaceAll(`-`,`_`)}async function te(e,t,n){let r={kind:`pending`};try{let i=ce(ie(e,t),`active`);e.store.write(n,i),r={kind:`persisted`},t.throwIfCanceled();let a=t.pendingHandle.transfer();r={kind:`transferred`,handle:a},t.sessionStore.set(t.sessionName,e.sessionSlot.replace(t.session,{handle:a,envelope:i}))}catch(i){throw await ne(e,t,n,r,i),i}}async function ne(e,t,n,r,i){let a=r.kind!==`pending`||b(e,t,n),o=re(e,t,n,await y(t,r));t.reportUndurableCleanup(t.device,!a&&o.cleanupError===void 0||o.confirmed?{confirmed:!0}:{confirmed:!1,reason:o.cleanupError instanceof Error?o.cleanupError.message:`The durable cleanup transition could not be confirmed`}),o.cleanupError!==void 0&&se(e,t,i,o.cleanupError)}function re(e,t,n,r){try{return{confirmed:oe(e,n,t.fence,r),cleanupError:r}}catch(n){return s({level:`error`,phase:`${v(e.resourceKind)}_pending_adoption_transition_failed`,data:{session:t.sessionName,transitionError:n instanceof Error?n.message:String(n)}}),{confirmed:!1,cleanupError:r??n}}}async function y(e,t){try{t.kind===`transferred`?await t.handle[Symbol.asyncDispose]():await e.pendingHandle[Symbol.asyncDispose]();return}catch(e){return e}}function b(e,t,n){try{return e.store.write(n,x(e,t,t.envelope.descriptor)),!0}catch(r){try{return e.store.write(n,x(e,t,{version:0,body:{reason:`runtime-contract-invalid`}})),!0}catch(n){return s({level:`error`,phase:`${v(e.resourceKind)}_runtime_contract_tombstone_failed`,data:{session:t.sessionName,descriptorError:r instanceof Error?r.message:String(r),persistenceError:n instanceof Error?n.message:String(n)}}),!1}}}function x(e,t,n){return f({resourceKind:e.resourceKind,sessionId:t.sessionName,device:r(t.device),owner:t.owner,fence:t.fence,lifecycle:`open`,descriptor:n,metadata:{phase:`runtime-contract-invalid`,runtimeContractInvalid:!0}})}function ie(t,n){let r=d(n.envelope);if(r.status===`decoded`&&ae(r.envelope,n,t.resourceKind))return r.envelope;throw new e(`COMMAND_FAILED`,`${_(t.displayName)} runtime returned an incoherent durable envelope`,{reason:`runtime-contract-invalid`,hint:`Retain the runtime diagnostics and report the selected device and owner.`})}function ae(e,n,i){return e.resourceKind===i&&e.sessionId===n.sessionName&&t(e.device,r(n.device))&&a(e.owner)===a(n.owner)&&e.fence.token===n.fence.token&&e.fence.generation===n.fence.generation&&e.lifecycle===`open`}function oe(e,t,n,r){let i=e.store.read(t);return i.status!==`decoded`||i.envelope.fence.token!==n.token||i.envelope.fence.generation!==n.generation?!1:(e.store.write(t,{...i.envelope,lifecycle:r===void 0?`completed`:`open`,metadata:{...i.envelope.metadata??{},phase:r===void 0?`completed`:`cleanup-pending`,cleanupStatus:r===void 0?`cleaned`:`cleanup-pending`}}),!0)}function se(e,t,n,r){s({level:`error`,phase:`${v(e.resourceKind)}_pending_adoption_cleanup_failed`,data:{session:t.sessionName,primaryError:n instanceof Error?n.message:String(n),cleanupError:r instanceof Error?r.message:String(r)}})}function ce(e,t){return Object.freeze({...e,lifecycle:`open`,metadata:{...e.metadata??{},phase:t}})}async function S(e){e.scope.signal.throwIfAborted();let t=new AbortController,n={...e.scope,signal:AbortSignal.any([e.scope.signal,t.signal])},r=()=>{},i=new Promise((e,t)=>{r=t}),a=()=>{},o=new Promise((t,n)=>{let r=()=>{try{e.scope.signal.throwIfAborted()}catch(e){n(e)}};if(e.scope.signal.aborted){r();return}e.scope.signal.addEventListener(`abort`,r,{once:!0}),a=()=>e.scope.signal.removeEventListener(`abort`,r)}),s=setTimeout(()=>{let n=new w(e.displayName,e.deadlineMs);t.abort(n),r(n)},e.deadlineMs);s.unref?.();let c=ue(e,n),l,u=c.then(e=>(l??={kind:`acquisition`},e),e=>{throw l??={kind:`acquisition-error`},e}),d=i.catch(e=>{throw l??={kind:`deadline`,error:e},e}),f=o.catch(e=>{throw l??={kind:`cancellation`,error:e},e});try{return await Promise.race([u,d,f])}finally{if(clearTimeout(s),a(),l?.kind===`deadline`||l?.kind===`cancellation`){let t=l.error;c.then(n=>le(e,n,t),()=>{}).catch(()=>{})}else c.catch(()=>{})}}async function le(e,t,n){try{t.reattached.status===`active`&&await C(e,t.reattached.handle,`late_handle_cleanup_failed`,n)}finally{await C(e,t.control,`late_control_cleanup_failed`,n)}}async function ue(e,t){let n,r;try{return n=await e.acquireControl(e.envelope,t),t.signal.throwIfAborted(),r=await n.reattach(e.envelope),t.signal.throwIfAborted(),{control:n,reattached:r}}catch(t){try{r?.status===`active`&&await C(e,r.handle,`late_handle_cleanup_failed`,t)}finally{n&&await C(e,n,`late_control_cleanup_failed`,t)}throw t}}async function C(e,t,n,r){try{await t[Symbol.asyncDispose]()}catch(t){e.onLateCleanupFailure(n,t,r)}}var w=class extends Error{deadlineMs;constructor(e,t){super(`${_(e)} recovery exceeded its ${t}ms deadline`),this.name=`DurableCaptureRecoveryDeadlineError`,this.deadlineMs=t}};const T=new Map;async function E(e){return await fe(e.resourcePath,async()=>{let t=e.store.read(e.resourcePath);if(t.status!==`decoded`)throw D(e.store,t.status===`missing`?`${e.store.displayName} resource record is missing`:`${e.store.displayName} resource record is unreattachable: ${t.message}`);if(!de(t.envelope.fence,e.expected))throw D(e.store,`${e.store.displayName} resource ownership fence was lost`);let n=t.envelope;return await e.run({get envelope(){return n},transition(t,r={}){return n=Object.freeze({...n,lifecycle:t,...r.descriptor===void 0?{}:{descriptor:r.descriptor},...r.metadata===void 0?{}:{metadata:r.metadata}}),e.store.write(e.resourcePath,n),n}})})}function de(e,t){return e.token===t.token&&e.generation===t.generation}async function fe(e,t){let n=T.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>i);T.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),T.get(e)===a&&T.delete(e)}}function D(t,n){return new e(`COMMAND_FAILED`,n,{reason:`ownership-fence-lost`,retriable:!1,hint:`Use the current ${t.displayName.toLowerCase()} resource owner or retain the recovery record for manual recovery.`})}async function pe(t,n,r){let i=t.sessionSlot.read(n.session);if(!i)throw new e(`INVALID_ARGS`,t.messages.noActive);try{let e=await O(t,{handle:i.handle,fence:i.envelope.fence,resourcePath:r,intent:n.intent});return j(t,n),e}catch(e){let i=t.store.read(r);throw i.status===`decoded`&&i.envelope.lifecycle===`completed`&&j(t,n),e}}async function O(e,t){return await E({store:e.store,resourcePath:t.resourcePath,expected:t.fence,run:async n=>{R(n);let r=L(n),i;try{i=await t.handle.finish(r)}catch(r){throw await k(e,n,t,r,t.intent),r}if(i.status===`completed`)return I(e,n,i),i.result;I(e,n,i);let a=F(e,i);throw await k(e,n,t,a,t.intent),a}})}async function k(e,t,n,r,i){if(i===`capture`&&e.failedFinishPolicy===`preserve-retry-material`){he(e,n,r);return}let a;try{a=await n.handle.forceCleanup()}catch(i){A(e,n,r,i,me(t,i));return}try{N(t,a)}catch(t){A(e,n,r,a.status===`cleanup-pending`?a.message??a.reason:`cleanup returned ${a.status}`,t);return}p(a)||A(e,n,r,a.message)}function me(e,t){try{N(e,{status:`cleanup-pending`,reason:`cleanup-unconfirmed`,message:M(t)});return}catch(e){return e}}function he(e,t,n){s({level:`error`,phase:`${v(e.resourceKind)}_finish_evidence_preserved`,data:{resourcePath:t.resourcePath,finishError:M(n),failedFinishPolicy:e.failedFinishPolicy}})}function A(e,t,n,r,i){s({level:`error`,phase:`${v(e.resourceKind)}_finish_cleanup_failed`,data:{resourcePath:t.resourcePath,finishError:M(n),cleanupError:r===void 0?`cleanup could not be confirmed`:M(r),...i===void 0?{}:{transitionError:M(i)}}})}function j(e,t){t.sessionStore.set(t.sessionName,e.sessionSlot.replace(t.session,void 0))}function M(e){return e instanceof Error?e.message:String(e)}async function ge(e,t){let n=e.sessionSlot.read(t.session);n&&(P(e,await E({store:e.store,resourcePath:t.resourcePath,expected:n.envelope.fence,run:async e=>{R(e);let t=await n.handle.forceCleanup();return N(e,t),t}})),t.sessionStore&&t.sessionName&&t.sessionStore.set(t.sessionName,e.sessionSlot.replace(t.session,void 0)))}function N(e,t){e.transition(p(t)?`completed`:`open`,{metadata:{...e.envelope.metadata??{},phase:p(t)?`completed`:`cleanup-pending`,cleanupStatus:t.status,...t.status===`cleanup-pending`?{cleanupPendingReason:t.reason,...t.message?{cleanupPendingMessage:t.message}:{}}:{}}})}function P(e,t){if(!p(t))throw F(e,t)}function F(t,n){return new e(`COMMAND_FAILED`,n.message??`${_(t.displayName)} cleanup could not be confirmed`,{reason:n.reason,retriable:n.reason!==`ownership-fence-lost`,hint:t.messages.cleanupPendingHint})}function I(e,t,n){if(n.status===`completed`){t.transition(`completed`,{metadata:{...t.envelope.metadata??{},...e.completionMetadata(n.result),phase:`completed`}});return}N(t,n)}function L(e){return Object.freeze({learned:e.envelope.metadata,record:t=>{e.transition(`open`,{metadata:{...e.envelope.metadata??{},...t}})}})}function R(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}async function _e(e){let t=e.definition.store.list(e.sessionsDir),n=[];for(let r of t)n.push(await z(e,r));return{scanned:t.length,recovered:n.filter(e=>e===`recovered`).length,retained:n.filter(e=>e===`retained`).length}}async function z(e,t){let n=ve(e,t);if(n.status!==`recoverable`)return n.status;try{return await ye(e,t,n.envelope,e.perRecordDeadlineMs??5e3)?`recovered`:`retained`}catch(n){return H(e,n instanceof w?`timed_out`:`failed`,t,{error:n instanceof Error?n.message:String(n),...n instanceof w?{deadlineMs:n.deadlineMs}:{}}),`retained`}}function ve(e,t){let n=e.definition.store.read(t);if(n.status===`unreattachable`)return H(e,`record_unreattachable`,t,{reason:n.reason,message:n.message,version:n.version}),{status:`retained`};if(n.status===`missing`||n.envelope.lifecycle===`completed`)return{status:`ignored`};let r=e.definition.store.resolvePath(e.resolveSessionDir(n.envelope.sessionId));return h.resolve(t)===h.resolve(r)?{status:`recoverable`,envelope:n.envelope}:(H(e,`session_path_mismatch`,t,{envelopeSessionId:n.envelope.sessionId,canonicalPath:r}),{status:`retained`})}async function ye(e,t,n,r){return await be(e,t,n,await S({displayName:e.definition.displayName,envelope:n,scope:e.scope,deadlineMs:r,acquireControl:e.acquireControl,onLateCleanupFailure:(n,r,i)=>H(e,n,t,{error:r instanceof Error?r.message:String(r),primaryError:i instanceof Error?i.message:String(i)})}))}async function be(e,t,n,r){try{switch(r.reattached.status){case`active`:{let i=r.reattached.handle,a=await E({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{xe(e);let t=await i.forceCleanup();return N(e,t),t}});return p(a)}case`completed`:return await B(e,t,n,{...e.definition.completionMetadata(r.reattached.result)}),!0;case`missing`:return await B(e,t,n,{recoveryStatus:`already-missing`}),!0;case`unreattachable`:{if(!V(r.reattached.reason))return H(e,`retained`,t,{reason:r.reattached.reason,message:r.reattached.message}),!1;let i=await r.control.cleanup(n);return await E({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>N(e,i)}),p(i)}}}finally{await r.control[Symbol.asyncDispose]()}}async function B(e,t,n,r){await E({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{e.transition(`completed`,{metadata:{...e.envelope.metadata??{},phase:`completed`,...r}})}})}function xe(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}function V(e){switch(e){case`descriptor-invalid`:case`descriptor-version-unsupported`:case`ownership-fence-lost`:return!1;case`owner-unavailable`:case`transport-not-reattachable`:return!0}}function H(e,t,n,r){let i={phase:`${v(e.definition.resourceKind)}_recovery_${t}`,resourcePath:n,data:r};e.onDiagnostic?e.onDiagnostic(i):s({level:`warn`,phase:i.phase,data:{resourcePath:n,...r}})}async function Se(t,n){let r=t.store.read(n.resourcePath);if(r.status!==`decoded`||r.envelope.lifecycle!==`open`)throw Ce(t,r.status);let i=r.envelope,a=await S({displayName:t.displayName,envelope:i,scope:n.scope,deadlineMs:n.deadlineMs??5e3,acquireControl:n.acquireControl,onLateCleanupFailure:(e,r,i)=>n.scope.diagnostics.emit({level:`error`,phase:`${v(t.resourceKind)}_recovery_${e}`,data:{resourcePath:n.resourcePath,error:U(r),primaryError:U(i)}})});try{switch(a.reattached.status){case`active`:return await O(t,{handle:a.reattached.handle,fence:i.fence,resourcePath:n.resourcePath,intent:`capture`});case`completed`:{let e=a.reattached.result;return await E({store:t.store,resourcePath:n.resourcePath,expected:i.fence,run:async n=>{I(t,n,{status:`completed`,result:e,alreadyCompleted:!0})}}),e}case`missing`:throw new e(`COMMAND_FAILED`,`${_(t.displayName)} is missing`,{reason:`resource-missing`,hint:t.messages.cleanupPendingHint});case`unreattachable`:if(V(a.reattached.reason)){let e=await a.control.cleanup(i);await E({store:t.store,resourcePath:n.resourcePath,expected:i.fence,run:async t=>N(t,e)}),P(t,e)}throw new e(`COMMAND_FAILED`,a.reattached.message??`${_(t.displayName)} cannot be reattached`,{reason:a.reattached.reason,hint:t.messages.cleanupPendingHint})}}finally{await a.control[Symbol.asyncDispose]()}}function Ce(t,n){return new e(`INVALID_ARGS`,n===`missing`?t.messages.noActive:`${_(t.displayName)} recovery record is not open`)}function U(e){return e instanceof Error?e.message:String(e)}function W(e){Te(e.fileName);let t=t=>h.join(t,e.fileName);return Object.freeze({resourceKind:e.resourceKind,displayName:e.displayName,resolvePath:t,read(t){let n,r;try{if(n=l(t),n===void 0)return{status:`missing`};r=JSON.parse(g.readFileSync(n,`utf8`))}catch(t){return K(t)?{status:`missing`}:G(De(t,e.displayName))}finally{n!==void 0&&g.closeSync(n)}return we(d(r),e.resourceKind)},write(e,t){let n=h.dirname(e);g.mkdirSync(n,{recursive:!0}),c({destination:e,contents:`${JSON.stringify(t)}\n`})},list(e){let n;try{n=g.readdirSync(e,{withFileTypes:!0})}catch{return[]}return n.filter(e=>e.isDirectory()).map(n=>t(h.join(e,n.name))).filter(Ee).sort()}})}function we(e,t){return e.status===`decoded`?e.envelope.resourceKind===t?{status:`decoded`,envelope:e.envelope}:G(`Expected ${t} resource record, received ${e.envelope.resourceKind}`):e}function Te(e){if(e.length===0||h.basename(e)!==e)throw TypeError(`Durable capture resource fileName must be one file name`)}function Ee(e){try{return g.lstatSync(e),!0}catch(e){return!K(e)}}function G(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function K(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function De(e,t){return e instanceof Error?e.message:`${t} resource record is invalid`}function Oe(e,t){t.admissionLedger.assertStartAllowed(t.device),ke(e,t.resourcePath,t.device);let n=e.store.read(t.resourcePath);return Object.freeze({token:ee.randomUUID(),generation:n.status===`decoded`?n.envelope.fence.generation+1:1})}function ke(t,i,a){let o=n(r(a));for(let r of t.store.list(h.dirname(h.dirname(i)))){let a=t.store.read(r);if(a.status===`unreattachable`)throw new e(`COMMAND_FAILED`,`${_(q(t.displayName))} ${t.displayName} recovery record is unreattachable: ${a.message}`,{reason:a.reason,retriable:!1,hint:`Retain the corrupt or future-version ${t.displayName} manifest for manual recovery; no replacement capture is safe.`});if(a.status===`decoded`&&a.envelope.lifecycle!==`completed`&&(r===i||n(a.envelope.device)===o))throw new e(`COMMAND_FAILED`,`${_(q(t.displayName))} ${t.displayName} resource for this device has not reached a confirmed terminal state`,{reason:`cleanup-unconfirmed`,hint:`Retry exact-owner cleanup using the existing ${t.displayName} manifest before starting a replacement.`})}}function q(e){return/^[aeiou]/i.test(e)?`an`:`a`}function J(e){let t=(t,n)=>e.store.resolvePath(t.resolveSessionDir(n)),n=t=>({definition:e,resolveSessionDir:e=>h.join(t.sessionsDir,u(e)),...t});return Object.freeze({store:e.store,resourcePath:t,createNextFence(t){return Oe(e,t)},adoptStarted(n){return te(e,{...n,reportUndurableCleanup:(e,t)=>{t.confirmed?n.admissionLedger.clearUndurableCleanup(e):n.admissionLedger.blockUndurableCleanup(e,t.reason)}},t(n.sessionStore,n.sessionName))},finishLive(n){return pe(e,n,t(n.sessionStore,n.sessionName))},finishRecovered(t){return Se(e,t)},forceCleanupLive(t){return ge(e,t)},recoverAll(e){return _e(n(e))},recoverOne(e,t){return z(n(e),t)}})}const Y=J({resourceKind:`screen-recording`,displayName:`screen recording`,store:W({resourceKind:m,fileName:`screen-recording.resource.json`,displayName:`screen recording`}),sessionSlot:{read:e=>e.screenRecording,replace:(e,t)=>({...e,screenRecording:t})},completionMetadata:Me,failedFinishPolicy:`preserve-retry-material`,messages:{noActive:`no active recording`,cleanupPendingHint:`Keep screen-recording.resource.json and retry stop through its exact runtime owner.`}});function Ae(e){return Y.adoptStarted(e)}function je(e){return Y.finishLive(e)}const X=`completion`;function Me(e){return{[X]:{backend:e.backend,outPath:e.outPath,startedAt:e.startedAt,completedAt:e.completedAt,...e.capturedDurationMs===void 0?{}:{capturedDurationMs:e.capturedDurationMs},...e.stopObservation===void 0?{}:{stopObservation:Pe(e.stopObservation)},...e.nativePathDisposition===void 0?{}:{nativePathDisposition:e.nativePathDisposition},scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath},...e.telemetryPath===void 0?{}:{telemetryPath:e.telemetryPath},...e.warning===void 0?{}:{warning:e.warning},...e.overlayWarning===void 0?{}:{overlayWarning:e.overlayWarning},...e.activeSessionApp===void 0?{}:{activeSessionApp:Ne(e.activeSessionApp)},...e.chunks===void 0?{}:{chunks:e.chunks.map(Fe)}}}}function Ne(e){return{bundleId:e.bundleId,...e.name===void 0?{}:{name:e.name}}}function Pe(e){return e.recorder===`confirmed`?{recorder:e.recorder}:{recorder:e.recorder,why:e.why}}function Fe(e){return{index:e.index,path:e.path,...e.clientOutPath===void 0?{}:{clientOutPath:e.clientOutPath}}}function Z(e){return Y.finishRecovered(e)}async function Q(e){let t;try{return t=await e.gateway.bind({device:Ie(e.envelope),intent:{kind:`exact-owner`,owner:e.envelope.owner,fence:e.envelope.fence},scope:e.scope}),e.scope.signal.throwIfAborted(),e.create(t)}catch(e){throw t&&await t[Symbol.asyncDispose](),e}}function Ie(e){return{platform:e.device.family,id:e.device.id,name:e.device.id,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.appleOs===void 0?{}:{appleOs:e.device.appleOs},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}}}function Le(e){return Y.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await Re(e.gateway,t,n)},e.resourcePath)}async function Re(e,t,n){return await Q({gateway:e,envelope:t,scope:n,create:e=>$({runtime:o(e,i),dispose:async()=>await e[Symbol.asyncDispose]()})})}function $(e){return Object.freeze({reattach:async t=>await e.runtime.operations.screenRecordingReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.screenRecordingCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}export{Ae as a,Y as c,X as i,J as l,Le as n,je as o,Q as r,Z as s,$ as t,W as u};
@@ -1 +1 @@
1
- const e=`screen-recording`;export{e as t};
1
+ const e=`screen-recording`,t=`recording-output-unplayable`;export{e as n,t};
@@ -1 +1 @@
1
- import{T as e,_ as t,g as n,v as r}from"./sdk-batch-runner.js";function i(e){return{...typeof e.path==`string`?{path:e.path}:{},...typeof e.width==`number`?{width:e.width}:{},...typeof e.height==`number`?{height:e.height}:{},...typeof e.logicalWidth==`number`?{logicalWidth:e.logicalWidth}:{},...typeof e.logicalHeight==`number`?{logicalHeight:e.logicalHeight}:{},...typeof e.pixelDensity==`number`?{pixelDensity:e.pixelDensity}:{},...e.overlayRefs?{overlayRefs:e.overlayRefs}:{},...e.warnings&&e.warnings.length>0?{warnings:e.warnings}:{}}}function a(t,n){let r=o(t);return{path:e(t,`path`),width:r?.width,height:r?.height,logicalWidth:r?.logicalWidth,logicalHeight:r?.logicalHeight,pixelDensity:r?.pixelDensity,overlayRefs:r?.overlayRefs,...r?.warnings?{warnings:r.warnings}:{},identifiers:{session:n}}}function o(e){if(!n(e))return;let t=u(e.warnings);return i({path:c(e,`path`),width:s(e,`width`),height:s(e,`height`),logicalWidth:s(e,`logicalWidth`),logicalHeight:s(e,`logicalHeight`),pixelDensity:s(e,`pixelDensity`),overlayRefs:l(e.overlayRefs),...t===void 0?{}:{warnings:t}})}function s(e,t){let n=e[t];return typeof n==`number`?n:void 0}function c(e,t){let n=e[t];return typeof n==`string`?n:void 0}function l(e){if(Array.isArray(e))return e.filter(m).flatMap(e=>{let t=d(e);return t?[t]:[]})}function u(e){if(Array.isArray(e))return e.filter(e=>typeof e==`string`&&e.length>0)}function d(e){if(typeof e.ref!=`string`||e.ref.length===0)return;let t=f(e);if(t)return{ref:e.ref,...p(e),...t}}function f(e){let n=r(e.rect);if(!n)return;let i=r(e.overlayRect);if(!i)return;let a=t(e.center);return a?{rect:n,overlayRect:i,center:a}:void 0}function p(e){return typeof e.label==`string`&&e.label.length>0?{label:e.label}:{}}function m(e){return n(e)}export{i as n,a as t};
1
+ import{T as e,_ as t,g as n,v as r}from"./sdk-batch-runner.js";import{n as i}from"./success-text.js";function a(e){return{...typeof e.path==`string`?{path:e.path}:{},...typeof e.width==`number`?{width:e.width}:{},...typeof e.height==`number`?{height:e.height}:{},...typeof e.logicalWidth==`number`?{logicalWidth:e.logicalWidth}:{},...typeof e.logicalHeight==`number`?{logicalHeight:e.logicalHeight}:{},...typeof e.pixelDensity==`number`?{pixelDensity:e.pixelDensity}:{},...e.overlayRefs?{overlayRefs:e.overlayRefs}:{},...e.warnings&&e.warnings.length>0?{warnings:e.warnings}:{}}}function o(t,n){let r=s(t);return{path:e(t,`path`),width:r?.width,height:r?.height,logicalWidth:r?.logicalWidth,logicalHeight:r?.logicalHeight,pixelDensity:r?.pixelDensity,overlayRefs:r?.overlayRefs,...r?.warnings?{warnings:r.warnings}:{},identifiers:{session:n}}}function s(e){if(!n(e))return;let t=d(e);return a({path:l(e,`path`),width:c(e,`width`),height:c(e,`height`),logicalWidth:c(e,`logicalWidth`),logicalHeight:c(e,`logicalHeight`),pixelDensity:c(e,`pixelDensity`),overlayRefs:u(e.overlayRefs),...t===void 0?{}:{warnings:t}})}function c(e,t){let n=e[t];return typeof n==`number`?n:void 0}function l(e,t){let n=e[t];return typeof n==`string`?n:void 0}function u(e){if(Array.isArray(e))return e.filter(h).flatMap(e=>{let t=f(e);return t?[t]:[]})}function d(e){if(Array.isArray(e.warnings))return i(e).filter(e=>e.length>0)}function f(e){if(typeof e.ref!=`string`||e.ref.length===0)return;let t=p(e);if(t)return{ref:e.ref,...m(e),...t}}function p(e){let n=r(e.rect);if(!n)return;let i=r(e.overlayRect);if(!i)return;let a=t(e.center);return a?{rect:n,overlayRect:i,center:a}:void 0}function m(e){return typeof e.label==`string`&&e.label.length>0?{label:e.label}:{}}function h(e){return n(e)}export{a as n,o as t};
@@ -1 +1 @@
1
- import{C as e,p as t}from"./sdk-contracts.js";import{c as n,d as r,l as i,r as a}from"./capture.js";import{S as o,l as s,v as c}from"./sdk-device.js";import{Er as l,Hr as u,Mr as d,Nt as f,Pr as p,Ur as m,d as h,jr as g,l as _,un as ee,x as te,y as ne,zr as v}from"./sdk-batch.js";import{t as re}from"./session-store.js";import{C as ie,E as ae,M as oe,m as se}from"./runtime.js";import{t as y}from"./snapshot-state.js";import{i as b}from"./request-runtime-binding.js";import{c as x,f as ce,i as le,m as S,o as ue}from"./session-snapshot.js";import{c as de,l as fe,u as pe}from"./quality-warnings.js";import{i as me,r as he,t as ge}from"./screenshot-density.js";import{a as _e,i as ve,n as ye,t as be}from"./session-runtime-admission.js";import C from"node:path";import{promises as w}from"node:fs";import T from"node:os";const E=_(h),xe=Ie(E);function Se(e){return A(e)?.route??`generic`}function Ce(e){return A(e)?.sessionKind}function we(e){return A(e)?.leaseAdmissionExempt===!0}function D(e){return A(e)?.selectorValidationExempt!==!0}function O(e){return A(e)?.sessionExecutionLockExempt!==!0}function k(e){return A(e)?.replayScopedAction===!0}function Te(e){return A(e)?.allowInvalidRecording!==!0}function Ee(e){return A(e)?.saveScriptFlagOwner===!0}function De(){return E.filter(e=>e.saveScriptFlagOwner===!0).map(e=>e.command).sort()}function Oe(e){return A(e)?.lockPolicySelectorOverride===!0}function ke(e){return A(e)?.androidBlockingDialogGuard===!0}function Ae(e){if(e.command===`human_control`||e.command===`lease_heartbeat`)return!1;let t=te(e);return t===void 0?Ce(e.command)!==`observability`&&ne(e.command)!==`observe`:t!==`observes-app`}function je(e){return A(e.command)?.preferExplicitDeviceOverExistingSession===!0}function Me(e){let t=A(e.command)?.allowSessionlessDefaultDevice;return typeof t==`function`&&t(e)}function Ne(e){return A(e.command)?.sessionlessLeaseAdmissionExemption?.(e)}function Pe(e){let t=A(e.command)?.refFrameEffect;return typeof t==`function`?t(e):t}function Fe(e,t){return t.hasExistingSession?je(e)&&t.hasExplicitDeviceIdentity?`explicit-device`:`existing-session`:Le(e)?`skip`:t.hasDeviceSelectionInput?`explicit-device`:Me(e)?`sessionless-default-device`:`skip`}function A(e){return xe.descriptorsByCommand.get(e)}function Ie(e){let t=new Map;for(let n of e){if(t.has(n.command))throw Error(`Duplicate daemon command descriptor: ${n.command}`);t.set(n.command,n)}return{descriptorsByCommand:t}}function Le(e){let t=A(e.command);if(t?.route===`lease`)return!0;let n=t?.skipSessionlessProviderDevice;return typeof n==`function`&&n(e)}const j=a.pendingPixelIdentityEvidence,Re=[{target:`ios-simulator`,status:`accepted`},{target:`android-emulator`,status:`accepted`},{target:`android-device`,status:`rejected`,rejectionReason:j},{target:`macos-app-window`,status:`rejected`,rejectionReason:j},{target:`ios-physical`,status:`rejected`,rejectionReason:j},{target:`macos-helper`,status:`rejected`,rejectionReason:j},{target:`web`,status:`rejected`,rejectionReason:j},{target:`linux`,status:`rejected`,rejectionReason:j},{target:`tvos`,status:`rejected`,rejectionReason:j},{target:`harmonyos`,status:`rejected`,rejectionReason:j},{target:`vega`,status:`rejected`,rejectionReason:j}];function ze(e,t){switch(e.platform){case`apple`:return Be(e,t);case`android`:return e.kind===`device`?`android-device`:`android-emulator`;case`harmonyos`:return`harmonyos`;case`vega`:return`vega`;case`linux`:return`linux`;case`web`:return`web`}}function Be(e,t){let n=o(e);switch(n){case`ios`:case`ipados`:return e.kind===`device`?`ios-physical`:`ios-simulator`;case`tvos`:return`tvos`;case`macos`:return Ve(t);case`watchos`:case`visionos`:throw M(n)}}function Ve(e){return e===`app`||e===`frontmost-app`?`macos-app-window`:`macos-helper`}function M(t,n){return new e(`UNSUPPORTED_OPERATION`,`screenshot --crop-on is not accepted on ${t} targets`,{reason:a.targetNotAccepted,...n?{rejectionReason:n}:{}})}function He(t){if(t.overlayRefs||t.fullscreen)throw new e(`INVALID_ARGS`,`--crop-on cannot be combined with --overlay-refs or --fullscreen: both move the captured frame away from the snapshot viewport the crop is measured against`,{reason:a.frameMismatch});try{ee(t.cropOn)}catch{throw new e(`INVALID_ARGS`,`screenshot --crop-on requires a valid selector expression`,{reason:a.selectorInvalid})}let n=ze(t.device,t.surface),r=Re.find(e=>e.target===n);if(!r||r.status===`rejected`)throw M(n,r?.status===`rejected`?r.rejectionReason:void 0)}async function Ue(t,n){if(!We(n))throw new e(`INVALID_ARGS`,`Screenshot crop box must be positive integer pixel offsets`);let r=await de(await w.readFile(t),n,`screenshot`);r!==null&&await w.writeFile(t,r)}function We(e){return Number.isInteger(e.x)&&e.x>=0&&Number.isInteger(e.y)&&e.y>=0&&Number.isInteger(e.width)&&e.width>0&&Number.isInteger(e.height)&&e.height>0}function Ge(t){switch(t){case`android`:return`device-pixels`;case`xctest`:case`macos-helper`:return`viewport-points`;default:throw new e(`UNSUPPORTED_OPERATION`,`screenshot --crop-on does not accept snapshot backend "${t??`unknown`}"`,{reason:a.targetNotAccepted})}}function N(e,t,n,r,i){if(e===`device-pixels`||t===null)return Ye(n);let a=r/t.width,o=i/t.height;return{x:Math.round((n.x-t.x)*a),y:Math.round((n.y-t.y)*o),width:Math.round(n.width*a),height:Math.round(n.height*o)}}function Ke(e,t,n){let r=Math.max(e.x,0),i=Math.max(e.y,0),a=Math.min(e.x+e.width,t),o=Math.min(e.y+e.height,n);return a<=r||o<=i?null:{x:r,y:i,width:a-r,height:o-i}}function P(e){let t=null;for(let n of e)!l(n)||!v(n.rect)||(!t||u(n.rect)>u(t))&&(t=n.rect);return t||qe(e.filter(e=>v(e.rect)&&!Je(e)))}function qe(e){let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)v(a.rect)&&(t=Math.min(t,a.rect.x),n=Math.min(n,a.rect.y),r=Math.max(r,a.rect.x+a.rect.width),i=Math.max(i,a.rect.y+a.rect.height));return!Number.isFinite(t)||!Number.isFinite(n)||r<=t||i<=n?null:{x:t,y:n,width:r-t,height:i-n}}function Je(e){return d(e.type??``)===`image`&&!g(e.label)}function Ye(e){return{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}const Xe=`${a.partialIntersection}: the selector frame extends past the captured image; the crop was clipped to the image frame`;function Ze(e){return e?.partialIntersection?[Xe]:[]}async function Qe(t){let{device:n,session:r,surface:i,cropOn:o,screenshotPath:s,logPath:c,dispatchContext:l}=t,u={snapshotInteractiveOnly:!1},d=await x({device:n,session:r,flags:u,logPath:c,snapshotScope:void 0,captureData:async()=>await t.captureSnapshot({options:{appBundleId:l.appBundleId,interactiveOnly:!1,includeRects:!0,surface:i},execution:S(l)})}),f=y(d,u);if(f.snapshotQuality?.state===`sparse`)throw new e(`COMMAND_FAILED`,`the snapshot taken for --crop-on was sparse and cannot be read as the screen`,{reason:a.captureUnreadable});let p=await $e(f.nodes,o,f.truncated,n),m=await me(s),h=N(Ge(f.backend),P(f.nodes),p.rect,m.width,m.height),g=Ke(h,m.width,m.height);if(g===null)throw new e(`COMMAND_FAILED`,`the frame resolved by --crop-on occupies no pixel of the capture`,{reason:a.emptyIntersection});let _=g.x!==h.x||g.y!==h.y||g.width<h.width||g.height<h.height;return await Ue(s,g),{partialIntersection:_}}async function $e(t,n,r,i){let o=await se(ie.cropTarget,t,n,{platform:c(i)});if(o.kind===`ambiguous`)throw new e(`COMMAND_FAILED`,`--crop-on matched ${o.matchedNodes.length} nodes and must resolve to one`,{reason:a.targetAmbiguous,candidates:o.matchedNodes.map(e=>e.label??e.ref),matches:o.matchedNodes.length});if(o.kind===`none`)throw r?new e(`COMMAND_FAILED`,`the snapshot taken for --crop-on was truncated, so a missing match is not proven`,{reason:a.captureIncomplete}):new e(`COMMAND_FAILED`,`--crop-on matched no node: ${n}`,{reason:a.targetNotFound,hint:`find ${n} list`});return o.node}function F(e){return!!(e&&e.width>0&&e.height>0)}function I(e,t,n){return Number.isFinite(e)?Math.max(t,Math.min(n,e)):t}function L(e){return e.width*e.height}function et(e){let t=e[0];if(t===void 0)throw Error(`unionRects requires at least one rect`);let n=t.x,r=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}}const tt=[`scroll`,`list`,`recyclerview`,`edittext`,`textfield`];function nt(e,t,n){if(e.backend!==`android`||!n.hittable||!F(n.rect)||l(n))return!1;let r=d(n.type??``);return!(tt.some(e=>r.includes(e))||t&&L(n.rect)>L(t)*.25)}function rt(e,t,n,r){return!e.rect||e.hittable!==!0||n(e)||r(e)?null:it(e,t,r)}function it(e,t,n){let r=e.rect,i=at(e,t,n);if(!i)return null;let a=i.y-r.y,o=r.y+r.height-(i.y+i.height);if(a<0||o<0||Math.abs(o-a)<16)return null;let s=Math.min(a,o),c=Math.round(i.y-s),l=Math.round(i.height+s*2);return l<=0||l>=r.height?null:{x:r.x,y:c,width:r.width,height:l}}function at(e,t,n){let r=e.rect,i=new Map(t.map(e=>[e.index,e])),a=t.filter(t=>t.ref!==e.ref&&st(t,e,i)&&ot(t,n)&&F(t.rect)&&m(r,t.rect)).map(e=>e.rect);return a.length<2?null:et(a)}function ot(e,t){let n=d(e.type??``);return n.includes(`text`)||n.includes(`image`)&&t(e)}function st(e,t,n){let r=e;for(;r.parentIndex!==void 0;){let e=n.get(r.parentIndex);if(!e)return!1;if(e.ref===t.ref)return!0;r=e}return!1}const ct=[255,59,48,255],lt=[255,214,10,255],ut=[0,0,0,255],dt={e:[`01110`,`10000`,`11110`,`10000`,`10000`,`10001`,`01110`],0:[`01110`,`10001`,`10011`,`10101`,`11001`,`10001`,`01110`],1:[`00100`,`01100`,`00100`,`00100`,`00100`,`00100`,`01110`],2:[`01110`,`10001`,`00001`,`00010`,`00100`,`01000`,`11111`],3:[`11110`,`00001`,`00001`,`01110`,`00001`,`00001`,`11110`],4:[`00010`,`00110`,`01010`,`10010`,`11111`,`00010`,`00010`],5:[`11111`,`10000`,`10000`,`11110`,`00001`,`00001`,`11110`],6:[`01110`,`10000`,`10000`,`11110`,`10001`,`10001`,`01110`],7:[`11111`,`00001`,`00010`,`00100`,`01000`,`01000`,`01000`],8:[`01110`,`10001`,`10001`,`01110`,`10001`,`10001`,`01110`],9:[`01110`,`10001`,`10001`,`01111`,`00001`,`00001`,`01110`]};function ft(e,t){pt(e,t.overlayRect,ct,2),mt(e,t.overlayRect,t.ref)}function pt(e,t,n,r){for(let i=0;i<r;i+=1)R(e,t.x,t.x+t.width-1,t.y+i,n),R(e,t.x,t.x+t.width-1,t.y+t.height-1-i,n),z(e,t.x+i,t.y,t.y+t.height-1,n),z(e,t.x+t.width-1-i,t.y,t.y+t.height-1,n)}function mt(e,t,n){let r=6+n.length*5+Math.max(0,n.length-1)*1,i=I(t.x,0,Math.max(0,e.width-r)),a=t.y-11-2,o=a>=0?a:I(t.y+2,0,Math.max(0,e.height-11));gt(e,i,o,r,11,lt),ht(e,i+3,o+2,n,ut)}function ht(e,t,n,r,i){let a=t;for(let t of r.toLowerCase()){let r=dt[t];if(r)for(let t=0;t<r.length;t+=1)for(let o=0;o<r[t].length;o+=1)r[t][o]===`1`&&B(e,a+o,n+t,i);a+=6}}function gt(e,t,n,r,i,a){for(let o=0;o<i;o+=1)for(let i=0;i<r;i+=1)B(e,t+i,n+o,a)}function R(e,t,n,r,i){for(let a=t;a<=n;a+=1)B(e,a,r,i)}function z(e,t,n,r,i){for(let a=n;a<=r;a+=1)B(e,t,a,i)}function B(e,t,n,r){if(t<0||n<0||t>=e.width||n>=e.height)return;let i=(e.width*n+t)*4;e.data[i]=r[0],e.data[i+1]=r[1],e.data[i+2]=r[2],e.data[i+3]=r[3]}const _t=[`button`,`link`,`menu`,`tab`,`textfield`,`searchfield`,`securetextfield`,`checkbox`,`radio`,`switch`,`cell`];async function V(e){let t=await w.readFile(e.screenshotPath),n=await fe(t,`screenshot`),r=vt(e.snapshot,n.width,n.height,{maxRefs:e.maxRefs});for(let e of r)ft(n,e);return await w.writeFile(e.screenshotPath,await pe(n)),r}function vt(e,n,r,i={}){let a=P(e.nodes),o=new Map;for(let t of e.nodes){if(!xt(e,a,t))continue;let i=St(e.nodes,t);if(!i?.rect||!F(i.rect))continue;let s=Ct(t,i,e.nodes),c=wt(t,i,s),l=H(e,a,bt(e,i,e.nodes),n,r);if(!F(l))continue;let u=o.get(i.ref);(!u||c>u.score)&&o.set(i.ref,{ref:i.ref,label:s,rect:i.rect,overlayRect:l,score:c})}return yt(e,a,o,n,r),Tt([...o.values()]).sort(Ft).slice(0,i.maxRefs??24).sort(J).map(e=>({ref:e.ref,label:e.label,rect:e.rect,overlayRect:e.overlayRect,center:t(e.overlayRect)}))}function yt(e,t,n,r,i){let a=oe(e.nodes).primaryAction;if(!a?.ref||!a.rect||!F(a.rect))return;let o=H(e,t,a.rect,r,i);if(!F(o))return;let s={ref:a.ref,label:a.label,rect:a.rect,overlayRect:o,score:100},c=n.get(a.ref);n.set(a.ref,c?{...c,score:Math.max(c.score,s.score)}:s)}function bt(e,t,n){return e.backend===`android`?rt(t,n,U,e=>!!q(e))??t.rect:t.rect}function xt(e,t,n){let r=[n.label,n.value].some(G)||K(n.identifier);return nt(e,t,n)?!0:U(n)?r:r&&Et(n)}function St(e,t){return[W(t)?t:null,p(e,t,W),t.hittable?t:null,p(e,t,e=>e.hittable===!0)].find(Dt)??null}function Ct(e,t,n){let r=q(e);return e.ref!==t.ref&&r?r:Ot(t,n)||q(t)}function wt(e,t,n){let r=0;return e.ref===t.ref&&(r+=4),t.hittable&&(r+=3),U(t)&&(r+=3),U(e)&&(r+=2),n&&(r+=2),K(t.identifier)&&(r+=1),g(t.value)&&(r+=1),r}function Tt(e){let t=[];for(let n of e.sort((e,t)=>L(e.overlayRect)-L(t.overlayRect))){let e=t.findIndex(e=>e.label!==void 0&&e.label===n.label&&(m(e.overlayRect,n.overlayRect)||m(n.overlayRect,e.overlayRect)));if(e===-1){t.push(n);continue}L(n.overlayRect)<L(t[e].overlayRect)&&(t[e]=n)}return t}function H(e,t,n,r,i){return Pt(N(e.backend===`android`?`device-pixels`:`viewport-points`,t,n,r,i),r,i)}function U(e){let t=[e.type,e.role,e.subrole].map(e=>d(e??``)).join(` `);return _t.some(e=>t.includes(e))}function W(e){return U(e)&&!l(e)}function Et(e){let t=d(e.type??``);return t.includes(`statictext`)||t.includes(`image`)||t.includes(`text`)||t.includes(`other`)}function Dt(e){return!!(e?.rect&&F(e.rect)&&!l(e))}function G(e){return g(e)?!jt(e):!1}function K(e){return typeof e!=`string`||!G(e)?!1:!Mt(e)}function q(e){let t=[e.label,e.value].find(G);if(t)return t.trim();if(K(e.identifier))return e.identifier.trim()}function Ot(e,t){let n=null;for(let r of t){if(r.ref===e.ref||!kt(r,e,t))continue;let i=q(r);if(!i)continue;let a=At(r);(!n||a>n.score)&&(n={label:i,score:a})}return n?.label}function kt(e,t,n){let r=e;for(;r.parentIndex!==void 0;){let e=n[r.parentIndex];if(!e)return!1;if(e.ref===t.ref)return!0;r=e}return!1}function At(e){let t=0;return d(e.type??``).includes(`text`)&&(t+=2),G(e.label)&&(t+=2),G(e.value)&&(t+=1),t}function jt(e){let t=e?.trim().toLowerCase();return t===`toolbar`||t===`window`||t===`application`||t?.startsWith(`vertical scroll bar`)===!0}function Mt(e){return/^[a-z0-9_.]+:id\/[a-z0-9_.-]+$/i.test(e.trim())}function Nt(e,t){return Number.parseInt(e.replace(/^\D+/,``),10)-Number.parseInt(t.replace(/^\D+/,``),10)}function Pt(e,t,n){let r=I(e.x,0,Math.max(0,t-1)),i=I(e.y,0,Math.max(0,n-1)),a=Math.max(1,t-r),o=Math.max(1,n-i);return{x:r,y:i,width:I(e.width,1,a),height:I(e.height,1,o)}}function J(e,t){let n=e.overlayRect.y-t.overlayRect.y;if(n!==0)return n;let r=e.overlayRect.x-t.overlayRect.x;return r===0?Nt(e.ref,t.ref):r}function Ft(e,t){return t.score===e.score?J(e,t):t.score-e.score}async function Y(e){let t=f({overlayRefs:e.overlayRefs,cropOn:e.cropOn!==void 0}),n=await be({device:e.device,plan:t,inspectFacts:e.inspectFacts});return n.admitted?{ok:!0,runtime:await It(e.bindDevice,n)}:{ok:!1,response:Rt(t.kind,n.operation,n.fact)}}async function It(e,t){let n=ye(e),{device:r,plan:i}=_e(t);switch(i.kind){case`capture`:{let e=await n(r,i.use);return Object.freeze({captureScreenshot:X(e)})}case`capture-with-overlay-refs`:case`capture-with-crop-on`:{let e=await n(r,i.use);return Object.freeze({captureScreenshot:X(e),captureSnapshot:Lt(e)})}}}function X(e){return async t=>await e.operations.captureScreenshot(t)}function Lt(e){return async t=>await e.operations.captureSnapshot(t)}function Rt(e,t,n){return t===`captureScreenshot`?ve(`screenshot`,n):e===`capture-with-crop-on`?b(`UNSUPPORTED_OPERATION`,`--crop-on crops the capture to a selector frame using a snapshot taken on the same screen, which this target cannot capture.`,{reason:n.available?void 0:n.reason},{hint:(n.available?void 0:n.hint)??`Re-run screenshot without --crop-on.`}):b(`UNSUPPORTED_OPERATION`,`--overlay-refs annotates a capture with the refs of a snapshot taken on the same screen, which this target cannot capture.`,{reason:n.available?void 0:n.reason},{hint:(n.available?void 0:n.hint)??`Re-run screenshot without --overlay-refs.`})}async function zt(t){let{req:r,session:i}=t,a=n(`screenshot`,r.flags);if(a)throw new e(`INVALID_ARGS`,a);ge(i.device,r.flags?.screenshotPixelDensity);let o=Ut(r),s=typeof r.flags?.screenshotCropOn==`string`&&r.flags.screenshotCropOn.length>0?r.flags.screenshotCropOn:void 0;s!==void 0&&He({device:i.device,surface:i.surface,cropOn:s,overlayRefs:r.flags?.overlayRefs===!0,fullscreen:r.flags?.screenshotFullscreen===!0});let c=await Y({device:i.device,overlayRefs:r.flags?.overlayRefs===!0,cropOn:s,inspectFacts:t.inspectFacts,bindDevice:t.bindDevice});if(!c.ok)return c;let l=c.runtime,u={warnings:[]};return{ok:!0,recorded:o.recorded,execute:async e=>await $({session:e.session,sessionName:e.sessionName,logPath:e.logPath,dispatchContext:e.dispatchContext,flags:e.request.flags,outPath:o.outPath,runtime:l,cropOn:s,cropRun:u})}}async function Z(e){let{session:t,sessionName:n,outPath:i,dispatchContext:a}=e;return await ce({backend:Wt(e),artifacts:Gt(),sessions:ue({sessionName:n,getSession:()=>t,recordOptions:{includeSnapshot:!1},setRecord:()=>{}}),policy:ae()}).capture.screenshot({session:n,requestId:a.requestId,appBundleId:t.appBundleId,...r(a),surface:t.surface,...i?{out:{kind:`path`,path:i}}:{}})}function Q(e){return S(e)}async function $(e){let{session:t,runtime:n,flags:r}=e,i=Bt({cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,cropRun:e.cropRun,logPath:e.logPath}),a=await Z({session:t,sessionName:e.sessionName,outPath:e.outPath,dispatchContext:e.dispatchContext,captureScreenshot:n.captureScreenshot,...i?{crop:i}:{}}),o=[...a.warnings??[],...i?.run?.warnings??[]];return{...a,...o.length>0?{warnings:o}:{},...await Vt({session:t,cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,screenshotPath:a.path,logPath:e.logPath,dispatchContext:e.dispatchContext}),...await he({device:t.device,path:a.path,requestedPixelDensity:r?.screenshotPixelDensity,scale:r?.screenshotScale})}}function Bt(e){let{cropOn:t,captureSnapshot:n,cropRun:r}=e;if(t!==void 0&&n!==void 0&&r!==void 0)return{cropOn:t,captureSnapshot:n,run:r,logPath:e.logPath}}async function Vt(e){let{session:t,cropOn:n,captureSnapshot:r}=e;return n!==void 0||r===void 0?{}:{overlayRefs:await Ht({session:t,logPath:e.logPath,screenshotPath:e.screenshotPath,dispatchContext:e.dispatchContext,captureSnapshot:r})}}async function Ht(e){let{session:t,dispatchContext:n}=e,r={snapshotInteractiveOnly:!0},i=await x({device:t.device,session:t,flags:r,logPath:e.logPath,snapshotScope:void 0,captureData:async()=>await e.captureSnapshot({options:{appBundleId:t.appBundleId,interactiveOnly:!0,surface:t.surface},execution:Q(n)})}),a=y(i,r);return le(t,a),await V({screenshotPath:e.screenshotPath,snapshot:a})}function Ut(e){let t=e.positionals??[],n=e.flags??{},r=t=>t===void 0?void 0:re.expandHome(t,e.meta?.cwd),i=r(t[0]),a=r(n.out);return{outPath:i??a,recorded:{positionals:i?[i,...t.slice(1)]:t,flags:a?{...n,out:a}:n}}}function Wt(e){let{session:t,dispatchContext:n,captureScreenshot:a,crop:o}=e;return{platform:c(t.device),captureScreenshot:async(e,c,l)=>{let u=r({...n,...i(l)});if(await a({outPath:c,options:{appBundleId:n.appBundleId,pixelDensity:u.pixelDensity,fullscreen:u.fullscreen,normalizeStatusBar:u.normalizeStatusBar,stabilize:u.stabilize,surface:l?.surface,skipIosSimulatorBootCheck:n.skipIosSimulatorBootCheck??(s(t.device)&&t.device.kind===`simulator`),captureBackend:n.screenshotCaptureBackend},execution:Q(n)}),o){let e=await Qe({device:t.device,session:t,surface:t.surface,cropOn:o.cropOn,screenshotPath:c,logPath:o.logPath,dispatchContext:n,captureSnapshot:o.captureSnapshot});o.run.warnings.push(...Ze(e))}}}}function Gt(){return{resolveInput:async()=>{throw new e(`UNSUPPORTED_OPERATION`,`screenshot does not resolve input artifacts`)},reserveOutput:async e=>{let t,n;return e?.kind===`path`?n=e.path:(t=await w.mkdtemp(C.join(T.tmpdir(),`agent-device-screenshot-`)),n=C.join(t,`screenshot.png`)),await w.mkdir(C.dirname(n),{recursive:!0}),{path:n,visibility:`client-visible`,publish:async()=>void 0,...t?{cleanup:async()=>{await w.rm(t,{recursive:!0,force:!0})}}:{}}},createTempFile:async e=>{let t=await w.mkdtemp(C.join(T.tmpdir(),`${e.prefix}-`));return{path:C.join(t,`file${e.ext}`),visibility:`internal`,cleanup:async()=>{await w.rm(t,{recursive:!0,force:!0})}}}}}export{ke as _,V as a,Se as c,De as d,Ee as f,Te as g,Ne as h,Y as i,Ae as l,Pe as m,zt as n,Oe as o,Fe as p,Q as r,k as s,Z as t,we as u,O as v,D as y};
1
+ import{C as e,p as t}from"./sdk-contracts.js";import{c as n,d as r,l as i,r as a}from"./capture.js";import{S as o,l as s,v as c}from"./sdk-device.js";import{Er as l,Hr as u,Mr as d,Nt as f,Pr as p,Ur as m,d as h,jr as g,l as _,un as ee,x as te,y as ne,zr as v}from"./sdk-batch.js";import{t as re}from"./session-store.js";import{C as ie,E as ae,M as oe,m as se}from"./runtime.js";import{t as y}from"./snapshot-state.js";import{i as b}from"./request-runtime-binding.js";import{c as x,f as ce,i as le,m as S,o as ue}from"./session-snapshot.js";import{c as de,l as fe,u as pe}from"./quality-warnings.js";import{i as me,r as he,t as ge}from"./screenshot-density.js";import{a as _e,i as ve,n as ye,t as be}from"./session-runtime-admission.js";import C from"node:path";import{promises as w}from"node:fs";import T from"node:os";const E=_(h),xe=Ie(E);function Se(e){return A(e)?.route??`generic`}function D(e){return A(e)?.sessionKind}function Ce(e){return A(e)?.leaseAdmissionExempt===!0}function we(e){return A(e)?.selectorValidationExempt!==!0}function O(e){return A(e)?.sessionExecutionLockExempt!==!0}function k(e){return A(e)?.replayScopedAction===!0}function Te(e){return A(e)?.allowInvalidRecording!==!0}function Ee(e){return A(e)?.saveScriptFlagOwner===!0}function De(){return E.filter(e=>e.saveScriptFlagOwner===!0).map(e=>e.command).sort()}function Oe(e){return A(e)?.lockPolicySelectorOverride===!0}function ke(e){return A(e)?.androidBlockingDialogGuard===!0}function Ae(e){if(e.command===`human_control`||e.command===`lease_heartbeat`)return!1;let t=te(e);return t===void 0?D(e.command)!==`observability`&&ne(e.command)!==`observe`:t!==`observes-app`}function je(e){return A(e.command)?.preferExplicitDeviceOverExistingSession===!0}function Me(e){let t=A(e.command)?.allowSessionlessDefaultDevice;return typeof t==`function`&&t(e)}function Ne(e){return A(e.command)?.sessionlessLeaseAdmissionExemption?.(e)}function Pe(e){let t=A(e.command)?.refFrameEffect;return typeof t==`function`?t(e):t}function Fe(e,t){return t.hasExistingSession?je(e)&&t.hasExplicitDeviceIdentity?`explicit-device`:`existing-session`:Le(e)?`skip`:t.hasDeviceSelectionInput?`explicit-device`:Me(e)?`sessionless-default-device`:`skip`}function A(e){return xe.descriptorsByCommand.get(e)}function Ie(e){let t=new Map;for(let n of e){if(t.has(n.command))throw Error(`Duplicate daemon command descriptor: ${n.command}`);t.set(n.command,n)}return{descriptorsByCommand:t}}function Le(e){let t=A(e.command);if(t?.route===`lease`)return!0;let n=t?.skipSessionlessProviderDevice;return typeof n==`function`&&n(e)}const j=a.pendingPixelIdentityEvidence,Re=[{target:`ios-simulator`,status:`accepted`},{target:`android-emulator`,status:`accepted`},{target:`android-device`,status:`rejected`,rejectionReason:j},{target:`macos-app-window`,status:`rejected`,rejectionReason:j},{target:`ios-physical`,status:`rejected`,rejectionReason:j},{target:`macos-helper`,status:`rejected`,rejectionReason:j},{target:`web`,status:`rejected`,rejectionReason:j},{target:`linux`,status:`rejected`,rejectionReason:j},{target:`tvos`,status:`rejected`,rejectionReason:j},{target:`harmonyos`,status:`rejected`,rejectionReason:j},{target:`vega`,status:`rejected`,rejectionReason:j}];function ze(e,t){switch(e.platform){case`apple`:return Be(e,t);case`android`:return e.kind===`device`?`android-device`:`android-emulator`;case`harmonyos`:return`harmonyos`;case`vega`:return`vega`;case`linux`:return`linux`;case`web`:return`web`}}function Be(e,t){let n=o(e);switch(n){case`ios`:case`ipados`:return e.kind===`device`?`ios-physical`:`ios-simulator`;case`tvos`:return`tvos`;case`macos`:return Ve(t);case`watchos`:case`visionos`:throw M(n)}}function Ve(e){return e===`app`||e===`frontmost-app`?`macos-app-window`:`macos-helper`}function M(t,n){return new e(`UNSUPPORTED_OPERATION`,`screenshot --crop-on is not accepted on ${t} targets`,{reason:a.targetNotAccepted,...n?{rejectionReason:n}:{}})}function He(t){if(t.overlayRefs||t.fullscreen)throw new e(`INVALID_ARGS`,`--crop-on cannot be combined with --overlay-refs or --fullscreen: both move the captured frame away from the snapshot viewport the crop is measured against`,{reason:a.frameMismatch});try{ee(t.cropOn)}catch{throw new e(`INVALID_ARGS`,`screenshot --crop-on requires a valid selector expression`,{reason:a.selectorInvalid})}let n=ze(t.device,t.surface),r=Re.find(e=>e.target===n);if(!r||r.status===`rejected`)throw M(n,r?.status===`rejected`?r.rejectionReason:void 0)}async function Ue(t,n){if(!We(n))throw new e(`INVALID_ARGS`,`Screenshot crop box must be positive integer pixel offsets`);let r=await de(await w.readFile(t),n,`screenshot`);r!==null&&await w.writeFile(t,r)}function We(e){return Number.isInteger(e.x)&&e.x>=0&&Number.isInteger(e.y)&&e.y>=0&&Number.isInteger(e.width)&&e.width>0&&Number.isInteger(e.height)&&e.height>0}function Ge(t){switch(t){case`android`:return`device-pixels`;case`xctest`:case`macos-helper`:return`viewport-points`;default:throw new e(`UNSUPPORTED_OPERATION`,`screenshot --crop-on does not accept snapshot backend "${t??`unknown`}"`,{reason:a.targetNotAccepted})}}function N(e,t,n,r,i){if(e===`device-pixels`||t===null)return Ye(n);let a=r/t.width,o=i/t.height;return{x:Math.round((n.x-t.x)*a),y:Math.round((n.y-t.y)*o),width:Math.round(n.width*a),height:Math.round(n.height*o)}}function Ke(e,t,n){let r=Math.max(e.x,0),i=Math.max(e.y,0),a=Math.min(e.x+e.width,t),o=Math.min(e.y+e.height,n);return a<=r||o<=i?null:{x:r,y:i,width:a-r,height:o-i}}function P(e){let t=null;for(let n of e)!l(n)||!v(n.rect)||(!t||u(n.rect)>u(t))&&(t=n.rect);return t||qe(e.filter(e=>v(e.rect)&&!Je(e)))}function qe(e){let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)v(a.rect)&&(t=Math.min(t,a.rect.x),n=Math.min(n,a.rect.y),r=Math.max(r,a.rect.x+a.rect.width),i=Math.max(i,a.rect.y+a.rect.height));return!Number.isFinite(t)||!Number.isFinite(n)||r<=t||i<=n?null:{x:t,y:n,width:r-t,height:i-n}}function Je(e){return d(e.type??``)===`image`&&!g(e.label)}function Ye(e){return{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}const Xe=`${a.partialIntersection}: the selector frame extends past the captured image; the crop was clipped to the image frame`;function Ze(e){return e?.partialIntersection?[Xe]:[]}async function Qe(t){let{device:n,session:r,surface:i,cropOn:o,screenshotPath:s,logPath:c,dispatchContext:l}=t,u={snapshotInteractiveOnly:!1},d=await x({device:n,session:r,flags:u,logPath:c,snapshotScope:void 0,captureData:async()=>await t.captureSnapshot({options:{appBundleId:l.appBundleId,interactiveOnly:!1,includeRects:!0,surface:i},execution:S(l)})}),f=y(d,u);if(f.snapshotQuality?.state===`sparse`)throw new e(`COMMAND_FAILED`,`the snapshot taken for --crop-on was sparse and cannot be read as the screen`,{reason:a.captureUnreadable});let p=await $e(f.nodes,o,f.truncated,n),m=await me(s),h=N(Ge(f.backend),P(f.nodes),p.rect,m.width,m.height),g=Ke(h,m.width,m.height);if(g===null)throw new e(`COMMAND_FAILED`,`the frame resolved by --crop-on occupies no pixel of the capture`,{reason:a.emptyIntersection});let _=g.x!==h.x||g.y!==h.y||g.width<h.width||g.height<h.height;return await Ue(s,g),{partialIntersection:_}}async function $e(t,n,r,i){let o=await se(ie.cropTarget,t,n,{platform:c(i)});if(o.kind===`ambiguous`)throw new e(`COMMAND_FAILED`,`--crop-on matched ${o.matchedNodes.length} nodes and must resolve to one`,{reason:a.targetAmbiguous,candidates:o.matchedNodes.map(e=>e.label??e.ref),matches:o.matchedNodes.length});if(o.kind===`none`)throw r?new e(`COMMAND_FAILED`,`the snapshot taken for --crop-on was truncated, so a missing match is not proven`,{reason:a.captureIncomplete}):new e(`COMMAND_FAILED`,`--crop-on matched no node: ${n}`,{reason:a.targetNotFound,hint:`find ${n} list`});return o.node}function F(e){return!!(e&&e.width>0&&e.height>0)}function I(e,t,n){return Number.isFinite(e)?Math.max(t,Math.min(n,e)):t}function L(e){return e.width*e.height}function et(e){let t=e[0];if(t===void 0)throw Error(`unionRects requires at least one rect`);let n=t.x,r=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}}const tt=[`scroll`,`list`,`recyclerview`,`edittext`,`textfield`];function nt(e,t,n){if(e.backend!==`android`||!n.hittable||!F(n.rect)||l(n))return!1;let r=d(n.type??``);return!(tt.some(e=>r.includes(e))||t&&L(n.rect)>L(t)*.25)}function rt(e,t,n,r){return!e.rect||e.hittable!==!0||n(e)||r(e)?null:it(e,t,r)}function it(e,t,n){let r=e.rect,i=at(e,t,n);if(!i)return null;let a=i.y-r.y,o=r.y+r.height-(i.y+i.height);if(a<0||o<0||Math.abs(o-a)<16)return null;let s=Math.min(a,o),c=Math.round(i.y-s),l=Math.round(i.height+s*2);return l<=0||l>=r.height?null:{x:r.x,y:c,width:r.width,height:l}}function at(e,t,n){let r=e.rect,i=new Map(t.map(e=>[e.index,e])),a=t.filter(t=>t.ref!==e.ref&&st(t,e,i)&&ot(t,n)&&F(t.rect)&&m(r,t.rect)).map(e=>e.rect);return a.length<2?null:et(a)}function ot(e,t){let n=d(e.type??``);return n.includes(`text`)||n.includes(`image`)&&t(e)}function st(e,t,n){let r=e;for(;r.parentIndex!==void 0;){let e=n.get(r.parentIndex);if(!e)return!1;if(e.ref===t.ref)return!0;r=e}return!1}const ct=[255,59,48,255],lt=[255,214,10,255],ut=[0,0,0,255],dt={e:[`01110`,`10000`,`11110`,`10000`,`10000`,`10001`,`01110`],0:[`01110`,`10001`,`10011`,`10101`,`11001`,`10001`,`01110`],1:[`00100`,`01100`,`00100`,`00100`,`00100`,`00100`,`01110`],2:[`01110`,`10001`,`00001`,`00010`,`00100`,`01000`,`11111`],3:[`11110`,`00001`,`00001`,`01110`,`00001`,`00001`,`11110`],4:[`00010`,`00110`,`01010`,`10010`,`11111`,`00010`,`00010`],5:[`11111`,`10000`,`10000`,`11110`,`00001`,`00001`,`11110`],6:[`01110`,`10000`,`10000`,`11110`,`10001`,`10001`,`01110`],7:[`11111`,`00001`,`00010`,`00100`,`01000`,`01000`,`01000`],8:[`01110`,`10001`,`10001`,`01110`,`10001`,`10001`,`01110`],9:[`01110`,`10001`,`10001`,`01111`,`00001`,`00001`,`01110`]};function ft(e,t){pt(e,t.overlayRect,ct,2),mt(e,t.overlayRect,t.ref)}function pt(e,t,n,r){for(let i=0;i<r;i+=1)R(e,t.x,t.x+t.width-1,t.y+i,n),R(e,t.x,t.x+t.width-1,t.y+t.height-1-i,n),z(e,t.x+i,t.y,t.y+t.height-1,n),z(e,t.x+t.width-1-i,t.y,t.y+t.height-1,n)}function mt(e,t,n){let r=6+n.length*5+Math.max(0,n.length-1)*1,i=I(t.x,0,Math.max(0,e.width-r)),a=t.y-11-2,o=a>=0?a:I(t.y+2,0,Math.max(0,e.height-11));gt(e,i,o,r,11,lt),ht(e,i+3,o+2,n,ut)}function ht(e,t,n,r,i){let a=t;for(let t of r.toLowerCase()){let r=dt[t];if(r)for(let t=0;t<r.length;t+=1)for(let o=0;o<r[t].length;o+=1)r[t][o]===`1`&&B(e,a+o,n+t,i);a+=6}}function gt(e,t,n,r,i,a){for(let o=0;o<i;o+=1)for(let i=0;i<r;i+=1)B(e,t+i,n+o,a)}function R(e,t,n,r,i){for(let a=t;a<=n;a+=1)B(e,a,r,i)}function z(e,t,n,r,i){for(let a=n;a<=r;a+=1)B(e,t,a,i)}function B(e,t,n,r){if(t<0||n<0||t>=e.width||n>=e.height)return;let i=(e.width*n+t)*4;e.data[i]=r[0],e.data[i+1]=r[1],e.data[i+2]=r[2],e.data[i+3]=r[3]}const _t=[`button`,`link`,`menu`,`tab`,`textfield`,`searchfield`,`securetextfield`,`checkbox`,`radio`,`switch`,`cell`];async function V(e){let t=await w.readFile(e.screenshotPath),n=await fe(t,`screenshot`),r=vt(e.snapshot,n.width,n.height,{maxRefs:e.maxRefs});for(let e of r)ft(n,e);return await w.writeFile(e.screenshotPath,await pe(n)),r}function vt(e,n,r,i={}){let a=P(e.nodes),o=new Map;for(let t of e.nodes){if(!xt(e,a,t))continue;let i=St(e.nodes,t);if(!i?.rect||!F(i.rect))continue;let s=Ct(t,i,e.nodes),c=wt(t,i,s),l=H(e,a,bt(e,i,e.nodes),n,r);if(!F(l))continue;let u=o.get(i.ref);(!u||c>u.score)&&o.set(i.ref,{ref:i.ref,label:s,rect:i.rect,overlayRect:l,score:c})}return yt(e,a,o,n,r),Tt([...o.values()]).sort(Ft).slice(0,i.maxRefs??24).sort(J).map(e=>({ref:e.ref,label:e.label,rect:e.rect,overlayRect:e.overlayRect,center:t(e.overlayRect)}))}function yt(e,t,n,r,i){let a=oe(e.nodes).primaryAction;if(!a?.ref||!a.rect||!F(a.rect))return;let o=H(e,t,a.rect,r,i);if(!F(o))return;let s={ref:a.ref,label:a.label,rect:a.rect,overlayRect:o,score:100},c=n.get(a.ref);n.set(a.ref,c?{...c,score:Math.max(c.score,s.score)}:s)}function bt(e,t,n){return e.backend===`android`?rt(t,n,U,e=>!!q(e))??t.rect:t.rect}function xt(e,t,n){let r=[n.label,n.value].some(G)||K(n.identifier);return nt(e,t,n)?!0:U(n)?r:r&&Et(n)}function St(e,t){return[W(t)?t:null,p(e,t,W),t.hittable?t:null,p(e,t,e=>e.hittable===!0)].find(Dt)??null}function Ct(e,t,n){let r=q(e);return e.ref!==t.ref&&r?r:Ot(t,n)||q(t)}function wt(e,t,n){let r=0;return e.ref===t.ref&&(r+=4),t.hittable&&(r+=3),U(t)&&(r+=3),U(e)&&(r+=2),n&&(r+=2),K(t.identifier)&&(r+=1),g(t.value)&&(r+=1),r}function Tt(e){let t=[];for(let n of e.sort((e,t)=>L(e.overlayRect)-L(t.overlayRect))){let e=t.findIndex(e=>e.label!==void 0&&e.label===n.label&&(m(e.overlayRect,n.overlayRect)||m(n.overlayRect,e.overlayRect)));if(e===-1){t.push(n);continue}L(n.overlayRect)<L(t[e].overlayRect)&&(t[e]=n)}return t}function H(e,t,n,r,i){return Pt(N(e.backend===`android`?`device-pixels`:`viewport-points`,t,n,r,i),r,i)}function U(e){let t=[e.type,e.role,e.subrole].map(e=>d(e??``)).join(` `);return _t.some(e=>t.includes(e))}function W(e){return U(e)&&!l(e)}function Et(e){let t=d(e.type??``);return t.includes(`statictext`)||t.includes(`image`)||t.includes(`text`)||t.includes(`other`)}function Dt(e){return!!(e?.rect&&F(e.rect)&&!l(e))}function G(e){return g(e)?!jt(e):!1}function K(e){return typeof e!=`string`||!G(e)?!1:!Mt(e)}function q(e){let t=[e.label,e.value].find(G);if(t)return t.trim();if(K(e.identifier))return e.identifier.trim()}function Ot(e,t){let n=null;for(let r of t){if(r.ref===e.ref||!kt(r,e,t))continue;let i=q(r);if(!i)continue;let a=At(r);(!n||a>n.score)&&(n={label:i,score:a})}return n?.label}function kt(e,t,n){let r=e;for(;r.parentIndex!==void 0;){let e=n[r.parentIndex];if(!e)return!1;if(e.ref===t.ref)return!0;r=e}return!1}function At(e){let t=0;return d(e.type??``).includes(`text`)&&(t+=2),G(e.label)&&(t+=2),G(e.value)&&(t+=1),t}function jt(e){let t=e?.trim().toLowerCase();return t===`toolbar`||t===`window`||t===`application`||t?.startsWith(`vertical scroll bar`)===!0}function Mt(e){return/^[a-z0-9_.]+:id\/[a-z0-9_.-]+$/i.test(e.trim())}function Nt(e,t){return Number.parseInt(e.replace(/^\D+/,``),10)-Number.parseInt(t.replace(/^\D+/,``),10)}function Pt(e,t,n){let r=I(e.x,0,Math.max(0,t-1)),i=I(e.y,0,Math.max(0,n-1)),a=Math.max(1,t-r),o=Math.max(1,n-i);return{x:r,y:i,width:I(e.width,1,a),height:I(e.height,1,o)}}function J(e,t){let n=e.overlayRect.y-t.overlayRect.y;if(n!==0)return n;let r=e.overlayRect.x-t.overlayRect.x;return r===0?Nt(e.ref,t.ref):r}function Ft(e,t){return t.score===e.score?J(e,t):t.score-e.score}async function Y(e){let t=f({overlayRefs:e.overlayRefs,cropOn:e.cropOn!==void 0}),n=await be({device:e.device,plan:t,inspectFacts:e.inspectFacts});return n.admitted?{ok:!0,runtime:await It(e.bindDevice,n)}:{ok:!1,response:Rt(t.kind,n.operation,n.fact)}}async function It(e,t){let n=ye(e),{device:r,plan:i}=_e(t);switch(i.kind){case`capture`:{let e=await n(r,i.use);return Object.freeze({captureScreenshot:X(e)})}case`capture-with-overlay-refs`:case`capture-with-crop-on`:{let e=await n(r,i.use);return Object.freeze({captureScreenshot:X(e),captureSnapshot:Lt(e)})}}}function X(e){return async t=>await e.operations.captureScreenshot(t)}function Lt(e){return async t=>await e.operations.captureSnapshot(t)}function Rt(e,t,n){return t===`captureScreenshot`?ve(`screenshot`,n):e===`capture-with-crop-on`?b(`UNSUPPORTED_OPERATION`,`--crop-on crops the capture to a selector frame using a snapshot taken on the same screen, which this target cannot capture.`,{reason:n.available?void 0:n.reason},{hint:(n.available?void 0:n.hint)??`Re-run screenshot without --crop-on.`}):b(`UNSUPPORTED_OPERATION`,`--overlay-refs annotates a capture with the refs of a snapshot taken on the same screen, which this target cannot capture.`,{reason:n.available?void 0:n.reason},{hint:(n.available?void 0:n.hint)??`Re-run screenshot without --overlay-refs.`})}async function zt(t){let{req:r,session:i}=t,a=n(`screenshot`,r.flags);if(a)throw new e(`INVALID_ARGS`,a);ge(i.device,r.flags?.screenshotPixelDensity);let o=Ut(r),s=typeof r.flags?.screenshotCropOn==`string`&&r.flags.screenshotCropOn.length>0?r.flags.screenshotCropOn:void 0;s!==void 0&&He({device:i.device,surface:i.surface,cropOn:s,overlayRefs:r.flags?.overlayRefs===!0,fullscreen:r.flags?.screenshotFullscreen===!0});let c=await Y({device:i.device,overlayRefs:r.flags?.overlayRefs===!0,cropOn:s,inspectFacts:t.inspectFacts,bindDevice:t.bindDevice});if(!c.ok)return c;let l=c.runtime,u={warnings:[]};return{ok:!0,recorded:o.recorded,execute:async e=>await $({session:e.session,sessionName:e.sessionName,logPath:e.logPath,dispatchContext:e.dispatchContext,flags:e.request.flags,outPath:o.outPath,runtime:l,cropOn:s,cropRun:u})}}async function Z(e){let{session:t,sessionName:n,outPath:i,dispatchContext:a}=e;return await ce({backend:Wt(e),artifacts:Gt(),sessions:ue({sessionName:n,getSession:()=>t,recordOptions:{includeSnapshot:!1},setRecord:()=>{}}),policy:ae()}).capture.screenshot({session:n,requestId:a.requestId,appBundleId:t.appBundleId,...r(a),surface:t.surface,...i?{out:{kind:`path`,path:i}}:{}})}function Q(e){return S(e)}async function $(e){let{session:t,runtime:n,flags:r}=e,i=Bt({cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,cropRun:e.cropRun,logPath:e.logPath}),a=await Z({session:t,sessionName:e.sessionName,outPath:e.outPath,dispatchContext:e.dispatchContext,captureScreenshot:n.captureScreenshot,...i?{crop:i}:{}}),o=[...a.warnings??[],...i?.run?.warnings??[]];return{...a,...o.length>0?{warnings:o}:{},...await Vt({session:t,cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,screenshotPath:a.path,logPath:e.logPath,dispatchContext:e.dispatchContext}),...await he({device:t.device,path:a.path,requestedPixelDensity:r?.screenshotPixelDensity,scale:r?.screenshotScale})}}function Bt(e){let{cropOn:t,captureSnapshot:n,cropRun:r}=e;if(t!==void 0&&n!==void 0&&r!==void 0)return{cropOn:t,captureSnapshot:n,run:r,logPath:e.logPath}}async function Vt(e){let{session:t,cropOn:n,captureSnapshot:r}=e;return n!==void 0||r===void 0?{}:{overlayRefs:await Ht({session:t,logPath:e.logPath,screenshotPath:e.screenshotPath,dispatchContext:e.dispatchContext,captureSnapshot:r})}}async function Ht(e){let{session:t,dispatchContext:n}=e,r={snapshotInteractiveOnly:!0},i=await x({device:t.device,session:t,flags:r,logPath:e.logPath,snapshotScope:void 0,captureData:async()=>await e.captureSnapshot({options:{appBundleId:t.appBundleId,interactiveOnly:!0,surface:t.surface},execution:Q(n)})}),a=y(i,r);return le(t,a),await V({screenshotPath:e.screenshotPath,snapshot:a})}function Ut(e){let t=e.positionals??[],n=e.flags??{},r=t=>t===void 0?void 0:re.expandHome(t,e.meta?.cwd),i=r(t[0]),a=r(n.out);return{outPath:i??a,recorded:{positionals:i?[i,...t.slice(1)]:t,flags:a?{...n,out:a}:n}}}function Wt(e){let{session:t,dispatchContext:n,captureScreenshot:a,crop:o}=e;return{platform:c(t.device),captureScreenshot:async(e,c,l)=>{let u=r({...n,...i(l)});if(await a({outPath:c,options:{appBundleId:n.appBundleId,pixelDensity:u.pixelDensity,fullscreen:u.fullscreen,normalizeStatusBar:u.normalizeStatusBar,stabilize:u.stabilize,surface:l?.surface,skipIosSimulatorBootCheck:n.skipIosSimulatorBootCheck??(s(t.device)&&t.device.kind===`simulator`),captureBackend:n.screenshotCaptureBackend},execution:Q(n)}),o){let e=await Qe({device:t.device,session:t,surface:t.surface,cropOn:o.cropOn,screenshotPath:c,logPath:o.logPath,dispatchContext:n,captureSnapshot:o.captureSnapshot});o.run.warnings.push(...Ze(e))}}}}function Gt(){return{resolveInput:async()=>{throw new e(`UNSUPPORTED_OPERATION`,`screenshot does not resolve input artifacts`)},reserveOutput:async e=>{let t,n;return e?.kind===`path`?n=e.path:(t=await w.mkdtemp(C.join(T.tmpdir(),`agent-device-screenshot-`)),n=C.join(t,`screenshot.png`)),await w.mkdir(C.dirname(n),{recursive:!0}),{path:n,visibility:`client-visible`,publish:async()=>void 0,...t?{cleanup:async()=>{await w.rm(t,{recursive:!0,force:!0})}}:{}}},createTempFile:async e=>{let t=await w.mkdtemp(C.join(T.tmpdir(),`${e.prefix}-`));return{path:C.join(t,`file${e.ext}`),visibility:`internal`,cleanup:async()=>{await w.rm(t,{recursive:!0,force:!0})}}}}}export{Te as _,V as a,we as b,Se as c,Ce as d,De as f,Ne as g,Pe as h,Y as i,D as l,Fe as m,zt as n,Oe as o,Ee as p,Q as r,k as s,Z as t,Ae as u,ke as v,O as y};