agent-device 0.21.1 → 0.21.2

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 (171) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.1.apk → agent-device-android-ime-helper-0.21.2.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.2.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.1.manifest.json → agent-device-android-ime-helper-0.21.2.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.2.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.1.manifest.json → agent-device-android-snapshot-helper-0.21.2.manifest.json} +6 -6
  7. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerScrollViewportPolicy.swift +413 -0
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +34 -0
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +56 -31
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +1 -13
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +4 -0
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +9 -1
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +1 -0
  14. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/RecordingExportSupport.swift +0 -4
  15. package/dist/src/absence-observation-errors.js +1 -0
  16. package/dist/src/adapter.js +1 -1
  17. package/dist/src/agent-browser-lifecycle.js +1 -1
  18. package/dist/src/agent-browser-process-record.js +1 -1
  19. package/dist/src/agent-browser-tool.js +1 -1
  20. package/dist/src/agent-device-client.js +2 -2
  21. package/dist/src/ai-sdk.d.ts +1 -1
  22. package/dist/src/ai-sdk.js +1 -1
  23. package/dist/src/alert-runtime.js +1 -1
  24. package/dist/src/android-input-ownership.js +1 -1
  25. package/dist/src/app-helpers.js +1 -1
  26. package/dist/src/app-inventory-contract.js +1 -1
  27. package/dist/src/app-inventory.js +1 -1
  28. package/dist/src/app-log-runtime2.js +2 -2
  29. package/dist/src/auth-session.js +1 -1
  30. package/dist/src/back-mode.js +1 -0
  31. package/dist/src/browser-launch.js +1 -0
  32. package/dist/src/catalog.js +1 -1
  33. package/dist/src/cli-config.js +1 -1
  34. package/dist/src/cli-help.js +12 -12
  35. package/dist/src/cli-runner.js +1 -1
  36. package/dist/src/cli.js +3 -3
  37. package/dist/src/client-metro-companion.js +1 -1
  38. package/dist/src/client-metro.js +1 -1
  39. package/dist/src/client-types.d.ts +2 -1
  40. package/dist/src/code-signature-cache.js +1 -1
  41. package/dist/src/code-signature.js +1 -1
  42. package/dist/src/command-metadata.js +1 -1
  43. package/dist/src/command-schema.js +3 -3
  44. package/dist/src/command-tools.js +2 -2
  45. package/dist/src/config.js +1 -1
  46. package/dist/src/connection-runtime.js +1 -1
  47. package/dist/src/contracts.d.ts +1 -1
  48. package/dist/src/daemon-client-lifecycle.js +1 -1
  49. package/dist/src/daemon-process.js +1 -1
  50. package/dist/src/daemon-shutdown-report.js +1 -1
  51. package/dist/src/device-boot.js +1 -0
  52. package/dist/src/device-claim-inspection.js +1 -1
  53. package/dist/src/device-claim-rule.js +1 -1
  54. package/dist/src/device-input-state.d.ts +1 -1
  55. package/dist/src/device-session.js +1 -1
  56. package/dist/src/durable-resource.js +1 -1
  57. package/dist/src/engine-eval-script.js +1 -0
  58. package/dist/src/file.js +1 -1
  59. package/dist/src/find.js +1 -1
  60. package/dist/src/finders.js +1 -1
  61. package/dist/src/format.js +1 -0
  62. package/dist/src/generic-settle.js +1 -1
  63. package/dist/src/gesture-plan.js +1 -1
  64. package/dist/src/gesture-runtime.js +1 -1
  65. package/dist/src/helper.js +1 -1
  66. package/dist/src/index.d.ts +1 -1
  67. package/dist/src/input-actions.js +1 -1
  68. package/dist/src/interaction-positionals.js +1 -1
  69. package/dist/src/interaction-ref-policy.js +1 -1
  70. package/dist/src/interaction.js +1 -1
  71. package/dist/src/interaction2.js +1 -1
  72. package/dist/src/interactor.js +5 -5
  73. package/dist/src/internal/bin.js +1 -1
  74. package/dist/src/internal/daemon.js +2 -2
  75. package/dist/src/internal/png-worker.d.ts +3 -0
  76. package/dist/src/internal/png-worker.js +1 -1
  77. package/dist/src/ios-snapshot-acquisition.js +1 -1
  78. package/dist/src/ios-snapshot-planning.js +1 -1
  79. package/dist/src/ios-snapshot-runtime.js +1 -1
  80. package/dist/src/lease.js +1 -1
  81. package/dist/src/limrun.d.ts +1 -1
  82. package/dist/src/local-interactor-operation-set.js +1 -1
  83. package/dist/src/mechanics.js +16 -16
  84. package/dist/src/mobile-snapshot-semantics.js +1 -1
  85. package/dist/src/mp4-atoms.js +1 -0
  86. package/dist/src/owner-identity.js +3 -3
  87. package/dist/src/parameterized-recorded-fill.js +1 -1
  88. package/dist/src/perf-facade.js +1 -1
  89. package/dist/src/perf-runtime-plan.js +1 -1
  90. package/dist/src/platform-request-scope.js +1 -1
  91. package/dist/src/platform-runtime-app-log-process.js +1 -1
  92. package/dist/src/platform-runtime-managed-owner.js +1 -1
  93. package/dist/src/platform-runtime-operation-host.js +1 -1
  94. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  95. package/dist/src/platform-runtime-screen-recording-apple-runner-host.js +1 -1
  96. package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
  97. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  98. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  99. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  100. package/dist/src/platform-runtime.js +1 -1
  101. package/dist/src/platform-runtime2.js +1 -1
  102. package/dist/src/png-crop-bytes.js +1 -0
  103. package/dist/src/png-worker-contract.js +1 -1
  104. package/dist/src/png.js +1 -0
  105. package/dist/src/process.js +1 -1
  106. package/dist/src/provider-webdriver.js +1 -1
  107. package/dist/src/quality-warnings.js +1 -0
  108. package/dist/src/react-native.js +1 -1
  109. package/dist/src/record-runtime.js +1 -1
  110. package/dist/src/registry.js +36 -37
  111. package/dist/src/replay.js +1 -1
  112. package/dist/src/request-admission.js +1 -1
  113. package/dist/src/request-cancellation.js +1 -1
  114. package/dist/src/request-runtime-binding.js +1 -1
  115. package/dist/src/runner-client.js +1 -1
  116. package/dist/src/runner-disposal.js +1 -1
  117. package/dist/src/runner-presentation.js +1 -1
  118. package/dist/src/runtime.js +3 -3
  119. package/dist/src/runtime10.js +1 -0
  120. package/dist/src/runtime2.js +4 -4
  121. package/dist/src/runtime4.js +3 -3
  122. package/dist/src/runtime6.js +1 -1
  123. package/dist/src/runtime7.js +1 -1
  124. package/dist/src/runtime8.js +1 -1
  125. package/dist/src/runtime9.js +1 -1
  126. package/dist/src/screen-recording-live-handle.js +1 -1
  127. package/dist/src/screen-recording-resource-recovery.js +1 -1
  128. package/dist/src/screenshot-runtime.js +1 -1
  129. package/dist/src/screenshot3.js +2 -2
  130. package/dist/src/script.js +1 -1
  131. package/dist/src/scroll-gesture.js +1 -1
  132. package/dist/src/sdk-batch.js +1 -1
  133. package/dist/src/sdk-contracts.d.ts +26 -26
  134. package/dist/src/sdk-finders.d.ts +1 -1
  135. package/dist/src/sdk-finders.js +1 -1
  136. package/dist/src/sdk-remote-config.d.ts +1 -1
  137. package/dist/src/sdk-selectors.d.ts +12 -4
  138. package/dist/src/sdk-selectors.js +1 -1
  139. package/dist/src/selection.js +0 -0
  140. package/dist/src/selector-runtime.js +1 -1
  141. package/dist/src/selectors.js +1 -1
  142. package/dist/src/semantic-index.js +1 -1
  143. package/dist/src/server.js +1 -1
  144. package/dist/src/session-snapshot.js +1 -1
  145. package/dist/src/session-store.js +2 -2
  146. package/dist/src/session-target-evidence.js +1 -1
  147. package/dist/src/session2.js +5 -5
  148. package/dist/src/simulator-boot.js +3 -0
  149. package/dist/src/snapshot-runtime-binding.js +1 -1
  150. package/dist/src/snapshot-runtime.js +1 -1
  151. package/dist/src/snapshot-state.js +1 -1
  152. package/dist/src/snapshot4.js +1 -1
  153. package/dist/src/src.js +1 -1
  154. package/dist/src/src7.js +1 -1
  155. package/dist/src/src8.js +2 -2
  156. package/dist/src/telemetry.js +1 -1
  157. package/dist/src/touch-reference-frame.js +1 -1
  158. package/dist/src/tree.js +1 -1
  159. package/dist/src/type-text-runtime.js +1 -1
  160. package/dist/src/vars.js +2 -0
  161. package/dist/src/version.js +1 -1
  162. package/dist/src/video.js +2 -2
  163. package/dist/src/viewport.js +1 -0
  164. package/dist/src/webdriver-ios-snapshot.js +1 -1
  165. package/package.json +2 -1
  166. package/server.json +2 -2
  167. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.1.apk.sha256 +0 -1
  168. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.1.apk +0 -0
  169. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.1.apk.sha256 +0 -1
  170. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-trim.swift +0 -93
  171. package/dist/src/snapshot-quality-verdict.js +0 -1
