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.
1 lines • 24 kB
JavaScript
import{Rr as e}from"./sdk-batch.js";import{v as t}from"./sdk-contracts.js";import{Z as n,et as r,it as i}from"./sdk-io.js";import{R as a,T as o,w as s,y as c}from"./sdk-device.js";import"./command.js";import{t as l}from"./parser.js";import{n as u,t as d}from"./numeric.js";import{E as ee,T as f,_ as te,b as ne,h as p,i as re,k as ie,o as m,u as h}from"./host-file.js";import{c as g,s as ae}from"./tool-provider.js";import{o as oe,t as se}from"./devicectl.js";import{r as ce}from"./simctl.js";import _ from"node:path";import{fileURLToPath as v}from"node:url";function y(e,t){for(let n of e){if(t(n))return n;let e=y(n.children,t);if(e)return e}}function b(e,t){let n=[];for(let r of e)t(r)&&n.push(r),n.push(...b(r.children,t));return n}function le(e,t){return e.children.find(e=>e.name===t)?.text??null}function x(e,t){let n=y(e,e=>e.name===`schema`&&e.attributes.name===t);return n?n.children.filter(e=>e.name===`col`).map(e=>le(e,`mnemonic`)??``):[]}function S(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 C(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.numberValue??null:S(e):null}function w(e,t){for(let n of e)w(n.children,t),n.attributes.id&&t.set(n.attributes.id,{numberValue:S(n),process:E(n)})}function T(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.process??null:E(e):null}function E(e){if(!e||e.children.some(e=>e.name===`sentinel`))return null;let t=S(y(e.children,e=>e.name===`pid`)),n=(e.attributes.fmt??``).trim().replace(/\s+\(\d+\)$/,``).trim();return t===null&&n.length===0?null:{pid:t??void 0,name:n.length>0?n:void 0}}function ue(e){return new Map(b(e,e=>!!e.attributes.id).flatMap(e=>{let t=e.attributes.id;return t?[[t,e]]:[]}))}function D(e,t){if(e)return e.attributes.ref?t.get(e.attributes.ref):e}const O=new Set([`backtrace`,`tagged-backtrace`]);function k(e,t=10){let n=l(e),r=ue(n),i=new Map,a=0,o=0;for(let e of b(n,e=>e.name===`row`)){let t=A(e,r),n=de(e,r);if(t===void 0||!n)continue;let s=n.attributes.name?.trim()||`<unknown>`,c=fe(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:j(n),selfSamplePercent:o>0?u(n/o*100):0}));return{sampleCount:a,totalSampleWeightMs:j(o),topFunctions:c}}function A(e,t){let n=D(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 de(e,t){return D(D(e.children.find(e=>O.has(e.name)),t)?.children.find(e=>e.name===`frame`),t)}function fe(e,t){return D(e.children.find(e=>e.name===`binary`),t)?.attributes.name?.trim()||void 0}function j(e){return Math.round(e/1e6*1e3)/1e3}async function pe(e){let t=await _e(e.device,e.appBundleId);await m(_.dirname(e.outPath));let n=P({device:e.device,template:e.template,target:t.pids,outPath:e.outPath}),r=new Date().toISOString(),o=await F(n,e.outPath,{device:e.device,appBundleId:e.appBundleId,failureMessage:`Failed to start Apple xctrace ${e.mode} capture for ${e.appBundleId}`},async()=>{let e=i(`xcrun`,n,{allowFailure:!0}),t=await ye(e.wait);return t?{failure:t}:{recorded:e}});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:o.child,wait:o.wait}}async function me(e,t=e.outPath){t!==e.outPath&&await m(_.dirname(t));let n=r(await L(e,{failOnForcedKill:!0}),`Failed to stop Apple xctrace ${e.mode} capture`,t=>({tracePath:e.outPath,captureCleanedUp:!0,hint:B(t.stdout,t.stderr)}));return t!==e.outPath&&await ee(e.outPath,t).catch(async()=>{await re(e.outPath,t),await f(e.outPath)}),await z(t,{message:`xctrace produced no trace data`,hint:`Keep the Apple device unlocked and connected, keep the app active, then retry perf.`,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 he(e){return await L(e,{failOnForcedKill:!1})}async function ge(e){let n=await p(`agent-device-xctrace-report-`),r=_.join(n,`trace-toc.xml`),i=_.join(n,`time-profile.xml`);try{let n=await N({tracePath:e.tracePath,outPath:r,query:`toc`,failureMessage:`Failed to export Apple xctrace report metadata`,failureDetails:{tracePath:e.tracePath}}),a=await N({tracePath:e.tracePath,outPath:i,query:{schema:`time-profile`},failureMessage:`Failed to export Apple xctrace Time Profiler samples`,failureDetails:{tracePath:e.tracePath}}),o=be({...e,tocXml:n,timeProfileXml:a});if(o.summary.sampleCount===0)throw new t(`COMMAND_FAILED`,`Apple xctrace CPU report contained no samples`,{tracePath:e.tracePath,tableSchemas:o.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 m(_.dirname(e.outPath)),await ie(e.outPath,`${JSON.stringify(o,null,2)}\n`),o}finally{await f(n).catch(()=>{})}}async function M(e){let t=P({device:e.device,template:e.template,target:e.target,timeLimit:e.timeLimit,outPath:e.tracePath}),{result:n,...r}=await F(t,e.tracePath,e,async()=>{let e=new Date().toISOString(),n=await g(t,{allowFailure:!0,timeoutMs:6e4});return n.exitCode===0?{recorded:{result:n,startedAt:e,endedAt:new Date().toISOString(),capturedAtMs:Date.now()}}:{failure:n}});return e.requireTraceData&&await z(e.tracePath,{message:`${e.failureMessage}: xctrace produced no trace data`,hint:`Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.`,appBundleId:e.appBundleId,deviceId:e.device.id,stdout:n.stdout,stderr:n.stderr}),r}async function N(e){let t=[`xctrace`,`export`,`--input`,e.tracePath,...e.query===`toc`?[`--toc`]:[`--xpath`,`/trace-toc/run/data/table[@schema="${e.query.schema}"]`],`--output`,e.outPath];return r(await g(t,{allowFailure:!0,timeoutMs:15e3}),e.failureMessage,n=>({cmd:`xcrun`,args:t,...e.failureDetails,hint:B(n.stdout,n.stderr)})),await ne(e.outPath)}async function _e(n,r){if(!c(n.platform))throw new t(`UNSUPPORTED_OPERATION`,`Apple xctrace perf is not supported on Android.`,{platform:n.platform,hint:`Android native profiling belongs to the Android perf rollout and is not implemented under Apple xctrace.`});let{readAppleProcessSamples:i,resolveAppleExecutable:a,resolveIosDevicePerfTarget:o}=await import(`./perf-target.js`);if(s(n)&&n.kind===`device`){let t=await o(n,r);return{pids:t.map(e=>e.pid),processNames:e(t.map(e=>_.basename(v(e.executable))))}}let l=await a(n,r),u=await i(n,l);if(u.length===0)throw new t(`COMMAND_FAILED`,`No running process found for ${r}`,{appBundleId:r,deviceId:n.id,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf.`});return{pids:u.map(e=>e.pid),processNames:[l.executableName]}}function P(e){return[`xctrace`,`record`,`--template`,e.template,...s(e.device)?[`--device`,e.device.id]:[],...e.target===`all-processes`?[`--all-processes`]:e.target.flatMap(e=>[`--attach`,String(e)]),...e.timeLimit?[`--time-limit`,e.timeLimit]:[],`--output`,e.outPath,`--quiet`,`--no-prompt`]}async function F(e,r,i,a){for(let o=1;;o+=1){await ve(r,o);let s=await a();if(`recorded`in s)return s.recorded;if(o<3&&I(s.failure))continue;let{failure:c}=s;throw new t(`COMMAND_FAILED`,i.failureMessage,n(c,{cmd:`xcrun`,args:e,appBundleId:i.appBundleId,deviceId:i.device.id,hint:B(c.stdout,c.stderr)}))}}function I(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 ve(e,t){t<=1||(await f(e).catch(()=>{}),await new Promise(e=>setTimeout(e,1500)))}async function ye(e){return await Promise.race([e,new Promise(e=>setTimeout(e,500))])}async function L(e,n){e.child.kill(`SIGINT`);let r=await R(e.wait,45e3);if(r)return r;e.child.kill(`SIGKILL`);let i=await R(e.wait,5e3);if(i&&!n.failOnForcedKill)return i;throw i?new t(`COMMAND_FAILED`,`Timed out waiting for Apple xctrace capture to stop`,{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,tracePath:e.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 t(`COMMAND_FAILED`,`Timed out waiting for Apple xctrace capture to stop after SIGKILL`,{tracePath:e.outPath,captureCleanedUp:!1,forcedKill:!0,hint:`xctrace did not exit after SIGKILL. Inspect running xctrace processes before retrying.`})}async function R(e,t){return await Promise.race([e,new Promise(e=>setTimeout(e,t))])}async function z(e,n){let r=await h(e).catch(()=>null);if(!(r?.isDirectory()===!0?(await te(e).catch(()=>[])).length>0:(r?.size??0)>0))throw new t(`COMMAND_FAILED`,n.message,{tracePath:e,appBundleId:n.appBundleId,deviceId:n.deviceId,stdout:n.stdout,stderr:n.stderr,hint:n.hint})}function be(t){let n=l(t.tocXml),r=b(n,e=>e.name===`run`),i=e(b(n,e=>e.name===`table`).map(e=>e.attributes.schema).filter(e=>typeof e==`string`&&e.length>0)).sort(),a=k(t.timeProfileXml);return{kind:`xctrace`,mode:`cpu-profile`,template:t.template,tracePath:t.tracePath,reportPath:t.outPath,appBundleId:t.appBundleId,generatedAt:new Date().toISOString(),summary:{runCount:r.length,tableSchemas:i,...a}}}function B(e,t){let n=oe(e,t);if(n)return n;let r=`${e}\n${t}`.toLowerCase();return r.includes(`no device matched`)||r.includes(`failed to find device`)?se: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.`}const V=`xctrace-animation-hitches`;function xe(t){let n=Se(t.frameLifetimesXml),r=Ce(t.displayInfoXml),i=we(t.hitchesXml).filter(e=>De(e,t.processIds,t.processNames)),a=i.length,o=Math.max(0,Math.round(Date.parse(t.windowEndedAt)-Date.parse(t.windowStartedAt))),s=H(i,Date.parse(t.windowStartedAt));return{droppedFramePercent:n>0?u(a/n*100):0,droppedFrameCount:a,totalFrameCount:n,sampleWindowMs:o,windowStartedAt:t.windowStartedAt,windowEndedAt:t.windowEndedAt,measuredAt:t.measuredAt,method:V,matchedProcesses:e(i.map(e=>e.processName).filter(e=>typeof e==`string`&&e.length>0)),frameDeadlineMs:r===void 0?void 0:d(1e3/r),refreshRateHz:r,worstWindows:s.length>0?s:void 0}}function Se(e){return ke(e,`hitches-frame-lifetimes`).length}function Ce(e){if(!e)return;let{rows:t,schema:n}=U(e,`device-display-info`),r=n.indexOf(`max-refresh-rate`);if(r<0)return;let i=new Map;for(let e of t){w(e.children,i);let t=C(e.children[r],i);if(t!==null&&t>0)return t}}function we(e){let t=l(e),n=Te(t);if(!n)return[];let r=new Map;return b(t,e=>e.name===`row`).map(e=>Ee(e,n,r)).filter(e=>!!e)}function Te(e){let t=x(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 Ee(e,t,n){if(w(e.children,n),Ae(e.children[t.isSystem],n)===!0)return null;let r=C(e.children[t.start],n),i=C(e.children[t.duration],n);if(r===null||i===null)return null;let a=T(e.children[t.process],n);return{startNs:r,durationNs:i,pid:a?.pid,processName:a?.name}}function De(e,t,n){return e.pid!==void 0&&t.includes(e.pid)?!0:e.processName?n.includes(e.processName):!1}function H(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=>Oe(e,t)).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}function Oe(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:d(Math.max(...e.map(e=>e.durationNs))/1e6)}}function ke(e,t){return U(e,t).rows}function U(e,t){let n=l(e),r=x(n,t);return{rows:r.length===0?[]:b(n,e=>e.name===`row`),schema:r}}function Ae(e,t){let n=C(e,t);return n===null?null:n!==0}const W=`ps-process-snapshot`,G=`xctrace-activity-monitor`,K=`leaks-output-graph`,q=12e4;async function je(e,n){if(s(e)&&e.kind===`device`)return await Ve(e,n);let{readAppleProcessSamples:r,resolveAppleExecutable:i}=await import(`./perf-target.js`),a=await i(e,n),o=await r(e,a);if(o.length===0)throw new t(`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 c=new Date().toISOString();return $({residentMemoryKb:o.reduce((e,t)=>e+t.rssKb,0),measuredAt:c,matchedProcesses:[a.executableName],memoryMethod:W})}async function Me(e,r,i){let a=Y(e);if(!a.memgraph)return{available:!1,kind:`memgraph`,reason:a.reason,hint:a.hint,support:a};let o=await Ge(e,r,a);if(o.available===!1)return o;let{process:s}=o;await m(_.dirname(i));let c=await Fe(i),l;try{l=await Ne(e,i,s.pid)}catch(t){throw await J(i,c),Pe(e,r,s,i,t)}if(l.exitCode!==0)throw await J(i,c),new t(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${r}`,n(l,{kind:`memgraph`,appBundleId:r,pid:s.pid,processName:_.basename(Z(s.command)),path:i,hint:Q(e,l.stdout,l.stderr)}));let u=await h(i).catch(()=>null);if(!u?.isFile()||u.size<=0)throw await J(i,c),new t(`COMMAND_FAILED`,`Apple memgraph artifact is missing or empty`,{kind:`memgraph`,appBundleId:r,pid:s.pid,path:i,hint:`Retry with a writable --out path. If the file is still empty, check free disk space at path.`});return{available:!0,kind:`memgraph`,path:i,sizeBytes:u.size,measuredAt:new Date().toISOString(),method:K,appBundleId:r,pid:s.pid,processName:_.basename(Z(s.command)),support:a}}async function Ne(e,t,n){return o(e)?await ae(`leaks`,[`--outputGraph=${t}`,String(n)],{allowFailure:!0,timeoutMs:q}):await g(ce(e,[`spawn`,e.id,`leaks`,`--outputGraph=${t}`,String(n)]),{allowFailure:!0,timeoutMs:q})}function Pe(e,n,r,i,a){if(a instanceof t){let o=a.details??{};return new t(a.code,`Failed to capture Apple memgraph for ${n}`,{...o,kind:`memgraph`,appBundleId:n,pid:r.pid,processName:_.basename(Z(r.command)),path:i,hint:Q(e,typeof o.stdout==`string`?o.stdout:``,typeof o.stderr==`string`&&o.stderr.length>0?o.stderr:a.message)},a)}return new t(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${n}`,{kind:`memgraph`,appBundleId:n,pid:r.pid,processName:_.basename(Z(r.command)),path:i,hint:`Retry perf memory snapshot. If it still fails, the Cause line names the leaks failure.`},a)}async function Fe(e){return await h(e).then(e=>e.isFile()).catch(()=>!1)}async function J(e,t){t||await f(e).catch(()=>{})}async function Ie(n,r){if(!s(n)||n.kind!==`device`)throw new t(`COMMAND_FAILED`,`Apple frame-health sampling is currently available only on connected iOS devices.`,{metric:`fps`,platform:a(n),deviceKind:n.kind});let{resolveIosDevicePerfTarget:i}=await import(`./perf-target.js`),o=await i(n,r),c=await ze(n,r,o);return xe({hitchesXml:c.hitchesXml,frameLifetimesXml:c.frameLifetimesXml,displayInfoXml:c.displayInfoXml,processIds:o.map(e=>e.pid),processNames:e(o.map(e=>_.basename(v(e.executable)))),windowStartedAt:c.windowStartedAt,windowEndedAt:c.windowEndedAt,measuredAt:c.windowEndedAt})}function Le(e){return s(e)&&e.kind===`device`?{method:V,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:V,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 Re(e){if(s(e)&&e.kind===`device`)return{method:G,description:`Resident memory snapshot from a short xctrace Activity Monitor sample on the connected iOS device.`,unit:`kB`};let t=o(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:W,description:`Resident memory snapshot from ${t}`,unit:`kB`}}function Y(e){return s(e)&&e.kind===`device`?{platform:a(e),deviceKind:e.kind,memgraph:!1,method:K,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.`}:s(e)&&e.kind===`simulator`?{platform:a(e),deviceKind:e.kind,memgraph:!0,method:K,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.`}:o(e)?{platform:a(e),deviceKind:e.kind,memgraph:!0,method:K,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:K,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 ze(e,t,n){let r=await p(`agent-device-ios-frame-perf-`),i=_.join(r,`animation-hitches.trace`);try{let a=await M({device:e,appBundleId:t,tracePath:i,template:`Animation Hitches`,timeLimit:`2s`,target:n.map(e=>e.pid),requireTraceData:!0,failureMessage:`Failed to record iOS frame-health sample for ${t}`}),o={device:e,appBundleId:t,tracePath:i,tempDir:r};return{windowStartedAt:a.startedAt,windowEndedAt:a.endedAt,hitchesXml:await X(o,`hitches`),frameLifetimesXml:await X(o,`hitches-frame-lifetimes`),displayInfoXml:await X(o,`device-display-info`).catch(()=>void 0)}}finally{await f(r).catch(()=>{})}}async function X(e,t){return await N({tracePath:e.tracePath,outPath:_.join(e.tempDir,`${t}.xml`),query:{schema:t},failureMessage:`Failed to export iOS device ${t} data`,failureDetails:{appBundleId:e.appBundleId,deviceId:e.device.id}})}async function Be(e){let n=l(e),r=x(n,`activity-monitor-process-live`);if(r.length===0)throw new t(`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 t(`COMMAND_FAILED`,`xctrace activity-monitor-process-live export is missing expected columns`);let s=b(n,e=>e.name===`row`),c=[],u=new Map;for(let e of s){let t=e.children;if(t.length===0)continue;w(t,u);let n=C(t[i],u),r=T(t[a],u)?.name;n===null||!Number.isFinite(n)||!r||c.push({pid:n,processName:r,residentMemoryBytes:C(t[o],u)})}return c}async function Ve(e,n){let{resolveIosDevicePerfTarget:r}=await import(`./perf-target.js`),i=await r(e,n),a=await He(e,n),o=Ue(await Be(a.xml),i,n,e);if(o.residentMemoryBytes===null)throw new t(`COMMAND_FAILED`,`Incomplete Activity Monitor sample for ${n}`,{appBundleId:n,deviceId:e.id,hint:`Keep the app running in the foreground while perf samples the device, then retry.`});return $({residentMemoryKb:o.residentMemoryBytes/1024,measuredAt:new Date(a.capturedAtMs).toISOString(),matchedProcesses:o.matchedProcesses,memoryMethod:G})}async function He(e,t){let n=await p(`agent-device-ios-perf-`),r=_.join(n,`sample.trace`);try{return{capturedAtMs:(await M({device:e,appBundleId:t,tracePath:r,template:`Activity Monitor`,timeLimit:`1s`,target:`all-processes`,failureMessage:`Failed to record iOS device Activity Monitor sample for ${t}`})).capturedAtMs,xml:await X({device:e,appBundleId:t,tracePath:r,tempDir:n},`activity-monitor-process-live`)}}finally{await f(n).catch(()=>{})}}function Ue(n,r,i,a){let o=new Set(r.map(e=>e.pid)),s=new Set(r.map(e=>_.basename(v(e.executable)))),c=n.filter(e=>o.has(e.pid)||s.has(e.processName));if(c.length===0)throw new t(`COMMAND_FAILED`,`No Activity Monitor sample found for ${i}`,{appBundleId:i,deviceId:a.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:qe(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:e(u.map(e=>e.processName))}}function Z(e){let[t=``]=e.trim().split(/\s+/,1);return t}async function We(e,n,r){let{readAppleProcessSamples:i}=await import(`./perf-target.js`),a=(await i(e,r)).sort((e,t)=>t.rssKb-e.rssKb)[0];if(a)return a;throw new t(`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 Ge(e,t,n){try{let{resolveAppleExecutable:n}=await import(`./perf-target.js`);return{available:!0,process:await We(e,t,await n(e,t))}}catch(t){if(Ke(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 Ke(e,n){if(!s(e)||e.kind!==`simulator`||!(n instanceof t))return!1;let r=n.details??{},i=Array.isArray(r.args)?r.args.join(` `):``,a=typeof r.stderr==`string`?r.stderr:``,o=`${n.message}\n${a}`.toLowerCase();return i.includes(`simctl spawn`)&&i.includes(` ps `)&&o.includes(`no such file`)}function Q(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`)?o(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. If it still fails, read the leaks output in error.details.stdout and error.details.stderr (--json).`}function $(e){return{residentMemoryKb:Math.round(e.residentMemoryKb),measuredAt:e.measuredAt,method:e.memoryMethod,matchedProcesses:e.matchedProcesses}}function qe(e,t){return e===null?t:t===null?e:Math.max(e,t)}export{Le as buildAppleFrameSamplingMetadata,Re as buildAppleMemorySamplingMetadata,Y as buildAppleMemorySnapshotSupport,Me as captureAppleMemorySnapshot,he as cleanupAppleXctracePerfCapture,I as isRetryableIosDeviceTraceRecordFailure,B as resolveIosDevicePerfHint,Ie as sampleAppleFramePerf,je as sampleAppleMemoryPerf,pe as startAppleXctracePerfCapture,me as stopAppleXctracePerfCapture,ge as writeAppleXctracePerfReport};