UNPKG

agent-device

Version:

Open source device layer for AI coding agents: a CLI, MCP server, and typed Node.js API to control mobile, web, TV, and desktop apps on devices and simulators, locally or in the cloud.

3 lines • 38.6 kB
import{An as e,Mn as t,jn as n,wn as r}from"./sdk-batch.js";import{S as i,v as a}from"./sdk-contracts.js";import{g as o}from"./sdk-batch-runner.js";import{Z as s}from"./sdk-io.js";import{J as c,T as l,w as u}from"./sdk-device.js";import{r as d}from"./session.js";import"./command.js";import{a as f,r as p}from"./durable-resource.js";import{n as m}from"./screen-recording-runtime.js";import{n as ee,t as te}from"./application-lifecycle-runtime.js";import{n as ne,t as re}from"./async-lifecycle.js";import{t as ie}from"./touch-runtime.js";import{n as ae}from"./artifact-paths.js";import{a as oe,i as se,n as ce,r as le,t as ue}from"./perf-runtime-operation-builder.js";import{C as de,H as fe,I as pe,N as me,R as he,T as ge,z as _e}from"./tv-remote-runtime.js";import{n as ve}from"./audio-probe-runtime.js";import{n as ye}from"./perf-runtime.js";import{a as be,n as xe}from"./screenshot-runtime2.js";import{t as Se}from"./viewport-runtime.js";import{a as Ce,i as we,n as h,o as Te,r as g,s as Ee,t as De}from"./network-traffic.js";import{a as Oe,i as ke,r as Ae}from"./src10.js";import{n as _,t as je}from"./screen-recording-completion.js";import{a as Me,i as Ne,n as Pe,o as v,r as Fe,s as y,t as b}from"./stop-sequence.js";import{t as x}from"./app-log-runtime.js";import{c as Ie,r as Le,s as S}from"./simctl.js";import{n as Re,t as ze}from"./runtime6.js";import{a as Be,i as Ve,o as He,t as Ue}from"./app-backend.js";import{_ as We,a as Ge,c as Ke,d as qe,g as Je,h as Ye,i as Xe,l as Ze,m as Qe,n as $e,o as et,p as tt,r as nt,s as rt,t as it,u as at,v as ot,y as C}from"./system-surface-foreground.js";import w from"node:path";function st(e){return e.hostApp?Object.freeze({available:!1,reason:`unsupported-device-scope`,hint:`This session holds one app of the Mac. Use a --surface desktop session for audio probe.`}):Me(e)?Object.freeze({available:!0}):l(e)||u(e)&&e.kind===`simulator`?Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`audio probe capture requires a macOS host.`}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`audio is supported for macOS sessions and iOS simulators on macOS hosts; physical iOS devices expose no host audio tap.`})}function ct(e){let{resolveHost:t,device:n,owner:r}=e;return Object.freeze({...ue({platform:`Apple`,expectedProfileKind:`xctrace`,start:async e=>await t().start(n,r,e),reattach:async e=>await t().reattach(n,e),cleanup:async e=>await t().cleanup(n,e),writeProfileReport:async e=>await t().writeProfileReport(e)}),perfFrames:async({appId:e})=>({metric:e?await se(t().sampleFrames(n,e)):ce(`Apple`,`bundle ID`),sampling:await t().frameSampling(n)}),perfMemorySample:async({appId:e})=>({metric:e?await se(t().sampleMemory(n,e)):ce(`Apple`,`bundle ID`),sampling:await t().memorySampling(n)}),perfMemorySnapshot:async({appId:e,kind:r,outPath:i,artifactsDir:a})=>{let o=r??`memgraph`,s={...await t().memorySnapshotSupport(n),androidHprof:!1,heapprofd:!1};if(o!==`memgraph`)return oe(`Apple`,o,s,`Use perf memory snapshot --kind memgraph for supported Apple app sessions.`);if(!e)throw le();let c=i??w.join(a,`memory-memgraph-${lt()}.memgraph`);return{artifact:await t().captureMemorySnapshot(n,e,c),support:s,sampling:{method:`xcrun memgraph`,description:`Native Apple memory graph captured for offline inspection.`,defaultKind:`memgraph`,artifactOnly:!0}}}})}function lt(){return new Date().toISOString().replaceAll(/[:.]/g,`-`)}const T=`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`;function E(e){return l(e)?`macos`:e.kind===`device`?`ios-device`:`ios-simulator`}const ut=Object.freeze({resourceKind:x,version:1,encode:e=>({...e}),decode:e=>!ft(e.transport)||!pt(e.backend)||!_t(e.outputPath)||!ht(e.pidPath)||!mt(e.transport,e.backend)?dt():{status:`decoded`,descriptor:Object.freeze({transport:e.transport,backend:e.backend,outputPath:e.outputPath,...e.pidPath===void 0?{}:{pidPath:e.pidPath}})}});function dt(){return{status:`invalid`,message:`Invalid Apple app-log descriptor`}}function ft(e){return e===`apple-log-stream`||e===`coredevice-console`}function pt(e){return e===`ios-simulator`||e===`ios-device`||e===`macos`}function mt(e,t){return e===`coredevice-console`?t===`ios-device`:t!==`ios-device`}function ht(e){return e===void 0||_t(e)}function gt(e){if(!e.device.appleOs)throw TypeError(`Apple app-log persistence requires an explicit appleOs identity`);return p({resourceKind:x,sessionId:e.sessionId,device:{id:e.device.id,family:`apple`,appleOs:e.device.appleOs,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:f(ut,e.descriptor)})}function _t(e){return typeof e==`string`&&e.trim().length>0}const vt={message:`iOS physical-device app console capture is not supported by the installed devicectl.`,hint:`This devicectl does not expose process launch --console. Markers can still be written to app.log, but app output is not being captured. Use an iOS simulator for agent-device app logs or inspect physical-device logs in Console.app/Xcode until this Xcode toolchain exposes scriptable console capture.`},D={message:`Could not verify iOS physical-device app console capture support.`,hint:`Retry logs clear --restart. If the probe keeps failing, run logs doctor and inspect the request diagnostics for the devicectl help command.`};async function O(e,t){try{let n=await e.appleTools.run({tool:`devicectl`,args:[`device`,`process`,`launch`,`--help`],allowFailure:!0,timeoutMs:5e3},t),r=n.stderr.trim()||void 0;if(n.exitCode!==0)return{supported:!1,reason:`probe-failed`,stderr:r};let i=`${n.stdout}\n${n.stderr}`;return/\bUSAGE:\s+devicectl device process launch\b/i.test(i)&&/--console\b/.test(i)&&/--terminate-existing\b/.test(i)?{supported:!0,...r?{stderr:r}:{}}:{supported:!1,reason:`unsupported`,...r?{stderr:r}:{}}}catch(e){if(t?.aborted)throw t.reason;return{supported:!1,reason:`probe-failed`,...e instanceof Error?{stderr:e.message}:{}}}}async function yt(e,t,n,r){let i={},a=n?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`];if(l(t))i.logAvailable=!!await e.commands.which(`log`);else if(t.kind===`simulator`)i.simctlAvailable=await y(async()=>v(await e.appleTools.run({tool:`simctl`,args:Ie(),allowFailure:!0},r)),r);else if(t.iosPhysicalDeviceBackend===`xctest`)i.devicectlAvailable=!1,i.devicectlConsoleCapture=!1,a.push(T);else{i.devicectlAvailable=await y(async()=>v(await e.appleTools.run({tool:`devicectl`,args:[`--version`],allowFailure:!0},r)),r);let t=await O(e,r);if(i.devicectlConsoleCapture=t.supported,!t.supported){let e=t.reason===`unsupported`?vt:D;a.push(`${e.message} ${e.hint}`)}}return{backend:E(t),checks:i,notes:a}}function k(e,t){let n=A(e),r=[`subsystem == "${n}"`,`subsystem CONTAINS "${n}"`,`processImagePath ENDSWITH[c] "/${n}"`,`senderImagePath ENDSWITH[c] "/${n}"`];if(t){let e=A(t);r.push(`process == "${e}"`,`processImagePath ENDSWITH[c] "/${e}"`,`senderImagePath ENDSWITH[c] "/${e}"`,`processImagePath CONTAINS[c] "/${e}.app/"`,`senderImagePath CONTAINS[c] "/${e}.app/"`)}return r.join(` OR `)}function bt(e,t){return Le(e,[`spawn`,e.id,`log`,`stream`,`--style`,`compact`,`--level`,`info`,`--predicate`,k(t.appBundleId,t.executableName)])}function xt(e,t){return[`devicectl`,`device`,`process`,`launch`,`--device`,e,`--console`,`--terminate-existing`,t]}function A(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}const j=1e4;async function St(e,t,n,r,i){Ct(t),we(e,n);let a=E(t),o=await Tt(e,t,n.appBundleId,i),s=new re,c=!1;try{let l=await e.outputs.openAppend(n.outputPath);s.defer(async()=>{c||await l[Symbol.asyncDispose]()}),i?.throwIfAborted();let u=Dt(l),d=await wt(e,t,o,u.sink,n.pidPath,i);s.defer(async()=>{c||await d[Symbol.asyncDispose]()}),t.kind===`simulator`&&await Ot(e,u.written,d.wait,i);let f=kt(e,d,l,a,n.outputPath),p={transport:a===`ios-device`?`coredevice-console`:`apple-log-stream`,backend:a,outputPath:n.outputPath,...n.pidPath===void 0?{}:{pidPath:n.pidPath}},m=Ee(f,gt({sessionId:n.sessionId,device:t,owner:r,fence:n.fence,descriptor:p}),{relaunched:a===`ios-device`});return c=!0,m}finally{await s[Symbol.asyncDispose]()}}function Ct(e){if(u(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`)throw new a(`UNSUPPORTED_OPERATION`,T,{hint:T})}async function wt(e,t,n,r,i,o){if(u(t)&&t.kind===`device`){let t=await O(e,o);if(!t.supported){let e=t.reason===`unsupported`?vt:D;throw new a(t.reason===`unsupported`?`UNSUPPORTED_OPERATION`:`COMMAND_FAILED`,e.message,{backend:`ios-device`,hint:e.hint,stderr:t.stderr})}}return o?.throwIfAborted(),await e.processes.start({command:{kind:`host`,request:n},output:r,...i?{markerPath:i}:{}})}async function Tt(e,t,n,r){return l(t)?{executable:`log`,args:[`stream`,`--style`,`compact`,`--predicate`,k(n)],allowFailure:!0}:t.kind===`device`?{executable:`xcrun`,args:xt(t.id,n),allowFailure:!0}:{executable:`xcrun`,args:bt(t,{appBundleId:n,executableName:await Et(e,t,n,r)}),allowFailure:!0}}async function Et(e,t,n,r){let i=await e.appleTools.run({tool:`simctl`,args:S(t,[`get_app_container`,t.id,n,`app`]),allowFailure:!0,timeoutMs:4e3},r),a=i.exitCode===0?i.stdout.trim():``;if(!a)return;let o=await e.commands.run({executable:`plutil`,args:[`-extract`,`CFBundleExecutable`,`raw`,`-o`,`-`,w.join(a,`Info.plist`)],allowFailure:!0,timeoutMs:4e3},r);return o.exitCode===0&&o.stdout.trim()||void 0}function Dt(e){let t=M,n=new Promise(e=>{t=e});return{sink:{write:async n=>{t(),await e.write(n)},[Symbol.asyncDispose]:async()=>await e[Symbol.asyncDispose]()},written:n}}async function Ot(e,t,n,r){r?.throwIfAborted();let i=M,o=new Promise((e,t)=>{i=()=>t(r?.reason),r?.addEventListener(`abort`,i,{once:!0})}),s=new AbortController,c=e.clock.sleep(j,s.signal).then(()=>`timed-out`);c.catch(M);try{let e=Promise.race([t,n.then(M,M)]).then(()=>`launched`);if(await Promise.race([e,c,o])===`timed-out`)throw new a(`COMMAND_FAILED`,`Simulator log stream did not start within ${j}ms`,{reason:`simulator-log-stream-launch-timeout`,timeoutMs:j,hint:`Check that the simulator finished booting, then retry logs start.`})}finally{s.abort(),r?.removeEventListener(`abort`,i)}}function M(){}function kt(e,t,n,r,i){let a=e.clock.now(),o=`active`;t.wait.then(e=>{o=e.exitCode===0?`ended`:`failed`},()=>{o=`failed`});let s=new Set([async()=>await t.terminate(),async()=>await t.wait.then(()=>void 0),async()=>await t[Symbol.asyncDispose](),async()=>await n[Symbol.asyncDispose]()]),c;return Ce({inspect:()=>({backend:r,state:o,startedAt:a}),finish:async()=>c??=(async()=>(await At(s)).length>0?(c=void 0,o=`failed`,{status:`cleanup-pending`,reason:`transport-failed`,message:`Apple app-log cleanup did not settle every owned resource`}):(o=`ended`,{status:`completed`,result:{backend:r,outputPath:i,completedAt:e.clock.now()}}))()})}async function At(e){let t=[];for(let n of e)try{await n(),e.delete(n)}catch(e){t.push(e)}return t}const N=r(`apple`),P=Object.freeze({available:!0});function jt(t){return Object.freeze({owner:N,ownsDevice:e=>e.platform===`apple`,inspectFacts:async e=>F(e),bind:async n=>{if(n.intent.kind===`exact-owner`&&!e(n.intent.owner,N))throw new a(`UNSUPPORTED_OPERATION`,`Apple app-log owner identity does not match`);return Mt(t,n.device,n.scope.signal)},shutdown:async()=>void 0})}function Mt(e,t,n){if(t.platform!==`apple`)throw new a(`UNSUPPORTED_PLATFORM`,`Apple app-log owner cannot bind ${t.platform}`);let r=Te({codec:ut,reattach:async(n,r)=>n.backend!==E(t)||!g(e,r.sessionId,n)?{status:`unreattachable`,reason:`descriptor-invalid`,message:`Apple app-log descriptor does not match the bound device or owning session`}:await ke(e,n.pidPath),cleanup:async(n,r)=>n.backend===E(t)&&g(e,r.sessionId,n)?await Ae(e,n.pidPath):{status:`cleanup-pending`,reason:`ownership-fence-lost`,message:`Apple app-log descriptor does not match the bound device or owning session`}}),i=Object.freeze({appLogInspect:async()=>({backend:E(t)}),appLogDoctor:async({appBundleId:r})=>await yt(e,t,r,n),appLogStart:async r=>await St(e,t,r,N,n),...r});return Object.freeze({device:t,owner:N,facts:F(t),operations:i,[Symbol.asyncDispose]:async()=>void 0})}function F(e){let t=u(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?{available:!1,reason:`unsupported-device-backend`,hint:T}:P;return Object.freeze({device:{family:`apple`,appleOs:e.appleOs,kind:e.kind,...e.target===void 0?{}:{target:e.target},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend},providerMode:`local`},operations:{appLogInspect:t,appLogDoctor:t,appLogStart:t,appLogReattach:P,appLogCleanup:P}})}async function Nt(e,t,n,r){let i=E(t),a=await e.appLogs.readRecent(n.sessionId,n.maxScanLines),o=h(a.text,{...n,path:a.path,exists:a.exists,lineNumberOffset:a.skippedLines,backend:i}),s=[];if(Ft(t,n,o.dump)){let i=await It(e,t,n,a.path,r);i&&(o=Pt(s,o,i,n.maxEntries))}return zt(s,t,n),Rt(s,o.dump),o.dump.entries.length===0&&s.push(Bt(t)),Object.freeze({source:`app-log`,backend:i,dump:o.dump,notes:Object.freeze(s)})}function Pt(e,t,n,r){let i=n.scan.dump.entries.length;return i===0&&(n.scan.dump.unnamedRequests??0)===0?(n.lineCount>0&&e.push(`Recovered ${n.lineCount} recent iOS simulator app log lines from simctl log show, but none looked like HTTP traffic. This app may not emit request URLs, status, or timing into Unified Logging for this repro window.`),t):(i>0&&e.push(`Recovered ${i} iOS simulator HTTP entr${i===1?`y`:`ies`} from simctl log show (${n.lineCount} app log lines scanned).`),De(n.scan,t,r))}function Ft(e,t,n){return u(e)&&e.kind===`simulator`&&!!t.appBundleId&&n.entries.length===0}async function It(e,t,n,r,i){let a=n.appLogSnapshot?.startedAt,o=S(t,[`spawn`,t.id,`log`,`show`,`--style`,`compact`,`--info`,`--predicate`,Lt(n.appBundleId),...typeof a==`number`&&Number.isFinite(a)&&a>0?[`--start`,`@${Math.floor(a/1e3)}`]:[`--last`,`5m`]]),s=await e.appleTools.run({tool:`simctl`,args:o,allowFailure:!0,timeoutMs:4e3},i);if(s.exitCode!==0||!s.stdout.trim())return;let c=s.stdout.split(` `).map(e=>e.trimEnd()).filter(e=>e.trim()&&!e.trim().startsWith(`Timestamp Ty Process[PID:TID]`));if(c.length!==0)return{scan:h(`${c.join(` `)}\n`,{...n,path:`${r} (simctl log show recovery)`,exists:!0,backend:`ios-simulator`}),lineCount:c.length}}function Lt(e){let t=e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`);return[`subsystem == "${t}"`,`subsystem CONTAINS "${t}"`,`processImagePath ENDSWITH[c] "/${t}"`,`senderImagePath ENDSWITH[c] "/${t}"`].join(` OR `)}function Rt(e,t){let n=t.entries.filter(e=>e.pathUnavailable).length,r=t.unnamedRequests??0,i=n+r;if(i===0)return;let a=[`${i} request${i===1?``:`s`} reused a keep-alive connection, so CFNetwork logged no request URL.`];n>0&&a.push(`${n} listed against the origin the connection was opened for, without a path.`),r>0&&a.push(`${r} opened before this scan window and are missing from the entries entirely; scan more lines, or run logs clear --restart before the repro.`),a.push(`Absence of an endpoint in this dump does not prove it was not called.`),e.push(a.join(` `))}function zt(e,t,n){n.appLogSnapshot?n.appLogSnapshot.state!==`active`&&e.length===0&&e.push(u(t)&&t.kind===`simulator`?`Session app log stream is inactive. The iOS simulator recovery path scanned recent simctl log history, but a fresh logs clear --restart window is still the most reliable repro loop.`:`Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.`):e.push(`Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests.`)}function Bt(e){return u(e)&&e.kind===`simulator`?`No HTTP(s) entries were found in recent iOS simulator app logs. If the app only emits non-HTTP diagnostics, inspect logs path or add app-side URLSession/network logging for per-request timing and payload details.`:u(e)?`No HTTP(s) entries were found in recent iOS device app logs. iOS network dump only sees what the app emits into Unified Logging for this process.`:`No HTTP(s) entries were found in recent session app logs.`}async function Vt(e){let{host:t,snapshot:n,targetLabel:r,recorderWarning:a,nativePathDisposition:o}=e,s=n.invalidatedReason?{recorder:`lost`,why:`owner-session-lost`}:e.stopObservation;if(n.invalidatedReason&&!n.showTouches)throw Error(`recording invalidated: ${n.invalidatedReason}`);let c;try{c=await t.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!n.invalidatedReason&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,...n.fps===void 0?{}:{fps:n.fps},targetLabel:r})}catch(e){throw i(e,`COMMAND_FAILED`)}let l=[...c.warning?[c.warning]:[],...a?[a]:[]];return je(n,{...c,...l.length>0?{warning:l.join(` `)}:{},...n.invalidatedReason?{overlayWarning:`overlay unavailable: ${n.invalidatedReason}`}:{}},{stopObservation:s,...o===void 0?{}:{nativePathDisposition:o}})}async function I(e){let{host:t,snapshot:n,targetLabel:r,collectedPath:i,exportPath:a,nativePath:o}=e;if(n.invalidatedReason&&!n.showTouches)throw Error(`recording invalidated: ${n.invalidatedReason}`);let s=e.overlayUnavailable??n.invalidatedReason,c;try{await t.screenRecording.outputs.copy({from:i,to:a}),c=await Ht(()=>t.screenRecording.finalize.complete({outputPath:a,showTouches:s===void 0&&n.showTouches,gestureEvents:n.gestureEvents,exportQuality:n.exportQuality??`medium`,...n.fps===void 0?{}:{fps:n.fps},targetLabel:r}))}catch(e){throw await t.screenRecording.outputs.remove(a),e}return{...c,...s===void 0?{}:{overlayWarning:`overlay unavailable: ${s}`},nativePathDisposition:await t.screenRecording.outputs.remove(o)===`removed`?`retired`:`retirable`}}async function Ht(e){try{return await e()}catch(e){throw i(e,`COMMAND_FAILED`)}}const Ut=[`outPath`,`startedAt`,`clientOutPath`,...Fe],L=Object.freeze({resourceKind:m,version:1,encode:e=>e.backend===`simctl`?{backend:e.backend,outputPath:e.outputPath,processes:e.processes.map(e=>({...e})),...e.recording===void 0?{}:{recording:{...e.recording}}}:{backend:e.backend,outputPath:e.outputPath,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}},decode:e=>$t(e)});function Wt(e){let{device:t,owner:n,input:r,descriptor:i}=e;return p({resourceKind:m,sessionId:r.sessionId,device:c(t),owner:n,fence:r.fence,lifecycle:`open`,descriptor:f(L,i)})}function Gt(e){let t={};for(let n of Ut)e[n]!==void 0&&Object.assign(t,{[n]:e[n]});return t}async function Kt(e,t,n,r){let i=L.decode(n);return i.status!==`decoded`||!U(t,i.descriptor)?{status:`cleanup-pending`,reason:`manual-recovery-required`}:i.descriptor.backend===`simctl`?await R(e,i.descriptor.processes,r):await qt(e,t,i.descriptor)}async function R(e,t,n){let r=await Promise.all(t.map(async t=>await e.screenRecording.apple.inspectProcess(t)));if(r.includes(`ownership-lost`))return{status:`cleanup-pending`,reason:`ownership-fence-lost`};if(r.every(e=>e===`missing`))return n!==void 0&&e.screenRecording.ownedProcesses.clear(z(n)),{status:`already-missing`};let i=await Promise.all(t.flatMap((t,n)=>r[n]===`owned-alive`?[e.screenRecording.apple.terminateProcess(t)]:[]));return i.includes(`ownership-lost`)?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(n!==void 0&&e.screenRecording.ownedProcesses.clear(z(n)),i.every(e=>e===`already-missing`)?{status:`already-missing`}:{status:`cleaned`})}function z(e){return{kind:`session`,sessionId:e}}async function qt(e,t,n){try{let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`already-missing`}:r===`ownership-lost`?{status:`cleanup-pending`,reason:`ownership-fence-lost`}:(await e.screenRecording.apple.runRunner(t,{kind:`stop`,appBundleId:n.appBundleId,runnerSessionId:n.runnerSessionId,runnerAuthority:n.runnerAuthority}),{status:`cleaned`})}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple recording cleanup failed`}}}async function Jt(e){let{host:t,device:n,envelope:r}=e,i=L.decode(r.descriptor.body);return i.status===`decoded`?U(n,i.descriptor)?i.descriptor.backend===`simctl`?await Yt(e,i.descriptor):await Zt(t,n,i.descriptor):B(`descriptor-invalid`,`Apple screen-recording descriptor does not match the bound device.`):B(`descriptor-invalid`,i.message)}async function Yt(e,t){let n=await Promise.all(t.processes.map(async t=>await e.host.screenRecording.apple.inspectProcess(t)));if(!n.every(e=>e===`missing`))return B(`transport-not-reattachable`,n.includes(`ownership-lost`)?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`);let{recording:r}=t,i=Xt(Pe(e.envelope.metadata),t.outputPath);return r===void 0||i!==void 0&&!await Qt(e.host,i)?{status:`missing`}:{status:`restore-export`,recording:r,nativePath:t.outputPath,cleanup:async()=>await R(e.host,t.processes,e.envelope.sessionId)}}function Xt(e,t){if(e.finalization===void 0)return e.collectedPath??t}async function Zt(e,t,n){let r=await e.screenRecording.apple.inspectRunner(t,n.runnerSessionId,n.runnerAuthority);return r===`missing`?{status:`missing`}:B(`transport-not-reattachable`,r===`ownership-lost`?`Apple recording ownership no longer matches the durable descriptor.`:`Apple screen recordings require exact cleanup after daemon restart.`)}async function Qt(e,t){try{return await e.screenRecording.finalize.sniff({outputPath:t}),!0}catch{return!1}}function B(e,t){return{status:`unreattachable`,reason:e,message:t}}function $t(e){return typeof e.outputPath!=`string`||e.outputPath.length===0?W():e.backend===`simctl`?en(e,e.outputPath):e.backend===`runner`?rn(e,e.outputPath):W()}function en(e,t){let n=ln(e.processes),r=tn(e.recording);return!n||r===`invalid`?W():{status:`decoded`,descriptor:Object.freeze({backend:`simctl`,outputPath:t,processes:n,...r===void 0?{}:{recording:r}})}}function tn(e){if(e!==void 0)return o(e)&&nn(e)?Object.freeze(e):`invalid`}function nn(e){return V(e.outPath)&&on(e.startedAt)&&an(e.clientOutPath)&&Ne(e)}function rn(e,t){return!V(e.appBundleId)||!V(e.runnerSessionId)||!sn(e.runnerAuthority)||!cn(e.remotePath)?W():{status:`decoded`,descriptor:Object.freeze({backend:`runner`,outputPath:t,appBundleId:e.appBundleId,runnerSessionId:e.runnerSessionId,runnerAuthority:e.runnerAuthority,...e.remotePath===void 0?{}:{remotePath:e.remotePath}})}}function V(e){return typeof e==`string`&&e.length>0}function an(e){return e===void 0||V(e)}function on(e){return typeof e==`number`&&Number.isFinite(e)}function sn(e){return e===`local-lease`||e===`scoped-provider`}function cn(e){return e===void 0||H(e)}function H(e){return typeof e==`string`&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(e)}function U(e,t){return e.kind===`simulator`?t.backend===`simctl`:t.backend===`runner`?e.appleOs===`macos`?t.remotePath===void 0:u(e)?t.remotePath!==void 0&&H(t.remotePath):t.remotePath===void 0:!1}function ln(e){if(!Array.isArray(e)||e.length===0)return;let t=e.filter(e=>typeof e==`object`&&!!e&&Number.isInteger(e.pid)&&(e.pid??0)>0&&typeof e.startTime==`string`&&e.startTime.length>0&&typeof e.command==`string`&&e.command.length>0);return t.length===e.length?Object.freeze([...t]):void 0}function W(){return{status:`invalid`,message:`Invalid Apple screen-recording descriptor`}}async function un(e,t,n){if(e.kind!==`simulator`||t.scope!==`app`)return;let r=t.activeSessionApp?.bundleId;if(!r)throw TypeError(`App-scoped recording requires an active app session; open the app under test before recording.`);if(await n(r))throw TypeError(`App-scoped recording requires a real application session; open the app under test before recording.`)}const G=`iOS recording`,K=`simctl recordVideo`;function dn(e){return u(e)&&e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?n(`unsupported-device-backend`,`This command requires a CoreDevice-backed physical iOS device. The selected XCTest backend supports open, close, interactions, snapshots, and screenshots.`):Object.freeze({available:!0})}function fn(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await pn({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async e=>{let r=await Jt({host:t,device:n,envelope:e.envelope});return r.status===`restore-export`?{status:`active`,handle:hn({host:t,restored:r})}:r},screenRecordingCleanup:async e=>await Kt(t,n,e.envelope.descriptor.body,e.envelope.sessionId)})}async function pn(e){return e.signal.throwIfAborted(),e.device.kind===`simulator`?await mn(e):await gn(e)}async function mn(e){let{host:t,device:n,owner:r,input:i,signal:a}=e;await un(n,i,t.screenRecording.apple.isRunnerBundleId);let o=i.activeSessionApp?await t.screenRecording.apple.captureClockAnchor(n,i.activeSessionApp.bundleId,a,i.requestId):void 0,s=ae(i.outputPath);await t.screenRecording.outputs.prepare(s);let c=await t.screenRecording.apple.startSimulator(n,s,a),l=c.markers;if(!l||l.length===0)throw await Y(c).catch(()=>{}),Error(`simctl recordVideo did not expose durable process identity`);try{a.throwIfAborted(),t.screenRecording.ownedProcesses.replace({kind:`session`,sessionId:i.sessionId},l.map(e=>({...e,purpose:`simctl-screen-recording`})))}catch(e){try{t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId})}catch{}throw await Y(c).catch(()=>{}),e}let u,d,f=async()=>{await c.terminate();let e=await c.wait;return d=e,u=vn(e),t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),{observation:{recorder:`confirmed`},...u===void 0?{}:{warning:`${u} before record stop; the video covers only what the recorder wrote before it stopped.`}}},p=Sn(i,K,{},o);return xn({device:n,owner:r,input:i,descriptor:{backend:`simctl`,outputPath:s,processes:l,recording:Gt(p)},snapshot:p,finish:(e,n)=>b({snapshot:e,progress:n,steps:{stop:f,collect:async e=>{try{await q(t,s,e)}catch(e){throw J(e,u,d)}},finalize:async({collectedPath:n,exportPath:r})=>{try{return await I({host:t,snapshot:e,targetLabel:G,collectedPath:n,exportPath:r,nativePath:s})}catch(e){throw J(e,u,d)}},discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),cleanup:async()=>{let e=await bn(c);return(e.status===`cleaned`||e.status===`already-missing`)&&t.screenRecording.ownedProcesses.clear({kind:`session`,sessionId:i.sessionId}),e}})}function hn(e){let{host:t,restored:{recording:n,nativePath:r,cleanup:i}}=e,a=Object.freeze({...n,backend:K,gestureEvents:[]});return _(a,{finish:(e,i)=>b({snapshot:e,progress:i,steps:{stop:async()=>({observation:{recorder:`confirmed`},warning:`simctl recordVideo had already ended when record stop reattached to it; the video covers only what the recorder wrote before it stopped.`}),collect:async e=>{await q(t,r,e)},finalize:async({collectedPath:i,exportPath:a})=>await I({host:t,snapshot:e,targetLabel:G,collectedPath:i,exportPath:a,nativePath:r,...n.showTouches?{overlayUnavailable:`the daemon that held the touch events ended before record stop`}:{}}),discard:async e=>{await t.screenRecording.outputs.remove(e)}}}),forceCleanup:async()=>await i()})}async function q(e,t,n){await e.screenRecording.outputs.copy({from:t,to:n}),await e.screenRecording.finalize.sniff({outputPath:n})}async function gn(e){let{host:t,device:n,owner:r,input:i,signal:a}=e,o=i.activeSessionApp?.bundleId;if(!o)throw TypeError(`Apple runner recording requires an active app session identity`);await t.screenRecording.outputs.prepare(i.outputPath);let s=await t.screenRecording.apple.runRunner(n,{kind:`start`,appBundleId:o,outputPath:i.outputPath,...i.fps===void 0?{}:{fps:i.fps}},a);if(!s.runnerSessionId||!s.runnerAuthority)throw Error(`Apple runner recording did not expose durable session ownership`);let c={runnerSessionId:s.runnerSessionId,runnerAuthority:s.runnerAuthority},l,u=()=>(l??=_n(()=>t.screenRecording.apple.runRunner(n,{kind:`stop`,appBundleId:o,...c}).then(()=>void 0)).catch(e=>{throw l=void 0,e}),l);if(!yn(n,s.remotePath))throw await u().catch(()=>{}),Error(`Apple runner recording did not expose coherent durable media ownership`);try{a.throwIfAborted()}catch(e){throw await u().catch(()=>{}),e}return xn({device:n,owner:r,input:i,descriptor:{backend:`runner`,outputPath:i.outputPath,appBundleId:o,...c,...s.remotePath===void 0?{}:{remotePath:s.remotePath}},snapshot:Sn(i,`runner AVAssetWriter`,s),finish:async e=>(await u(),s.remotePath!==void 0&&await t.screenRecording.apple.retrieveRunnerRecording(n,s.remotePath,e.outPath),await Vt({host:t,snapshot:e,targetLabel:n.appleOs===`macos`?`macOS recording`:`iOS recording`,stopObservation:{recorder:`confirmed`},...s.remotePath===void 0?{}:{nativePathDisposition:`retirable`}})),cleanup:async()=>(await u(),{status:`cleaned`})})}async function _n(e){try{return await e()}catch(e){throw i(e,`COMMAND_FAILED`)}}function vn(e){if(e.exitCode!==0)return e.signal?`simctl recordVideo was killed by ${e.signal}`:`simctl recordVideo exited with code ${e.exitCode}`}function J(e,t,n){let r=i(e,`COMMAND_FAILED`);return t===void 0||n===void 0||r.details?.reason!==`recording-output-unplayable`?e:new a(r.code,`${r.message}; ${t}`,s(n,{...r.details??{},...n.signal===void 0?{}:{signal:n.signal},retriable:!1,hint:`The recorder exited before record stop, so the next record stop reads the same file. Close this session to release the device, then record again.`}))}function yn(e,t){return e.appleOs===`macos`||!u(e)?t===void 0:t!==void 0&&/^tmp\/agent-device-recording-\d+\.mp4$/.test(t)}async function Y(e){return await e.terminate(),await e.wait}async function bn(e){try{return await Y(e),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Apple simulator cleanup failed`}}}function xn(e){let{device:t,owner:n,input:r,descriptor:i,snapshot:a,finish:o,cleanup:s}=e,c=_(a,{finish:o,forceCleanup:s});return Object.freeze({pendingHandle:new ne(c),envelope:Wt({device:t,owner:n,input:r,descriptor:i})})}function Sn(e,t,n={},r){let i=Date.now();return Object.freeze({backend:t,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:i,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},...e.exportQuality===void 0?{}:{exportQuality:e.exportQuality},...e.fps===void 0?{}:{fps:e.fps},gestureEvents:[],...r===void 0?{}:{gestureClockOriginAtMs:r.wallClockAtMs,gestureClockOriginUptimeMs:r.uptimeMs},...n.recorderStartUptimeMs===void 0?{}:{gestureClockOriginAtMs:i,gestureClockOriginUptimeMs:n.recorderStartUptimeMs,runnerStartedAtUptimeMs:n.recorderStartUptimeMs},...n.runnerSessionId===void 0?{}:{runnerSessionId:n.runnerSessionId}})}const X=Object.freeze({available:!1,reason:`unsupported-device-backend`,hint:`The native macOS app backend never starts the XCTest runner, which this command needs. Unset AGENT_DEVICE_MACOS_APP_BACKEND to use XCTest.`});function Cn(e,t){return!l(e)||t!==`native`?{}:Object.freeze({screenRecordingStart:X,screenRecordingReattach:X,prepareAppleRunner:X,longPressPoint:X,...de({back:X}),...he({unsupported:X})})}function wn(e){let t,n=!1,r=async()=>(t??=import(`./host4.js`).then(e=>e.t).then(({createSnapshotSourceHost:t})=>import(`./adapter.js`).then(({createSimulatorSnapshotSource:n})=>n({host:t(e)}))),await t);return{acquire:async e=>n?{stage:`failed`,failure:{kind:`unsupported`,code:`source-closed`}}:await(await r()).acquire(e),close:async()=>{n=!0,t&&await(await t).close()}}}function Tn(e,t={}){let n=t.source??wn(e.hostEnvironment),r=t.targets??Ye(),i=$e(async(t,n)=>await e.snapshot.presentIosAcquisition(t,n),{source:n,servesDevice:Qe,resolveTarget:r.resolveTarget,refreshTarget:r.refreshTarget,resolutionVerifiesIdentity:!0,awaitsDiscovery:async(t,n,r)=>Je(t)&&!await e.appleApplications.hasLiveRunnerSession(n,r),observeOnlySupported:!0,circuit:{scope:`route`}},t.systemSurfaceForeground??it()),a=tt({source:n,resolveTarget:r.resolveTarget,clock:e.clock,isBridgeDisabled:i.isBridgeDisabled});return Object.freeze({awaitObservable:a.awaitObservable,capture:i.capture,shutdown:i.shutdown})}const Z=r(`apple`),Q=Object.freeze({available:!0}),En=n(`unsupported-platform-leaf`),Dn=n(`unsupported-platform-leaf`,`viewport resizes web targets only (--platform web). Apple screen geometry is fixed by the selected simulator or device type — open a different simulator to test another screen size.`),On=n(`unsupported-platform-leaf`,`the stateless audio page probe is a web-session operation; Apple targets use the host capture.`),kn=n(`unsupported-device-backend`,`perf requires an Apple simulator, macOS device, or CoreDevice-backed physical Apple device.`),An=n(`unsupported-platform-leaf`,`telephony simulates calls and SMS through the Android emulator console; Apple simulators and devices expose no host control that injects a call or text message.`),jn=n(`unsupported-provider-mode`,`Headless boot is supported only for local Android emulators.`),Mn=n(`unsupported-device-kind`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),Nn=$(`open is supported only for Apple simulators and devices.`),Pn=$(`close is supported only for Apple simulators and devices.`),Fn=n(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),In=n(`unsupported-device-kind`,`shutdown is supported only for Apple simulators and Android emulators.`),Ln=$(`screenshot is supported only for Apple simulators and devices.`);function $(e){return n(`unsupported-device-kind`,e)}function Rn(e){return u(e)?e.kind===`simulator`?Q:In:En}function zn(e){let t=Bn(e),n=rt(e),r=Vn(e),i=Hn(e);return te({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:i,clearRuntimeHints:i,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:n,configureProviderPortReverse:Fn})}function Bn(e){return e.kind===`simulator`||e.kind===`device`?Q:Nn}function Vn(e){return e.kind===`simulator`||e.kind===`device`?Q:Pn}function Hn(e){return u(e)&&e.kind===`simulator`?Q:Mn}function Un(e){return e.kind===`device`&&e.iosPhysicalDeviceBackend===`xctest`?n(`unsupported-device-backend`,`App inventory is available only on CoreDevice-backed physical iOS devices.`):Q}function Wn(e){let r=jt(e),i=Tn(e),a,o=t=>l(t)?a??=Ue(e.hostEnvironment.env):`xctest`,s=async t=>{let i=await r.inspectFacts(t),a=We(t),s=dn(t),c=s.available?await e.screenRecording.apple.availability(t):void 0,u=s.available&&c?.available===!1?n(`unsupported-provider-mode`,c.hint):s,d=l(t)?En:Q,f=Un(t);return Object.freeze({device:i.device,operations:Ve(t,{...i.operations,...a,networkDump:Q,screenRecordingStart:u,screenRecordingReattach:u,screenRecordingCleanup:u,...Ke(t),...be({capture:Kn(t)}),...Se({setViewport:Dn}),...ze(t),sendTelephonyEvent:An,...ve({capture:st(t),query:On}),...ye(Gn(t)),ensureReady:Q,bootTarget:d,bootTargetHeadless:jn,listApps:f,...zn(t),shutdownTarget:Rn(t),...Cn(t,o(t))})})};return Object.freeze({owner:Z,ownsDevice:e=>e.platform===`apple`,inspectFacts:s,bind:async n=>{let a=await r.bind(n),c=await s(n.device),u=c.operations.screenRecordingStart,f=t(c.operations.appState,()=>et(e,{device:n.device,signal:n.scope.signal,resolveInteractor:e.localInteractors.resolve})),p=t(c.operations.querySelector,()=>nt({device:n.device,signal:n.scope.signal})),m={...f,...p,...a.operations,...ot({host:e,device:n.device,signal:n.scope.signal}),networkDump:async t=>await Nt(e,n.device,t,n.scope.signal),...t(u,()=>fn({host:e,device:n.device,owner:Z,signal:n.scope.signal})),...t(c.operations.audioProbeStart,()=>Oe({host:e.audioProbe.hostCapture,device:n.device,owner:Z})),...t(c.operations.perfFrames,()=>ct({resolveHost:()=>e.perf.apple,device:n.device,owner:Z})),...t(c.operations.captureSnapshot,()=>Ge(e,{device:n.device,signal:n.scope.signal,appBackend:o(n.device)},i)),...t(c.operations.captureScreenshot,()=>xe({device:n.device,signal:n.scope.signal,resolveInteractor:e.localInteractors.resolve,captureCapabilities:e=>He(n.device,e,l(n.device)?d(e.surface,o(n.device)):void 0)})),...t(c.operations.focusPoint,()=>_e({device:n.device,signal:n.scope.signal,resolveInteractor:e.localInteractors.resolve})),...pe({device:n.device,signal:n.scope.signal,facts:c.operations,resolveInteractor:e.localInteractors.resolve}),...t(c.operations.scrollDirection,()=>me({device:n.device,signal:n.scope.signal,resolveInteractor:e.localInteractors.resolve})),...t(c.operations.typeText,()=>ge({device:n.device,signal:n.scope.signal,resolveInteractor:e.localInteractors.resolve})),...t(c.operations.tapPoint,()=>ie({device:n.device,signal:n.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:c.operations,pause:async t=>await e.clock.sleep(t,n.scope.signal)})),...t(c.operations.readTextAtPoint,()=>fe({device:n.device,signal:n.scope.signal,resolveInteractor:e.localInteractors.resolve})),...t(c.operations.findText,()=>Xe(e,{device:n.device,signal:n.scope.signal,appBackend:o(n.device)})),...at({host:e,device:n.device,signal:n.scope.signal,admitted:c.operations}),...Ze({host:e,device:n.device,signal:n.scope.signal}),...Re({device:n.device,signal:n.scope.signal}),...t(c.operations.ensureReady,()=>({ensureReady:async()=>await C(e,n.device,n.scope.signal)})),...t(c.operations.bootTarget,()=>({bootTarget:async t=>await C(e,n.device,n.scope.signal,{deadlineAtMs:t.deadlineAtMs})})),...t(c.operations.listApps,()=>({listApps:async e=>{n.scope.signal.throwIfAborted();let{listIosApps:t}=await import(`./app-resolution.js`).then(e=>e.t);return(await t(e.device,e.filter)).map(e=>({id:e.bundleId,name:e.name}))}})),...ee(qe({host:e,device:n.device,signal:n.scope.signal,observation:i}),c.operations),...t(c.operations.shutdownTarget,()=>({shutdownTarget:async()=>await e.deviceShutdown.apple.shutdownTarget(n.device,n.scope.signal)}))};return Object.freeze({device:a.device,owner:Z,facts:c,operations:Object.freeze(Be(n.device,c.operations,m)),[Symbol.asyncDispose]:async()=>await a[Symbol.asyncDispose]()})},shutdown:async()=>{await Promise.all([r.shutdown(),i.shutdown()])}})}function Gn(e){let t=e.iosPhysicalDeviceBackend===`xctest`?kn:Q;return{frames:t,memorySample:t,memorySnapshot:t,nativeCapture:t,profileReport:t}}function Kn(e){return e.kind===`simulator`||e.kind===`device`?Q:Ln}export{Wn as createApplePlatformRuntime};