@@ -1 +1 @@
1
- import{Cr as e,Dr as t,Sr as n,xr as r,zr as i}from"./sdk-batch.js";import{t as a}from"./scroll-indicator.js";function o(e){if(e.length===0)return{nodes:e,hiddenCount:0,summaryLines:[]};let{visibility:t,visibleNodeIndexes:n,offscreenNodes:r,hintedContainers:i}=c(e),a=n.size===0?e:e.filter(e=>n.has(e.index));return{nodes:a.map(e=>m(e,i.directionsByContainer)),hiddenCount:n.size===0?0:e.length-a.length,summaryLines:h(r.filter(e=>!i.coveredNodeIndexes.has(e.index)&&v(e)),t)}}function s(e){if(e.length===0)return new Map;let{hintedContainers:t}=c(e);return p(t.directionsByContainer)}function c(e){let t=r(e),n=t.nodeByIndex,i=new Set,a=[];for(let r of e){if(t.isVisibleInEffectiveViewport(r)){b(r,i,n);continue}a.push(r)}return{visibility:t,visibleNodeIndexes:i,offscreenNodes:a,hintedContainers:f(e,a,i,n)}}function l(t,n){return t.hittable&&e(t.rect,n)}function u(t,n){if(!t.rect)return null;let r=n.resolveEffectiveViewport(t);if(r&&!i(t.rect,r)){let e=d(t.rect,r);if(e)return e}let a=n.resolveViewport(t.rect);if(a&&!e(t.rect,a)){let e=d(t.rect,a);if(e)return e}return null}function d(e,t){let n=e.x+e.width/2,r=e.y+e.height/2,i=[{direction:`down`,amount:r-(t.y+t.height)},{direction:`up`,amount:t.y-r},{direction:`right`,amount:n-(t.x+t.width)},{direction:`left`,amount:t.x-n}],a=null;for(let e of i)e.amount>0&&(!a||e.amount>a.amount)&&(a=e);return a?.direction??null}function f(e,t,n,r){let i=new Map,a=new Map,o=new Set;for(let e of t){if(!e.rect)continue;let t=x(e,n,r);if(!t?.rect)continue;let s=_(e.rect,t.rect);if(!s)continue;let c=i.get(t.index)??new Set;c.add(s),i.set(t.index,c);let l=a.get(t.index)??new Set;l.add(s),a.set(t.index,l),o.add(e.index)}return S(e,n,r,i,a),{directionsByContainer:i,coveredNodeIndexes:o}}function p(e){let t=new Map;for(let[n,r]of e){let e={};r.has(`above`)&&(e.hiddenContentAbove=!0),r.has(`below`)&&(e.hiddenContentBelow=!0),(e.hiddenContentAbove||e.hiddenContentBelow)&&t.set(n,e)}return t}function m(e,t){let n=t.get(e.index);if(!n||n.size===0)return e;let r=e.hiddenContentAbove===!0||n.has(`above`)?!0:void 0,i=e.hiddenContentBelow===!0||n.has(`below`)?!0:void 0;return{...e,hiddenContentAbove:r,hiddenContentBelow:i}}function h(e,t){let n=new Map;for(let r of e){let e=g(r,t);if(!e)continue;let i=n.get(e)??[];i.push(r),n.set(e,i)}return[`above`,`below`].flatMap(e=>{let t=n.get(e);if(!t||t.length===0)return[];let r=y(t).slice(0,3).map(e=>`"${e}"`),i=t.length===1?`interactive item`:`interactive items`,a=r.length>0?`: ${r.join(`, `)}`:``;return[`[off-screen ${e}] ${t.length} ${i}${a}`]})}function g(e,t){if(!e.rect)return null;let n=t.resolveEffectiveViewport(e);return n?_(e.rect,n):null}function _(e,t){return e.y+e.height<=t.y?`above`:e.y>=t.y+t.height?`below`:null}function v(e){if(e.hittable===!0)return!0;let n=(e.type??``).toLowerCase();return n.includes(`button`)||n.includes(`link`)||n.includes(`textfield`)||n.includes(`edittext`)||n.includes(`searchfield`)||n.includes(`checkbox`)||n.includes(`radio`)||n.includes(`switch`)||n.includes(`menuitem`)||!!t(e)}function y(e){let n=new Set,r=[];for(let i of e){let e=t(i);!e||n.has(e)||(n.add(e),r.push(e))}return r}function b(e,t,n){let r=e,i=new Set;for(;r&&!i.has(r.index);)i.add(r.index),t.add(r.index),r=typeof r.parentIndex==`number`?n.get(r.parentIndex):void 0}function x(e,t,r){return n(e,r,e=>t.has(e.index))}function S(e,t,n,r,i){for(let a of e){let e=C(a);if(!e||e.size===0)continue;let o=x(a,t,n);if(!o)continue;let s=r.get(o.index)??new Set,c=i.get(o.index);for(let t of e)c&&c.size>0&&!c.has(t)||s.add(t);r.set(o.index,s)}}function C(e){let t=a(e.label,e.value);if(!t)return null;let n=new Set;return t.above&&n.add(`above`),t.below&&n.add(`below`),n.size>0?n:null}export{l as i,u as n,s as r,o as t};
1
+ import{Br as e,Cr as t,Or as n,Sr as r,wr as i}from"./sdk-batch.js";import{t as a}from"./scroll-indicator.js";function o(e){if(e.length===0)return{nodes:e,hiddenCount:0,summaryLines:[]};let{visibility:t,visibleNodeIndexes:n,offscreenNodes:r,hintedContainers:i}=c(e),a=n.size===0?e:e.filter(e=>n.has(e.index));return{nodes:a.map(e=>m(e,i.directionsByContainer)),hiddenCount:n.size===0?0:e.length-a.length,summaryLines:h(r.filter(e=>!i.coveredNodeIndexes.has(e.index)&&v(e)),t)}}function s(e){if(e.length===0)return new Map;let{hintedContainers:t}=c(e);return p(t.directionsByContainer)}function c(e){let t=r(e),n=t.nodeByIndex,i=new Set,a=[];for(let r of e){if(t.isVisibleInEffectiveViewport(r)){b(r,i,n);continue}a.push(r)}return{visibility:t,visibleNodeIndexes:i,offscreenNodes:a,hintedContainers:f(e,a,i,n)}}function l(e,t){return e.hittable&&i(e.rect,t)}function u(t,n){if(!t.rect)return null;let r=n.resolveEffectiveViewport(t);if(r&&!e(t.rect,r)){let e=d(t.rect,r);if(e)return e}let a=n.resolveViewport(t.rect);if(a&&!i(t.rect,a)){let e=d(t.rect,a);if(e)return e}return null}function d(e,t){let n=e.x+e.width/2,r=e.y+e.height/2,i=[{direction:`down`,amount:r-(t.y+t.height)},{direction:`up`,amount:t.y-r},{direction:`right`,amount:n-(t.x+t.width)},{direction:`left`,amount:t.x-n}],a=null;for(let e of i)e.amount>0&&(!a||e.amount>a.amount)&&(a=e);return a?.direction??null}function f(e,t,n,r){let i=new Map,a=new Map,o=new Set;for(let e of t){if(!e.rect)continue;let t=x(e,n,r);if(!t?.rect)continue;let s=_(e.rect,t.rect);if(!s)continue;let c=i.get(t.index)??new Set;c.add(s),i.set(t.index,c);let l=a.get(t.index)??new Set;l.add(s),a.set(t.index,l),o.add(e.index)}return S(e,n,r,i,a),{directionsByContainer:i,coveredNodeIndexes:o}}function p(e){let t=new Map;for(let[n,r]of e){let e={};r.has(`above`)&&(e.hiddenContentAbove=!0),r.has(`below`)&&(e.hiddenContentBelow=!0),(e.hiddenContentAbove||e.hiddenContentBelow)&&t.set(n,e)}return t}function m(e,t){let n=t.get(e.index);if(!n||n.size===0)return e;let r=e.hiddenContentAbove===!0||n.has(`above`)?!0:void 0,i=e.hiddenContentBelow===!0||n.has(`below`)?!0:void 0;return{...e,hiddenContentAbove:r,hiddenContentBelow:i}}function h(e,t){let n=new Map;for(let r of e){let e=g(r,t);if(!e)continue;let i=n.get(e)??[];i.push(r),n.set(e,i)}return[`above`,`below`].flatMap(e=>{let t=n.get(e);if(!t||t.length===0)return[];let r=y(t).slice(0,3).map(e=>`"${e}"`),i=t.length===1?`interactive item`:`interactive items`,a=r.length>0?`: ${r.join(`, `)}`:``;return[`[off-screen ${e}] ${t.length} ${i}${a}`]})}function g(e,t){if(!e.rect)return null;let n=t.resolveEffectiveViewport(e);return n?_(e.rect,n):null}function _(e,t){return e.y+e.height<=t.y?`above`:e.y>=t.y+t.height?`below`:null}function v(e){if(e.hittable===!0)return!0;let t=(e.type??``).toLowerCase();return t.includes(`button`)||t.includes(`link`)||t.includes(`textfield`)||t.includes(`edittext`)||t.includes(`searchfield`)||t.includes(`checkbox`)||t.includes(`radio`)||t.includes(`switch`)||t.includes(`menuitem`)||!!n(e)}function y(e){let t=new Set,r=[];for(let i of e){let e=n(i);!e||t.has(e)||(t.add(e),r.push(e))}return r}function b(e,t,n){let r=e,i=new Set;for(;r&&!i.has(r.index);)i.add(r.index),t.add(r.index),r=typeof r.parentIndex==`number`?n.get(r.parentIndex):void 0}function x(e,n,r){return t(e,r,e=>n.has(e.index))}function S(e,t,n,r,i){for(let a of e){let e=C(a);if(!e||e.size===0)continue;let o=x(a,t,n);if(!o)continue;let s=r.get(o.index)??new Set,c=i.get(o.index);for(let t of e)c&&c.size>0&&!c.has(t)||s.add(t);r.set(o.index,s)}}function C(e){let t=a(e.label,e.value);if(!t)return null;let n=new Set;return t.above&&n.add(`above`),t.below&&n.add(`below`),n.size>0?n:null}export{l as i,u as n,s as r,o as t};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime.js";import t from"node:fs";var n=e({findMp4Atom:()=>r});function r(e,n){if(n.length===0)return;let r;try{r=t.openSync(e,`r`);let a={type:``,offset:0,headerSize:0,size:t.fstatSync(r).size};return i(r,a,n,0)}catch{return}finally{r!==void 0&&t.closeSync(r)}}function i(e,t,n,r){for(let o of a(e,t)){if(o.type!==n[r])continue;if(r+1===n.length)return o;let t=i(e,o,n,r+1);if(t)return t}}function*a(e,t){let n=t.offset+t.size,r=t.offset+t.headerSize;for(let t=0;r+8<=n&&t<32;t+=1){let t=o(e,r,n);if(!t||(yield t,!Number.isSafeInteger(t.size)||t.size<t.headerSize||t.offset+t.size>n))return;r+=t.size}}function o(e,t,n){let r=s(e,t,8);if(!r)return;let i=r.readUInt32BE(0),a=8;if(i===1){let n=s(e,t+8,8);if(!n)return;i=Number(n.readBigUInt64BE(0)),a+=8}return{type:r.toString(`latin1`,4,8),offset:t,headerSize:a,size:i===0?n-t:i}}function s(e,n,r){let i=Buffer.alloc(r);try{return t.readSync(e,i,0,r,n)===r?i:void 0}catch{return}}export{n,r as t};
@@ -1,3 +1,3 @@
1
- import{r as e}from"./diagnostics.js";import{c as t,p as n}from"./exec.js";import{t as r}from"./timeouts.js";import i from"node:path";import a from"node:fs";import o from"node:crypto";function s(e){l(e.destination,t=>{e.mode===void 0?a.writeFileSync(t,e.contents,`utf8`):a.writeFileSync(t,e.contents,{encoding:`utf8`,mode:e.mode}),e.publish===`link-exclusive`?a.linkSync(t,e.destination):a.renameSync(t,e.destination)})}function c(e){let t=i.dirname(e.destination);l(e.destination,n=>{let r,i=!1,o;try{f(e.destination),r=a.openSync(n,`wx`,e.mode??384),a.writeFileSync(r,e.contents,`utf8`),a.fsyncSync(r),a.closeSync(r),r=void 0,f(e.destination),e.publish===`link-exclusive`?a.linkSync(n,e.destination):a.renameSync(n,e.destination),u(t)}catch(e){i=!0,o=e}if(r!==void 0)try{a.closeSync(r)}catch(e){i||(i=!0,o=e)}if(i)throw o})}function l(t,n){let r=d(t);try{return n(r)}finally{try{a.rmSync(r,{force:!0})}catch(n){e({level:`warn`,phase:`atomic_file_cleanup_failed`,data:{destination:t,temporaryPath:r,error:n instanceof Error?n.message:String(n)}})}}}function u(e){let t;try{t=a.openSync(e,`r`),a.fsyncSync(t)}catch{}finally{if(t!==void 0)try{a.closeSync(t)}catch{}}}function d(e){return i.join(i.dirname(e),`.${i.basename(e)}.${process.pid}-${o.randomUUID()}.tmp`)}function f(e){let t=p(e);if(t?.isSymbolicLink())throw Error(`Refusing to replace a durable file symbolic link: ${e}`);if(t&&!t.isFile())throw Error(`Refusing to replace a durable path that is not a regular file: ${e}`)}function p(e){try{return a.lstatSync(e)}catch(e){if(e.code===`ENOENT`)return;throw e}}const m=1e3,h=process.platform===`win32`?`ps`:`/bin/ps`;function g(){return process.env}function _(e){return g()[e]}function v(e){process.stderr.write(e)}function y(){return process.cwd()}function b(){return process.execPath}function x(){return process.version}function S(){return process.platform}function C(){return process.pid}function w(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function T(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(-e,0),!0}catch(e){return e.code===`EPERM`}}function E(e){return A(e,`lstart=`)}function D(e){return A(e,`command=`)}function O(e){return A(e,`state=`)?.startsWith(`Z`)??!1}function k(e){let t=new Map,r=P(e);if(r.length===0)return t;try{let e=n(`ps`,[`-p`,r.join(`,`),`-o`,`pid=,state=,lstart=`],{allowFailure:!0,timeoutMs:m});if(e.exitCode!==0)return t;for(let n of e.stdout.split(`
2
- `)){let e=/^\s*(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(n);if(!e)continue;let r=Number.parseInt(e[1],10);!Number.isInteger(r)||r<=0||t.set(r,{state:e[2],startTime:e[3]})}}catch{}return t}function A(e,t){if(!Number.isInteger(e)||e<=0)return null;try{let r=n(h,[`-p`,String(e),`-o`,t],{allowFailure:!0,timeoutMs:m});if(r.exitCode!==0)return null;let i=r.stdout.trim();return i.length>0?i:null}catch{return null}}function j(e){let t=[];for(let n of e.split(`
3
- `)){let e=/^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(n);if(!e)continue;let r=Number.parseInt(e[1],10),i=Number.parseInt(e[2],10),a=e[3];!Number.isInteger(r)||r<=0||t.push({pid:r,ppid:Number.isInteger(i)&&i>0?i:void 0,command:a})}return t}async function M(e){let n=await(e.runCommand??t)(e.runCommand?`ps`:h,[`-ax`,`-o`,`pid=,ppid=,command=`],{allowFailure:!0,timeoutMs:e.timeoutMs});return n.exitCode===0?j(n.stdout):[]}function N(e,t){let n=new Set(P(e)),r=!0;for(;r;){r=!1;for(let e of t)e.ppid===void 0||!n.has(e.ppid)||n.has(e.pid)||(n.add(e.pid),r=!0)}return t.filter(e=>n.has(e.pid))}function P(e,t={}){return[...new Set(e)].filter(e=>Number.isInteger(e)&&e>0&&e!==t.excludePid)}function F(e,t){let n=P(e,{excludePid:process.pid}),r=0;for(let e of n)try{process.kill(e,t),r+=1}catch{}return r}function I(e,t){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(-e,t),!0}catch{return!1}}async function L(e,t){if(!w(e))return!0;let n=Date.now();for(;Date.now()-n<t;)if(await r(50),!w(e))return!0;return!w(e)}async function R(e){let t=P(e.pids,{excludePid:process.pid});t.length!==0&&(F(t,`SIGTERM`),await Promise.all(t.map(async t=>await L(t,e.termTimeoutMs))),F(t.filter(e=>w(e)),`SIGKILL`),await Promise.all(t.map(async t=>await L(t,e.killTimeoutMs))))}function z(){return{pid:process.pid,startTime:E(process.pid)}}function B(e,t){return e.pid===t.pid&&e.startTime===t.startTime}function V(e,t){return e.pid!==t.pid||!!(e.startTime&&t.startTime&&e.startTime!==t.startTime)}function H(e){return U(e)}function U(e,t){let{owner:n,stateDir:r}=e;if(!w(n.pid)||(t===void 0?O(n.pid):t?.state.startsWith(`Z`)))return`owner-process-dead`;if(n.startTime){let e=t===void 0?E(n.pid):t?.startTime??null;if(e!==null&&e!==n.startTime)return`owner-process-reused`}if(!r)return`live`;try{return a.statSync(r),`live`}catch(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`?`owner-state-dir-gone`:`unknown`}}export{R as C,s as D,c as E,l as O,I as S,v as T,_,z as a,E as b,g as c,S as d,C as f,M as g,O as h,B as i,b as l,T as m,U as n,N as o,w as p,V as r,y as s,H as t,x as u,k as v,L as w,F as x,D as y};
1
+ import{r as e}from"./diagnostics.js";import{c as t,p as n}from"./exec.js";import{t as r}from"./timeouts.js";import i from"node:path";import a from"node:fs";import o from"node:crypto";function s(e){l(e.destination,t=>{e.mode===void 0?a.writeFileSync(t,e.contents,`utf8`):a.writeFileSync(t,e.contents,{encoding:`utf8`,mode:e.mode}),e.publish===`link-exclusive`?a.linkSync(t,e.destination):a.renameSync(t,e.destination)})}function c(e){let t=i.dirname(e.destination);l(e.destination,n=>{let r,i=!1,o;try{f(e.destination),r=a.openSync(n,`wx`,e.mode??384),a.writeFileSync(r,e.contents,`utf8`),a.fsyncSync(r),a.closeSync(r),r=void 0,f(e.destination),e.publish===`link-exclusive`?a.linkSync(n,e.destination):a.renameSync(n,e.destination),u(t)}catch(e){i=!0,o=e}if(r!==void 0)try{a.closeSync(r)}catch(e){i||(i=!0,o=e)}if(i)throw o})}function l(t,n){let r=d(t);try{return n(r)}finally{try{a.rmSync(r,{force:!0})}catch(n){e({level:`warn`,phase:`atomic_file_cleanup_failed`,data:{destination:t,temporaryPath:r,error:n instanceof Error?n.message:String(n)}})}}}function u(e){let t;try{t=a.openSync(e,`r`),a.fsyncSync(t)}catch{}finally{if(t!==void 0)try{a.closeSync(t)}catch{}}}function d(e){return i.join(i.dirname(e),`.${i.basename(e)}.${process.pid}-${o.randomUUID()}.tmp`)}function f(e){let t=p(e);if(t?.isSymbolicLink())throw Error(`Refusing to replace a durable file symbolic link: ${e}`);if(t&&!t.isFile())throw Error(`Refusing to replace a durable path that is not a regular file: ${e}`)}function p(e){try{return a.lstatSync(e)}catch(e){if(e.code===`ENOENT`)return;throw e}}const m=1e3,h=process.platform===`win32`?`ps`:`/bin/ps`;function g(){return process.env}function _(e){return g()[e]}function v(e){process.stderr.write(e)}function y(){return process.cwd()}function b(){return process.execPath}function x(){return process.version}function S(){return process.platform}function C(){return process.pid}function w(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function T(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(-e,0),!0}catch(e){return e.code===`EPERM`}}async function E(e,t=m){let[n,r,i]=await Promise.all([M(e,`lstart=`,t),M(e,`command=`,t),M(e,`state=`,t)]);return{startTime:n,command:r,zombie:i===null?null:i.startsWith(`Z`)}}function D(e){return j(e,`lstart=`)}function O(e){return j(e,`command=`)}function k(e){return j(e,`state=`)?.startsWith(`Z`)??!1}function A(e){let t=new Map,r=L(e);if(r.length===0)return t;try{let e=n(`ps`,[`-p`,r.join(`,`),`-o`,`pid=,state=,lstart=`],{allowFailure:!0,timeoutMs:m});if(e.exitCode!==0)return t;for(let n of e.stdout.split(`
2
+ `)){let e=/^\s*(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(n);if(!e)continue;let r=Number.parseInt(e[1],10);!Number.isInteger(r)||r<=0||t.set(r,{state:e[2],startTime:e[3]})}}catch{}return t}function j(e,t){if(!Number.isInteger(e)||e<=0)return null;try{return N(n(h,[`-p`,String(e),`-o`,t],{allowFailure:!0,timeoutMs:m}))}catch{return null}}async function M(e,n,r){if(!Number.isInteger(e)||e<=0)return null;try{return N(await t(h,[`-p`,String(e),`-o`,n],{allowFailure:!0,timeoutMs:r}))}catch{return null}}function N(e){if(e.exitCode!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}function P(e){let t=[];for(let n of e.split(`
3
+ `)){let e=/^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(n);if(!e)continue;let r=Number.parseInt(e[1],10),i=Number.parseInt(e[2],10),a=e[3];!Number.isInteger(r)||r<=0||t.push({pid:r,ppid:Number.isInteger(i)&&i>0?i:void 0,command:a})}return t}async function F(e){let n=await(e.runCommand??t)(e.runCommand?`ps`:h,[`-ax`,`-o`,`pid=,ppid=,command=`],{allowFailure:!0,timeoutMs:e.timeoutMs});return n.exitCode===0?P(n.stdout):[]}function I(e,t){let n=new Set(L(e)),r=!0;for(;r;){r=!1;for(let e of t)e.ppid===void 0||!n.has(e.ppid)||n.has(e.pid)||(n.add(e.pid),r=!0)}return t.filter(e=>n.has(e.pid))}function L(e,t={}){return[...new Set(e)].filter(e=>Number.isInteger(e)&&e>0&&e!==t.excludePid)}function R(e,t){let n=L(e,{excludePid:process.pid}),r=0;for(let e of n)try{process.kill(e,t),r+=1}catch{}return r}function z(e,t){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(-e,t),!0}catch{return!1}}async function B(e,t){if(!w(e))return!0;let n=Date.now();for(;Date.now()-n<t;)if(await r(50),!w(e))return!0;return!w(e)}async function V(e){let t=L(e.pids,{excludePid:process.pid});t.length!==0&&(R(t,`SIGTERM`),await Promise.all(t.map(async t=>await B(t,e.termTimeoutMs))),R(t.filter(e=>w(e)),`SIGKILL`),await Promise.all(t.map(async t=>await B(t,e.killTimeoutMs))))}function H(){return{pid:process.pid,startTime:D(process.pid)}}function U(e,t){return e.pid===t.pid&&e.startTime===t.startTime}function W(e,t){return e.pid!==t.pid||!!(e.startTime&&t.startTime&&e.startTime!==t.startTime)}function G(e){return K(e)}function K(e,t){let{owner:n,stateDir:r}=e;if(!w(n.pid)||(t===void 0?k(n.pid):t?.state.startsWith(`Z`)))return`owner-process-dead`;if(n.startTime){let e=t===void 0?D(n.pid):t?.startTime??null;if(e!==null&&e!==n.startTime)return`owner-process-reused`}if(!r)return`live`;try{return a.statSync(r),`live`}catch(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`?`owner-state-dir-gone`:`unknown`}}export{z as C,c as D,v as E,s as O,R as S,B as T,_,H as a,E as b,g as c,S as d,C as f,F as g,k as h,U as i,l as k,b as l,T as m,K as n,I as o,w as p,W as r,y as s,G as t,x as u,A as v,V as w,D as x,O as y};
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";import{cn as t}from"./sdk-batch.js";import{t as n}from"./script.js";import{t as r}from"./session-paths.js";const i=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function a(t){if(t!==t.trim()||!n.test(t))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": use uppercase letters, digits, and underscores (for example PASSWORD).`);if(t.startsWith(`AD_`))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": the AD_* namespace is reserved for built-in replay variables.`);return t}function o(e){return`\${${e}}`}function s(e){let t=i.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}const c={kind:`none`};function l(e,t){if(t.path===void 0){let n=e??{kind:`default`,force:!1};return t.force?{...n,force:!0}:n}let n=e?.force===!0&&(e.kind==="default"||e.path===t.path);return{kind:`explicit`,path:t.path,force:t.force||n}}function ee(e){return e.kind===`repair`?{...e,status:`armed`}:e}function u(e){return e.kind===`none`?void 0:e.target}function te(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function d(e){return e.kind===`authoring`&&e.status===`aborted`}function f(e){return e.kind===`authoring`?e.status===`armed`:e.kind===`repair`}function p(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function m(e){return{kind:`authoring`,status:`armed`,target:l(void 0,e)}}function h(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function g(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function _(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:l(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function v(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function y(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function ne(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function re(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function ie(e){return e.kind===`repair`?e.boundary:void 0}function b(e){return e.kind===`repair`?e.sourcePath:void 0}function x(e){return e.kind===`repair`&&e.status!==`committed`}function S(e){let t=u(e);return t?.kind===`explicit`?t.path:void 0}function C(e){return u(e)?.force===!0}function w(e){return e?.scriptPublication??c}function T(e){let t=w(e);return t.kind===`authoring`&&t.status===`armed`}function E(e,t){e.scriptPublication=m({path:t.path===void 0?void 0:r(t.path),force:t.force===!0})}function D(e){e.scriptPublication=h(w(e))}function O(e){return f(w(e))}function k(e,t){if(!t.saveScript||d(w(e)))return;let n={path:typeof t.saveScript==`string`?r(t.saveScript):void 0,force:t.force===!0},i=w(e);if(i.kind===`repair`){e.scriptPublication=_(i,{requested:n,boundary:i.boundary,sourcePath:i.sourcePath});return}if(i.kind===`authoring`){e.scriptPublication={...i,target:l(i.target,n)};return}e.scriptPublication=m(n)}function A(e,t){let n=w(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:l(n.target,{path:t.explicitPath===void 0?void 0:r(t.explicitPath),force:t.liveForce===!0})})}function j(e,t){e.scriptPublication=g(w(e),t)}function M(e,t){let n=w(e);n.kind===`authoring`&&(e.scriptPublication=g(n,t))}function N(e,t){return t===!0||C(w(e))}function P(e){return p(w(e))}function F(e){let t=e.result?.text;if(typeof t==`string`)return t;let n=e.positionals??[];return n.length===0?``:n[0]?.startsWith(`@`)?n.length>=3?n.slice(2).join(` `):n.slice(1).join(` `):n.length>=3&&!Number.isNaN(Number(n[0]))&&!Number.isNaN(Number(n[1]))?n.slice(2).join(` `):n.slice(1).join(` `)}const ae=new Set(`action.backend.cost.delayMs.evidence.gesture.hint.kind.maestroFallbackReason.maestroNonHittableCoordinateFallbackAllowed.maestroNonHittableCoordinateFallbackUsed.message.platform.ref.referenceHeight.referenceWidth.refLabel.resolution.selector.selectorChain.settle.targetHittable.targetKind.text.warning.x.y`.split(`.`)),I=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),L=new Set([`cost`,`evidence`,`resolution`,`settle`]),R=new Map([[`cost`,new Set([`nodeCount`,`runnerRoundTrips`,`wallClockMs`])],[`evidence`,new Set([`changedFromBefore`,`digest`,`foregroundApp`,`interactiveNodeCount`,`nodeCount`])],[`resolution`,new Set([`alternatives`,`kind`,`matchCount`,`phase`,`source`,`tiebreak`,`winnerDiagnostic`])],[`resolution.alternatives`,new Set([`diagnosticRef`,`label`,`role`])],[`resolution.winnerDiagnostic`,new Set([`diagnosticRef`,`label`,`role`])],[`settle`,new Set([`captures`,`diff`,`hint`,`quietMs`,`refs`,`refsGeneration`,`settled`,`tail`,`tailTruncated`,`timeoutMs`,`waitedMs`])],[`settle.diff`,new Set([`lines`,`summary`,`truncated`])],[`settle.diff.lines`,new Set([`kind`,`ref`,`text`])],[`settle.diff.summary`,new Set([`additions`,`removals`,`unchanged`])],[`settle.refs`,new Set([`ref`])],[`settle.tail`,new Set([`label`,`ref`,`role`])]]),z=new Set([`evidence.digest`,`evidence.foregroundApp`,`resolution.alternatives.diagnosticRef`,`resolution.alternatives.role`,`resolution.kind`,`resolution.phase`,`resolution.source`,`resolution.tiebreak`,`resolution.winnerDiagnostic.diagnosticRef`,`resolution.winnerDiagnostic.role`,`settle.diff.lines.kind`,`settle.diff.lines.ref`,`settle.refs.ref`,`settle.tail.ref`,`settle.tail.role`]);function B(e,t,n){if(!e)return e;let r=le(e.selectorChain),i=e=>q(e,t);return{...J(e,e=>ce(e,t,n),i),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!i(e))}:{}}}function V(e,t){if(!e)return e;let n=Z(t);return J(e,e=>Q(e,n),e=>G(e,t))}function H(e,t){if(!e)return e;let n=Z(t);return{...e,...e.label===void 0?{}:{label:Q(e.label,n)},ancestry:e.ancestry.map(e=>({...e,...e.label===void 0?{}:{label:Q(e.label,n)}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===void 0?{}:{label:Q(e.scrollRegion.label,n)}}}:{}}}function U(e,t){return!!(e.label!==void 0&&W(e.label,t)||e.ancestry.some(e=>e.label&&W(e.label,t))||e.scrollRegion?.label&&W(e.scrollRegion.label,t))}function W(e,t){for(let n of t.keys())if(e.includes(n))return!0;return!1}function G(e,t){for(let n of t.keys())if(q(e,n))return!0;return!1}function K(e,t,n){return!e||!t?e:{...e,...e.label===t?{label:n}:{},ancestry:e.ancestry.map(e=>({...e,...e.label===t?{label:n}:{}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===t?{label:n}:{}}}:{}}}function q(e,n){return t(e,n)}function J(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[ae.has(e)?e:t(e),oe(r,e,t,n)]))}function oe(e,t,n,r){return typeof e==`string`&&I.has(t)?e:t===`selectorChain`&&$(e)?se(e,r):Y(e,n,r,L.has(t)?t:void 0)}function Y(e,t,n,r){if(typeof e==`string`)return r&&z.has(r)?e:t(e);if(Array.isArray(e))return e.map(e=>Y(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?R.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:t(e),Y(a,t,n,o?`${r}.${e}`:void 0)]}))}function se(e,t){return e.filter(e=>!t(e))}function ce(e,t,n){if(!t)return e;let r=n?e.split(n):[e];return r.every(e=>!e.includes(t))?e:t.trim()?r.map(e=>e.replaceAll(t,n)).join(n):n}const X=/\$\{[A-Z_][A-Z0-9_]*\}/y;function Z(e){return[...e].sort(([e],[t])=>t.length-e.length)}function Q(e,t){if(!e||t.length===0)return e;let n=``,r=0;scan:for(;r<e.length;){for(let[i,a]of t)if(e.startsWith(i,r)){n+=a,r+=i.length;continue scan}if(e[r]===`$`){X.lastIndex=r;let t=X.exec(e);if(t){n+=t[0],r+=t[0].length;continue}}n+=e[r],r+=1}return n}function $(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function le(e){return $(e)?e:void 0}export{S as A,te as C,ie as D,y as E,o as M,a as N,b as O,f as S,v as T,c as _,U as a,ne as b,k as c,T as d,O as f,A as g,M as h,H as i,s as j,C as k,E as l,j as m,K as n,F as o,P as p,V as r,D as s,B as t,N as u,re as v,x as w,ee as x,_ as y};
1
+ import{C as e}from"./sdk-contracts.js";import{ln as t}from"./sdk-batch.js";import{t as n}from"./script.js";import{t as r}from"./session-paths.js";const i=/^\$\{([A-Z_][A-Z0-9_]*)\}$/;function a(t){if(t!==t.trim()||!n.test(t))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": use uppercase letters, digits, and underscores (for example PASSWORD).`);if(t.startsWith(`AD_`))throw new e(`INVALID_ARGS`,`Invalid --record-as variable "${t}": the AD_* namespace is reserved for built-in replay variables.`);return t}function o(e){return`\${${e}}`}function s(e){let t=i.exec(e);if(!(!t?.[1]||t[1].startsWith(`AD_`)))return t[1]}const c={kind:`none`};function l(e,t){if(t.path===void 0){let n=e??{kind:`default`,force:!1};return t.force?{...n,force:!0}:n}let n=e?.force===!0&&(e.kind==="default"||e.path===t.path);return{kind:`explicit`,path:t.path,force:t.force||n}}function ee(e){return e.kind===`repair`?{...e,status:`armed`}:e}function u(e){return e.kind===`none`?void 0:e.target}function te(e){return e.kind===`repair`&&(e.status===`complete`||e.status===`close-succeeded`)}function d(e){return e.kind===`authoring`&&e.status===`aborted`}function f(e){return e.kind===`authoring`?e.status===`armed`:e.kind===`repair`}function p(e){return e.kind===`repair`?e.status===`committed`:e.kind===`authoring`&&e.status===`published`}function m(e){return{kind:`authoring`,status:`armed`,target:l(void 0,e)}}function h(e){return e.kind!==`authoring`||e.status!==`armed`?e:{...e,status:`aborted`}}function g(e,t){return e.kind===`authoring`?{kind:`authoring`,status:`published`,target:{kind:`explicit`,path:t,force:e.target.force}}:e}function _(e,t){let n=e.kind===`repair`?e:void 0,r=n?.sourcePath??t.sourcePath;return{kind:`repair`,status:n?.status??`armed`,target:l(n?.target,t.requested),boundary:n?.boundary??t.boundary,...r===void 0?{}:{sourcePath:r},...n?.closeReceipt===void 0?{}:{closeReceipt:n.closeReceipt}}}function v(e){return e.kind!==`repair`||e.status!==`armed`?e:{...e,status:`complete`}}function y(e,t){return e.kind===`repair`?{...e,status:e.status===`complete`?`close-succeeded`:e.status,closeReceipt:t}:e}function ne(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`committed`}}function re(e){if(e.kind!==`repair`)return e;let{closeReceipt:t,...n}=e;return{...n,status:`aborted`}}function ie(e){return e.kind===`repair`?e.boundary:void 0}function b(e){return e.kind===`repair`?e.sourcePath:void 0}function x(e){return e.kind===`repair`&&e.status!==`committed`}function S(e){let t=u(e);return t?.kind===`explicit`?t.path:void 0}function C(e){return u(e)?.force===!0}function w(e){return e?.scriptPublication??c}function T(e){let t=w(e);return t.kind===`authoring`&&t.status===`armed`}function E(e,t){e.scriptPublication=m({path:t.path===void 0?void 0:r(t.path),force:t.force===!0})}function D(e){e.scriptPublication=h(w(e))}function O(e){return f(w(e))}function k(e,t){if(!t.saveScript||d(w(e)))return;let n={path:typeof t.saveScript==`string`?r(t.saveScript):void 0,force:t.force===!0},i=w(e);if(i.kind===`repair`){e.scriptPublication=_(i,{requested:n,boundary:i.boundary,sourcePath:i.sourcePath});return}if(i.kind===`authoring`){e.scriptPublication={...i,target:l(i.target,n)};return}e.scriptPublication=m(n)}function A(e,t){let n=w(e);n.kind===`authoring`&&(e.scriptPublication={...n,target:l(n.target,{path:t.explicitPath===void 0?void 0:r(t.explicitPath),force:t.liveForce===!0})})}function j(e,t){e.scriptPublication=g(w(e),t)}function M(e,t){let n=w(e);n.kind===`authoring`&&(e.scriptPublication=g(n,t))}function N(e,t){return t===!0||C(w(e))}function P(e){return p(w(e))}function F(e){let t=e.result?.text;if(typeof t==`string`)return t;let n=e.positionals??[];return n.length===0?``:n[0]?.startsWith(`@`)?n.length>=3?n.slice(2).join(` `):n.slice(1).join(` `):n.length>=3&&!Number.isNaN(Number(n[0]))&&!Number.isNaN(Number(n[1]))?n.slice(2).join(` `):n.slice(1).join(` `)}const ae=new Set(`action.backend.cost.delayMs.evidence.gesture.hint.kind.maestroFallbackReason.maestroNonHittableCoordinateFallbackAllowed.maestroNonHittableCoordinateFallbackUsed.message.platform.ref.referenceHeight.referenceWidth.refLabel.resolution.selector.selectorChain.settle.targetHittable.targetKind.text.warning.x.y`.split(`.`)),I=new Set([`action`,`backend`,`gesture`,`kind`,`platform`,`ref`,`selector`,`targetKind`]),L=new Set([`cost`,`evidence`,`resolution`,`settle`]),R=new Map([[`cost`,new Set([`nodeCount`,`runnerRoundTrips`,`wallClockMs`])],[`evidence`,new Set([`changedFromBefore`,`digest`,`foregroundApp`,`interactiveNodeCount`,`nodeCount`])],[`resolution`,new Set([`alternatives`,`kind`,`matchCount`,`phase`,`source`,`tiebreak`,`winnerDiagnostic`])],[`resolution.alternatives`,new Set([`diagnosticRef`,`label`,`role`])],[`resolution.winnerDiagnostic`,new Set([`diagnosticRef`,`label`,`role`])],[`settle`,new Set([`captures`,`diff`,`hint`,`quietMs`,`refs`,`refsGeneration`,`settled`,`tail`,`tailTruncated`,`timeoutMs`,`waitedMs`])],[`settle.diff`,new Set([`lines`,`summary`,`truncated`])],[`settle.diff.lines`,new Set([`kind`,`ref`,`text`])],[`settle.diff.summary`,new Set([`additions`,`removals`,`unchanged`])],[`settle.refs`,new Set([`ref`])],[`settle.tail`,new Set([`label`,`ref`,`role`])]]),z=new Set([`evidence.digest`,`evidence.foregroundApp`,`resolution.alternatives.diagnosticRef`,`resolution.alternatives.role`,`resolution.kind`,`resolution.phase`,`resolution.source`,`resolution.tiebreak`,`resolution.winnerDiagnostic.diagnosticRef`,`resolution.winnerDiagnostic.role`,`settle.diff.lines.kind`,`settle.diff.lines.ref`,`settle.refs.ref`,`settle.tail.ref`,`settle.tail.role`]);function B(e,t,n){if(!e)return e;let r=le(e.selectorChain),i=e=>q(e,t);return{...J(e,e=>ce(e,t,n),i),...typeof e.text==`string`?{text:n}:{},...r?{selectorChain:r.filter(e=>!i(e))}:{}}}function V(e,t){if(!e)return e;let n=Z(t);return J(e,e=>Q(e,n),e=>G(e,t))}function H(e,t){if(!e)return e;let n=Z(t);return{...e,...e.label===void 0?{}:{label:Q(e.label,n)},ancestry:e.ancestry.map(e=>({...e,...e.label===void 0?{}:{label:Q(e.label,n)}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===void 0?{}:{label:Q(e.scrollRegion.label,n)}}}:{}}}function U(e,t){return!!(e.label!==void 0&&W(e.label,t)||e.ancestry.some(e=>e.label&&W(e.label,t))||e.scrollRegion?.label&&W(e.scrollRegion.label,t))}function W(e,t){for(let n of t.keys())if(e.includes(n))return!0;return!1}function G(e,t){for(let n of t.keys())if(q(e,n))return!0;return!1}function K(e,t,n){return!e||!t?e:{...e,...e.label===t?{label:n}:{},ancestry:e.ancestry.map(e=>({...e,...e.label===t?{label:n}:{}})),...e.scrollRegion?{scrollRegion:{...e.scrollRegion,...e.scrollRegion.label===t?{label:n}:{}}}:{}}}function q(e,n){return t(e,n)}function J(e,t,n){return Object.fromEntries(Object.entries(e).map(([e,r])=>[ae.has(e)?e:t(e),oe(r,e,t,n)]))}function oe(e,t,n,r){return typeof e==`string`&&I.has(t)?e:t===`selectorChain`&&$(e)?se(e,r):Y(e,n,r,L.has(t)?t:void 0)}function Y(e,t,n,r){if(typeof e==`string`)return r&&z.has(r)?e:t(e);if(Array.isArray(e))return e.map(e=>Y(e,t,n,r));if(!e||typeof e!=`object`)return e;let i=r?R.get(r):void 0;return Object.fromEntries(Object.entries(e).map(([e,a])=>{let o=i?.has(e)===!0;return[o?e:t(e),Y(a,t,n,o?`${r}.${e}`:void 0)]}))}function se(e,t){return e.filter(e=>!t(e))}function ce(e,t,n){if(!t)return e;let r=n?e.split(n):[e];return r.every(e=>!e.includes(t))?e:t.trim()?r.map(e=>e.replaceAll(t,n)).join(n):n}const X=/\$\{[A-Z_][A-Z0-9_]*\}/y;function Z(e){return[...e].sort(([e],[t])=>t.length-e.length)}function Q(e,t){if(!e||t.length===0)return e;let n=``,r=0;scan:for(;r<e.length;){for(let[i,a]of t)if(e.startsWith(i,r)){n+=a,r+=i.length;continue scan}if(e[r]===`$`){X.lastIndex=r;let t=X.exec(e);if(t){n+=t[0],r+=t[0].length;continue}}n+=e[r],r+=1}return n}function $(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function le(e){return $(e)?e:void 0}export{S as A,te as C,ie as D,y as E,o as M,a as N,b as O,f as S,v as T,c as _,U as a,ne as b,k as c,T as d,O as f,A as g,M as h,H as i,s as j,C as k,E as l,j as m,K as n,F as o,P as p,V as r,D as s,B as t,N as u,re as v,x as w,ee as x,_ as y};
@@ -1,2 +1,2 @@
1
- import{C as e}from"./sdk-contracts.js";import{E as t}from"./sdk-batch-runner.js";import{c as n,l as r,u as i,v as a}from"./sdk-device.js";import{nr as o}from"./sdk-batch.js";import{a as s,l as c,n as l}from"./exec.js";import"./command.js";import{t as u}from"./parser.js";import{n as d,t as f}from"./numeric.js";import{C as p,D as ee,g as m,i as te,m as h,o as g,u as _,w as ne,y as v}from"./host-file.js";import{a as y,o as b}from"./tool-provider.js";import{a as re,i as ie,t as ae}from"./physical-device-control.js";import{t as x}from"./simctl.js";import{t as oe}from"./plist.js";import S from"node:path";import{fileURLToPath as C}from"node:url";function w(e,t){for(let n of e){if(t(n))return n;let e=w(n.children,t);if(e)return e}}function T(e,t){let n=[];for(let r of e)t(r)&&n.push(r),n.push(...T(r.children,t));return n}function se(e,t){return e.children.find(e=>e.name===t)?.text??null}function E(e,t){let n=w(e,e=>e.name===`schema`&&e.attributes.name===t);return n?n.children.filter(e=>e.name===`col`).map(e=>se(e,`mnemonic`)??``):[]}function D(e){if(!e||e.children.some(e=>e.name===`sentinel`)||!e.text)return null;let t=Number(e.text);return Number.isFinite(t)?t:null}function O(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.numberValue??null:D(e):null}function ce(e){return new Map(T(e,e=>!!e.attributes.id).flatMap(e=>{let t=e.attributes.id;return t?[[t,e]]:[]}))}function k(e,t){if(e)return e.attributes.ref?t.get(e.attributes.ref):e}const A=`xctrace-animation-hitches`;function le(e){let t=ue(e.frameLifetimesXml),n=de(e.displayInfoXml),r=fe(e.hitchesXml).filter(t=>he(t,e.processIds,e.processNames)),i=r.length,a=Math.max(0,Math.round(Date.parse(e.windowEndedAt)-Date.parse(e.windowStartedAt))),s=ge(r,Date.parse(e.windowStartedAt));return{droppedFramePercent:t>0?d(i/t*100):0,droppedFrameCount:i,totalFrameCount:t,sampleWindowMs:a,windowStartedAt:e.windowStartedAt,windowEndedAt:e.windowEndedAt,measuredAt:e.measuredAt,method:A,matchedProcesses:o(r.map(e=>e.processName).filter(e=>typeof e==`string`&&e.length>0)),frameDeadlineMs:n===void 0?void 0:f(1e3/n),refreshRateHz:n,worstWindows:s.length>0?s:void 0}}function ue(e){return ve(e,`hitches-frame-lifetimes`).length}function de(e){if(!e)return;let{rows:t,schema:n}=j(e,`device-display-info`),r=n.indexOf(`max-refresh-rate`);if(r<0)return;let i=new Map;for(let e of t){M(e.children,i);let t=O(e.children[r],i);if(t!==null&&t>0)return t}}function fe(e){let t=u(e),n=pe(t);if(!n)return[];let r=new Map;return T(t,e=>e.name===`row`).map(e=>me(e,n,r)).filter(e=>!!e)}function pe(e){let t=E(e,`hitches`),n={start:t.indexOf(`start`),duration:t.indexOf(`duration`),process:t.indexOf(`process`),isSystem:t.indexOf(`is-system`)};return Object.values(n).every(e=>e>=0)?n:null}function me(e,t,n){if(M(e.children,n),ye(e.children[t.isSystem],n)===!0)return null;let r=O(e.children[t.start],n),i=O(e.children[t.duration],n);if(r===null||i===null)return null;let a=be(e.children[t.process],n);return{startNs:r,durationNs:i,pid:a?.pid,processName:a?.name}}function he(e,t,n){return e.pid!==void 0&&t.includes(e.pid)?!0:e.processName?n.includes(e.processName):!1}function ge(e,t){if(e.length===0)return[];let n=[...e].sort((e,t)=>e.startNs-t.startNs),r=[],i=[];for(let e of n){let t=i.at(-1);if(!t||e.startNs-(t.startNs+t.durationNs)<=5e8){i.push(e);continue}r.push(i),i=[e]}return i.length>0&&r.push(i),r.map(e=>_e(e,t)).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}function _e(e,t){let n=Math.min(...e.map(e=>e.startNs)),r=Math.max(...e.map(e=>e.startNs+e.durationNs)),i=Math.max(0,Math.round(n/1e6)),a=Math.max(i,Math.round(r/1e6));return{startOffsetMs:i,endOffsetMs:a,startAt:new Date(t+i).toISOString(),endAt:new Date(t+a).toISOString(),missedDeadlineFrameCount:e.length,worstFrameMs:f(Math.max(...e.map(e=>e.durationNs))/1e6)}}function ve(e,t){return j(e,t).rows}function j(e,t){let n=u(e),r=E(n,t);return{rows:r.length===0?[]:T(n,e=>e.name===`row`),schema:r}}function M(e,t){for(let n of e)M(n.children,t),n.attributes.id&&t.set(n.attributes.id,{numberValue:D(n),process:N(n)})}function ye(e,t){let n=O(e,t);return n===null?null:n!==0}function be(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.process??null:N(e):null}function N(e){if(!e||e.children.some(e=>e.name===`sentinel`))return null;let t=D(w(e.children,e=>e.name===`pid`)),n=(e.attributes.fmt??``).replace(/\s+\(\d+\)$/,``).trim();return t===null&&n.length===0?null:{pid:t??void 0,name:n.length>0?n:void 0}}const P=`ps-process-snapshot`,F=`xctrace-activity-monitor`,I=`leaks-output-graph`,L=15e3,R=12e4;async function xe(t,n){if(r(t)&&t.kind===`device`)return await Fe(t,n);let i=await G(t,n),a=await q(t,i);if(a.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{appBundleId:n,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf.`});let o=new Date().toISOString();return X({residentMemoryKb:a.reduce((e,t)=>e+t.rssKb,0),measuredAt:o,matchedProcesses:[i.executableName],memoryMethod:P})}async function Se(t,n,r){let i=B(t);if(!i.memgraph)return{available:!1,kind:`memgraph`,reason:i.reason,hint:i.hint,support:i};let a=await Ve(t,n,i);if(a.available===!1)return a;let{process:o}=a;await g(S.dirname(r));let s=await Te(r),c;try{c=await Ce(t,r,o.pid)}catch(e){throw await z(r,s),we(t,n,o,r,e)}if(c.exitCode!==0)throw await z(r,s),new e(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${n}`,l(c,{kind:`memgraph`,appBundleId:n,pid:o.pid,processName:S.basename(J(o.command)),path:r,hint:Y(t,c.stdout,c.stderr)}));let u=await _(r).catch(()=>null);if(!u?.isFile()||u.size<=0)throw await z(r,s),new e(`COMMAND_FAILED`,`Apple memgraph artifact is missing or empty`,{kind:`memgraph`,appBundleId:n,pid:o.pid,path:r,hint:`Retry with a writable --out path. If the file is still empty, run with --debug and inspect leaks output.`});return{available:!0,kind:`memgraph`,path:r,sizeBytes:u.size,measuredAt:new Date().toISOString(),method:I,appBundleId:n,pid:o.pid,processName:S.basename(J(o.command)),support:i}}async function Ce(e,t,n){return i(e)?await y(`leaks`,[`--outputGraph=${t}`,String(n)],{allowFailure:!0,timeoutMs:R}):await b(x(e,[`spawn`,e.id,`leaks`,`--outputGraph=${t}`,String(n)]),{allowFailure:!0,timeoutMs:R})}function we(t,n,r,i,a){if(a instanceof e){let o=a.details??{};return new e(a.code,`Failed to capture Apple memgraph for ${n}`,{...o,kind:`memgraph`,appBundleId:n,pid:r.pid,processName:S.basename(J(r.command)),path:i,hint:Y(t,typeof o.stdout==`string`?o.stdout:``,typeof o.stderr==`string`&&o.stderr.length>0?o.stderr:a.message)},a)}return new e(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${n}`,{kind:`memgraph`,appBundleId:n,pid:r.pid,processName:S.basename(J(r.command)),path:i,hint:`Retry perf memory snapshot. If it still fails, run with --debug and inspect leaks output.`},a)}async function Te(e){return await _(e).then(e=>e.isFile()).catch(()=>!1)}async function z(e,t){t||await p(e).catch(()=>{})}async function Ee(t,n){if(!r(t)||t.kind!==`device`)throw new e(`COMMAND_FAILED`,`Apple frame-health sampling is currently available only on connected iOS devices.`,{metric:`fps`,platform:a(t),deviceKind:t.kind});let i=await K(t,n),s=await ke(t,n,i);return le({hitchesXml:s.hitchesXml,frameLifetimesXml:s.frameLifetimesXml,displayInfoXml:s.displayInfoXml,processIds:i.map(e=>e.pid),processNames:o(i.map(e=>S.basename(C(e.executable)))),windowStartedAt:s.windowStartedAt,windowEndedAt:s.windowEndedAt,measuredAt:s.windowEndedAt})}function De(e){return r(e)&&e.kind===`device`?{method:A,description:`Rendered-frame hitch health from xctrace Animation Hitches on connected iOS devices. Dropped frames are counted from native hitch rows for the attached app process, with total frames from the same trace frame-lifetime table.`,unit:`percent`,primaryField:`droppedFramePercent`,window:`short 2s xctrace Animation Hitches record of the active app process`,resetsAfterRead:!1}:{method:A,description:`Unavailable on iOS simulators and macOS because local Apple tooling does not expose reliable app frame hitches for these targets.`,unit:`percent`,primaryField:`droppedFramePercent`}}function Oe(e){if(r(e)&&e.kind===`device`)return{method:F,description:`Resident memory snapshot from a short xctrace Activity Monitor sample on the connected iOS device.`,unit:`kB`};let t=i(e)?`host ps for the running macOS app executable resolved from the bundle ID.`:`xcrun simctl spawn ps, with host ps fallback, for the running iOS simulator app executable resolved from the bundle ID.`;return{method:P,description:`Resident memory snapshot from ${t}`,unit:`kB`}}function B(e){return r(e)&&e.kind===`device`?{platform:a(e),deviceKind:e.kind,memgraph:!1,method:I,reason:`Physical iOS device memgraph capture is not exposed through reliable local agent-device tooling.`,hint:`Use perf memory sample for a compact resident-memory reading, or reproduce on an iOS simulator/macOS target for memgraph capture.`}:r(e)&&e.kind===`simulator`?{platform:a(e),deviceKind:e.kind,memgraph:!0,method:I,reason:`iOS simulator processes are host-visible through simctl spawn leaks.`,hint:`Keep the simulator app running in the foreground while the memgraph is captured.`}:i(e)?{platform:a(e),deviceKind:e.kind,memgraph:!0,method:I,reason:`macOS app processes are host-visible to leaks --outputGraph.`,hint:`Grant Terminal/agent process permissions if macOS denies process inspection.`}:{platform:a(e),deviceKind:e.kind,memgraph:!1,method:I,reason:`Apple memgraph capture is available only for iOS simulator and macOS app sessions.`,hint:`Use perf memory sample on supported app sessions, or rerun against iOS simulator/macOS for memgraph capture.`}}async function ke(e,t,n){let r=await h(`agent-device-ios-frame-perf-`),i=S.join(r,`animation-hitches.trace`),a=S.join(r,`hitches.xml`),o=S.join(r,`frame-lifetimes.xml`),s=S.join(r,`display-info.xml`);try{let r=await V({device:e,appBundleId:t,tracePath:i,template:`Animation Hitches`,duration:`2s`,targetPids:n.map(e=>e.pid),validateTraceOutput:!0,failureMessage:`Failed to record iOS frame-health sample for ${t}`});await W(e,t,i,`hitches`,a),await W(e,t,i,`hitches-frame-lifetimes`,o);let c=await Me(e,t,i,`device-display-info`,s);return{windowStartedAt:r.startedAt,windowEndedAt:r.endedAt,hitchesXml:await v(a),frameLifetimesXml:await v(o),displayInfoXml:c?await v(s):void 0}}finally{await p(r).catch(()=>{})}}async function V(t){let{device:n,appBundleId:r,tracePath:i,template:a,duration:o}=t,s=t.allProcesses?[`--all-processes`]:(t.targetPids??[]).flatMap(e=>[`--attach`,String(e)]),c=[`xctrace`,`record`,`--template`,a,`--device`,n.id,...s,`--time-limit`,o,`--output`,i,`--quiet`,`--no-prompt`],u=await Ae(c,t.tracePath);if(u.result.exitCode===0)return t.validateTraceOutput&&await je(t,u.result.stdout,u.result.stderr),{startedAt:u.startedAt,endedAt:u.endedAt,capturedAtMs:u.capturedAtMs};throw new e(`COMMAND_FAILED`,t.failureMessage,l(u.result,{cmd:`xcrun`,args:c,appBundleId:r,deviceId:n.id,hint:Q(u.result.stdout,u.result.stderr)}))}async function Ae(e,t){let n;for(let r=1;r<=3;r+=1){await U(t,r,1500);let i=new Date().toISOString(),a=await b(e,{allowFailure:!0,timeoutMs:6e4});if(n={result:a,startedAt:i,endedAt:new Date().toISOString(),capturedAtMs:Date.now()},a.exitCode===0||!H(a))return n}return n}function H(e){let t=`${e.stdout}\n${e.stderr}`.toLowerCase();return t.includes(`_lockkperf`)||t.includes(`could not lock kperf`)||t.includes(`likely another session just started`)}async function U(e,t,n){t<=1||(await p(e).catch(()=>{}),await new Promise(e=>setTimeout(e,n)))}async function je(t,n,r){let i=await _(t.tracePath).catch(()=>null);if(!(i?.isDirectory()===!0?(await m(t.tracePath).catch(()=>[])).length>0:(i?.size??0)>0))throw new e(`COMMAND_FAILED`,`${t.failureMessage}: xctrace produced no trace data`,{tracePath:t.tracePath,appBundleId:t.appBundleId,deviceId:t.device.id,stdout:n,stderr:r,hint:`Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.`})}async function W(e,t,n,r,i){let a=[`xctrace`,`export`,`--input`,n,`--xpath`,`/trace-toc/run/data/table[@schema="${r}"]`,`--output`,i];s(await b(a,{allowFailure:!0,timeoutMs:15e3}),`Failed to export iOS device ${r} data`,n=>({cmd:`xcrun`,args:a,appBundleId:t,deviceId:e.id,hint:Q(n.stdout,n.stderr)}))}async function Me(e,t,n,r,i){try{return await W(e,t,n,r,i),!0}catch{return!1}}function Ne(e){let n=[];for(let r of t(e)){let e=r.match(/^(\d+)\s+([0-9]+(?:\.[0-9]+)?)\s+(\d+)\s+(.+)$/);if(!e)continue;let[t,i,a,o]=e.slice(1);if(t===void 0||i===void 0||a===void 0||o===void 0)continue;let s=Number(t),c=Number(i),l=Number(a),u=o.trim();!Number.isFinite(s)||!Number.isFinite(c)||!Number.isFinite(l)||n.push({pid:s,cpuPercent:c,rssKb:l,command:u})}return n}async function Pe(t){let n=u(t),r=E(n,`activity-monitor-process-live`);if(r.length===0)throw new e(`COMMAND_FAILED`,`Failed to parse xctrace activity-monitor-process-live schema`);let i=r.indexOf(`pid`),a=r.indexOf(`process`),o=r.indexOf(`memory-real`);if(i<0||a<0||o<0)throw new e(`COMMAND_FAILED`,`xctrace activity-monitor-process-live export is missing expected columns`);let s=T(n,e=>e.name===`row`),c=[],l=new Map;for(let e of s){let t=e.children;if(t.length===0)continue;for(let e of t){let t=w(e.children,e=>e.name===`pid`&&typeof e.attributes.id==`string`);if(t?.attributes.id){let e=Number(t.text);l.set(t.attributes.id,{numberValue:Number.isFinite(e)?e:null})}e.attributes.id&&l.set(e.attributes.id,{numberValue:D(e),processName:Z(e)})}let n=O(t[i],l),r=We(t[a],l);n===null||!Number.isFinite(n)||!r||c.push({pid:n,processName:r,residentMemoryBytes:O(t[o],l)})}return c}async function G(t,n){let r=i(t)?await Re(n):await ze(t,n),a=i(t)?S.join(r,`Contents`,`Info.plist`):S.join(r,`Info.plist`),o=await oe(a,`CFBundleExecutable`);if(!o)throw new e(`COMMAND_FAILED`,`Failed to resolve executable for ${n}`,{appBundleId:n,appPath:r});return{executableName:o,executablePath:i(t)?S.join(r,`Contents`,`MacOS`,o):S.join(r,o)}}async function Fe(t,n){let r=await K(t,n),i=await Ie(t,n),a=Le(await Pe(i.xml),r,n,t);if(a.residentMemoryBytes===null)throw new e(`COMMAND_FAILED`,`Incomplete Activity Monitor sample for ${n}`,{appBundleId:n,deviceId:t.id,hint:`Keep the app running in the foreground while perf samples the device, then retry.`});return X({residentMemoryKb:a.residentMemoryBytes/1024,measuredAt:new Date(i.capturedAtMs).toISOString(),matchedProcesses:a.matchedProcesses,memoryMethod:F})}async function K(t,n){let{appBundleUrl:r,processes:i}=await ae(t).resolveAppProcesses(t,n),a=C(r);if(i.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{appBundleId:n,deviceId:t.id,appBundlePath:a,hint:`Run open <app> for this session again to ensure the iOS app is active, then retry perf.`});return i}async function Ie(e,t){let n=await h(`agent-device-ios-perf-`),r=S.join(n,`sample.trace`),i=S.join(n,`activity-monitor-process-live.xml`);try{let n=await V({device:e,appBundleId:t,tracePath:r,template:`Activity Monitor`,duration:`1s`,allProcesses:!0,failureMessage:`Failed to record iOS device Activity Monitor sample for ${t}`});return await W(e,t,r,`activity-monitor-process-live`,i),{capturedAtMs:n.capturedAtMs,xml:await v(i)}}finally{await p(n).catch(()=>{})}}function Le(t,n,r,i){let a=new Set(n.map(e=>e.pid)),s=new Set(n.map(e=>S.basename(C(e.executable)))),c=t.filter(e=>a.has(e.pid)||s.has(e.processName));if(c.length===0)throw new e(`COMMAND_FAILED`,`No Activity Monitor sample found for ${r}`,{appBundleId:r,deviceId:i.id,hint:`Keep the app running in the foreground while perf samples the device, then retry.`});let l=new Map;for(let e of c){let t=l.get(e.pid);if(!t){l.set(e.pid,e);continue}l.set(e.pid,{pid:e.pid,processName:e.processName||t.processName,residentMemoryBytes:Ge(t.residentMemoryBytes,e.residentMemoryBytes)})}let u=[...l.values()],d=u.map(e=>e.residentMemoryBytes).filter(e=>e!==null);return{residentMemoryBytes:d.length>0?d.reduce((e,t)=>e+t,0):null,matchedProcesses:o(u.map(e=>e.processName))}}async function Re(t){let n=`kMDItemCFBundleIdentifier == "${t.replaceAll(`"`,String.raw`\"`)}"`,r=s(await y(`mdfind`,[n],{allowFailure:!0,timeoutMs:L}),`Failed to resolve macOS app bundle for ${t}`,{appBundleId:t}).stdout.split(`
1
+ import{C as e}from"./sdk-contracts.js";import{E as t}from"./sdk-batch-runner.js";import{c as n,l as r,u as i,v as a}from"./sdk-device.js";import{rr as o}from"./sdk-batch.js";import{a as s,l as c,n as l}from"./exec.js";import"./command.js";import{t as u}from"./parser.js";import{n as d,t as f}from"./numeric.js";import{C as p,D as ee,g as m,i as te,m as h,o as g,u as _,w as ne,y as v}from"./host-file.js";import{a as y,o as b}from"./tool-provider.js";import{a as re,i as ie,t as ae}from"./physical-device-control.js";import{t as x}from"./simctl.js";import{t as oe}from"./plist.js";import S from"node:path";import{fileURLToPath as C}from"node:url";function w(e,t){for(let n of e){if(t(n))return n;let e=w(n.children,t);if(e)return e}}function T(e,t){let n=[];for(let r of e)t(r)&&n.push(r),n.push(...T(r.children,t));return n}function se(e,t){return e.children.find(e=>e.name===t)?.text??null}function E(e,t){let n=w(e,e=>e.name===`schema`&&e.attributes.name===t);return n?n.children.filter(e=>e.name===`col`).map(e=>se(e,`mnemonic`)??``):[]}function D(e){if(!e||e.children.some(e=>e.name===`sentinel`)||!e.text)return null;let t=Number(e.text);return Number.isFinite(t)?t:null}function O(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.numberValue??null:D(e):null}function ce(e){return new Map(T(e,e=>!!e.attributes.id).flatMap(e=>{let t=e.attributes.id;return t?[[t,e]]:[]}))}function k(e,t){if(e)return e.attributes.ref?t.get(e.attributes.ref):e}const A=`xctrace-animation-hitches`;function le(e){let t=ue(e.frameLifetimesXml),n=de(e.displayInfoXml),r=fe(e.hitchesXml).filter(t=>he(t,e.processIds,e.processNames)),i=r.length,a=Math.max(0,Math.round(Date.parse(e.windowEndedAt)-Date.parse(e.windowStartedAt))),s=ge(r,Date.parse(e.windowStartedAt));return{droppedFramePercent:t>0?d(i/t*100):0,droppedFrameCount:i,totalFrameCount:t,sampleWindowMs:a,windowStartedAt:e.windowStartedAt,windowEndedAt:e.windowEndedAt,measuredAt:e.measuredAt,method:A,matchedProcesses:o(r.map(e=>e.processName).filter(e=>typeof e==`string`&&e.length>0)),frameDeadlineMs:n===void 0?void 0:f(1e3/n),refreshRateHz:n,worstWindows:s.length>0?s:void 0}}function ue(e){return ve(e,`hitches-frame-lifetimes`).length}function de(e){if(!e)return;let{rows:t,schema:n}=j(e,`device-display-info`),r=n.indexOf(`max-refresh-rate`);if(r<0)return;let i=new Map;for(let e of t){M(e.children,i);let t=O(e.children[r],i);if(t!==null&&t>0)return t}}function fe(e){let t=u(e),n=pe(t);if(!n)return[];let r=new Map;return T(t,e=>e.name===`row`).map(e=>me(e,n,r)).filter(e=>!!e)}function pe(e){let t=E(e,`hitches`),n={start:t.indexOf(`start`),duration:t.indexOf(`duration`),process:t.indexOf(`process`),isSystem:t.indexOf(`is-system`)};return Object.values(n).every(e=>e>=0)?n:null}function me(e,t,n){if(M(e.children,n),ye(e.children[t.isSystem],n)===!0)return null;let r=O(e.children[t.start],n),i=O(e.children[t.duration],n);if(r===null||i===null)return null;let a=be(e.children[t.process],n);return{startNs:r,durationNs:i,pid:a?.pid,processName:a?.name}}function he(e,t,n){return e.pid!==void 0&&t.includes(e.pid)?!0:e.processName?n.includes(e.processName):!1}function ge(e,t){if(e.length===0)return[];let n=[...e].sort((e,t)=>e.startNs-t.startNs),r=[],i=[];for(let e of n){let t=i.at(-1);if(!t||e.startNs-(t.startNs+t.durationNs)<=5e8){i.push(e);continue}r.push(i),i=[e]}return i.length>0&&r.push(i),r.map(e=>_e(e,t)).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}function _e(e,t){let n=Math.min(...e.map(e=>e.startNs)),r=Math.max(...e.map(e=>e.startNs+e.durationNs)),i=Math.max(0,Math.round(n/1e6)),a=Math.max(i,Math.round(r/1e6));return{startOffsetMs:i,endOffsetMs:a,startAt:new Date(t+i).toISOString(),endAt:new Date(t+a).toISOString(),missedDeadlineFrameCount:e.length,worstFrameMs:f(Math.max(...e.map(e=>e.durationNs))/1e6)}}function ve(e,t){return j(e,t).rows}function j(e,t){let n=u(e),r=E(n,t);return{rows:r.length===0?[]:T(n,e=>e.name===`row`),schema:r}}function M(e,t){for(let n of e)M(n.children,t),n.attributes.id&&t.set(n.attributes.id,{numberValue:D(n),process:N(n)})}function ye(e,t){let n=O(e,t);return n===null?null:n!==0}function be(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.process??null:N(e):null}function N(e){if(!e||e.children.some(e=>e.name===`sentinel`))return null;let t=D(w(e.children,e=>e.name===`pid`)),n=(e.attributes.fmt??``).replace(/\s+\(\d+\)$/,``).trim();return t===null&&n.length===0?null:{pid:t??void 0,name:n.length>0?n:void 0}}const P=`ps-process-snapshot`,F=`xctrace-activity-monitor`,I=`leaks-output-graph`,L=15e3,R=12e4;async function xe(t,n){if(r(t)&&t.kind===`device`)return await Fe(t,n);let i=await G(t,n),a=await q(t,i);if(a.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{appBundleId:n,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf.`});let o=new Date().toISOString();return X({residentMemoryKb:a.reduce((e,t)=>e+t.rssKb,0),measuredAt:o,matchedProcesses:[i.executableName],memoryMethod:P})}async function Se(t,n,r){let i=B(t);if(!i.memgraph)return{available:!1,kind:`memgraph`,reason:i.reason,hint:i.hint,support:i};let a=await Ve(t,n,i);if(a.available===!1)return a;let{process:o}=a;await g(S.dirname(r));let s=await Te(r),c;try{c=await Ce(t,r,o.pid)}catch(e){throw await z(r,s),we(t,n,o,r,e)}if(c.exitCode!==0)throw await z(r,s),new e(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${n}`,l(c,{kind:`memgraph`,appBundleId:n,pid:o.pid,processName:S.basename(J(o.command)),path:r,hint:Y(t,c.stdout,c.stderr)}));let u=await _(r).catch(()=>null);if(!u?.isFile()||u.size<=0)throw await z(r,s),new e(`COMMAND_FAILED`,`Apple memgraph artifact is missing or empty`,{kind:`memgraph`,appBundleId:n,pid:o.pid,path:r,hint:`Retry with a writable --out path. If the file is still empty, run with --debug and inspect leaks output.`});return{available:!0,kind:`memgraph`,path:r,sizeBytes:u.size,measuredAt:new Date().toISOString(),method:I,appBundleId:n,pid:o.pid,processName:S.basename(J(o.command)),support:i}}async function Ce(e,t,n){return i(e)?await y(`leaks`,[`--outputGraph=${t}`,String(n)],{allowFailure:!0,timeoutMs:R}):await b(x(e,[`spawn`,e.id,`leaks`,`--outputGraph=${t}`,String(n)]),{allowFailure:!0,timeoutMs:R})}function we(t,n,r,i,a){if(a instanceof e){let o=a.details??{};return new e(a.code,`Failed to capture Apple memgraph for ${n}`,{...o,kind:`memgraph`,appBundleId:n,pid:r.pid,processName:S.basename(J(r.command)),path:i,hint:Y(t,typeof o.stdout==`string`?o.stdout:``,typeof o.stderr==`string`&&o.stderr.length>0?o.stderr:a.message)},a)}return new e(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${n}`,{kind:`memgraph`,appBundleId:n,pid:r.pid,processName:S.basename(J(r.command)),path:i,hint:`Retry perf memory snapshot. If it still fails, run with --debug and inspect leaks output.`},a)}async function Te(e){return await _(e).then(e=>e.isFile()).catch(()=>!1)}async function z(e,t){t||await p(e).catch(()=>{})}async function Ee(t,n){if(!r(t)||t.kind!==`device`)throw new e(`COMMAND_FAILED`,`Apple frame-health sampling is currently available only on connected iOS devices.`,{metric:`fps`,platform:a(t),deviceKind:t.kind});let i=await K(t,n),s=await ke(t,n,i);return le({hitchesXml:s.hitchesXml,frameLifetimesXml:s.frameLifetimesXml,displayInfoXml:s.displayInfoXml,processIds:i.map(e=>e.pid),processNames:o(i.map(e=>S.basename(C(e.executable)))),windowStartedAt:s.windowStartedAt,windowEndedAt:s.windowEndedAt,measuredAt:s.windowEndedAt})}function De(e){return r(e)&&e.kind===`device`?{method:A,description:`Rendered-frame hitch health from xctrace Animation Hitches on connected iOS devices. Dropped frames are counted from native hitch rows for the attached app process, with total frames from the same trace frame-lifetime table.`,unit:`percent`,primaryField:`droppedFramePercent`,window:`short 2s xctrace Animation Hitches record of the active app process`,resetsAfterRead:!1}:{method:A,description:`Unavailable on iOS simulators and macOS because local Apple tooling does not expose reliable app frame hitches for these targets.`,unit:`percent`,primaryField:`droppedFramePercent`}}function Oe(e){if(r(e)&&e.kind===`device`)return{method:F,description:`Resident memory snapshot from a short xctrace Activity Monitor sample on the connected iOS device.`,unit:`kB`};let t=i(e)?`host ps for the running macOS app executable resolved from the bundle ID.`:`xcrun simctl spawn ps, with host ps fallback, for the running iOS simulator app executable resolved from the bundle ID.`;return{method:P,description:`Resident memory snapshot from ${t}`,unit:`kB`}}function B(e){return r(e)&&e.kind===`device`?{platform:a(e),deviceKind:e.kind,memgraph:!1,method:I,reason:`Physical iOS device memgraph capture is not exposed through reliable local agent-device tooling.`,hint:`Use perf memory sample for a compact resident-memory reading, or reproduce on an iOS simulator/macOS target for memgraph capture.`}:r(e)&&e.kind===`simulator`?{platform:a(e),deviceKind:e.kind,memgraph:!0,method:I,reason:`iOS simulator processes are host-visible through simctl spawn leaks.`,hint:`Keep the simulator app running in the foreground while the memgraph is captured.`}:i(e)?{platform:a(e),deviceKind:e.kind,memgraph:!0,method:I,reason:`macOS app processes are host-visible to leaks --outputGraph.`,hint:`Grant Terminal/agent process permissions if macOS denies process inspection.`}:{platform:a(e),deviceKind:e.kind,memgraph:!1,method:I,reason:`Apple memgraph capture is available only for iOS simulator and macOS app sessions.`,hint:`Use perf memory sample on supported app sessions, or rerun against iOS simulator/macOS for memgraph capture.`}}async function ke(e,t,n){let r=await h(`agent-device-ios-frame-perf-`),i=S.join(r,`animation-hitches.trace`),a=S.join(r,`hitches.xml`),o=S.join(r,`frame-lifetimes.xml`),s=S.join(r,`display-info.xml`);try{let r=await V({device:e,appBundleId:t,tracePath:i,template:`Animation Hitches`,duration:`2s`,targetPids:n.map(e=>e.pid),validateTraceOutput:!0,failureMessage:`Failed to record iOS frame-health sample for ${t}`});await W(e,t,i,`hitches`,a),await W(e,t,i,`hitches-frame-lifetimes`,o);let c=await Me(e,t,i,`device-display-info`,s);return{windowStartedAt:r.startedAt,windowEndedAt:r.endedAt,hitchesXml:await v(a),frameLifetimesXml:await v(o),displayInfoXml:c?await v(s):void 0}}finally{await p(r).catch(()=>{})}}async function V(t){let{device:n,appBundleId:r,tracePath:i,template:a,duration:o}=t,s=t.allProcesses?[`--all-processes`]:(t.targetPids??[]).flatMap(e=>[`--attach`,String(e)]),c=[`xctrace`,`record`,`--template`,a,`--device`,n.id,...s,`--time-limit`,o,`--output`,i,`--quiet`,`--no-prompt`],u=await Ae(c,t.tracePath);if(u.result.exitCode===0)return t.validateTraceOutput&&await je(t,u.result.stdout,u.result.stderr),{startedAt:u.startedAt,endedAt:u.endedAt,capturedAtMs:u.capturedAtMs};throw new e(`COMMAND_FAILED`,t.failureMessage,l(u.result,{cmd:`xcrun`,args:c,appBundleId:r,deviceId:n.id,hint:Q(u.result.stdout,u.result.stderr)}))}async function Ae(e,t){let n;for(let r=1;r<=3;r+=1){await U(t,r,1500);let i=new Date().toISOString(),a=await b(e,{allowFailure:!0,timeoutMs:6e4});if(n={result:a,startedAt:i,endedAt:new Date().toISOString(),capturedAtMs:Date.now()},a.exitCode===0||!H(a))return n}return n}function H(e){let t=`${e.stdout}\n${e.stderr}`.toLowerCase();return t.includes(`_lockkperf`)||t.includes(`could not lock kperf`)||t.includes(`likely another session just started`)}async function U(e,t,n){t<=1||(await p(e).catch(()=>{}),await new Promise(e=>setTimeout(e,n)))}async function je(t,n,r){let i=await _(t.tracePath).catch(()=>null);if(!(i?.isDirectory()===!0?(await m(t.tracePath).catch(()=>[])).length>0:(i?.size??0)>0))throw new e(`COMMAND_FAILED`,`${t.failureMessage}: xctrace produced no trace data`,{tracePath:t.tracePath,appBundleId:t.appBundleId,deviceId:t.device.id,stdout:n,stderr:r,hint:`Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.`})}async function W(e,t,n,r,i){let a=[`xctrace`,`export`,`--input`,n,`--xpath`,`/trace-toc/run/data/table[@schema="${r}"]`,`--output`,i];s(await b(a,{allowFailure:!0,timeoutMs:15e3}),`Failed to export iOS device ${r} data`,n=>({cmd:`xcrun`,args:a,appBundleId:t,deviceId:e.id,hint:Q(n.stdout,n.stderr)}))}async function Me(e,t,n,r,i){try{return await W(e,t,n,r,i),!0}catch{return!1}}function Ne(e){let n=[];for(let r of t(e)){let e=r.match(/^(\d+)\s+([0-9]+(?:\.[0-9]+)?)\s+(\d+)\s+(.+)$/);if(!e)continue;let[t,i,a,o]=e.slice(1);if(t===void 0||i===void 0||a===void 0||o===void 0)continue;let s=Number(t),c=Number(i),l=Number(a),u=o.trim();!Number.isFinite(s)||!Number.isFinite(c)||!Number.isFinite(l)||n.push({pid:s,cpuPercent:c,rssKb:l,command:u})}return n}async function Pe(t){let n=u(t),r=E(n,`activity-monitor-process-live`);if(r.length===0)throw new e(`COMMAND_FAILED`,`Failed to parse xctrace activity-monitor-process-live schema`);let i=r.indexOf(`pid`),a=r.indexOf(`process`),o=r.indexOf(`memory-real`);if(i<0||a<0||o<0)throw new e(`COMMAND_FAILED`,`xctrace activity-monitor-process-live export is missing expected columns`);let s=T(n,e=>e.name===`row`),c=[],l=new Map;for(let e of s){let t=e.children;if(t.length===0)continue;for(let e of t){let t=w(e.children,e=>e.name===`pid`&&typeof e.attributes.id==`string`);if(t?.attributes.id){let e=Number(t.text);l.set(t.attributes.id,{numberValue:Number.isFinite(e)?e:null})}e.attributes.id&&l.set(e.attributes.id,{numberValue:D(e),processName:Z(e)})}let n=O(t[i],l),r=We(t[a],l);n===null||!Number.isFinite(n)||!r||c.push({pid:n,processName:r,residentMemoryBytes:O(t[o],l)})}return c}async function G(t,n){let r=i(t)?await Re(n):await ze(t,n),a=i(t)?S.join(r,`Contents`,`Info.plist`):S.join(r,`Info.plist`),o=await oe(a,`CFBundleExecutable`);if(!o)throw new e(`COMMAND_FAILED`,`Failed to resolve executable for ${n}`,{appBundleId:n,appPath:r});return{executableName:o,executablePath:i(t)?S.join(r,`Contents`,`MacOS`,o):S.join(r,o)}}async function Fe(t,n){let r=await K(t,n),i=await Ie(t,n),a=Le(await Pe(i.xml),r,n,t);if(a.residentMemoryBytes===null)throw new e(`COMMAND_FAILED`,`Incomplete Activity Monitor sample for ${n}`,{appBundleId:n,deviceId:t.id,hint:`Keep the app running in the foreground while perf samples the device, then retry.`});return X({residentMemoryKb:a.residentMemoryBytes/1024,measuredAt:new Date(i.capturedAtMs).toISOString(),matchedProcesses:a.matchedProcesses,memoryMethod:F})}async function K(t,n){let{appBundleUrl:r,processes:i}=await ae(t).resolveAppProcesses(t,n),a=C(r);if(i.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{appBundleId:n,deviceId:t.id,appBundlePath:a,hint:`Run open <app> for this session again to ensure the iOS app is active, then retry perf.`});return i}async function Ie(e,t){let n=await h(`agent-device-ios-perf-`),r=S.join(n,`sample.trace`),i=S.join(n,`activity-monitor-process-live.xml`);try{let n=await V({device:e,appBundleId:t,tracePath:r,template:`Activity Monitor`,duration:`1s`,allProcesses:!0,failureMessage:`Failed to record iOS device Activity Monitor sample for ${t}`});return await W(e,t,r,`activity-monitor-process-live`,i),{capturedAtMs:n.capturedAtMs,xml:await v(i)}}finally{await p(n).catch(()=>{})}}function Le(t,n,r,i){let a=new Set(n.map(e=>e.pid)),s=new Set(n.map(e=>S.basename(C(e.executable)))),c=t.filter(e=>a.has(e.pid)||s.has(e.processName));if(c.length===0)throw new e(`COMMAND_FAILED`,`No Activity Monitor sample found for ${r}`,{appBundleId:r,deviceId:i.id,hint:`Keep the app running in the foreground while perf samples the device, then retry.`});let l=new Map;for(let e of c){let t=l.get(e.pid);if(!t){l.set(e.pid,e);continue}l.set(e.pid,{pid:e.pid,processName:e.processName||t.processName,residentMemoryBytes:Ge(t.residentMemoryBytes,e.residentMemoryBytes)})}let u=[...l.values()],d=u.map(e=>e.residentMemoryBytes).filter(e=>e!==null);return{residentMemoryBytes:d.length>0?d.reduce((e,t)=>e+t,0):null,matchedProcesses:o(u.map(e=>e.processName))}}async function Re(t){let n=`kMDItemCFBundleIdentifier == "${t.replaceAll(`"`,String.raw`\"`)}"`,r=s(await y(`mdfind`,[n],{allowFailure:!0,timeoutMs:L}),`Failed to resolve macOS app bundle for ${t}`,{appBundleId:t}).stdout.split(`
2
2
  `).map(e=>e.trim()).find(e=>e.endsWith(`.app`));if(!r)throw new e(`APP_NOT_INSTALLED`,`No macOS app found for ${t}`,{appBundleId:t});return r}async function ze(t,n){let r=x(t,[`get_app_container`,t.id,n,`app`]),i=s(await b(r,{allowFailure:!0,timeoutMs:L}),`Failed to resolve iOS simulator app container for ${n}`,{appBundleId:n,hint:`Ensure the iOS simulator app is installed and booted, then retry perf.`}).stdout.trim();if(i.length===0)throw new e(`APP_NOT_INSTALLED`,`No iOS simulator app container found for ${n}`,{appBundleId:n});return i}async function q(e,t){let n=i(e)?[`-axo`,`pid=,%cpu=,rss=,command=`]:x(e,[`spawn`,e.id,`ps`,`-axo`,`pid=,%cpu=,rss=,command=`]),r=i(e)?await y(`ps`,n,{timeoutMs:L}):await Ue(n),{matchesAppleExecutableProcess:a}=await import(`./perf-process-identity.js`);return Ne(r.stdout).filter(e=>a(e.command,t))}function J(e){let[t=``]=e.trim().split(/\s+/,1);return t}async function Be(t,n,r){let i=(await q(t,r)).sort((e,t)=>t.rssKb-e.rssKb)[0];if(i)return i;throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{kind:`memgraph`,appBundleId:n,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf memory snapshot.`})}async function Ve(e,t,n){try{return{available:!0,process:await Be(e,t,await G(e,t))}}catch(t){if(He(e,t))return{available:!1,kind:`memgraph`,reason:`iOS simulator memgraph capture needs process tools inside simctl spawn, but this simulator runtime did not provide ps.`,hint:`Use perf memory sample when available, or retry memgraph on a simulator runtime that includes process tools such as ps and leaks.`,support:{...n,memgraph:!1}};throw t}}function He(t,n){if(!r(t)||t.kind!==`simulator`||!(n instanceof e))return!1;let i=n.details??{},a=Array.isArray(i.args)?i.args.join(` `):``,o=typeof i.stderr==`string`?i.stderr:``,s=`${n.message}\n${o}`.toLowerCase();return a.includes(`simctl spawn`)&&a.includes(` ps `)&&s.includes(`no such file`)}function Y(e,t,n){let r=`${t}\n${n}`.toLowerCase();return r.includes(`timed out`)||r.includes(`timeout`)?`Apple memgraph capture can take longer than metric sampling. Keep the app running and retry; if it times out again, collect a smaller reproduction before capturing leaks --outputGraph.`:r.includes(`not found`)||r.includes(`no such file`)?`Install Xcode command line tools and ensure leaks is available, then retry.`:r.includes(`permission`)||r.includes(`denied`)||r.includes(`not authorized`)?i(e)?`Grant the agent terminal process permission to inspect this macOS app, then retry.`:`Keep the simulator booted and app running; if inspection is denied, retry with a debug simulator build.`:`Keep the app process running and retry perf memory snapshot with --debug if the failure persists.`}async function Ue(e){let t=await b(e,{allowFailure:!0,timeoutMs:L});return t.exitCode===0?t:await y(`ps`,[`-axo`,`pid=,%cpu=,rss=,command=`],{timeoutMs:L})}function X(e){return{residentMemoryKb:Math.round(e.residentMemoryKb),measuredAt:e.measuredAt,method:e.memoryMethod,matchedProcesses:e.matchedProcesses}}function Z(e){let t=e?.attributes.fmt?.trim()??``;return t?t.replace(/\s+\(\d+\)$/,``).trim():null}function We(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.processName??null:Z(e):null}function Q(e,t){let n=re(e,t);if(n)return n;let r=`${e}\n${t}`.toLowerCase();return r.includes(`no device matched`)||r.includes(`failed to find device`)?ie:r.includes(`timed out`)?`Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.`:`Ensure the iOS device is unlocked, trusted, visible to xctrace, and the target app stays active while perf samples it.`}function Ge(e,t){return e===null?t:t===null?e:Math.max(e,t)}function Ke(e,t=10){let n=u(e),r=ce(n),i=new Map,a=0,o=0;for(let e of T(n,e=>e.name===`row`)){let t=qe(e,r),n=Je(e,r);if(t===void 0||!n)continue;let s=n.attributes.name?.trim()||`<unknown>`,c=Ye(n,r),l=`${c??``}\u0000${s}`,u=i.get(l);i.set(l,{symbol:s,binary:c,weightNs:(u?.weightNs??0)+t}),a+=1,o+=t}let s=Math.max(0,Math.floor(t)),c=[...i.values()].sort((e,t)=>t.weightNs-e.weightNs||e.symbol.localeCompare(t.symbol)).slice(0,s).map(({symbol:e,binary:t,weightNs:n})=>({symbol:e,binary:t,selfSampleMs:$(n),selfSamplePercent:o>0?d(n/o*100):0}));return{sampleCount:a,totalSampleWeightMs:$(o),topFunctions:c}}function qe(e,t){let n=k(e.children.find(e=>e.name===`weight`),t);if(!n?.text)return;let r=Number(n.text);return Number.isFinite(r)&&r>0?r:void 0}function Je(e,t){return k(k(e.children.find(e=>e.name===`backtrace`),t)?.children.find(e=>e.name===`frame`),t)}function Ye(e,t){return k(e.children.find(e=>e.name===`binary`),t)?.attributes.name?.trim()||void 0}function $(e){return Math.round(e/1e6*1e3)/1e3}const Xe=15e3;async function Ze(e){let t=await nt(e.device,e.appBundleId);await g(S.dirname(e.outPath));let n=rt({device:e.device,template:e.template,targetPids:t.pids,outPath:e.outPath}),r=new Date().toISOString(),i=await it(n,e.outPath,{device:e.device,appBundleId:e.appBundleId,failureMessage:`Failed to start Apple xctrace ${e.mode} capture for ${e.appBundleId}`});return{kind:`xctrace`,mode:e.mode,template:e.template,outPath:e.outPath,appBundleId:e.appBundleId,deviceId:e.device.id,platform:a(e.device),targetPids:t.pids,targetProcesses:t.processNames,startedAt:r,child:i.child,wait:i.wait}}async function Qe(e,t=e.outPath){t!==e.outPath&&await g(S.dirname(t));let n=s(await ot(e,{failOnForcedKill:!0}),`Failed to stop Apple xctrace ${e.mode} capture`,t=>({tracePath:e.outPath,captureCleanedUp:!0,hint:Q(t.stdout,t.stderr)}));return t!==e.outPath&&await ne(e.outPath,t).catch(async()=>{await te(e.outPath,t),await p(e.outPath)}),await ct(t,{appBundleId:e.appBundleId,deviceId:e.deviceId,stdout:n.stdout,stderr:n.stderr}),{kind:`xctrace`,mode:e.mode,template:e.template,outPath:t,appBundleId:e.appBundleId,deviceId:e.deviceId,platform:e.platform,targetPids:e.targetPids,targetProcesses:e.targetProcesses,startedAt:e.startedAt,endedAt:new Date().toISOString()}}async function $e(e){return await ot(e,{failOnForcedKill:!1})}async function et(t){let n=await h(`agent-device-xctrace-report-`),r=S.join(n,`trace-toc.xml`),i=S.join(n,`time-profile.xml`);try{let n=[`xctrace`,`export`,`--input`,t.tracePath,`--toc`,`--output`,r];s(await b(n,{allowFailure:!0,timeoutMs:Xe}),`Failed to export Apple xctrace report metadata`,e=>({cmd:`xcrun`,args:n,tracePath:t.tracePath,hint:Q(e.stdout,e.stderr)}));let a=await v(r),o=await tt(t.tracePath,i),c=lt({...t,tocXml:a,timeProfileXml:o});if(c.summary.sampleCount===0)throw new e(`COMMAND_FAILED`,`Apple xctrace CPU report contained no samples`,{tracePath:t.tracePath,tableSchemas:c.summary.tableSchemas,hint:`Keep the app active while recording, then retry. Open the raw trace in Instruments if it still contains no Time Profiler samples.`});return await g(S.dirname(t.outPath)),await ee(t.outPath,`${JSON.stringify(c,null,2)}\n`),c}finally{await p(n).catch(()=>{})}}async function tt(e,t){let n=[`xctrace`,`export`,`--input`,e,`--xpath`,`/trace-toc/run/data/table[@schema="time-profile"]`,`--output`,t];return s(await b(n,{allowFailure:!0,timeoutMs:Xe}),`Failed to export Apple xctrace Time Profiler samples`,t=>({cmd:`xcrun`,args:n,tracePath:e,hint:Q(t.stdout,t.stderr)})),await v(t)}async function nt(t,i){if(!n(t.platform))throw new e(`UNSUPPORTED_OPERATION`,`Apple xctrace perf is not supported on Android.`,{platform:t.platform,hint:`Android native profiling belongs to the Android perf rollout and is not implemented under Apple xctrace.`});if(r(t)&&t.kind===`device`){let e=await K(t,i);return{pids:e.map(e=>e.pid),processNames:o(e.map(e=>S.basename(C(e.executable))))}}let a=await G(t,i),s=await q(t,a);if(s.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${i}`,{appBundleId:i,deviceId:t.id,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf.`});return{pids:s.map(e=>e.pid),processNames:[a.executableName]}}function rt(e){return[`xctrace`,`record`,`--template`,e.template,...r(e.device)?[`--device`,e.device.id]:[],...e.targetPids.flatMap(e=>[`--attach`,String(e)]),`--output`,e.outPath,`--quiet`,`--no-prompt`]}async function it(t,n,r){let i;for(let e=1;e<=3;e+=1){await U(n,e,1500);let r=c(`xcrun`,t,{allowFailure:!0}),a=await at(r.wait);if(!a)return r;if(i=a,!H(a))break}let a=i??{stdout:``,stderr:``,exitCode:1};throw new e(`COMMAND_FAILED`,r.failureMessage,l(a,{cmd:`xcrun`,args:t,appBundleId:r.appBundleId,deviceId:r.device.id,hint:Q(a.stdout,a.stderr)}))}async function at(e){return await Promise.race([e,new Promise(e=>setTimeout(e,500))])}async function ot(t,n){t.child.kill(`SIGINT`);let r=await st(t.wait,45e3);if(r)return r;t.child.kill(`SIGKILL`);let i=await st(t.wait,5e3);if(i&&!n.failOnForcedKill)return i;throw i?new e(`COMMAND_FAILED`,`Timed out waiting for Apple xctrace capture to stop`,{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,tracePath:t.outPath,captureCleanedUp:!0,forcedKill:!0,hint:`xctrace did not finish after SIGINT, so it was force-killed. Retry the perf command after confirming no other xctrace session is active.`}):new e(`COMMAND_FAILED`,`Timed out waiting for Apple xctrace capture to stop after SIGKILL`,{tracePath:t.outPath,captureCleanedUp:!1,forcedKill:!0,hint:`xctrace did not exit after SIGKILL. Inspect running xctrace processes before retrying.`})}async function st(e,t){return await Promise.race([e,new Promise(e=>setTimeout(e,t))])}async function ct(t,n){let r=await _(t).catch(()=>null);if(!(r?.isDirectory()===!0?(await m(t).catch(()=>[])).length>0:(r?.size??0)>0))throw new e(`COMMAND_FAILED`,`xctrace produced no trace data`,{tracePath:t,appBundleId:n.appBundleId,deviceId:n.deviceId,stdout:n.stdout,stderr:n.stderr,hint:`Keep the Apple device unlocked and connected, keep the app active, then retry perf.`})}function lt(e){let t=u(e.tocXml),n=T(t,e=>e.name===`run`),r=o(T(t,e=>e.name===`table`).map(e=>e.attributes.schema).filter(e=>typeof e==`string`&&e.length>0)).sort(),i=Ke(e.timeProfileXml);return{kind:`xctrace`,mode:`cpu-profile`,template:e.template,tracePath:e.tracePath,reportPath:e.outPath,appBundleId:e.appBundleId,generatedAt:new Date().toISOString(),summary:{runCount:n.length,tableSchemas:r,...i}}}export{De as buildAppleFrameSamplingMetadata,Oe as buildAppleMemorySamplingMetadata,B as buildAppleMemorySnapshotSupport,Se as captureAppleMemorySnapshot,$e as cleanupAppleXctracePerfCapture,H as isRetryableIosDeviceTraceRecordFailure,q as readAppleProcessSamples,G as resolveAppleExecutable,Q as resolveIosDevicePerfHint,K as resolveIosDevicePerfTarget,Ee as sampleAppleFramePerf,xe as sampleAppleMemoryPerf,Ze as startAppleXctracePerfCapture,Qe as stopAppleXctracePerfCapture,et as writeAppleXctracePerfReport};
@@ -1 +1 @@
1
- import{C as e,M as t}from"./sdk-contracts.js";import{S as n,c as r,w as i}from"./sdk-device.js";import{Et as a,Ot as o,Tt as s,kt as c,wt as l}from"./sdk-batch.js";import{m as u}from"./observability.js";import{r as d}from"./diagnostics.js";import{D as f,a as p,i as m}from"./owner-identity.js";import{t as h}from"./file.js";import"./diagnostics2.js";import"./process.js";import{c as g,i as ee,l as _,r as v,s as y,t as b}from"./device-claim-inspection.js";import{c as x,l as S}from"./screen-recording-resource-recovery.js";import C from"node:path";import w from"node:fs";import te from"node:crypto";function T(e){let t=g(e.deviceKey);w.mkdirSync(C.dirname(t),{recursive:!0,mode:448}),f({destination:t,contents:`${JSON.stringify(e)}\n`,mode:384})}async function E(e,t){let n=p(),r=await h({lockDirPath:`${g(e)}.lock`,owner:{pid:n.pid,startTime:n.startTime,acquiredAtMs:Date.now()},timeoutMs:3e4,description:`device claim for ${e}`});try{return await t()}finally{await r()}}function ne(e){return`transient:${e}`}async function re(e){let t=N(e.device),n=y(t);return await E(n,async()=>await O({...e,deviceKey:n,identity:t}))}async function D(e){let t=N(e.device),n=y(t);return await E(n,async()=>{let r=v(g(n));return r?.claim&&!A(r.claim)&&k(r.claim,e.stateDir,p())?{status:`covered-by-owned-claim`}:await O({device:e.device,deviceKey:n,identity:t,session:ne(e.command),workspace:e.workspace,stateDir:e.stateDir,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim})})}async function O(e){let{deviceKey:t,identity:n}=e,r=p(),i=await P({deviceKey:t,owner:r,session:e.session,workspace:e.workspace,stateDir:e.stateDir,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim});if(i.status!==`available`)return i;let a=Date.now(),o={schemaVersion:2,deviceKey:t,device:{...n,name:e.device.name},session:e.session,workspace:e.workspace,stateDir:e.stateDir,ownerPid:r.pid,ownerStartTime:r.startTime,ownerToken:te.randomUUID(),createdAtMs:a,updatedAtMs:a};return T(o),{status:`acquired`,ownership:J(o)}}function k(e,t,n){return e.stateDir===t&&m({pid:e.ownerPid,startTime:e.ownerStartTime},n)}function A(e){return e.abandonedAtMs!==void 0}function j(e){let t=y(N(e)),n=v(g(t))?.claim;return n!==void 0&&n.deviceKey===t&&!A(n)&&m({pid:n.ownerPid,startTime:n.ownerStartTime},p())}function M(e,t,n){return A(e)&&k(e,t,n)}function N(e){return i({...e,...r(e.platform)?{appleOs:n(e)}:{}})}async function P(e){let t=v(g(e.deviceKey));if(!t)return{status:`available`};if(t.claim&&M(t.claim,e.stateDir,e.owner))return K(e.deviceKey,t.claim),{status:`available`};if(t.claim&&ie(t.claim,e,e.owner))return{status:`acquired`,ownership:J(t.claim)};if(!t.claim||!b(t.classification))return W(e.deviceKey,t),{status:`conflict`,conflict:t};let n=await q(t.claim,e.reconcileOrphanedDeviceClaim);return n.status===`retained`?(W(e.deviceKey,t,n.reason),{status:`conflict`,conflict:t}):{status:`available`}}function ie(e,t,n){return e.session===t.session&&e.workspace===t.workspace&&e.stateDir===t.stateDir&&m({pid:e.ownerPid,startTime:e.ownerStartTime},n)}async function F(e){let t=[];for(let n of ee(e.selectors))t.push(await I(n,e.reconcile));return t}async function I(e,t){let n=e.claim,r={fileName:e.fileName,classification:e.classification,...e.deviceKey?{deviceKey:e.deviceKey}:{},...n?{device:n.device,session:n.session,workspace:n.workspace,stateDir:n.stateDir}:{},...e.allocatorClaim?{device:e.allocatorClaim.device,stateDir:e.allocatorClaim.stateDir,allocator:e.allocatorClaim.allocator}:{}};if(!n||!b(e.classification))return{...r,status:`refused`,reason:R(e.classification)};if(g(n.deviceKey)!==C.join(_(),e.fileName))return{...r,status:`refused`,reason:`claim-file-name-mismatch`};let{deviceKey:i,ownerToken:a}=n;return await E(i,async()=>{let e=v(g(i));if(!e?.claim||e.claim.ownerToken!==a||!b(e.classification))return{...r,status:`changed`,reason:`claim-changed-during-release`};let o=await q(e.claim,t);return o.status===`retained`?{...r,status:`retained`,reason:o.reason}:(d({level:`info`,phase:`device_claim_stale_released`,data:{deviceKey:i,ownerSession:n.session,ownerStateDir:n.stateDir}}),{...r,status:`released`})})}const L=Object.freeze({live:`live-owner`,"owner-process-reused":`owner-pid-reused`,"owner-state-dir-gone":`owner-process-still-running`,unknown:`owner-liveness-unknown`,inconsistent:`claim-record-inconsistent`,"allocator-inconsistent":`allocator-claim-record-inconsistent`,"allocator-held":`allocator-held-owner`,"owner-process-dead":`claim-record-unreadable`,"owner-daemon-superseded":`claim-record-unreadable`});function R(e){return L[e]}async function z(e){return e?await E(e.deviceKey,async()=>{let t=g(e.deviceKey),n=v(t);if(!n)return`absent`;let r=n.claim;if(!r||!V(r,e))return`ownership-changed`;try{w.unlinkSync(t)}catch(e){if(e.code!==`ENOENT`)throw e;return`absent`}return`deleted`}):`absent`}async function B(e){return e?await E(e.deviceKey,async()=>{let t=v(g(e.deviceKey));if(!t)return`absent`;let n=t.claim;if(!n||!V(n,e))return`ownership-changed`;let r=Date.now();return T({...n,abandonedAtMs:r,updatedAtMs:r}),`abandoned`}):`absent`}function V(e,t){return e.ownerToken===t.ownerToken&&m({pid:e.ownerPid,startTime:e.ownerStartTime},{pid:t.ownerPid,startTime:t.ownerStartTime})}async function H(e,t){let n=_(),r;try{r=w.readdirSync(n,{withFileTypes:!0})}catch{return{examined:0,reconciled:0,retained:0,changed:0}}let i=0,a=0,o=0,s=0;for(let c of r){if(!c.isFile()||!c.name.endsWith(`.json`))continue;let r=C.join(n,c.name),l=v(r);if(!l?.claim||!U(l.classification,l.claim.stateDir,t))continue;i+=1;let{deviceKey:u,ownerToken:d}=l.claim;if(g(u)!==r){o+=1;continue}await E(u,async()=>{let n=v(r);if(!n?.claim||!U(n.classification,n.claim.stateDir,t)||n.claim.ownerToken!==d){s+=1;return}if((await q(n.claim,e)).status===`retained`){o+=1;return}a+=1})}return{examined:i,reconciled:a,retained:o,changed:s}}function U(e,t,n){return b(e)?e!==`owner-daemon-superseded`||C.resolve(t)===C.resolve(n):!1}function W(e,t,n){d({level:`warn`,phase:`device_claim_conflict`,data:{deviceKey:e,classification:t.classification,...G(t),...n?{reconciliationReason:n}:{}}})}function G(e){return e.allocatorClaim?{ownerStateDir:e.allocatorClaim.stateDir,allocatorInstanceId:e.allocatorClaim.allocator.instanceId,identityIncarnationId:e.allocatorClaim.allocator.identityIncarnationId}:{ownerSession:e.claim?.session,ownerStateDir:e.claim?.stateDir}}function K(e,t){d({level:`info`,phase:`device_claim_abandoned_superseded`,data:{deviceKey:e,abandonedSession:t.session,abandonedAtMs:t.abandonedAtMs}})}async function q(e,t){let n=await t(e);if(n.status===`retained`)return n;try{w.unlinkSync(g(e.deviceKey))}catch(e){if(e.code!==`ENOENT`)throw e}return{status:`reconciled`}}function J(e){return{deviceKey:e.deviceKey,ownerToken:e.ownerToken,ownerPid:e.ownerPid,ownerStartTime:e.ownerStartTime}}const Y=S({resourceKind:`app-log`,fileName:`app-log.resource.json`,displayName:`App-log`}),X=x({resourceKind:`app-log`,displayName:`app-log`,store:Y,sessionSlot:{read:e=>e.appLog,replace:(e,t)=>({...e,appLog:t,appLogFailure:void 0})},completionMetadata:e=>({backend:e.backend,outputPath:e.outputPath,completedAt:e.completedAt}),messages:{noActive:`no app log stream active`,cleanupPendingHint:`Keep app-log.resource.json and retry cleanup through its exact runtime owner.`}});function ae(e){if(e.appLog){let t=e.appLog.handle.inspect();return{active:t.state===`active`||t.state===`recovering`,...t}}return e.appLogFailure?{active:!1,state:`failed`,backend:e.appLogFailure.backend,failureCode:e.appLogFailure.code,failureMessage:e.appLogFailure.message,hint:e.appLogFailure.hint}:{active:!1,state:`inactive`}}function oe(e){return X.adoptStarted(e)}function se(e){return X.finishLive(e)}function ce(e){return X.forceCleanupLive(e)}function le(e){let n=t(e.error);return e.sessionStore.set(e.sessionName,{...e.session,appLog:void 0,appLogFailure:{backend:e.backend,code:n.code,message:n.message,hint:n.hint}}),n}function ue(e){e.sessionStore.set(e.sessionName,{...e.session,appLogFailure:void 0})}const de=S({resourceKind:`audio-probe`,fileName:`audio-probe.resource.json`,displayName:`Audio probe`}),Z=x({resourceKind:`audio-probe`,displayName:`audio probe`,store:de,sessionSlot:{read:e=>e.audioProbe,replace:(e,t)=>({...e,audioProbe:t})},completionMetadata:e=>({backend:e.backend??`unknown`,source:e.source,durationMs:e.durationMs,elapsedMs:e.elapsedMs,bucketMs:e.bucketMs,sampleCount:e.sampleCount,heard:e.heard}),messages:{noActive:`no active audio probe`,cleanupPendingHint:`Keep audio-probe.resource.json and retry stop through its exact runtime owner.`}});function Q(e){return Z.adoptStarted(e)}function fe(e){return Z.finishLive(e)}const pe=S({resourceKind:`perf-capture`,fileName:`perf-capture.resource.json`,displayName:`Perf capture`}),$=x({resourceKind:`perf-capture`,displayName:`perf capture`,store:pe,sessionSlot:{read:e=>e.perfCapture,replace:(e,t)=>({...e,perfCapture:t})},completionMetadata:e=>({kind:typeof e.kind==`string`?e.kind:`unknown`,mode:typeof e.mode==`string`?e.mode:`unknown`,...typeof e.outPath==`string`?{outPath:e.outPath}:{}}),messages:{noActive:`no active native perf capture`,cleanupPendingHint:`Keep perf-capture.resource.json and retry stop through its exact runtime owner.`}});function me(e){return $.adoptStarted(e)}function he(e){return $.finishLive(e)}function ge(e){if(e.area===`frames`)return Object.freeze({kind:`frames`,request:e,use:l});if(e.area===`memory`)return e.action===`snapshot`?Object.freeze({kind:`memory-snapshot`,request:e,use:a}):Object.freeze({kind:`memory-sample`,request:e,use:s});if(e.area===`trace`)return e.action===`start`?Object.freeze({kind:`capture-start`,request:e,use:o}):Object.freeze({kind:`capture-stop`,request:e});switch(e.action){case`start`:return Object.freeze({kind:`capture-start`,request:e,use:o});case`stop`:return Object.freeze({kind:`capture-stop`,request:e});case`report`:return Object.freeze({kind:`profile-report`,request:e,use:c})}}function _e(t){let n=t.positionals??[],r=n[0]?.toLowerCase();if(r===`frames`){let i=n[1]?.toLowerCase();if(i!==void 0&&i!==`sample`||n.length>2||t.kind!==void 0)throw new e(`INVALID_ARGS`,`perf action must be frames, memory sample|snapshot, cpu profile start|stop|report, or trace start|stop`);return Object.freeze({area:r,action:`sample`})}if(r===`memory`)return ve(n,t);if(r===`cpu`)return ye(n,t.outPath);if(r===`trace`)return be(n,t.outPath);throw new e(`INVALID_ARGS`,`perf requires frames, memory, cpu, or trace`)}function ve(t,n){let r=(t[1]??`sample`).toLowerCase();if(r!==`sample`&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(n.kind!==void 0&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(r===`sample`&&t.length>2)throw new e(`INVALID_ARGS`,`perf memory sample does not accept additional positionals`);if(r===`snapshot`&&t.length>3)throw new e(`INVALID_ARGS`,`perf memory snapshot accepts at most one positional kind`);let i=n.kind??t[2];if(i!==void 0&&!u(i))throw new e(`INVALID_ARGS`,`perf memory snapshot --kind must be android-hprof or memgraph`);return Object.freeze({area:`memory`,action:r,...i===void 0?{}:{kind:i},...n.outPath===void 0?{}:{outPath:n.outPath}})}function ye(t,n){if(t[1]?.toLowerCase()!==`profile`)throw new e(`INVALID_ARGS`,`perf cpu requires profile`);let r=t[2]?.toLowerCase();if(r!==`start`&&r!==`stop`&&r!==`report`)throw new e(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`);let i=t[3]?.toLowerCase();if(i!==`xctrace`&&i!==`simpleperf`)throw new e(`INVALID_ARGS`,`perf cpu profile requires --kind xctrace or simpleperf`);let a=n??t[5];return Object.freeze({area:`cpu`,subject:`profile`,action:r,kind:i,...t[4]?{template:t[4]}:{},...a?{outPath:a}:{},...t[6]?{tracePath:t[6]}:{}})}function be(t,n){let r=t[1]?.toLowerCase();if(r!==`start`&&r!==`stop`)throw new e(`INVALID_ARGS`,`perf trace action must be start or stop`);let i=t[2]?.toLowerCase();if(i!==`xctrace`&&i!==`perfetto`)throw new e(`INVALID_ARGS`,`perf trace requires --kind xctrace or perfetto`);let a=n??t[4];return Object.freeze({area:`trace`,action:r,kind:i,...t[3]?{template:t[3]}:{},...a?{outPath:a}:{}})}export{H as C,j as S,B as _,$ as a,z as b,fe as c,ue as d,se as f,Y as g,le as h,he as i,oe as l,ae as m,ge as n,Q as o,ce as p,me as r,Z as s,_e as t,X as u,re as v,F as w,N as x,D as y};
1
+ import{C as e,M as t}from"./sdk-contracts.js";import{S as n,c as r,w as i}from"./sdk-device.js";import{At as a,Dt as o,Et as s,Tt as c,kt as l}from"./sdk-batch.js";import{m as u}from"./observability.js";import{r as d}from"./diagnostics.js";import{O as ee,a as f,i as p}from"./owner-identity.js";import{t as m}from"./file.js";import"./diagnostics2.js";import"./process.js";import{c as h,i as g,l as _,r as v,s as y,t as b,u as x}from"./device-claim-inspection.js";import{l as S,u as C}from"./screen-recording-resource-recovery.js";import w from"node:path";import T from"node:fs";import E from"node:crypto";async function te(e){let t=await e.observeDeviceBoot?.observeBootTimeMs(e.device);if(t?.observed!==!0||t.bootedAtMs<=e.claim.updatedAtMs)return;let{session:n,workspace:r,stateDir:i}=e.claim;return{session:n,workspace:r,stateDir:i,bootedAtMs:t.bootedAtMs}}function ne(e){d({level:`info`,phase:`device_claim_reboot_released`,data:{deviceKey:e.deviceKey,ownerSession:e.claim.session,ownerStateDir:e.claim.stateDir,ownerWorkspace:e.claim.workspace,claimUpdatedAtMs:e.claim.updatedAtMs,deviceBootedAtMs:e.bootedAtMs}})}function D(e){let t=_(e.deviceKey);T.mkdirSync(w.dirname(t),{recursive:!0,mode:448}),ee({destination:t,contents:`${JSON.stringify(e)}\n`,mode:384})}async function O(e,t){let n=f(),r=await m({lockDirPath:`${_(e)}.lock`,owner:{pid:n.pid,startTime:n.startTime,acquiredAtMs:Date.now()},timeoutMs:3e4,description:`device claim for ${e}`});try{return await t()}finally{await r()}}async function re(e){let t=v(_(e.deviceKey));return t?t.claim&&se(t.claim,e.stateDir,e.owner)?(F(e.deviceKey,t.claim),{status:`available`}):t.claim&&M(t.claim,e,e.owner)?{status:`held`,ownership:ie(t.claim)}:await ae(t,e):{status:`available`}}function ie(e){if(e.updatedAtMs>=Date.now())return y(e);let t={...e,updatedAtMs:Date.now()};return D(t),y(t)}async function ae(e,t){let n=e.claim;if(!n)return N(t.deviceKey,e),{status:`conflict`,conflict:e};let r=await oe({classification:e.classification,claim:n,device:t.device,observeDeviceBoot:t.observeDeviceBoot});if(!r.settles)return N(t.deviceKey,e),{status:`conflict`,conflict:e};let i=await k(n,t.reconcileOrphanedDeviceClaim);return i.status===`retained`?(N(t.deviceKey,e,i.reason),{status:`conflict`,conflict:e}):r.tookOver?(ne({deviceKey:t.deviceKey,claim:n,bootedAtMs:r.tookOver.bootedAtMs}),{status:`available`,tookOver:r.tookOver}):{status:`available`}}async function oe(e){if(b(e.classification))return{settles:!0};let t=await te(e);return t?{settles:!0,tookOver:t}:{settles:!1}}async function k(e,t){let n=await t(e);if(n.status===`retained`)return n;try{T.unlinkSync(_(e.deviceKey))}catch(e){if(e.code!==`ENOENT`)throw e}return{status:`reconciled`}}function A(e,t,n){return e.stateDir===t&&p({pid:e.ownerPid,startTime:e.ownerStartTime},n)}function j(e){return e.abandonedAtMs!==void 0}function se(e,t,n){return j(e)&&A(e,t,n)}function M(e,t,n){return e.session===t.session&&e.workspace===t.workspace&&A(e,t.stateDir,n)}function N(e,t,n){d({level:`warn`,phase:`device_claim_conflict`,data:{deviceKey:e,classification:t.classification,...P(t),...n?{reconciliationReason:n}:{}}})}function P(e){return e.allocatorClaim?{ownerStateDir:e.allocatorClaim.stateDir,allocatorInstanceId:e.allocatorClaim.allocator.instanceId,identityIncarnationId:e.allocatorClaim.allocator.identityIncarnationId}:{ownerSession:e.claim?.session,ownerStateDir:e.claim?.stateDir}}function F(e,t){d({level:`info`,phase:`device_claim_abandoned_superseded`,data:{deviceKey:e,abandonedSession:t.session,abandonedAtMs:t.abandonedAtMs}})}function I(e){return`transient:${e}`}async function L(e){let t=V(e.device),n=h(t);return await O(n,async()=>await z({...e,deviceKey:n,identity:t}))}async function R(e){let t=V(e.device),n=h(t);return await O(n,async()=>{let r=v(_(n));return r?.claim&&!j(r.claim)&&A(r.claim,e.stateDir,f())?{status:`covered-by-owned-claim`}:await z({device:e.device,deviceKey:n,identity:t,session:I(e.command),workspace:e.workspace,stateDir:e.stateDir,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim})})}async function z(e){let{deviceKey:t,identity:n}=e,r=f(),i=await re({...e,owner:r});if(i.status===`conflict`)return i;if(i.status===`held`)return{status:`acquired`,ownership:i.ownership};let a=Date.now(),o={schemaVersion:2,deviceKey:t,device:{...n,name:e.device.name},session:e.session,workspace:e.workspace,stateDir:e.stateDir,ownerPid:r.pid,ownerStartTime:r.startTime,ownerToken:E.randomUUID(),createdAtMs:a,updatedAtMs:a};return D(o),{status:`acquired`,ownership:y(o),...i.tookOver?{tookOver:i.tookOver}:{}}}function B(e){let t=h(V(e)),n=v(_(t))?.claim;return n!==void 0&&n.deviceKey===t&&!j(n)&&p({pid:n.ownerPid,startTime:n.ownerStartTime},f())}function V(e){return i({...e,...r(e.platform)?{appleOs:n(e)}:{}})}async function H(e){let t=[];for(let n of g(e.selectors))t.push(await U(n,e.reconcile));return t}async function U(e,t){let n=e.claim,r={fileName:e.fileName,classification:e.classification,...e.deviceKey?{deviceKey:e.deviceKey}:{},...n?{device:n.device,session:n.session,workspace:n.workspace,stateDir:n.stateDir}:{},...e.allocatorClaim?{device:e.allocatorClaim.device,stateDir:e.allocatorClaim.stateDir,allocator:e.allocatorClaim.allocator}:{}};if(!n||!b(e.classification))return{...r,status:`refused`,reason:G(e.classification)};if(_(n.deviceKey)!==w.join(x(),e.fileName))return{...r,status:`refused`,reason:`claim-file-name-mismatch`};let{deviceKey:i,ownerToken:a}=n;return await O(i,async()=>{let e=v(_(i));if(!e?.claim||e.claim.ownerToken!==a||!b(e.classification))return{...r,status:`changed`,reason:`claim-changed-during-release`};let o=await k(e.claim,t);return o.status===`retained`?{...r,status:`retained`,reason:o.reason}:(d({level:`info`,phase:`device_claim_stale_released`,data:{deviceKey:i,ownerSession:n.session,ownerStateDir:n.stateDir}}),{...r,status:`released`})})}const W=Object.freeze({live:`live-owner`,"owner-process-reused":`owner-pid-reused`,"owner-state-dir-gone":`owner-process-still-running`,unknown:`owner-liveness-unknown`,inconsistent:`claim-record-inconsistent`,"allocator-inconsistent":`allocator-claim-record-inconsistent`,"allocator-held":`allocator-held-owner`,"owner-process-dead":`claim-record-unreadable`,"owner-daemon-superseded":`claim-record-unreadable`});function G(e){return W[e]}async function K(e){return e?await q(e,(e,t)=>{try{T.unlinkSync(t)}catch(e){if(e.code!==`ENOENT`)throw e;return`absent`}return`deleted`},e=>e?`ownership-changed`:`absent`):`absent`}async function ce(e){return e?await q(e,e=>{let t=Date.now();return D({...e,abandonedAtMs:t,updatedAtMs:t}),`abandoned`},e=>e?`ownership-changed`:`absent`):`absent`}async function le(e){return e?await q(e,e=>(D({...e,updatedAtMs:Date.now()}),{status:`renewed`}),e=>({status:`lost`,conflict:e})):{status:`lost`,conflict:void 0}}async function q(e,t,n){return await O(e.deviceKey,async()=>{let r=_(e.deviceKey),i=v(r);if(!i)return n(void 0);let a=i.claim;return!a||!ue(a,e)?n(i):t(a,r)})}function ue(e,t){return e.ownerToken===t.ownerToken&&p({pid:e.ownerPid,startTime:e.ownerStartTime},{pid:t.ownerPid,startTime:t.ownerStartTime})}async function de(e,t){let n=x(),r;try{r=T.readdirSync(n,{withFileTypes:!0})}catch{return{examined:0,reconciled:0,retained:0,changed:0}}let i=0,a=0,o=0,s=0;for(let c of r){if(!c.isFile()||!c.name.endsWith(`.json`))continue;let r=w.join(n,c.name),l=v(r);if(!l?.claim||!J(l.classification,l.claim.stateDir,t))continue;i+=1;let{deviceKey:u,ownerToken:d}=l.claim;if(_(u)!==r){o+=1;continue}await O(u,async()=>{let n=v(r);if(!n?.claim||!J(n.classification,n.claim.stateDir,t)||n.claim.ownerToken!==d){s+=1;return}if((await k(n.claim,e)).status===`retained`){o+=1;return}a+=1})}return{examined:i,reconciled:a,retained:o,changed:s}}function J(e,t,n){return b(e)?e!==`owner-daemon-superseded`||w.resolve(t)===w.resolve(n):!1}const Y=C({resourceKind:`app-log`,fileName:`app-log.resource.json`,displayName:`App-log`}),X=S({resourceKind:`app-log`,displayName:`app-log`,store:Y,sessionSlot:{read:e=>e.appLog,replace:(e,t)=>({...e,appLog:t,appLogFailure:void 0})},completionMetadata:e=>({backend:e.backend,outputPath:e.outputPath,completedAt:e.completedAt}),messages:{noActive:`no app log stream active`,cleanupPendingHint:`Keep app-log.resource.json and retry cleanup through its exact runtime owner.`}});function fe(e){if(e.appLog){let t=e.appLog.handle.inspect();return{active:t.state===`active`||t.state===`recovering`,...t}}return e.appLogFailure?{active:!1,state:`failed`,backend:e.appLogFailure.backend,failureCode:e.appLogFailure.code,failureMessage:e.appLogFailure.message,hint:e.appLogFailure.hint}:{active:!1,state:`inactive`}}function pe(e){return X.adoptStarted(e)}function me(e){return X.finishLive(e)}function he(e){return X.forceCleanupLive(e)}function ge(e){let n=t(e.error);return e.sessionStore.set(e.sessionName,{...e.session,appLog:void 0,appLogFailure:{backend:e.backend,code:n.code,message:n.message,hint:n.hint}}),n}function _e(e){e.sessionStore.set(e.sessionName,{...e.session,appLogFailure:void 0})}const ve=C({resourceKind:`audio-probe`,fileName:`audio-probe.resource.json`,displayName:`Audio probe`}),Z=S({resourceKind:`audio-probe`,displayName:`audio probe`,store:ve,sessionSlot:{read:e=>e.audioProbe,replace:(e,t)=>({...e,audioProbe:t})},completionMetadata:e=>({backend:e.backend??`unknown`,source:e.source,durationMs:e.durationMs,elapsedMs:e.elapsedMs,bucketMs:e.bucketMs,sampleCount:e.sampleCount,heard:e.heard}),messages:{noActive:`no active audio probe`,cleanupPendingHint:`Keep audio-probe.resource.json and retry stop through its exact runtime owner.`}});function ye(e){return Z.adoptStarted(e)}function be(e){return Z.finishLive(e)}const xe=C({resourceKind:`perf-capture`,fileName:`perf-capture.resource.json`,displayName:`Perf capture`}),Q=S({resourceKind:`perf-capture`,displayName:`perf capture`,store:xe,sessionSlot:{read:e=>e.perfCapture,replace:(e,t)=>({...e,perfCapture:t})},completionMetadata:e=>({kind:typeof e.kind==`string`?e.kind:`unknown`,mode:typeof e.mode==`string`?e.mode:`unknown`,...typeof e.outPath==`string`?{outPath:e.outPath}:{}}),messages:{noActive:`no active native perf capture`,cleanupPendingHint:`Keep perf-capture.resource.json and retry stop through its exact runtime owner.`}});function Se(e){return Q.adoptStarted(e)}function $(e){return Q.finishLive(e)}function Ce(e){if(e.area===`frames`)return Object.freeze({kind:`frames`,request:e,use:c});if(e.area===`memory`)return e.action===`snapshot`?Object.freeze({kind:`memory-snapshot`,request:e,use:o}):Object.freeze({kind:`memory-sample`,request:e,use:s});if(e.area===`trace`)return e.action===`start`?Object.freeze({kind:`capture-start`,request:e,use:l}):Object.freeze({kind:`capture-stop`,request:e});switch(e.action){case`start`:return Object.freeze({kind:`capture-start`,request:e,use:l});case`stop`:return Object.freeze({kind:`capture-stop`,request:e});case`report`:return Object.freeze({kind:`profile-report`,request:e,use:a})}}function we(t){let n=t.positionals??[],r=n[0]?.toLowerCase();if(r===`frames`){let i=n[1]?.toLowerCase();if(i!==void 0&&i!==`sample`||n.length>2||t.kind!==void 0)throw new e(`INVALID_ARGS`,`perf action must be frames, memory sample|snapshot, cpu profile start|stop|report, or trace start|stop`);return Object.freeze({area:r,action:`sample`})}if(r===`memory`)return Te(n,t);if(r===`cpu`)return Ee(n,t.outPath);if(r===`trace`)return De(n,t.outPath);throw new e(`INVALID_ARGS`,`perf requires frames, memory, cpu, or trace`)}function Te(t,n){let r=(t[1]??`sample`).toLowerCase();if(r!==`sample`&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(n.kind!==void 0&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(r===`sample`&&t.length>2)throw new e(`INVALID_ARGS`,`perf memory sample does not accept additional positionals`);if(r===`snapshot`&&t.length>3)throw new e(`INVALID_ARGS`,`perf memory snapshot accepts at most one positional kind`);let i=n.kind??t[2];if(i!==void 0&&!u(i))throw new e(`INVALID_ARGS`,`perf memory snapshot --kind must be android-hprof or memgraph`);return Object.freeze({area:`memory`,action:r,...i===void 0?{}:{kind:i},...n.outPath===void 0?{}:{outPath:n.outPath}})}function Ee(t,n){if(t[1]?.toLowerCase()!==`profile`)throw new e(`INVALID_ARGS`,`perf cpu requires profile`);let r=t[2]?.toLowerCase();if(r!==`start`&&r!==`stop`&&r!==`report`)throw new e(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`);let i=t[3]?.toLowerCase();if(i!==`xctrace`&&i!==`simpleperf`)throw new e(`INVALID_ARGS`,`perf cpu profile requires --kind xctrace or simpleperf`);let a=n??t[5];return Object.freeze({area:`cpu`,subject:`profile`,action:r,kind:i,...t[4]?{template:t[4]}:{},...a?{outPath:a}:{},...t[6]?{tracePath:t[6]}:{}})}function De(t,n){let r=t[1]?.toLowerCase();if(r!==`start`&&r!==`stop`)throw new e(`INVALID_ARGS`,`perf trace action must be start or stop`);let i=t[2]?.toLowerCase();if(i!==`xctrace`&&i!==`perfetto`)throw new e(`INVALID_ARGS`,`perf trace requires --kind xctrace or perfetto`);let a=n??t[4];return Object.freeze({area:`trace`,action:r,kind:i,...t[3]?{template:t[3]}:{},...a?{outPath:a}:{}})}export{de as C,B as S,le as T,ce as _,Q as a,K as b,be as c,_e as d,me as f,Y as g,ge as h,$ as i,pe as l,fe as m,Ce as n,ye as o,he as p,Se as r,Z as s,we as t,X as u,L as v,H as w,V as x,R as y};
@@ -1 +1 @@
1
- import{D as e}from"./sdk-device.js";import{Dt as t,Kt as n,ft as r,j as i}from"./sdk-batch.js";import{t as a}from"./session-store.js";import{r as o}from"./diagnostics.js";import"./diagnostics2.js";import{n as s}from"./config.js";import{t as c}from"./process.js";import{r as l}from"./session-paths.js";import{r as u}from"./request-cancel.js";import{t as d}from"./request.js";import{r as f}from"./platform-runtime.js";import{a as p,s as m,u as h}from"./perf-runtime-plan.js";import{n as g,r as _,s as v}from"./screen-recording-resource-recovery.js";import y from"node:path";const b=r({required:[`appLogReattach`,`appLogCleanup`]});function x(e){return h.recoverAll({sessionsDir:e.sessionsDir,...C(e)})}function S(e){return h.recoverOne({sessionsDir:e.sessionsDir,...C(e)},e.resourcePath)}function C(e){return{scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await w(e.gateway,t,n)}}async function w(e,t,r){return await _({gateway:e,envelope:t,scope:r,create:e=>{let t=n(e,b);return Object.freeze({reattach:async e=>await t.operations.appLogReattach({envelope:e}),cleanup:async e=>await t.operations.appLogCleanup({envelope:e}),[Symbol.asyncDispose]:async()=>await e[Symbol.asyncDispose]()})}})}function T(e){return m.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await E(e.gateway,t,n)},e.resourcePath)}async function E(e,t,r){return await _({gateway:e,envelope:t,scope:r,create:e=>D({runtime:n(e,i),dispose:async()=>await e[Symbol.asyncDispose]()})})}function D(e){return Object.freeze({reattach:async t=>await e.runtime.operations.audioProbeReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.audioProbeCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}function O(e){return p.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await k(e.gateway,t,n)},e.resourcePath)}async function k(e,r,i){return await _({gateway:e,envelope:r,scope:i,create:e=>A({runtime:n(e,t),dispose:async()=>await e[Symbol.asyncDispose]()})})}function A(e){return Object.freeze({reattach:async t=>await e.runtime.operations.perfNativeCaptureReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.perfNativeCaptureCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}function j(e){return async t=>{let n=s(t.stateDir).sessionsDir,r=y.join(n,l(t.session));try{for(let i of Object.values(M)){let a=N(i,t,r);if(a.status===`retained`)return{status:`retained`,reason:a.reason};if(a.status===`owned`&&await i.recover(e,n,a.resourcePath)===`retained`)return{status:`retained`,reason:`${i.resourceKind}-cleanup-pending`}}return{status:`reconciled`}}catch(e){return o({level:`warn`,phase:`device_claim_orphan_reconciliation_failed`,data:{deviceKey:t.deviceKey,ownerSession:t.session,error:e instanceof Error?e.message:String(e)}}),{status:`retained`,reason:`durable-resource-reconciliation-failed`}}}}const M={"app-log":{resourceKind:`app-log`,store:h.store,recover:async(e,t,n)=>await S({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"screen-recording":{resourceKind:`screen-recording`,store:v.store,recover:async(e,t,n)=>await g({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"audio-probe":{resourceKind:`audio-probe`,store:m.store,recover:async(e,t,n)=>await T({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"perf-capture":{resourceKind:`perf-capture`,store:p.store,recover:async(e,t,n)=>await O({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})}};function N(t,n,r){let i=t.store.resolvePath(r),a=t.store.read(i);return a.status===`missing`?{status:`missing`}:a.status===`unreattachable`?{status:`retained`,reason:`${t.resourceKind}-${a.reason}`}:a.envelope.sessionId!==n.session||!e(a.envelope.device,n.device)?{status:`retained`,reason:`${t.resourceKind}-owner-mismatch`}:{status:`owned`,resourcePath:i}}function P(e,t){let n=t??(t=>F(t,e));return async e=>{let t=n(e.stateDir);try{return await t.reconcile(e)}finally{await t.dispose()}}}function F(e,t){let n=s(e),r=new a(n.sessionsDir),i=f({sessionsDir:n.sessionsDir,ownedProcesses:c({stateDir:n.baseDir,sessionsDir:n.sessionsDir,resolveSessionDir:e=>r.resolveSessionDir(e)}),resolveSessionArtifacts:e=>({outputPath:r.resolveAppLogPath(e),pidPath:r.resolveAppLogPidPath(e)})});return{reconcile:j({gateway:i,scope:t}),dispose:async()=>{await i.shutdown()}}}const I=new AbortController().signal;function L(e){return Object.freeze({signal:u(e.meta?.requestId)??I,diagnostics:Object.freeze({emit:e=>o(e)}),progress:Object.freeze({report:e=>d({type:`command`,status:`progress`,message:e.message})})})}function R(){return Object.freeze({signal:I,diagnostics:Object.freeze({emit:e=>o(e)}),progress:Object.freeze({report:()=>{}})})}export{x as i,L as n,P as r,R as t};
1
+ import{D as e}from"./sdk-device.js";import{M as t,Ot as n,pt as r,qt as i}from"./sdk-batch.js";import{t as a}from"./session-store.js";import{r as o}from"./diagnostics.js";import"./diagnostics2.js";import{n as s}from"./config.js";import{t as c}from"./process.js";import{r as l}from"./session-paths.js";import{r as u}from"./request-cancel.js";import{t as d}from"./request.js";import{r as f}from"./platform-runtime.js";import{a as p,s as m,u as h}from"./perf-runtime-plan.js";import{c as g,n as _,r as v}from"./screen-recording-resource-recovery.js";import y from"node:path";const b=r({required:[`appLogReattach`,`appLogCleanup`]});function x(e){return h.recoverAll({sessionsDir:e.sessionsDir,...C(e)})}function S(e){return h.recoverOne({sessionsDir:e.sessionsDir,...C(e)},e.resourcePath)}function C(e){return{scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await w(e.gateway,t,n)}}async function w(e,t,n){return await v({gateway:e,envelope:t,scope:n,create:e=>{let t=i(e,b);return Object.freeze({reattach:async e=>await t.operations.appLogReattach({envelope:e}),cleanup:async e=>await t.operations.appLogCleanup({envelope:e}),[Symbol.asyncDispose]:async()=>await e[Symbol.asyncDispose]()})}})}function T(e){return m.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await E(e.gateway,t,n)},e.resourcePath)}async function E(e,n,r){return await v({gateway:e,envelope:n,scope:r,create:e=>D({runtime:i(e,t),dispose:async()=>await e[Symbol.asyncDispose]()})})}function D(e){return Object.freeze({reattach:async t=>await e.runtime.operations.audioProbeReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.audioProbeCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}function O(e){return p.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await k(e.gateway,t,n)},e.resourcePath)}async function k(e,t,r){return await v({gateway:e,envelope:t,scope:r,create:e=>A({runtime:i(e,n),dispose:async()=>await e[Symbol.asyncDispose]()})})}function A(e){return Object.freeze({reattach:async t=>await e.runtime.operations.perfNativeCaptureReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.perfNativeCaptureCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}function j(e){return async t=>{let n=s(t.stateDir).sessionsDir,r=y.join(n,l(t.session));try{for(let i of Object.values(M)){let a=N(i,t,r);if(a.status===`retained`)return{status:`retained`,reason:a.reason};if(a.status===`owned`&&await i.recover(e,n,a.resourcePath)===`retained`)return{status:`retained`,reason:`${i.resourceKind}-cleanup-pending`}}return{status:`reconciled`}}catch(e){return o({level:`warn`,phase:`device_claim_orphan_reconciliation_failed`,data:{deviceKey:t.deviceKey,ownerSession:t.session,error:e instanceof Error?e.message:String(e)}}),{status:`retained`,reason:`durable-resource-reconciliation-failed`}}}}const M={"app-log":{resourceKind:`app-log`,store:h.store,recover:async(e,t,n)=>await S({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"screen-recording":{resourceKind:`screen-recording`,store:g.store,recover:async(e,t,n)=>await _({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"audio-probe":{resourceKind:`audio-probe`,store:m.store,recover:async(e,t,n)=>await T({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"perf-capture":{resourceKind:`perf-capture`,store:p.store,recover:async(e,t,n)=>await O({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})}};function N(t,n,r){let i=t.store.resolvePath(r),a=t.store.read(i);return a.status===`missing`?{status:`missing`}:a.status===`unreattachable`?{status:`retained`,reason:`${t.resourceKind}-${a.reason}`}:a.envelope.sessionId!==n.session||!e(a.envelope.device,n.device)?{status:`retained`,reason:`${t.resourceKind}-owner-mismatch`}:{status:`owned`,resourcePath:i}}function P(e,t){let n=t??(t=>F(t,e));return async e=>{let t=n(e.stateDir);try{return await t.reconcile(e)}finally{await t.dispose()}}}function F(e,t){let n=s(e),r=new a(n.sessionsDir),i=f({sessionsDir:n.sessionsDir,ownedProcesses:c({stateDir:n.baseDir,sessionsDir:n.sessionsDir,resolveSessionDir:e=>r.resolveSessionDir(e)}),resolveSessionArtifacts:e=>({outputPath:r.resolveAppLogPath(e),pidPath:r.resolveAppLogPidPath(e)})});return{reconcile:j({gateway:i,scope:t}),dispose:async()=>{await i.shutdown()}}}const I=new AbortController().signal;function L(e){return Object.freeze({signal:u(e.meta?.requestId)??I,diagnostics:Object.freeze({emit:e=>o(e)}),progress:Object.freeze({report:e=>d({type:`command`,status:`progress`,message:e.message})})})}function R(){return Object.freeze({signal:I,diagnostics:Object.freeze({emit:e=>o(e)}),progress:Object.freeze({report:()=>{}})})}export{x as i,L as n,P as r,R as t};
@@ -1 +1 @@
1
- import{b as e,p as t,w as n,y as r}from"./owner-identity.js";import{i}from"./verified-file.js";import{l as a}from"./exec.js";import"./file.js";import"./command.js";import"./process.js";import{p as o}from"./src7.js";import s from"node:path";import c from"node:fs";function l(e){let t=s.resolve(e.sessionsDir),n=s.resolve(e.pathname);if(s.basename(n)!==e.basename)throw Error(`${e.label} is outside the daemon-owned sessions directory`);if(c.existsSync(t)&&c.existsSync(s.dirname(n))){let r=c.realpathSync.native(t),i=c.realpathSync.native(s.dirname(n));if(i!==r&&!i.startsWith(`${r}${s.sep}`))throw Error(`${e.label} resolves outside the daemon-owned sessions directory`);return s.join(i,e.basename)}if(n!==t&&!n.startsWith(`${t}${s.sep}`))throw Error(`${e.label} is outside the daemon-owned sessions directory`);return n}const u=`app-log.pid`;function d(e,t={}){let n=s.resolve(e),r=t.launch??h;return Object.freeze({start:async(e,t)=>await m(n,e,r,t),readMarker:async e=>T(n,e),clearMarker:async e=>D(n,e),inspect:async e=>k(e),terminate:async e=>await A(e)})}async function f(e){let t=[],n=[];if(!c.existsSync(e))return{recovered:t,retained:n};let r=s.resolve(e);for(let e of c.readdirSync(r,{withFileTypes:!0})){if(!e.isDirectory())continue;let i=s.join(r,e.name);if(c.existsSync(s.join(i,`app-log.resource.json`)))continue;let a=s.join(i,u),o=T(r,a);if(o.status!==`missing`){if(o.status===`invalid`){n.push({markerPath:a,reason:`invalid`,message:o.message});continue}if(await A(o.marker)===`ownership-lost`){let e=p(o.marker.command);n.push({markerPath:a,reason:`ownership-lost`,...e?{device:e}:{}});continue}D(r,a),t.push(a)}}return Object.freeze({recovered:Object.freeze(t),retained:Object.freeze(n)})}function p(e){let t=/(?:^|\s)(?:\S*\/)?adb\s+-s\s+([^\s]+)/.exec(e)?.[1];if(t)return Object.freeze({id:t,family:`android`,kind:t.startsWith(`emulator-`)?`emulator`:`device`,target:`mobile`});let n=/(?:^|\s)xcrun\s+(?:--set\s+\S+\s+)?simctl\s+spawn\s+([^\s]+)/.exec(e)?.[1];if(n)return Object.freeze({id:n,family:`apple`,appleOs:`ios`,kind:`simulator`,target:`mobile`});let r=/(?:^|\s)xcrun\s+devicectl\b[^\n]*?\s--device\s+([^\s]+)/.exec(e)?.[1];if(r)return Object.freeze({id:r,family:`apple`,appleOs:`ios`,kind:`device`,target:`mobile`,iosPhysicalDeviceBackend:`coredevice`})}async function m(e,t,n,r){_(e,t.markerPath),r?.throwIfAborted();let i=await n(t.command,r),a=i.child,o=v(a,t.output),s=await y(e,t.markerPath,i),c=i.wait.then(async e=>(await o(),e)).finally(()=>{t.markerPath&&s&&S(e,t.markerPath,s)}),l=b(a,c);return{marker:s,wait:c,terminate:l,[Symbol.asyncDispose]:l}}function h(e,t){let n=g(e);return a(n.executable,[...n.args],{allowFailure:n.allowFailure,cwd:n.cwd,env:n.env?{...process.env,...n.env}:void 0,timeoutMs:n.timeoutMs,captureOutput:!1,signal:t})}function g(e){return e.kind===`host`?e.request:{executable:`adb`,args:[`-s`,e.serial,...e.args],...e.options}}function _(e,t){if(t&&T(e,t).status!==`missing`)throw Error(`Existing app-log process marker evidence must be recovered before start`)}function v(e,t){let n=Promise.resolve(),r,i=i=>{n=n.then(async()=>await t.write(i)).catch(t=>{r??=t,typeof e.exitCode!=`number`&&e.kill(`SIGKILL`)})};return e.stdout?.on(`data`,i),e.stderr?.on(`data`,i),async()=>{if(await n,r!==void 0)throw r}}async function y(e,t,n){let r=n.child.pid?await w(n.child.pid):void 0;try{if(!r)throw Error(`Managed app-log process did not expose a complete ownership marker`);return t&&E(e,t,r),r}catch(e){throw n.child.kill(`SIGKILL`),await n.wait.catch(()=>void 0),e}}function b(e,t){let n;return async()=>await(n??=(async()=>{typeof e.exitCode!=`number`&&(e.kill(`SIGINT`),await x(t,2e3)||e.kill(`SIGKILL`),await t.catch(()=>void 0))})())}async function x(e,t){return await new Promise(n=>{let r=setTimeout(()=>n(!1),t),i=()=>{clearTimeout(r),n(!0)};e.then(i,i)})}function S(e,t,n){let r=T(e,t);r.status===`decoded`&&r.marker.pid===n.pid&&r.marker.startTime===n.startTime&&r.marker.command===n.command&&D(e,t)}function C(t){let n=e(t),i=r(t);if(!(!n||!i))return Object.freeze({pid:t,startTime:n,command:i})}async function w(e){for(let t=0;t<5;t+=1){let t=C(e);if(t)return t;await new Promise(e=>setTimeout(e,10))}}function T(e,t){let n=O(e,t),r;try{let e=i(n);if(e===void 0)return{status:`missing`};r=e}catch(e){return{status:`invalid`,message:e instanceof Error?e.message:`App-log process marker is invalid`}}try{let e=JSON.parse(c.readFileSync(r,`utf8`));return o(e)}catch(e){return{status:`invalid`,message:e instanceof Error?e.message:`App-log process marker is invalid`}}finally{c.closeSync(r)}}function E(e,t,n){let r=O(e,t);if(T(e,r).status!==`missing`)throw Error(`Existing app-log process marker evidence must be recovered before replacement`);c.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.${process.pid}.${Date.now()}.tmp`,a,o=!1,l=!1;try{a=c.openSync(i,`wx`,384),c.writeFileSync(a,`${JSON.stringify(n)}\n`),c.fsyncSync(a),c.closeSync(a),a=void 0,c.linkSync(i,r),o=!0,c.unlinkSync(i);let e=c.openSync(s.dirname(r),`r`);try{c.fsyncSync(e)}finally{c.closeSync(e)}l=!0}finally{if(a!==void 0)try{c.closeSync(a)}catch{}if(!l)for(let e of o?[r,i]:[i])try{c.unlinkSync(e)}catch{}}}function D(e,t){let n=O(e,t);try{c.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`)throw e}}function O(e,t){return l({sessionsDir:e,pathname:t,basename:u,label:`App-log process marker`})}function k(e){return t(e.pid)?j(e)?`owned-alive`:`ownership-lost`:`missing`}async function A(e){if(!t(e.pid))return`already-missing`;if(!j(e))return`ownership-lost`;try{process.kill(e.pid,`SIGTERM`)}catch{return`already-missing`}if(!await n(e.pid,2e3)){if(!j(e))return`ownership-lost`;try{process.kill(e.pid,`SIGKILL`)}catch{return`already-missing`}await n(e.pid,2e3)}return t(e.pid)?`ownership-lost`:`terminated`}function j(t){return!t.startTime||!t.command?!1:e(t.pid)===t.startTime&&r(t.pid)===t.command}export{f as n,l as r,d as t};
1
+ import{T as e,p as t,x as n,y as r}from"./owner-identity.js";import{i}from"./verified-file.js";import{l as a}from"./exec.js";import"./file.js";import"./command.js";import"./process.js";import{p as o}from"./src7.js";import s from"node:path";import c from"node:fs";function l(e){let t=s.resolve(e.sessionsDir),n=s.resolve(e.pathname);if(s.basename(n)!==e.basename)throw Error(`${e.label} is outside the daemon-owned sessions directory`);if(c.existsSync(t)&&c.existsSync(s.dirname(n))){let r=c.realpathSync.native(t),i=c.realpathSync.native(s.dirname(n));if(i!==r&&!i.startsWith(`${r}${s.sep}`))throw Error(`${e.label} resolves outside the daemon-owned sessions directory`);return s.join(i,e.basename)}if(n!==t&&!n.startsWith(`${t}${s.sep}`))throw Error(`${e.label} is outside the daemon-owned sessions directory`);return n}const u=`app-log.pid`;function d(e,t={}){let n=s.resolve(e),r=t.launch??h;return Object.freeze({start:async(e,t)=>await m(n,e,r,t),readMarker:async e=>T(n,e),clearMarker:async e=>D(n,e),inspect:async e=>k(e),terminate:async e=>await A(e)})}async function f(e){let t=[],n=[];if(!c.existsSync(e))return{recovered:t,retained:n};let r=s.resolve(e);for(let e of c.readdirSync(r,{withFileTypes:!0})){if(!e.isDirectory())continue;let i=s.join(r,e.name);if(c.existsSync(s.join(i,`app-log.resource.json`)))continue;let a=s.join(i,u),o=T(r,a);if(o.status!==`missing`){if(o.status===`invalid`){n.push({markerPath:a,reason:`invalid`,message:o.message});continue}if(await A(o.marker)===`ownership-lost`){let e=p(o.marker.command);n.push({markerPath:a,reason:`ownership-lost`,...e?{device:e}:{}});continue}D(r,a),t.push(a)}}return Object.freeze({recovered:Object.freeze(t),retained:Object.freeze(n)})}function p(e){let t=/(?:^|\s)(?:\S*\/)?adb\s+-s\s+([^\s]+)/.exec(e)?.[1];if(t)return Object.freeze({id:t,family:`android`,kind:t.startsWith(`emulator-`)?`emulator`:`device`,target:`mobile`});let n=/(?:^|\s)xcrun\s+(?:--set\s+\S+\s+)?simctl\s+spawn\s+([^\s]+)/.exec(e)?.[1];if(n)return Object.freeze({id:n,family:`apple`,appleOs:`ios`,kind:`simulator`,target:`mobile`});let r=/(?:^|\s)xcrun\s+devicectl\b[^\n]*?\s--device\s+([^\s]+)/.exec(e)?.[1];if(r)return Object.freeze({id:r,family:`apple`,appleOs:`ios`,kind:`device`,target:`mobile`,iosPhysicalDeviceBackend:`coredevice`})}async function m(e,t,n,r){_(e,t.markerPath),r?.throwIfAborted();let i=await n(t.command,r),a=i.child,o=v(a,t.output),s=await y(e,t.markerPath,i),c=i.wait.then(async e=>(await o(),e)).finally(()=>{t.markerPath&&s&&S(e,t.markerPath,s)}),l=b(a,c);return{marker:s,wait:c,terminate:l,[Symbol.asyncDispose]:l}}function h(e,t){let n=g(e);return a(n.executable,[...n.args],{allowFailure:n.allowFailure,cwd:n.cwd,env:n.env?{...process.env,...n.env}:void 0,timeoutMs:n.timeoutMs,captureOutput:!1,signal:t})}function g(e){return e.kind===`host`?e.request:{executable:`adb`,args:[`-s`,e.serial,...e.args],...e.options}}function _(e,t){if(t&&T(e,t).status!==`missing`)throw Error(`Existing app-log process marker evidence must be recovered before start`)}function v(e,t){let n=Promise.resolve(),r,i=i=>{n=n.then(async()=>await t.write(i)).catch(t=>{r??=t,typeof e.exitCode!=`number`&&e.kill(`SIGKILL`)})};return e.stdout?.on(`data`,i),e.stderr?.on(`data`,i),async()=>{if(await n,r!==void 0)throw r}}async function y(e,t,n){let r=n.child.pid?await w(n.child.pid):void 0;try{if(!r)throw Error(`Managed app-log process did not expose a complete ownership marker`);return t&&E(e,t,r),r}catch(e){throw n.child.kill(`SIGKILL`),await n.wait.catch(()=>void 0),e}}function b(e,t){let n;return async()=>await(n??=(async()=>{typeof e.exitCode!=`number`&&(e.kill(`SIGINT`),await x(t,2e3)||e.kill(`SIGKILL`),await t.catch(()=>void 0))})())}async function x(e,t){return await new Promise(n=>{let r=setTimeout(()=>n(!1),t),i=()=>{clearTimeout(r),n(!0)};e.then(i,i)})}function S(e,t,n){let r=T(e,t);r.status===`decoded`&&r.marker.pid===n.pid&&r.marker.startTime===n.startTime&&r.marker.command===n.command&&D(e,t)}function C(e){let t=n(e),i=r(e);if(!(!t||!i))return Object.freeze({pid:e,startTime:t,command:i})}async function w(e){for(let t=0;t<5;t+=1){let t=C(e);if(t)return t;await new Promise(e=>setTimeout(e,10))}}function T(e,t){let n=O(e,t),r;try{let e=i(n);if(e===void 0)return{status:`missing`};r=e}catch(e){return{status:`invalid`,message:e instanceof Error?e.message:`App-log process marker is invalid`}}try{let e=JSON.parse(c.readFileSync(r,`utf8`));return o(e)}catch(e){return{status:`invalid`,message:e instanceof Error?e.message:`App-log process marker is invalid`}}finally{c.closeSync(r)}}function E(e,t,n){let r=O(e,t);if(T(e,r).status!==`missing`)throw Error(`Existing app-log process marker evidence must be recovered before replacement`);c.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.${process.pid}.${Date.now()}.tmp`,a,o=!1,l=!1;try{a=c.openSync(i,`wx`,384),c.writeFileSync(a,`${JSON.stringify(n)}\n`),c.fsyncSync(a),c.closeSync(a),a=void 0,c.linkSync(i,r),o=!0,c.unlinkSync(i);let e=c.openSync(s.dirname(r),`r`);try{c.fsyncSync(e)}finally{c.closeSync(e)}l=!0}finally{if(a!==void 0)try{c.closeSync(a)}catch{}if(!l)for(let e of o?[r,i]:[i])try{c.unlinkSync(e)}catch{}}}function D(e,t){let n=O(e,t);try{c.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`)throw e}}function O(e,t){return l({sessionsDir:e,pathname:t,basename:u,label:`App-log process marker`})}function k(e){return t(e.pid)?j(e)?`owned-alive`:`ownership-lost`:`missing`}async function A(n){if(!t(n.pid))return`already-missing`;if(!j(n))return`ownership-lost`;try{process.kill(n.pid,`SIGTERM`)}catch{return`already-missing`}if(!await e(n.pid,2e3)){if(!j(n))return`ownership-lost`;try{process.kill(n.pid,`SIGKILL`)}catch{return`already-missing`}await e(n.pid,2e3)}return t(n.pid)?`ownership-lost`:`terminated`}function j(e){return!e.startTime||!e.command?!1:n(e.pid)===e.startTime&&r(e.pid)===e.command}export{f as n,l as r,d as t};
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";import{Yt as t}from"./sdk-batch.js";import{n}from"./scoped-provider.js";import{r,t as i}from"./platform-runtime-unavailable.js";import{a,t as o}from"./managed-device-scope.js";const s={ensureReady:`both`,deployApp:`both`,materializeAppSource:`both`,deployMaterializedApp:`both`,sendPushNotification:`both`,setSetting:`both`,readClipboard:`both`,writeClipboard:`both`,captureScreenshot:`android`},c=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`This operation has no verified managed-device automation path.`});function l(s){return Object.freeze({owner:s.owner,ownsDevice:()=>!1,inspectFacts:async e=>r(e,s.owner,i(c)),bind:async r=>{if(r.intent.kind!==`exact-owner`||!t(r.intent.owner,s.owner))throw new e(`COMMAND_FAILED`,`A managed local owner binds only under an exact-owner intent naming it`,{reason:`runtime-contract-invalid`});let i=r.scope.managedDevice;if(!i||!t(i.owner,s.owner)||i.fence.token!==r.intent.fence.token||i.fence.generation!==r.intent.fence.generation)throw new e(`COMMAND_FAILED`,`Managed automation requires its exact request authority.`,{reason:`runtime-contract-invalid`});o(i,r.device);let c=e=>i.run(()=>a(i,e)),l=await s.loadLocal(r.device.platform),f=await c(()=>l.bind({device:r.device,intent:{kind:`ordinary`},scope:r.scope})),p=u(f.facts);return Object.freeze({device:f.device,owner:s.owner,facts:p,operations:d(n({...f.operations},e=>c(async()=>(r.scope.signal.throwIfAborted(),await i.admit(async()=>(r.scope.signal.throwIfAborted(),await e()))))),p),[Symbol.asyncDispose]:async()=>await c(async()=>await f[Symbol.asyncDispose]())})},shutdown:async()=>void 0})}function u(e){let t=Object.fromEntries(Object.entries(e.operations).map(([t,n])=>{let r=s[t];return[t,(e.device.family===`android`||e.device.family===`apple`&&e.device.appleOs===`ios`)&&(r===`both`||r===e.device.family)?n:c]}));return Object.freeze({device:e.device,operations:Object.freeze(t)})}function d(e,t){let n={};for(let[r,i]of Object.entries(e))t.operations[r]?.available===!0&&(n[r]=i);return Object.freeze(n)}export{l as createManagedLocalRuntimeOwner};
1
+ import{C as e}from"./sdk-contracts.js";import{Xt as t}from"./sdk-batch.js";import{n}from"./scoped-provider.js";import{r,t as i}from"./platform-runtime-unavailable.js";import{a,t as o}from"./managed-device-scope.js";const s={ensureReady:`both`,deployApp:`both`,materializeAppSource:`both`,deployMaterializedApp:`both`,sendPushNotification:`both`,setSetting:`both`,readClipboard:`both`,writeClipboard:`both`,captureScreenshot:`android`},c=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`This operation has no verified managed-device automation path.`});function l(s){return Object.freeze({owner:s.owner,ownsDevice:()=>!1,inspectFacts:async e=>r(e,s.owner,i(c)),bind:async r=>{if(r.intent.kind!==`exact-owner`||!t(r.intent.owner,s.owner))throw new e(`COMMAND_FAILED`,`A managed local owner binds only under an exact-owner intent naming it`,{reason:`runtime-contract-invalid`});let i=r.scope.managedDevice;if(!i||!t(i.owner,s.owner)||i.fence.token!==r.intent.fence.token||i.fence.generation!==r.intent.fence.generation)throw new e(`COMMAND_FAILED`,`Managed automation requires its exact request authority.`,{reason:`runtime-contract-invalid`});o(i,r.device);let c=e=>i.run(()=>a(i,e)),l=await s.loadLocal(r.device.platform),f=await c(()=>l.bind({device:r.device,intent:{kind:`ordinary`},scope:r.scope})),p=u(f.facts);return Object.freeze({device:f.device,owner:s.owner,facts:p,operations:d(n({...f.operations},e=>c(async()=>(r.scope.signal.throwIfAborted(),await i.admit(async()=>(r.scope.signal.throwIfAborted(),await e()))))),p),[Symbol.asyncDispose]:async()=>await c(async()=>await f[Symbol.asyncDispose]())})},shutdown:async()=>void 0})}function u(e){let t=Object.fromEntries(Object.entries(e.operations).map(([t,n])=>{let r=s[t];return[t,(e.device.family===`android`||e.device.family===`apple`&&e.device.appleOs===`ios`)&&(r===`both`||r===e.device.family)?n:c]}));return Object.freeze({device:e.device,operations:Object.freeze(t)})}function d(e,t){let n={};for(let[r,i]of Object.entries(e))t.operations[r]?.available===!0&&(n[r]=i);return Object.freeze(n)}export{l as createManagedLocalRuntimeOwner};
@@ -1,4 +1,4 @@
1
- import{C as e}from"./sdk-contracts.js";import{l as t,p as n,u as r,w as i}from"./sdk-device.js";import{r as a}from"./diagnostics.js";import{C as o}from"./owner-identity.js";import{i as s,r as c}from"./verified-file.js";import{c as l,m as u,u as d}from"./exec.js";import"./file.js";import"./diagnostics2.js";import"./command.js";import"./process.js";import{t as f}from"./platform-runtime-android-mechanics.js";import{t as p}from"./perf-runtime.js";import{a as ee,n as te}from"./durable-resource.js";import{n as ne}from"./async-lifecycle.js";import{m}from"./src7.js";import{r as re}from"./device-inventory-context.js";import{t as ie}from"./app-log-files.js";import{n as ae,r as oe,t as h}from"./platform-runtime-app-log-process.js";import{createTemporaryTextFile as g,n as _,t as v}from"./platform-runtime-host.js";import{i as y,n as b,t as x}from"./platform-runtime-screen-recording-process-host.js";import S from"node:fs";import{setTimeout as se}from"node:timers/promises";async function ce(e,t){t=C(e,t),ie(t);let n=c(t),r;try{r=S.createWriteStream(t,{fd:n,autoClose:!0})}catch(e){throw S.closeSync(n),e}let i;r.on(`error`,e=>{i??=e});let a=ue(),o=``,s=Promise.resolve(),l,u=e=>{let t=s.then(e);return s=t.catch(()=>void 0),t},d=async e=>{let t=`${o}${e}`.split(`
1
+ import{C as e}from"./sdk-contracts.js";import{l as t,p as n,u as r,w as i}from"./sdk-device.js";import{r as a}from"./diagnostics.js";import{w as o}from"./owner-identity.js";import{i as s,r as c}from"./verified-file.js";import{c as l,m as u,u as d}from"./exec.js";import"./file.js";import"./diagnostics2.js";import"./command.js";import"./process.js";import{t as f}from"./platform-runtime-android-mechanics.js";import{t as p}from"./perf-runtime.js";import{a as ee,n as te}from"./durable-resource.js";import{n as ne}from"./async-lifecycle.js";import{m}from"./src7.js";import{r as re}from"./device-inventory-context.js";import{t as ie}from"./app-log-files.js";import{n as ae,r as oe,t as h}from"./platform-runtime-app-log-process.js";import{createTemporaryTextFile as g,n as _,t as v}from"./platform-runtime-host.js";import{i as y,n as b,t as x}from"./platform-runtime-screen-recording-process-host.js";import S from"node:fs";import{setTimeout as se}from"node:timers/promises";async function ce(e,t){t=C(e,t),ie(t);let n=c(t),r;try{r=S.createWriteStream(t,{fd:n,autoClose:!0})}catch(e){throw S.closeSync(n),e}let i;r.on(`error`,e=>{i??=e});let a=ue(),o=``,s=Promise.resolve(),l,u=e=>{let t=s.then(e);return s=t.catch(()=>void 0),t},d=async e=>{let t=`${o}${e}`.split(`
2
2
  `);o=t.pop()??``;for(let e of t)await T(r,w(`${e}\n`,a))};return{write:async e=>await u(async()=>await d(de(e))),[Symbol.asyncDispose]:async()=>{l??=u(async()=>{if(o&&=(await T(r,w(o,a)),``),await fe(r),i)throw i}),await l}}}async function le(e,t,n){if(t=C(e,t),!Number.isInteger(n)||n<1||n>1048576)throw TypeError(`App-log tail size must be between 1 byte and 1 MiB`);let r=s(t);if(r===void 0)return``;let i=S.fstatSync(r).size,a=Math.min(i,n),o=i-a,c=+(o>0),l=Buffer.alloc(a+c);try{S.readSync(r,l,0,l.length,o-c)}finally{S.closeSync(r)}let u=l.subarray(c).toString(`utf8`);if(c===0||l[0]===10)return u;let d=u.indexOf(`
3
3
  `);return d<0?``:u.slice(d+1)}function C(e,t){return oe({sessionsDir:e,pathname:t,basename:`app.log`,label:`App-log output`})}function ue(){return(process.env.AGENT_DEVICE_APP_LOG_REDACT_PATTERNS??``).split(`,`).map(e=>e.trim()).filter(Boolean).flatMap(e=>{try{return[new RegExp(e,`gi`)]}catch{return[]}})}function w(e,t){return t.reduce((e,t)=>e.replace(t,`[REDACTED]`),e)}function de(e){return typeof e==`string`?e:Buffer.from(e).toString(`utf8`)}async function T(e,t){t&&await new Promise((n,r)=>{e.write(t,e=>e?r(e):n())})}async function fe(e){e.closed||await new Promise((t,n)=>{e.once(`error`,n),e.end(()=>{e.off(`error`,n),t()})})}function pe(e){return Object.freeze({appLogs:Object.freeze({resolveSession:e.resolveSessionArtifacts,readRecent:async(t,n)=>{let{outputPath:r}=e.resolveSessionArtifacts(t);return me(r,n)},readProcessMarker:async t=>{let{pidPath:n}=e.resolveSessionArtifacts(t);return await e.processes.readMarker(n)}}),networkTransports:Object.freeze({resolve:e.resolveTransport})})}function me(e,t){if(!Number.isInteger(t)||t<1||t>2e4)throw TypeError(`Network app-log scan lines must be between 1 and 20000`);let n=s(e);if(n===void 0)return Object.freeze({path:e,exists:!1,text:``,skippedLines:0});try{let r=he(S.readFileSync(n,`utf8`),t);return Object.freeze({path:e,exists:!0,...r})}finally{S.closeSync(n)}}function he(e,t){let n=e.split(`
4
4
  `),r=Math.max(0,n.length-t);return Object.freeze({text:n.slice(r).join(`
@@ -1 +1 @@
1
- import{n as e}from"./command.js";import{t}from"./platform-runtime-android-mechanics.js";import{t as n}from"./video.js";import r from"node:path";const i={medium:8e6,high:2e7};async function a(a){let{resolveAndroidAdbExecutor:s,resolveScopedAndroidAdbBackgroundTransport:c}=await t(),l=s(a),u=c(a),d=async(e,t)=>await l([`shell`,e],{allowFailure:!0,timeoutMs:5e3,signal:t});return Object.freeze({mode:u.mode,start:async({remotePath:t,quality:n=`medium`},r)=>{let a=(await d(`screenrecord --bit-rate ${i[n]} ${e(t)} >/dev/null 2>&1 & echo $!`,r)).stdout.split(/\s+/).find(e=>/^\d+$/.test(e));if(!a)throw Error(`Android screenrecord did not return a process id`);let s=await o(d,{pid:a,remotePath:t,startTime:``},r);if(s.status!==`owned-alive`||!s.process)throw Error(`Android screenrecord did not expose a complete process identity`);return Object.freeze({process:s.process})},inspect:async(e,t)=>(await o(d,e,t)).status,stop:async(e,t,n)=>{let r=await o(d,e,n);return r.status===`missing`?`already-missing`:r.status===`foreign-writer`?`ownership-lost`:r.status===`owned-alive`?(await d(`kill ${t?.force?`-9 `:`-2 `}${e.pid}`,n)).exitCode===0?`stopped`:`uncertain`:r.status},exists:async(t,n)=>(await d(`test -e ${e(t)}`,n)).exitCode===0,size:async(t,n)=>{let r=await d(`test -e ${e(t)}`,n);if(r.exitCode!==0)return r.stderr.trim()===``?void 0:`uncertain`;let i=await d(`stat -c %s ${e(t)}`,n);if(i.exitCode!==0)return`uncertain`;let a=Number(i.stdout.trim());return Number.isSafeInteger(a)&&a>=0?a:`uncertain`},findRunning:async(e,t)=>{let n=await d(`ps -A -o pid=`,t);if(n.exitCode!==0)throw Error(`failed to enumerate Android screenrecord processes`);let r=n.stdout.split(/\s+/).filter(e=>/^\d+$/.test(e));return(await Promise.all(r.map(async n=>await o(d,{pid:n,remotePath:e,startTime:``},t)))).flatMap(e=>e.status===`owned-alive`&&e.process?[e.process]:[])},pullPlayable:async({remotePath:e,outputPath:t},r)=>{let i=await l([`pull`,e,t],{allowFailure:!0,signal:r});return{...i,playable:i.exitCode===0&&await n(t)}},remove:async(t,n)=>(await d(`rm -f ${e(t)}`,n)).exitCode===0,manifestPathFor:e=>`${r.posix.dirname(e)}/agent-device-recording-active.json`,readManifest:async(t,n)=>{let r=await d(`test -e ${e(t)}`,n);if(r.exitCode!==0)return r.exitCode===1&&r.stderr.trim()===``?{status:`missing`}:{status:`unavailable`,message:r.stderr.trim()||`Android recording manifest probe failed`};let i=await d(`cat ${e(t)}`,n);return i.exitCode===0?{status:`read`,contents:i.stdout}:{status:`unavailable`,message:i.stderr.trim()||`Android recording manifest could not be read`}},writeManifest:async({manifestPath:t,contents:n},r)=>{let i=`${t}.tmp`;if((await d(`printf %s ${e(n)} > ${e(i)} && mv -f ${e(i)} ${e(t)}`,r)).exitCode!==0)throw Error(`failed to write Android recording manifest`)},removeManifest:async(t,n)=>(await d(`rm -f ${e(t)}`,n)).exitCode===0})}async function o(e,t,n){let r=await s(e,t.pid,n);if(r!==`present`)return{status:r};let i=await e(`cat /proc/${t.pid}/stat`,n);if(i.exitCode!==0)return{status:`uncertain`};let a=l(i.stdout);if(!a)return{status:`uncertain`};let o=await e(`cat /proc/${t.pid}/cmdline`,n);return o.exitCode===0?c(o.stdout,t.remotePath)?t.startTime.length>0&&t.startTime!==a?{status:`foreign-writer`}:{status:`owned-alive`,process:Object.freeze({pid:t.pid,remotePath:t.remotePath,startTime:a})}:{status:`ownership-lost`}:{status:`uncertain`}}async function s(e,t,n){let r=await e(`test -d /proc/${t}`,n);return r.exitCode===0?`present`:r.exitCode===1&&r.stderr.trim()===``?`missing`:`uncertain`}function c(e,t){let n=e.split(`\0`).filter(e=>e.length>0),i=n[0];return i!==void 0&&r.posix.basename(i)===`screenrecord`&&n.at(-1)===t}function l(e){let t=e.lastIndexOf(`)`);if(t<0)return;let n=e.slice(t+1).trim().split(/\s+/)[19];return n&&/^\d+$/.test(n)?n:void 0}export{a as createAndroidScreenRecordingTransport};
1
+ import{n as e}from"./command.js";import{t}from"./platform-runtime-android-mechanics.js";import{t as n}from"./video.js";import r from"node:path";const i={medium:8e6,high:2e7};async function a(a){let{resolveAndroidAdbExecutor:s,resolveScopedAndroidAdbBackgroundTransport:c}=await t(),l=s(a),u=c(a),d=async(e,t)=>await l([`shell`,e],{allowFailure:!0,timeoutMs:5e3,signal:t});return Object.freeze({mode:u.mode,start:async({remotePath:t,quality:n=`medium`},r)=>{let a=(await d(`screenrecord --bit-rate ${i[n]} ${e(t)} >/dev/null 2>&1 & echo $!`,r)).stdout.split(/\s+/).find(e=>/^\d+$/.test(e));if(!a)throw Error(`Android screenrecord did not return a process id`);let s=await o(d,{pid:a,remotePath:t,startTime:``},r);if(s.status!==`owned-alive`||!s.process)throw Error(`Android screenrecord did not expose a complete process identity`);return Object.freeze({process:s.process})},inspect:async(e,t)=>(await o(d,e,t)).status,stop:async(e,t,n)=>{let r=await o(d,e,n);return r.status===`missing`?`already-missing`:r.status===`foreign-writer`?`ownership-lost`:r.status===`owned-alive`?(await d(`kill ${t?.force?`-9 `:`-2 `}${e.pid}`,n)).exitCode===0?`stopped`:`uncertain`:r.status},exists:async(t,n)=>(await d(`test -e ${e(t)}`,n)).exitCode===0,size:async(t,n)=>{let r=await d(`test -e ${e(t)}`,n);if(r.exitCode!==0)return r.stderr.trim()===``?void 0:`uncertain`;let i=await d(`stat -c %s ${e(t)}`,n);if(i.exitCode!==0)return`uncertain`;let a=Number(i.stdout.trim());return Number.isSafeInteger(a)&&a>=0?a:`uncertain`},probeRunningWriters:async(e,t)=>{let n=await d(`ps -A -o pid=`,t);if(n.exitCode!==0)return{writers:[],conclusive:!1};let r=n.stdout.split(/\s+/).filter(e=>/^\d+$/.test(e)),i=await Promise.all(r.map(async n=>await o(d,{pid:n,remotePath:e,startTime:``},t)));return{writers:i.flatMap(e=>e.status===`owned-alive`&&e.process?[e.process]:[]),conclusive:!i.some(e=>e.status===`uncertain`)}},pullPlayable:async({remotePath:e,outputPath:t},r)=>{let i=await l([`pull`,e,t],{allowFailure:!0,signal:r});return{...i,playable:i.exitCode===0&&await n(t)}},remove:async(t,n)=>(await d(`rm -f ${e(t)}`,n)).exitCode===0,manifestPathFor:e=>`${r.posix.dirname(e)}/agent-device-recording-active.json`,readManifest:async(t,n)=>{let r=await d(`test -e ${e(t)}`,n);if(r.exitCode!==0)return r.exitCode===1&&r.stderr.trim()===``?{status:`missing`}:{status:`unavailable`,message:r.stderr.trim()||`Android recording manifest probe failed`};let i=await d(`cat ${e(t)}`,n);return i.exitCode===0?{status:`read`,contents:i.stdout}:{status:`unavailable`,message:i.stderr.trim()||`Android recording manifest could not be read`}},writeManifest:async({manifestPath:t,contents:n},r)=>{let i=`${t}.tmp`;if((await d(`printf %s ${e(n)} > ${e(i)} && mv -f ${e(i)} ${e(t)}`,r)).exitCode!==0)throw Error(`failed to write Android recording manifest`)},removeManifest:async(t,n)=>(await d(`rm -f ${e(t)}`,n)).exitCode===0})}async function o(e,t,n){let r=await s(e,t.pid,n);if(r!==`present`)return{status:r};let i=await e(`cat /proc/${t.pid}/stat`,n);if(i.exitCode!==0)return{status:`uncertain`};let a=l(i.stdout);if(!a)return{status:`uncertain`};let o=await e(`cat /proc/${t.pid}/cmdline`,n);return o.exitCode===0?c(o.stdout,t.remotePath)?t.startTime.length>0&&t.startTime!==a?{status:`foreign-writer`}:{status:`owned-alive`,process:Object.freeze({pid:t.pid,remotePath:t.remotePath,startTime:a})}:{status:`ownership-lost`}:{status:`uncertain`}}async function s(e,t,n){let r=await e(`test -d /proc/${t}`,n);return r.exitCode===0?`present`:r.exitCode===1&&r.stderr.trim()===``?`missing`:`uncertain`}function c(e,t){let n=e.split(`\0`).filter(e=>e.length>0),i=n[0];return i!==void 0&&r.posix.basename(i)===`screenrecord`&&n.at(-1)===t}function l(e){let t=e.lastIndexOf(`)`);if(t<0)return;let n=e.slice(t+1).trim().split(/\s+/)[19];return n&&/^\d+$/.test(n)?n:void 0}export{a as createAndroidScreenRecordingTransport};
@@ -1 +1 @@
1
- async function e(e,t,n){let{resolveAppleRunnerScreenRecordingTransport:r}=await import(`./platform-runtime-screen-recording-apple-runner-transport.js`),i=r();if(t.kind===`stop`){if(i.authority!==t.runnerAuthority)throw Error(`Apple runner recording ownership changed before cleanup`);return await i.stop({device:e,runnerSessionId:t.runnerSessionId,appBundleId:t.appBundleId,signal:n}),{}}let a=await i.start({device:e,appBundleId:t.appBundleId,outputPath:t.outputPath,fps:t.fps,signal:n});return Object.freeze({runnerSessionId:a.runnerSessionId,runnerAuthority:i.authority,...a.remotePath===void 0?{}:{remotePath:a.remotePath},...typeof a.recorderStartUptimeMs==`number`?{recorderStartUptimeMs:a.recorderStartUptimeMs}:{},...typeof a.targetAppReadyUptimeMs==`number`?{targetAppReadyUptimeMs:a.targetAppReadyUptimeMs}:{}})}async function t(e,t,n){let{resolveAppleRunnerScreenRecordingTransport:r}=await import(`./platform-runtime-screen-recording-apple-runner-transport.js`),i=r();return i.authority===n?await i.inspect(e,t):`ownership-lost`}async function n(e,t,n,r){r?.throwIfAborted();let{resolveIosPhysicalDeviceControl:i}=await import(`./physical-device-facade.js`);await i(e).copyRunnerFile(e,t,n),r?.throwIfAborted()}async function r(e,t,n){try{let[r,i]=await Promise.all([import(`./platform-runtime-screen-recording-apple-transport.js`).then(e=>e.resolveAppleSimulatorScreenRecordingTransport()),import(`./platform-runtime-screen-recording-apple-runner-transport.js`).then(e=>e.resolveAppleRunnerScreenRecordingTransport())]);if(r.mode===`transport-composed`&&i.authority!==`scoped-provider`)return;let{runAppleRunnerCommand:a}=await import(`./runner-operations-facade.js`),o=await a(e,{command:`snapshot`,appBundleId:t,interactiveOnly:!0,depth:1},{signal:n}),s=Date.now();return typeof o.currentUptimeMs==`number`&&Number.isFinite(o.currentUptimeMs)&&o.currentUptimeMs>0?{wallClockAtMs:s,uptimeMs:o.currentUptimeMs}:void 0}catch{n?.throwIfAborted();return}}async function i(e){let{IOS_RUNNER_CONTAINER_BUNDLE_IDS:t}=await import(`./runner.js`).then(e=>e.t);return t.includes(e)}export{r as captureAppleClockAnchor,t as inspectAppleRunnerOwnership,i as isAppleRunnerBundleId,n as retrieveAppleRunnerRecording,e as runAppleRecordingRunner};
1
+ async function e(e,t,n){let{resolveAppleRunnerScreenRecordingTransport:r}=await import(`./platform-runtime-screen-recording-apple-runner-transport.js`),i=r();if(t.kind===`stop`){if(i.authority!==t.runnerAuthority)throw Error(`Apple runner recording ownership changed before cleanup`);return await i.stop({device:e,runnerSessionId:t.runnerSessionId,appBundleId:t.appBundleId,signal:n}),{}}let a=await i.start({device:e,appBundleId:t.appBundleId,outputPath:t.outputPath,fps:t.fps,signal:n});return Object.freeze({runnerSessionId:a.runnerSessionId,runnerAuthority:i.authority,...a.remotePath===void 0?{}:{remotePath:a.remotePath},...typeof a.recorderStartUptimeMs==`number`?{recorderStartUptimeMs:a.recorderStartUptimeMs}:{}})}async function t(e,t,n){let{resolveAppleRunnerScreenRecordingTransport:r}=await import(`./platform-runtime-screen-recording-apple-runner-transport.js`),i=r();return i.authority===n?await i.inspect(e,t):`ownership-lost`}async function n(e,t,n,r){r?.throwIfAborted();let{resolveIosPhysicalDeviceControl:i}=await import(`./physical-device-facade.js`);await i(e).copyRunnerFile(e,t,n),r?.throwIfAborted()}async function r(e,t,n){try{let[r,i]=await Promise.all([import(`./platform-runtime-screen-recording-apple-transport.js`).then(e=>e.resolveAppleSimulatorScreenRecordingTransport()),import(`./platform-runtime-screen-recording-apple-runner-transport.js`).then(e=>e.resolveAppleRunnerScreenRecordingTransport())]);if(r.mode===`transport-composed`&&i.authority!==`scoped-provider`)return;let{runAppleRunnerCommand:a}=await import(`./runner-operations-facade.js`),o=await a(e,{command:`snapshot`,appBundleId:t,interactiveOnly:!0,depth:1},{signal:n}),s=Date.now();return typeof o.currentUptimeMs==`number`&&Number.isFinite(o.currentUptimeMs)&&o.currentUptimeMs>0?{wallClockAtMs:s,uptimeMs:o.currentUptimeMs}:void 0}catch{n?.throwIfAborted();return}}async function i(e){let{IOS_RUNNER_CONTAINER_BUNDLE_IDS:t}=await import(`./runner.js`).then(e=>e.t);return t.includes(e)}export{r as captureAppleClockAnchor,t as inspectAppleRunnerOwnership,i as isAppleRunnerBundleId,n as retrieveAppleRunnerRecording,e as runAppleRecordingRunner};
@@ -1 +1 @@
1
- import{p as e}from"./owner-identity.js";import"./process.js";import{t}from"./scoped-provider.js";import n from"node:path";const r=Object.freeze({authority:`local-lease`,available:!0,start:i,inspect:async(e,t)=>await d(e,t),stop:async({device:e,runnerSessionId:t,appBundleId:n,signal:r})=>{let{runAppleRunnerCommand:i}=await import(`./runner-operations-facade.js`);await i(e,{command:`recordStop`,appBundleId:n},{signal:r,expectedRunnerSessionId:t})}});async function i({device:e,appBundleId:t,outputPath:n,fps:r,signal:i}){let{getRunnerSessionSnapshot:s,runAppleRunnerCommand:c}=await import(`./runner-operations-facade.js`),l=`agent-device-recording-${Date.now()}.mp4`,u=e.appleOs===`macos`||e.kind!==`device`?void 0:`tmp/${l}`,d=await c(e,{command:`recordStart`,outPath:a(e,n,l,u),...r===void 0?{}:{fps:r},appBundleId:t},{signal:i}),f=await s(e.id);if(!f?.alive)throw Error(`Apple runner recording did not expose a durable runner session identity`);try{i?.throwIfAborted()}catch(n){throw await c(e,{command:`recordStop`,appBundleId:t},{expectedRunnerSessionId:f.sessionId}).catch(()=>{}),n}return o(f.sessionId,u,d)}function a(e,t,r,i){return e.appleOs===`macos`?t:i===void 0?n.basename(t):r}function o(e,t,n){return Object.freeze({runnerSessionId:e,...t===void 0?{}:{remotePath:t},...typeof n.recorderStartUptimeMs==`number`?{recorderStartUptimeMs:n.recorderStartUptimeMs}:{},...typeof n.targetAppReadyUptimeMs==`number`?{targetAppReadyUptimeMs:n.targetAppReadyUptimeMs}:{}})}const s=Object.freeze({authority:`scoped-provider`,available:!1,start:async()=>{throw Error(`Scoped Apple runner provider does not expose durable recording authority`)},inspect:async()=>`ownership-lost`,stop:async()=>{throw Error(`Scoped Apple runner recording authority is unavailable`)}}),c=t(r);function l(){return c.resolve()}async function u(e,t){return await c.run(e??s,t)}async function d(t,n){let{getRunnerSessionSnapshot:r,readStaleRunnerLease:i,verifyLeaseRunnerPidIdentity:a}=await import(`./runner-operations-facade.js`),o=await r(t.id);if(o)return o.alive?o.sessionId===n?`owned-alive`:`ownership-lost`:`missing`;let s=await i(t.id);return s?s.sessionId===n?s.runnerPid===null||!e(s.runnerPid)?`missing`:await a(s,s.runnerPid)?`owned-alive`:`ownership-lost`:`ownership-lost`:`missing`}export{l as resolveAppleRunnerScreenRecordingTransport,u as withAppleRunnerScreenRecordingTransport};
1
+ import{p as e}from"./owner-identity.js";import"./process.js";import{t}from"./scoped-provider.js";import n from"node:path";const r=Object.freeze({authority:`local-lease`,available:!0,start:i,inspect:async(e,t)=>await d(e,t),stop:async({device:e,runnerSessionId:t,appBundleId:n,signal:r})=>{let{runAppleRunnerCommand:i}=await import(`./runner-operations-facade.js`);await i(e,{command:`recordStop`,appBundleId:n},{signal:r,expectedRunnerSessionId:t})}});async function i({device:e,appBundleId:t,outputPath:n,fps:r,signal:i}){let{getRunnerSessionSnapshot:s,runAppleRunnerCommand:c}=await import(`./runner-operations-facade.js`),l=`agent-device-recording-${Date.now()}.mp4`,u=e.appleOs===`macos`||e.kind!==`device`?void 0:`tmp/${l}`,d=await c(e,{command:`recordStart`,outPath:a(e,n,l,u),...r===void 0?{}:{fps:r},appBundleId:t},{signal:i}),f=await s(e.id);if(!f?.alive)throw Error(`Apple runner recording did not expose a durable runner session identity`);try{i?.throwIfAborted()}catch(n){throw await c(e,{command:`recordStop`,appBundleId:t},{expectedRunnerSessionId:f.sessionId}).catch(()=>{}),n}return o(f.sessionId,u,d)}function a(e,t,r,i){return e.appleOs===`macos`?t:i===void 0?n.basename(t):r}function o(e,t,n){return Object.freeze({runnerSessionId:e,...t===void 0?{}:{remotePath:t},...typeof n.recorderStartUptimeMs==`number`?{recorderStartUptimeMs:n.recorderStartUptimeMs}:{}})}const s=Object.freeze({authority:`scoped-provider`,available:!1,start:async()=>{throw Error(`Scoped Apple runner provider does not expose durable recording authority`)},inspect:async()=>`ownership-lost`,stop:async()=>{throw Error(`Scoped Apple runner recording authority is unavailable`)}}),c=t(r);function l(){return c.resolve()}async function u(e,t){return await c.run(e??s,t)}async function d(t,n){let{getRunnerSessionSnapshot:r,readStaleRunnerLease:i,verifyLeaseRunnerPidIdentity:a}=await import(`./runner-operations-facade.js`),o=await r(t.id);if(o)return o.alive?o.sessionId===n?`owned-alive`:`ownership-lost`:`missing`;let s=await i(t.id);return s?s.sessionId===n?s.runnerPid===null||!e(s.runnerPid)?`missing`:await a(s,s.runnerPid)?`owned-alive`:`ownership-lost`:`ownership-lost`:`missing`}export{l as resolveAppleRunnerScreenRecordingTransport,u as withAppleRunnerScreenRecordingTransport};
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";import{n as t}from"./exec.js";import"./command.js";import{i as n,n as r,r as i,t as a}from"./platform-runtime-screen-recording-process-host.js";import o from"node:fs";const s=(e,t)=>{if(e===t)return!0;let n=/^(?:\S*\/)?xcrun simctl (.+)$/.exec(e)?.[1],r=/^(?:\S*\/)?simctl (.+)$/.exec(t)?.[1];return n!==void 0&&n===r&&/^(?:--set .+ )?io \S+ recordVideo .+$/.test(n)};async function c(e,t,a){let{resolveAppleSimulatorScreenRecordingTransport:c}=await import(`./platform-runtime-screen-recording-apple-transport.js`);a?.throwIfAborted();let p;try{p=await u(c().start({device:e,outputPath:t,signal:a}),a),a?.throwIfAborted()}catch(e){throw p&&await d(p),o.rmSync(t,{force:!0}),a?.throwIfAborted(),e}if(!p)throw Error(`simctl recordVideo acquisition did not return a process`);let m;try{if(m=await l(p.child.pid,p.wait,a),!m)throw Error(`simctl recordVideo did not expose a complete process identity`)}catch(e){throw await d(p),a?.throwIfAborted(),e}try{await h(t,p.wait,a);let e=await r(m.pid)??m,n=await i(e);return f(p,n)}catch(e){throw await n([m],p,s).catch(()=>{}),await p.wait.catch(()=>void 0),o.rmSync(t,{force:!0}),a?.throwIfAborted(),e}}async function l(e,t,n){let i=g(t),a=e===void 0?0:80;for(let t=0;t<=a;t+=1){n?.throwIfAborted();let o=await r(e);if(o)return o;let s=await Promise.race([i,t<a?v(25,n).then(()=>void 0):Promise.resolve(void 0)]);if(s)throw _(s)}}async function u(e,t){let n=Promise.resolve(e);if(!t)return await n;if(t.aborted)throw`child`in e?await d(e):n.then(d),t.reason;let r=()=>{},i=new Promise((e,n)=>{let i=()=>n(t.reason);t.addEventListener(`abort`,i,{once:!0}),r=()=>t.removeEventListener(`abort`,i),t.aborted&&i()});try{return await Promise.race([n,i])}catch(e){throw t.aborted?(n.then(d),t.reason):e}finally{r()}}async function d(e){e.child.kill(`SIGINT`);let t=new AbortController;await Promise.race([e.wait.then(()=>!0,()=>!0),v(5e3,t.signal).then(()=>!1)]).finally(()=>t.abort())||(e.child.kill(`SIGKILL`),await e.wait.catch(()=>void 0))}function f(e,t){let r,i=!1,a=()=>r??=n(t,e,s).then(e=>{if(e===`ownership-lost`)throw Error(`simctl recordVideo process ownership changed before cleanup`);if(e!==`terminated`&&e!==`already-missing`)throw Error(`simctl recordVideo cleanup was not confirmed`);i=e===`terminated`}),o=e.wait.then(async e=>{let t=r;return t&&await t.catch(()=>void 0),i&&e.exitCode!==0?{...e,exitCode:0}:e});return Object.freeze({markers:Object.freeze([...t]),wait:o,terminate:a})}function p(e){return a(e,s)}async function m(e){return await n([e],void 0,s)}async function h(e,t,n){let r=g(t),i;r.then(e=>{i=e}),await Promise.resolve();for(let t=0;t<=60;t+=1){if(n?.throwIfAborted(),i)throw _(i);if(o.existsSync(e)){let e=await Promise.race([r,v(50,n).then(()=>void 0)]);if(e)throw _(e);return}if(t===60)throw Error(`simctl recordVideo did not create its output within 15000ms`);let a=await Promise.race([r,v(250,n).then(()=>void 0)]);if(a)throw _(a)}}function g(e){return e.then(e=>({kind:`exited`,result:e}),e=>({kind:`failed`,error:e}))}function _(n){if(n.kind===`failed`)return n.error instanceof Error?n.error:Error(String(n.error));let{exitCode:r}=n.result;return r===16?new e(`DEVICE_IN_USE`,`CoreSimulator host recording is already in progress`,t({...n.result,exitCode:r},{reason:`apple_simulator_recording_busy`,retriable:!1,hint:`Stop the active recording with record stop in its owning session. If a previous recorder died and no recording is active, ask the host operator to restart the CoreSimulator stream service before retrying.`})):Error(`simctl recordVideo exited with code ${r}`)}function v(e,t){return t?.throwIfAborted(),new Promise((n,r)=>{let i=e=>{clearTimeout(a),t?.removeEventListener(`abort`,o),e===void 0?n():r(e)},a=setTimeout(()=>i(),e);if(!t)return;let o=()=>i(t.reason);t.addEventListener(`abort`,o,{once:!0}),t.aborted&&o()})}export{p as inspectAppleSimulatorRecordingProcess,c as startAppleSimulatorRecording,m as terminateAppleSimulatorRecordingProcess};
1
+ import{C as e}from"./sdk-contracts.js";import{n as t}from"./exec.js";import"./command.js";import{i as n,n as r,r as i,t as a}from"./platform-runtime-screen-recording-process-host.js";import o from"node:fs";const s=(e,t)=>{if(e===t)return!0;let n=/^(?:\S*\/)?xcrun simctl (.+)$/.exec(e)?.[1],r=/^(?:\S*\/)?simctl (.+)$/.exec(t)?.[1];return n!==void 0&&n===r&&/^(?:--set .+ )?io \S+ recordVideo .+$/.test(n)};async function c(e,t,a){let{resolveAppleSimulatorScreenRecordingTransport:c}=await import(`./platform-runtime-screen-recording-apple-transport.js`);a?.throwIfAborted();let p;try{p=await u(c().start({device:e,outputPath:t,signal:a}),a),a?.throwIfAborted()}catch(e){throw p&&await d(p),o.rmSync(t,{force:!0}),a?.throwIfAborted(),e}if(!p)throw Error(`simctl recordVideo acquisition did not return a process`);let m;try{if(m=await l(p.child.pid,p.wait,a),!m)throw Error(`simctl recordVideo did not expose a complete process identity`)}catch(e){throw await d(p),a?.throwIfAborted(),e}try{await h(t,p.wait,a);let e=await r(m.pid)??m,n=await i(e);return f(p,n)}catch(e){throw await n([m],p,s).catch(()=>{}),await p.wait.catch(()=>void 0),o.rmSync(t,{force:!0}),a?.throwIfAborted(),e}}async function l(e,t,n){let i=g(t),a=e===void 0?0:80;for(let t=0;t<=a;t+=1){n?.throwIfAborted();let o=await r(e);if(o)return o;let s=await Promise.race([i,t<a?v(25,n).then(()=>void 0):Promise.resolve(void 0)]);if(s)throw _(s)}}async function u(e,t){let n=Promise.resolve(e);if(!t)return await n;if(t.aborted)throw`child`in e?await d(e):n.then(d).catch(()=>void 0),t.reason;let r=()=>{},i=new Promise((e,n)=>{let i=()=>n(t.reason);t.addEventListener(`abort`,i,{once:!0}),r=()=>t.removeEventListener(`abort`,i),t.aborted&&i()});try{return await Promise.race([n,i])}catch(e){throw t.aborted?(n.then(d).catch(()=>void 0),t.reason):e}finally{r()}}async function d(e){e.child.kill(`SIGINT`);let t=new AbortController;await Promise.race([e.wait.then(()=>!0,()=>!0),v(5e3,t.signal).then(()=>!1)]).finally(()=>t.abort())||(e.child.kill(`SIGKILL`),await e.wait.catch(()=>void 0))}function f(e,t){let r,i=!1,a=()=>n(t,e,s).then(e=>{if(e===`ownership-lost`)throw Error(`simctl recordVideo process ownership changed before cleanup`);i=e===`terminated`}),o=()=>(r??=a().catch(e=>{throw r=void 0,e}),r),c=e.wait.then(async e=>{let t=r;return t&&await t.catch(()=>void 0),i&&e.exitCode!==0?{...e,exitCode:0}:e});return Object.freeze({markers:Object.freeze([...t]),wait:c,terminate:o})}function p(e){return a(e,s)}async function m(e){return await n([e],void 0,s)}async function h(e,t,n){let r=g(t),i;r.then(e=>{i=e}),await Promise.resolve();for(let t=0;t<=60;t+=1){if(n?.throwIfAborted(),i)throw _(i);if(o.existsSync(e)){let e=await Promise.race([r,v(50,n).then(()=>void 0)]);if(e)throw _(e);return}if(t===60)throw Error(`simctl recordVideo did not create its output within 15000ms`);let a=await Promise.race([r,v(250,n).then(()=>void 0)]);if(a)throw _(a)}}function g(e){return e.then(e=>({kind:`exited`,result:e}),e=>({kind:`failed`,error:e}))}function _(n){if(n.kind===`failed`)return n.error instanceof Error?n.error:Error(String(n.error));let{exitCode:r}=n.result;return r===16?new e(`DEVICE_IN_USE`,`CoreSimulator host recording is already in progress`,t({...n.result,exitCode:r},{reason:`apple_simulator_recording_busy`,retriable:!1,hint:`Stop the active recording with record stop in its owning session. If a previous recorder died and no recording is active, ask the host operator to restart the CoreSimulator stream service before retrying.`})):Error(`simctl recordVideo exited with code ${r}`)}function v(e,t){return t?.throwIfAborted(),new Promise((n,r)=>{let i=e=>{clearTimeout(a),t?.removeEventListener(`abort`,o),e===void 0?n():r(e)},a=setTimeout(()=>i(),e);if(!t)return;let o=()=>i(t.reason);t.addEventListener(`abort`,o,{once:!0}),t.aborted&&o()})}export{p as inspectAppleSimulatorRecordingProcess,c as startAppleSimulatorRecording,m as terminateAppleSimulatorRecordingProcess};
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";import{t}from"./recording-export-quality.js";import{c as n}from"./exec.js";import"./command.js";import{n as r}from"./version.js";import{n as i}from"./telemetry.js";import{a,i as o,n as s,r as c,t as l}from"./video.js";import u from"node:path";import d from"node:fs";import{fileURLToPath as f}from"node:url";function p(e,t,n,r){let i=`apple/runner/AgentDeviceRunner/RecordingScripts/${e}`,a=`dist/${i}`;return[u.resolve(t,e),u.resolve(n,i),u.resolve(t,`../${i}`),u.resolve(t,`../../${i}`),u.resolve(t,`../../../${i}`),u.resolve(n,a),u.resolve(r,i)]}function m(t){let n=p(t,u.dirname(f(import.meta.url)),r(),process.cwd());for(let e of n)if(d.existsSync(e))return e;throw new e(`COMMAND_FAILED`,`Missing recording helper script: ${t}`,{hint:`Ensure apple/runner/AgentDeviceRunner/RecordingScripts is present in this checkout or bundled under dist/apple/runner in the package.`,scriptName:t,searchedPaths:n})}let h,g,_;function v(e=process.platform){if(e!==`darwin`)return`touch overlay burn-in is only available on macOS hosts; returning raw video plus gesture telemetry`}function y(){return h??=m(`recording-overlay.swift`),h}function b(){return g??=m(`recording-trim.swift`),g}function x(){return _??=m(`RecordingExportSupport.swift`),_}async function S(t){let{videoPath:r,scriptPath:i,scriptArgs:l,commandDescription:u}=t;await c(r),await s(r);let f=C(r);try{let e=await a({sourcePath:i,extraSourcePaths:[x()]});await n(e,[`--input`,r,`--output`,f,...l],{timeoutMs:12e4,env:o()}),await s(f),d.renameSync(f,r)}catch(t){let n=t instanceof e?t:new e(`COMMAND_FAILED`,String(t),void 0,t instanceof Error?t:void 0);throw new e(`COMMAND_FAILED`,u,{...n.details,videoPath:r,script:i},n)}finally{d.rmSync(f,{force:!0})}}function C(e){let t=u.parse(e),n=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return u.join(t.dir,`.${t.name}.agent-device-${n}${t.ext||`.mp4`}`)}async function w(e){let{videoPath:t,trimStartMs:n}=e;n>0&&await S({videoPath:t,scriptPath:b(),scriptArgs:[`--trim-start-ms`,String(n)],commandDescription:`Failed to trim the start of the iOS recording`})}async function T(e){let{videoPath:n,telemetryPath:r,exportQuality:i=t,targetLabel:a=`recording`}=e;await S({videoPath:n,scriptPath:y(),scriptArgs:[`--events`,r,`--quality`,i],commandDescription:`Failed to add touch overlays to the ${a}`})}function E(){return Object.freeze({complete:D})}async function D(e){if(await c(e.outputPath),await s(e.outputPath),!await l(e.outputPath))throw Error(`recording was not finalized into a playable video: ${e.outputPath}`);e.trimStartMs&&e.trimStartMs>0&&await w({videoPath:e.outputPath,trimStartMs:e.trimStartMs});let t=i({recording:{outPath:e.outputPath,gestureEvents:[...e.gestureEvents]},...e.trimStartMs===void 0?{}:{trimStartMs:e.trimStartMs}});return!e.showTouches||e.gestureEvents.length===0?{telemetryPath:t}:await O(e,t)}async function O(e,t){let n=v();if(n)return{telemetryPath:t,overlayWarning:n};try{if(await T({videoPath:e.outputPath,telemetryPath:t,exportQuality:e.exportQuality,targetLabel:e.targetLabel}),!await l(e.outputPath))throw Error(`recording post-processing produced an unplayable video`);return{telemetryPath:t}}catch(e){return{telemetryPath:t,overlayWarning:`failed to overlay recording touches: ${e instanceof Error?e.message:String(e)}`}}}export{E as createScreenRecordingFinalizer};
1
+ import{C as e}from"./sdk-contracts.js";import{t}from"./recording-export-quality.js";import{c as n}from"./exec.js";import"./command.js";import{n as r}from"./version.js";import{n as i}from"./telemetry.js";import{a,i as o,n as s,r as c,t as l}from"./video.js";import u from"node:path";import d from"node:fs";import{fileURLToPath as f}from"node:url";function p(e,t,n,r){let i=`apple/runner/AgentDeviceRunner/RecordingScripts/${e}`,a=`dist/${i}`;return[u.resolve(t,e),u.resolve(n,i),u.resolve(t,`../${i}`),u.resolve(t,`../../${i}`),u.resolve(t,`../../../${i}`),u.resolve(n,a),u.resolve(r,i)]}function m(t){let n=p(t,u.dirname(f(import.meta.url)),r(),process.cwd());for(let e of n)if(d.existsSync(e))return e;throw new e(`COMMAND_FAILED`,`Missing recording helper script: ${t}`,{hint:`Ensure apple/runner/AgentDeviceRunner/RecordingScripts is present in this checkout or bundled under dist/apple/runner in the package.`,scriptName:t,searchedPaths:n})}let h,g;function _(e=process.platform){if(e!==`darwin`)return`touch overlay burn-in is only available on macOS hosts; returning raw video plus gesture telemetry`}function v(){return h??=m(`recording-overlay.swift`),h}function y(){return g??=m(`RecordingExportSupport.swift`),g}async function b(t){let{videoPath:r,scriptPath:i,scriptArgs:l,commandDescription:u}=t;await c(r),await s(r);let f=x(r);try{let e=await a({sourcePath:i,extraSourcePaths:[y()]});await n(e,[`--input`,r,`--output`,f,...l],{timeoutMs:12e4,env:o()}),await s(f),d.renameSync(f,r)}catch(t){let n=t instanceof e?t:new e(`COMMAND_FAILED`,String(t),void 0,t instanceof Error?t:void 0);throw new e(`COMMAND_FAILED`,u,{...n.details,videoPath:r,script:i},n)}finally{d.rmSync(f,{force:!0})}}function x(e){let t=u.parse(e),n=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;return u.join(t.dir,`.${t.name}.agent-device-${n}${t.ext||`.mp4`}`)}async function S(e){let{videoPath:n,telemetryPath:r,exportQuality:i=t,targetLabel:a=`recording`}=e;await b({videoPath:n,scriptPath:v(),scriptArgs:[`--events`,r,`--quality`,i],commandDescription:`Failed to add touch overlays to the ${a}`})}function C(){return Object.freeze({complete:w})}async function w(e){if(await c(e.outputPath),await s(e.outputPath),!await l(e.outputPath))throw Error(`recording was not finalized into a playable video: ${e.outputPath}`);let t=i({recording:{outPath:e.outputPath,gestureEvents:[...e.gestureEvents]}});return!e.showTouches||e.gestureEvents.length===0?{telemetryPath:t}:await T(e,t)}async function T(e,t){let n=_();if(n)return{telemetryPath:t,overlayWarning:n};try{if(await S({videoPath:e.outputPath,telemetryPath:t,exportQuality:e.exportQuality,targetLabel:e.targetLabel}),!await l(e.outputPath))throw Error(`recording post-processing produced an unplayable video`);return{telemetryPath:t}}catch(e){return{telemetryPath:t,overlayWarning:`failed to overlay recording touches: ${e instanceof Error?e.message:String(e)}`}}}export{C as createScreenRecordingFinalizer};
@@ -1 +1 @@
1
- import{b as e,g as t,h as n,o as r,p as i,w as a,x as o,y as s}from"./owner-identity.js";import"./process.js";const c=2e3,l=(e,t)=>e===t;async function u(t){if(t===void 0)return;let[n,r]=await Promise.all([Promise.resolve(e(t)),Promise.resolve(s(t))]);return n&&r?Object.freeze({pid:t,startTime:n,command:r}):void 0}async function d(e){let n=await t({timeoutMs:1e3}),i=r([e.pid],n),a=(await Promise.all(i.map(async e=>await u(e.pid)))).filter(e=>e!==void 0);return Object.freeze([e,...a.filter(t=>t.pid!==e.pid)])}function f(e,t=l){return!i(e.pid)||n(e.pid)?`missing`:_(e,t)?`owned-alive`:`ownership-lost`}async function p(e,t,n=l){let r=e.map(e=>({marker:e,ownership:f(e,n)}));if(r.some(({ownership:e})=>e===`ownership-lost`))return`ownership-lost`;let i=r.filter(({ownership:e})=>e===`owned-alive`).map(({marker:e})=>e);if(i.length===0)return`already-missing`;let a=e[0],o=a&&f(a,n)===`owned-alive`?await d(a):[],s=g([...i,...o]);if(s.some(e=>f(e,n)===`ownership-lost`))return`ownership-lost`;for(let[e,r]of[[`SIGINT`,5e3],[`SIGTERM`,c],[`SIGKILL`,c]])if(m(s,e,t),await h(s,r,t?.wait,n))return`terminated`;return`ownership-lost`}function m(e,t,n){let r=n?.child.pid;o(e.map(({pid:e})=>e).filter(e=>e!==r),t),r!==void 0&&e.some(({pid:e})=>e===r)&&n?.child.kill(t)}async function h(e,t,n,r=l){let i=e[0]?.pid,o=n?await v(n,t):!1;return await Promise.all(e.filter(({pid:e})=>!o||e!==i).map(async({pid:e})=>await a(e,t))),e.every(e=>o&&e.pid===i||f(e,r)===`missing`)}function g(e){return[...new Map(e.map(e=>[e.pid,e])).values()]}function _(t,n){let r=s(t.pid);return t.startTime.length>0&&t.command.length>0&&e(t.pid)===t.startTime&&r!==null&&n(t.command,r)}async function v(e,t){return await Promise.race([e.then(()=>!0,()=>!0),new Promise(e=>setTimeout(()=>e(!1),t))])}export{p as i,u as n,d as r,f as t};
1
+ import{D as e}from"./sdk-contracts.js";import{r as t}from"./diagnostics.js";import{S as n,T as r,b as i,g as a,h as o,o as s,p as c,x as l,y as u}from"./owner-identity.js";import"./diagnostics2.js";import"./process.js";const d=2e3,f=(e,t)=>e===t;async function p(e){if(e===void 0)return;let[t,n]=await Promise.all([Promise.resolve(l(e)),Promise.resolve(u(e))]);return t&&n?Object.freeze({pid:e,startTime:t,command:n}):void 0}async function m(e){let t=await h(e.pid),n=s([e.pid],t),r=(await Promise.all(n.map(async e=>await p(e.pid)))).filter(e=>e!==void 0);return Object.freeze([e,...r.filter(t=>t.pid!==e.pid)])}async function h(n){try{return await a({timeoutMs:5e3})}catch(r){return t({level:`warn`,phase:`screen_recording_process_tree_unreadable`,data:{rootPid:n,reason:e(r)}}),[]}}function g(e,t=f){return!c(e.pid)||o(e.pid)?`missing`:S(e,t)?`owned-alive`:`ownership-lost`}async function _(e,t){if(!c(e.pid))return`gone`;let n=await i(e.pid,5e3);return n.zombie===!0?`gone`:e.startTime.length===0||e.command.length===0?`not-ours`:n.startTime===null||n.command===null?`unprovable`:n.startTime===e.startTime&&t(e.command,n.command)?`ours`:`not-ours`}async function v(e,t,n=f){let r=t?.child.pid,i=async e=>({marker:e,evidence:await _(e,n)}),a=({marker:e,evidence:t})=>t===`ours`||t===`unprovable`&&e.pid===r,o=await Promise.all(e.map(i)),s=o[0],c=new Set(e.map(({pid:e})=>e)),l=s!==void 0&&a(s)?await m(s.marker):[],u=await Promise.all(l.filter(({pid:e})=>!c.has(e)).map(async e=>await i(e))),p=[...o,...u],h=p.filter(a).map(({marker:e})=>e);if(h.length===0)return y(p.map(({evidence:e})=>e));let g=new Set(h.map(({pid:e})=>e)),v=p.filter(({marker:e,evidence:t})=>!g.has(e.pid)&&t!==`gone`);for(let[e,r]of[[`SIGINT`,5e3],[`SIGTERM`,d],[`SIGKILL`,d]])if(b(h,e,t),await x(h,r,t,n))return v.length===0?`terminated`:`ownership-lost`;return`ownership-lost`}function y(e){return e.every(e=>e===`gone`)?`already-missing`:`ownership-lost`}function b(e,t,r){let i=r?.child.pid;n(e.map(({pid:e})=>e).filter(e=>e!==i),t),i!==void 0&&e.some(({pid:e})=>e===i)&&r?.child.kill(t)}async function x(e,t,n,i){let a=n?.child.pid,o=n?await C(n.wait,t):!1;return await Promise.all(e.filter(({pid:e})=>!o||e!==a).map(async({pid:e})=>await r(e,t))),e.every(e=>o&&e.pid===a||g(e,i)===`missing`)}function S(e,t){let n=u(e.pid);return e.startTime.length>0&&e.command.length>0&&l(e.pid)===e.startTime&&n!==null&&t(e.command,n)}async function C(e,t){return await Promise.race([e.then(()=>!0,()=>!0),new Promise(e=>setTimeout(()=>e(!1),t))])}export{v as i,p as n,m as r,g as t};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{C as t}from"./sdk-contracts.js";import{D as n,E as r,O as i,c as a,w as o}from"./sdk-device.js";import{Jt as s,O as c,Yt as l,qt as u}from"./sdk-batch.js";import{a as d,i as f,t as p}from"./device.js";import{t as ee}from"./startup-recovery-fence.js";import{i as m,n as h,r as g}from"./src2.js";import{i as _,m as v}from"./src3.js";import{n as te,t as ne}from"./src4.js";import{c as re,g as y,n as b}from"./src5.js";import{r as x,t as S}from"./src6.js";import{n as C,r as ie,t as w}from"./platform-runtime-unavailable.js";const T=Object.freeze({family:`android`});function ae(e){let t,n=()=>(t??=import(`./observation.js`).then(({createAndroidObservationAdapter:t})=>t(e)),t);return Object.freeze({readAppState:async(...e)=>await(await n()).readAppState(...e),readBlockingDialog:async(...e)=>await(await n()).readBlockingDialog(...e),readAppFocus:async(...e)=>await(await n()).readAppFocus(...e),readSnapshotNodes:async(...e)=>await(await n()).readSnapshotNodes(...e),tap:async(...e)=>await(await n()).tap(...e),openApp:async(...e)=>await(await n()).openApp(...e),readScreenSize:async(...e)=>await(await n()).readScreenSize(...e),isPermissionPackage:async(...e)=>await(await n()).isPermissionPackage(...e)})}async function oe(e,t){let{readAndroidAppStateWithExecutor:n}=await import(`./app-state.js`);return await n(e,t)}function se(e){return Object.freeze({...T,loadRuntime:async t=>{await e.bindAdbHost();let{createAndroidPlatformRuntime:n}=await import(`./runtime2.js`);return n(t)}})}function ce(e){let t=Object.freeze({sdkRoots:Object.freeze([...new Set(e.sdkRoots.map(e=>e.trim()).filter(Boolean))])});return Object.freeze({...T,loadInventory:async e=>{let{createAndroidInventory:n}=await import(`./inventory.js`);return n(e,t)}})}async function le(e){let{createAndroidShutdownRuntime:t}=await import(`./runtime3.js`);return t(e)}function ue(e){let t=new Map,n=new Map;for(let r of e.providerModules??[]){let{runtime:e,module:i}=r,a=s(i.owner);if(i.owner.provider!==e.provider)throw z(`Provider platform runtime metadata is invalid: ${a}`);if(t.has(a))throw z(`Duplicate platform runtime owner: ${a}`);if(n.has(e))throw z(`Duplicate platform module registration for ${e.provider}`);t.set(a,r),n.set(e,i)}let r=new Map;for(let t of e.managedOwners??[]){let e=s(t);if(r.has(e))throw z(`Duplicate platform runtime owner: ${e}`);r.set(e,t)}let i=new Map,a=new Map,o=new Map,c=new Map,u,d=async()=>{u??=e.loadHost();try{return await u}catch(e){throw u=void 0,e}},f,p,m=Object.freeze({recoverStartupResources:async e=>{await ee(e.stateDir,async()=>{await(await d()).applicationResources.recoverStartupResources(e)})},detachForDaemonShutdown:async()=>{f??=d().then(async e=>await e.applicationResources.detachForDaemonShutdown()),await f},finalizeDaemonShutdown:async()=>{p??=d().then(async e=>await e.applicationResources.finalizeDaemonShutdown()),await p}}),h=e=>{let t=s(e.owner),n=c.get(t);if(n&&n!==e)throw z(`Duplicate platform runtime owner: ${t}`);return c.set(t,e),e},g=async t=>{let n=i.get(t);if(n)return await n;let r=e.modules.get(t);if(!r)throw z(`Missing platform runtime module for ${t}`);if(r.family!==t)throw z(`Platform runtime module registered for ${t} declares ${r.family}`);let a=d().then(async e=>{let n=await r.loadRuntime(e);if(n.owner.kind!==`local-family`||n.owner.family!==t)throw z(`Platform runtime module for ${t} returned a different local owner`);return h(n)});i.set(t,a);try{return await a}catch(e){throw i.get(t)===a&&i.delete(t),e}},_=async e=>{let t=a.get(e);if(t)return await t;let n=d().then(async t=>{let n=await e.loadRuntime(t);if(!l(n.owner,e.owner))throw z(`Provider platform runtime returned a different advertised owner`);return h(n)});a.set(e,n);try{return await n}catch(t){throw a.get(e)===n&&a.delete(e),t}},v=async e=>{let t=s(e),n=r.get(t);if(!n)throw R(e);let i=o.get(t);if(i)return i;let{createManagedLocalRuntimeOwner:a}=await import(`./platform-runtime-managed-owner.js`),c=h(a({owner:n,loadLocal:g}));return o.set(t,c),c};return Object.freeze({applicationLifecycle:m,inspectFacts:async t=>{let r=E(e.providerRuntimes,t);if(r){let e=n.get(r);return e?await D(await _(e),t):L(r,t)}return await D(await g(t.platform),t)},bind:async r=>{if(r.intent.kind===`exact-owner`)return await O(await P(r.intent.owner,t,_,g,v),r);let i=E(e.providerRuntimes,r.device);if(i){let e=n.get(i);return e?await O(await _(e),r):I(i,r.device)}return await O(await g(r.device.platform),r)},shutdown:async()=>{await Promise.allSettled([...c.values()].map(async e=>await e.shutdown())),c.clear(),i.clear(),a.clear(),o.clear()}})}function E(e,t){let n=(e??[]).filter(e=>e.ownsDevice(t));if(n.length>1)throw z(`Multiple provider runtimes claim the selected device`);return n[0]}async function D(e,t){let n=await e.inspectFacts(t);if(!M(t,e.owner,n))throw z(`Platform runtime facts do not match the selected device and owner`);return n}async function O(e,t){let n=await e.bind(t),r=k(e,n,t);if(!r)return n;let i;try{await n[Symbol.asyncDispose]()}catch(e){i=e instanceof Error?e.message:String(e)}throw z(r,i)}function k(e,t,r){if(!l(t.owner,e.owner))return`Platform binding returned a different owner than the selected runtime`;if(!A(t.owner,r))return`Exact platform binding returned a different persisted owner`;if(!n(o(t.device),o(r.device)))return`Platform binding returned a different device identity`;if(!j(t))return`Platform binding facts do not match its device and owner`}function A(e,t){return t.intent.kind!==`exact-owner`||l(e,t.intent.owner)}function j(e){return M(e.device,e.owner,e.facts)}function M(e,t,n){return i(n.device,r(e))&&N(n.device.providerMode,t)}function N(e,t){switch(t.kind){case`local-family`:return e===`local`||e===`transport-composed`;case`managed-local`:return e===`local`||e===`transport-composed`;case`provider-runtime`:return e===`provider-runtime`}}async function P(e,t,n,r,i){switch(e.kind){case`local-family`:{let t=await r(e.family);if(l(t.owner,e))return t;throw R(e)}case`managed-local`:return await i(e);case`provider-runtime`:{let r=t.get(s(e));if(r)return await n(r.module);throw R(e)}}}const F=Object.freeze({available:!1,reason:`unsupported-provider-mode`});function I(e,t){let n=u(e.provider,`default`);return C(t,n,w(F))}function L(e,t){return ie(t,u(e.provider,`default`),w(F))}function R(e){return new t(`UNSUPPORTED_OPERATION`,`The exact platform runtime owner is unavailable.`,{reason:`owner-unavailable`,owner:s(e)})}function z(e,n){return new t(`COMMAND_FAILED`,e,{reason:`runtime-contract-invalid`,...n?{cleanupError:n}:{}})}function B(e){let t=V(e.registry,e.loadHost),n=e.provider,r=n?async(e,r)=>{r.signal.throwIfAborted();let i=await n.discover(d(e),r.signal);return r.signal.throwIfAborted(),ge(i),i.kind===`inventory`?{devices:f(i.devices.map(e=>({...e})),e),source:`provider`}:{devices:await t.discover(e,r),source:`local`}}:async(e,n)=>({devices:await t.discover(e,n),source:`local`}),i=Object.freeze({discover:async(e,t)=>(await r(e,t)).devices,discoverWithSource:r});return Object.freeze({providerFirst:i,localOnly:t,findInstalledApp:async(e,t)=>{let{findIosSimulatorInstalledApp:n}=await import(`./app-resolution-facade.js`);return await n(e,t)}})}function V(e,t){let n,r=async()=>{n??=t();try{return await n}catch(e){throw n=void 0,e}},i=new Map,a=async t=>{let n=i.get(t);if(n)return await n;let a=H(e.get(t),r);i.set(t,a);try{return await a}catch(e){throw i.get(t)===a&&i.delete(t),e}};return Object.freeze({discover:async(e,t)=>{if(t.signal.throwIfAborted(),e.platform)return await W(a,G(e.platform),e,t);let n=await Promise.all(p.map(async n=>{try{let r=await W(a,G(n),{...e,platform:n},t);return Array.isArray(r)?r:[]}catch{return[]}}));return t.signal.throwIfAborted(),n.flat()}})}async function H(e,t){switch(e.family){case`apple`:return await e.loadInventory(U(await t()));case`android`:return await e.loadInventory(de(await t()));case`harmonyos`:return await e.loadInventory(fe(await t()));case`vega`:return await e.loadInventory(pe(await t()));case`linux`:return await e.loadInventory(me(await t()));case`web`:return await e.loadInventory()}}function U(e){return Object.freeze({appleTools:e.appleTools,files:e.files,hostName:e.hostName,hostOs:e.hostOs,observations:e.observations})}function de(e){return Object.freeze({commands:e.commands,files:e.files,homeDirectory:e.homeDirectory,toolchains:e.toolchains})}function fe(e){return Object.freeze({commands:e.commands,files:e.files,toolchains:e.toolchains})}function pe(e){return Object.freeze({commands:e.commands,files:e.files,homeDirectory:e.homeDirectory})}function me(e){return Object.freeze({hostName:e.hostName,hostOs:e.hostOs})}async function W(e,t,n,r){let i=await e(t);r.signal.throwIfAborted();let a=await i.discover(n,r);return r.signal.throwIfAborted(),he(t,a),f(a,n)}function G(e){return a(e)?`apple`:e}function he(e,n){let r=n.find(t=>t.platform!==e);if(r)throw new t(`COMMAND_FAILED`,`Platform inventory source ${e} returned a ${r.platform} device.`,{expectedFamily:e,actualFamily:r.platform,deviceId:r.id})}function ge(e){if(typeof e==`object`&&e){let t=e;if(t.kind===`declined`&&!(`devices`in t)||t.kind===`inventory`&&Array.isArray(t.devices))return}throw new t(`COMMAND_FAILED`,`Provider device inventory returned an invalid outcome.`,{reason:`provider_inventory_contract_violation`})}function _e(){return Object.freeze({async runAdb(e,t,n){let{runAndroidAdb:r}=await K(),i=await r(e,[...t],n);return{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}},async readSnapshotNodes(e){let{snapshotAndroid:t,androidSnapshotPublicationInput:n}=await K(),{buildSnapshotState:r}=await import(`./snapshot-state.js`).then(e=>e.n);return r(n(await t(e,{interactiveOnly:!1})),void 0).nodes},async openApp(e,t){let{openAndroidApp:n}=await K();await n(e,t)}})}async function K(){let{loadAndroidMechanics:e}=await import(`./platform-runtime-android-mechanics.js`).then(e=>e.n);return await e()}var ve=e({androidObservation:()=>J,createPlatformDeviceInventoryGateways:()=>X,createPlatformRuntimeGateway:()=>Q,createRequestPlatformProviders:()=>$,getAndroidAppStateWithAdb:()=>ye,platformModuleRegistry:()=>Y,platformRuntimeModules:()=>Z});async function ye(e,t){return await oe(e,t)}const q=ce({sdkRoots:Ce(process.env.ANDROID_SDK_ROOT,process.env.ANDROID_HOME)}),J=ae(_e()),be=Object.freeze({apple:async e=>await g(e),android:async e=>await le(e)}),xe=_({hdcSdkPath:process.env.HDC_SDK_PATH,devecoSdkHome:process.env.DEVECO_SDK_HOME,commandLineToolsHome:process.env.HARMONYOS_COMMAND_LINE_TOOLS}),Y=c([h,q,xe,ne,re,S]);function X(e){return B({registry:Y,loadHost:async()=>{let{createDeviceInventoryHost:e}=await import(`./platform-runtime-host.js`);return e()},provider:e})}const Se=se({bindAdbHost:async()=>{await import(`./platform-runtime-android-adb-host.js`).then(e=>e.t)}}),Z=new Map([[`apple`,m],[`android`,Se],[`harmonyos`,v],[`vega`,te],[`linux`,y],[`web`,x]]);function Q(e){return ue({modules:Z,loadHost:async()=>{let{createPlatformRuntimeHost:t,createSnapshotRuntimeHost:n,loadMacOsSurfaceSnapshot:r}=await import(`./platform-runtime-operation-host.js`);return t({sessionsDir:e.sessionsDir,resolveSessionArtifacts:e.resolveSessionArtifacts,shutdownLoaders:be,snapshot:n({linux:b,macos:r}),ownedProcesses:e.ownedProcesses})},providerRuntimes:e.providerRuntimes,providerModules:e.providerModules})}function $(e={}){let t,n=()=>(t??=import(`./request-providers.js`).then(({createComposedRequestPlatformProviders:t})=>t(e)),t);return Object.freeze({hasConfiguredResolvers:Object.values(e.providers??{}).some(Boolean),run:async(e,t)=>await(await n()).run(e,t)})}function Ce(...e){return e.flatMap(e=>{let t=e?.trim();return t?[t]:[]})}export{ve as a,$ as i,X as n,Q as r,J as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{C as t}from"./sdk-contracts.js";import{D as n,E as r,O as i,c as a,w as o}from"./sdk-device.js";import{Jt as s,Xt as c,Yt as l,k as u}from"./sdk-batch.js";import{a as d,i as f,t as p}from"./device.js";import{t as ee}from"./startup-recovery-fence.js";import{i as m,n as h,r as g}from"./src2.js";import{i as _,m as v}from"./src3.js";import{n as te,t as ne}from"./src4.js";import{c as re,g as y,n as b}from"./src5.js";import{r as x,t as S}from"./src6.js";import{n as C,r as ie,t as w}from"./platform-runtime-unavailable.js";const T=Object.freeze({family:`android`});function ae(e){let t,n=()=>(t??=import(`./observation.js`).then(({createAndroidObservationAdapter:t})=>t(e)),t);return Object.freeze({readAppState:async(...e)=>await(await n()).readAppState(...e),readBlockingDialog:async(...e)=>await(await n()).readBlockingDialog(...e),readAppFocus:async(...e)=>await(await n()).readAppFocus(...e),readSnapshotNodes:async(...e)=>await(await n()).readSnapshotNodes(...e),tap:async(...e)=>await(await n()).tap(...e),openApp:async(...e)=>await(await n()).openApp(...e),readScreenSize:async(...e)=>await(await n()).readScreenSize(...e),isPermissionPackage:async(...e)=>await(await n()).isPermissionPackage(...e)})}async function oe(e,t){let{readAndroidAppStateWithExecutor:n}=await import(`./app-state.js`);return await n(e,t)}function se(e){return Object.freeze({...T,loadRuntime:async t=>{await e.bindAdbHost();let{createAndroidPlatformRuntime:n}=await import(`./runtime2.js`);return n(t)}})}function ce(e){let t=Object.freeze({sdkRoots:Object.freeze([...new Set(e.sdkRoots.map(e=>e.trim()).filter(Boolean))])});return Object.freeze({...T,loadInventory:async e=>{let{createAndroidInventory:n}=await import(`./inventory.js`);return n(e,t)}})}async function le(e){let{createAndroidShutdownRuntime:t}=await import(`./runtime3.js`);return t(e)}function ue(e){let t=new Map,n=new Map;for(let r of e.providerModules??[]){let{runtime:e,module:i}=r,a=l(i.owner);if(i.owner.provider!==e.provider)throw z(`Provider platform runtime metadata is invalid: ${a}`);if(t.has(a))throw z(`Duplicate platform runtime owner: ${a}`);if(n.has(e))throw z(`Duplicate platform module registration for ${e.provider}`);t.set(a,r),n.set(e,i)}let r=new Map;for(let t of e.managedOwners??[]){let e=l(t);if(r.has(e))throw z(`Duplicate platform runtime owner: ${e}`);r.set(e,t)}let i=new Map,a=new Map,o=new Map,s=new Map,u,d=async()=>{u??=e.loadHost();try{return await u}catch(e){throw u=void 0,e}},f,p,m=Object.freeze({recoverStartupResources:async e=>{await ee(e.stateDir,async()=>{await(await d()).applicationResources.recoverStartupResources(e)})},detachForDaemonShutdown:async()=>{f??=d().then(async e=>await e.applicationResources.detachForDaemonShutdown()),await f},finalizeDaemonShutdown:async()=>{p??=d().then(async e=>await e.applicationResources.finalizeDaemonShutdown()),await p}}),h=e=>{let t=l(e.owner),n=s.get(t);if(n&&n!==e)throw z(`Duplicate platform runtime owner: ${t}`);return s.set(t,e),e},g=async t=>{let n=i.get(t);if(n)return await n;let r=e.modules.get(t);if(!r)throw z(`Missing platform runtime module for ${t}`);if(r.family!==t)throw z(`Platform runtime module registered for ${t} declares ${r.family}`);let a=d().then(async e=>{let n=await r.loadRuntime(e);if(n.owner.kind!==`local-family`||n.owner.family!==t)throw z(`Platform runtime module for ${t} returned a different local owner`);return h(n)});i.set(t,a);try{return await a}catch(e){throw i.get(t)===a&&i.delete(t),e}},_=async e=>{let t=a.get(e);if(t)return await t;let n=d().then(async t=>{let n=await e.loadRuntime(t);if(!c(n.owner,e.owner))throw z(`Provider platform runtime returned a different advertised owner`);return h(n)});a.set(e,n);try{return await n}catch(t){throw a.get(e)===n&&a.delete(e),t}},v=async e=>{let t=l(e),n=r.get(t);if(!n)throw R(e);let i=o.get(t);if(i)return i;let{createManagedLocalRuntimeOwner:a}=await import(`./platform-runtime-managed-owner.js`),s=h(a({owner:n,loadLocal:g}));return o.set(t,s),s};return Object.freeze({applicationLifecycle:m,inspectFacts:async t=>{let r=E(e.providerRuntimes,t);if(r){let e=n.get(r);return e?await D(await _(e),t):L(r,t)}return await D(await g(t.platform),t)},bind:async r=>{if(r.intent.kind===`exact-owner`)return await O(await P(r.intent.owner,t,_,g,v),r);let i=E(e.providerRuntimes,r.device);if(i){let e=n.get(i);return e?await O(await _(e),r):I(i,r.device)}return await O(await g(r.device.platform),r)},shutdown:async()=>{await Promise.allSettled([...s.values()].map(async e=>await e.shutdown())),s.clear(),i.clear(),a.clear(),o.clear()}})}function E(e,t){let n=(e??[]).filter(e=>e.ownsDevice(t));if(n.length>1)throw z(`Multiple provider runtimes claim the selected device`);return n[0]}async function D(e,t){let n=await e.inspectFacts(t);if(!M(t,e.owner,n))throw z(`Platform runtime facts do not match the selected device and owner`);return n}async function O(e,t){let n=await e.bind(t),r=k(e,n,t);if(!r)return n;let i;try{await n[Symbol.asyncDispose]()}catch(e){i=e instanceof Error?e.message:String(e)}throw z(r,i)}function k(e,t,r){if(!c(t.owner,e.owner))return`Platform binding returned a different owner than the selected runtime`;if(!A(t.owner,r))return`Exact platform binding returned a different persisted owner`;if(!n(o(t.device),o(r.device)))return`Platform binding returned a different device identity`;if(!j(t))return`Platform binding facts do not match its device and owner`}function A(e,t){return t.intent.kind!==`exact-owner`||c(e,t.intent.owner)}function j(e){return M(e.device,e.owner,e.facts)}function M(e,t,n){return i(n.device,r(e))&&N(n.device.providerMode,t)}function N(e,t){switch(t.kind){case`local-family`:return e===`local`||e===`transport-composed`;case`managed-local`:return e===`local`||e===`transport-composed`;case`provider-runtime`:return e===`provider-runtime`}}async function P(e,t,n,r,i){switch(e.kind){case`local-family`:{let t=await r(e.family);if(c(t.owner,e))return t;throw R(e)}case`managed-local`:return await i(e);case`provider-runtime`:{let r=t.get(l(e));if(r)return await n(r.module);throw R(e)}}}const F=Object.freeze({available:!1,reason:`unsupported-provider-mode`});function I(e,t){let n=s(e.provider,`default`);return C(t,n,w(F))}function L(e,t){return ie(t,s(e.provider,`default`),w(F))}function R(e){return new t(`UNSUPPORTED_OPERATION`,`The exact platform runtime owner is unavailable.`,{reason:`owner-unavailable`,owner:l(e)})}function z(e,n){return new t(`COMMAND_FAILED`,e,{reason:`runtime-contract-invalid`,...n?{cleanupError:n}:{}})}function B(e){let t=V(e.registry,e.loadHost),n=e.provider,r=n?async(e,r)=>{r.signal.throwIfAborted();let i=await n.discover(d(e),r.signal);return r.signal.throwIfAborted(),ge(i),i.kind===`inventory`?{devices:f(i.devices.map(e=>({...e})),e),source:`provider`}:{devices:await t.discover(e,r),source:`local`}}:async(e,n)=>({devices:await t.discover(e,n),source:`local`}),i=Object.freeze({discover:async(e,t)=>(await r(e,t)).devices,discoverWithSource:r});return Object.freeze({providerFirst:i,localOnly:t,findInstalledApp:async(e,t)=>{let{findIosSimulatorInstalledApp:n}=await import(`./app-resolution-facade.js`);return await n(e,t)}})}function V(e,t){let n,r=async()=>{n??=t();try{return await n}catch(e){throw n=void 0,e}},i=new Map,a=async t=>{let n=i.get(t);if(n)return await n;let a=H(e.get(t),r);i.set(t,a);try{return await a}catch(e){throw i.get(t)===a&&i.delete(t),e}};return Object.freeze({discover:async(e,t)=>{if(t.signal.throwIfAborted(),e.platform)return await W(a,G(e.platform),e,t);let n=await Promise.all(p.map(async n=>{try{let r=await W(a,G(n),{...e,platform:n},t);return Array.isArray(r)?r:[]}catch{return[]}}));return t.signal.throwIfAborted(),n.flat()}})}async function H(e,t){switch(e.family){case`apple`:return await e.loadInventory(U(await t()));case`android`:return await e.loadInventory(de(await t()));case`harmonyos`:return await e.loadInventory(fe(await t()));case`vega`:return await e.loadInventory(pe(await t()));case`linux`:return await e.loadInventory(me(await t()));case`web`:return await e.loadInventory()}}function U(e){return Object.freeze({appleTools:e.appleTools,files:e.files,hostName:e.hostName,hostOs:e.hostOs,observations:e.observations})}function de(e){return Object.freeze({commands:e.commands,files:e.files,homeDirectory:e.homeDirectory,toolchains:e.toolchains})}function fe(e){return Object.freeze({commands:e.commands,files:e.files,toolchains:e.toolchains})}function pe(e){return Object.freeze({commands:e.commands,files:e.files,homeDirectory:e.homeDirectory})}function me(e){return Object.freeze({hostName:e.hostName,hostOs:e.hostOs})}async function W(e,t,n,r){let i=await e(t);r.signal.throwIfAborted();let a=await i.discover(n,r);return r.signal.throwIfAborted(),he(t,a),f(a,n)}function G(e){return a(e)?`apple`:e}function he(e,n){let r=n.find(t=>t.platform!==e);if(r)throw new t(`COMMAND_FAILED`,`Platform inventory source ${e} returned a ${r.platform} device.`,{expectedFamily:e,actualFamily:r.platform,deviceId:r.id})}function ge(e){if(typeof e==`object`&&e){let t=e;if(t.kind===`declined`&&!(`devices`in t)||t.kind===`inventory`&&Array.isArray(t.devices))return}throw new t(`COMMAND_FAILED`,`Provider device inventory returned an invalid outcome.`,{reason:`provider_inventory_contract_violation`})}function _e(){return Object.freeze({async runAdb(e,t,n){let{runAndroidAdb:r}=await K(),i=await r(e,[...t],n);return{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}},async readSnapshotNodes(e){let{snapshotAndroid:t,androidSnapshotPublicationInput:n}=await K(),{buildSnapshotState:r}=await import(`./snapshot-state.js`).then(e=>e.n);return r(n(await t(e,{interactiveOnly:!1})),void 0).nodes},async openApp(e,t){let{openAndroidApp:n}=await K();await n(e,t)}})}async function K(){let{loadAndroidMechanics:e}=await import(`./platform-runtime-android-mechanics.js`).then(e=>e.n);return await e()}var ve=e({androidObservation:()=>J,createPlatformDeviceInventoryGateways:()=>X,createPlatformRuntimeGateway:()=>Q,createRequestPlatformProviders:()=>$,getAndroidAppStateWithAdb:()=>ye,platformModuleRegistry:()=>Y,platformRuntimeModules:()=>Z});async function ye(e,t){return await oe(e,t)}const q=ce({sdkRoots:Ce(process.env.ANDROID_SDK_ROOT,process.env.ANDROID_HOME)}),J=ae(_e()),be=Object.freeze({apple:async e=>await g(e),android:async e=>await le(e)}),xe=_({hdcSdkPath:process.env.HDC_SDK_PATH,devecoSdkHome:process.env.DEVECO_SDK_HOME,commandLineToolsHome:process.env.HARMONYOS_COMMAND_LINE_TOOLS}),Y=u([h,q,xe,ne,re,S]);function X(e){return B({registry:Y,loadHost:async()=>{let{createDeviceInventoryHost:e}=await import(`./platform-runtime-host.js`);return e()},provider:e})}const Se=se({bindAdbHost:async()=>{await import(`./platform-runtime-android-adb-host.js`).then(e=>e.t)}}),Z=new Map([[`apple`,m],[`android`,Se],[`harmonyos`,v],[`vega`,te],[`linux`,y],[`web`,x]]);function Q(e){return ue({modules:Z,loadHost:async()=>{let{createPlatformRuntimeHost:t,createSnapshotRuntimeHost:n,loadMacOsSurfaceSnapshot:r}=await import(`./platform-runtime-operation-host.js`);return t({sessionsDir:e.sessionsDir,resolveSessionArtifacts:e.resolveSessionArtifacts,shutdownLoaders:be,snapshot:n({linux:b,macos:r}),ownedProcesses:e.ownedProcesses})},providerRuntimes:e.providerRuntimes,providerModules:e.providerModules})}function $(e={}){let t,n=()=>(t??=import(`./request-providers.js`).then(({createComposedRequestPlatformProviders:t})=>t(e)),t);return Object.freeze({hasConfiguredResolvers:Object.values(e.providers??{}).some(Boolean),run:async(e,t)=>await(await n()).run(e,t)})}function Ce(...e){return e.flatMap(e=>{let t=e?.trim();return t?[t]:[]})}export{ve as a,$ as i,X as n,Q as r,J as t};