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.
5 lines • 14.2 kB
JavaScript
import{v as e}from"./sdk-contracts.js";import{g as t}from"./sdk-batch-runner.js";import{et as n,rt as r}from"./sdk-io.js";import"./command.js";import{_ as i,b as a,k as o,o as s,u as c}from"./host-file.js";import l from"node:path";const u=/^[0-9a-fA-F-]{32,36}$/;function d(e){if(!(!e||!u.test(e)))return e.replaceAll(`-`,``).toUpperCase()}function f(e,t){return`${e.uuid}:${p(t)}`}function p(e){return`0x${e.toString(16)}`}function m(e){return typeof e==`string`&&e.length>0?e:void 0}function h(...e){for(let t of e){let e=m(t);if(e)return e}}function g(e){let t=e.filter(e=>!!e);return t.length>0?t.join(` `):void 0}function _(e){try{let n=JSON.parse(e);return t(n)?n:null}catch{return null}}function v(e){if(typeof e==`number`&&Number.isSafeInteger(e))return e;if(typeof e==`string`){let t=e.startsWith(`0x`)?Number.parseInt(e,16):Number(e);return Number.isSafeInteger(t)?t:void 0}}function y(e,t,n){if(!Object.hasOwn(e,t))return;let r=v(e[t]);if(r!==void 0)return r;S(n,t)}function b(e,t,n){if(!Object.hasOwn(e,t))return;let r=x(e[t]);if(r!==void 0)return r;S(n,t)}function x(e){if(typeof e==`bigint`)return e;if(typeof e==`number`&&Number.isSafeInteger(e)||typeof e==`string`&&/^(?:0x[0-9a-fA-F]+|\d+)$/.test(e))return BigInt(e)}function S(t,n){throw new e(`INVALID_ARGS`,`Invalid ${t} numeric field: ${n}`,{hint:`Crash artifact numeric fields must be integer numbers or integer numeric strings.`})}function C(e){return e.length===1?e[0]:void 0}function w(e){return[...new Set(e)]}function ee(e){let t=e.match(/^(.*) \+ (\d+)$/);return t?{symbol:t[1],location:Number(t[2])}:{symbol:e}}const te=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;function ne(e){return re(e)??O(e)}function re(e){let t=ie(e);if(!t)return null;let n=(Array.isArray(t.payload.usedImages)?t.payload.usedImages:[]).flatMap((e,t)=>D(e,t));if(n.length===0)return null;let r=ae(Array.isArray(t.payload.threads)?t.payload.threads:[],n);return{format:`ips`,images:n,addresses:r.map(({frame:e,...t})=>t),document:t,frameMatches:r,write:e=>T(t,r,e)}}function ie(e){let t=_(e);if(t)return{payload:t};let n=e.indexOf(`
`);if(n===-1)return null;let r=e.slice(0,n),i=_(e.slice(n+1));return i?{header:r,payload:i}:null}function ae(e,t){let n=new Map(t.map(e=>[e.index,e]));return e.flatMap((e,t)=>oe(e).flatMap((e,r)=>se(e,n,t,r)))}function oe(e){return!t(e)||!Array.isArray(e.frames)?[]:e.frames.filter(t)}function se(e,t,n,r){let i=y(e,`imageIndex`,`IPS frame`),a=b(e,`imageOffset`,`IPS frame`);if(i===void 0||a===void 0)return[];let o=t.get(i);return o?[{frame:e,frameIndex:r,threadIndex:n,image:o,address:o.base+a}]:[]}function T(e,t,n){for(let e of t){let t=n.get(f(e.image,e.address))?.text;t&&E(e.frame,t)}e.payload.agentDeviceSymbolication={tool:`agent-device debug symbols`,symbolicatedFrames:[...n.values()].filter(e=>e.text).length};let r=`${JSON.stringify(e.payload,null,2)}\n`;return e.header?`${e.header}\n${r}`:r}function E(e,t){let n=ee(t);e.symbol=n.symbol,n.location!==void 0&&(e.symbolLocation=n.location)}function D(e,n){if(!t(e))return[];let r=d(m(e.uuid)),i=b(e,`base`,`IPS usedImages`);if(!r||i===void 0)return[];let a=m(e.path);return[{index:n,name:m(e.name)??(a?l.basename(a):`image-${n}`),uuid:r,arch:m(e.arch),base:i,path:a}]}function O(e){let t=e.split(`
`),n=k(t);if(n.length===0)return null;let r=M(t,n);return{format:`text`,images:n,addresses:r,lines:t,frameMatches:r,write(e){let n=new Map(r.map(e=>[e.lineIndex,e]));return t.map((t,r)=>{let i=n.get(r);if(!i)return t;let a=e.get(f(i.image,i.address))?.text;return!a||t.includes(a)?t:`${t} // ${a}`}).join(`
`)}}}function k(e){let t=[],n=e.findIndex(e=>/^Binary Images:/i.test(e.trim()));if(n===-1)return t;for(let r of e.slice(n+1)){let e=A(r);e&&t.push(e)}return t}function A(e){let t=e.match(/^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+\+?(.+?)\s+<([0-9a-fA-F-]{32,36})>\s+(.+)$/);if(!t)return null;let n=d(t[4]);if(!n)return null;let r=j(t[3].trim(),t[5].trim());return{name:r.name,arch:r.arch,uuid:n,base:BigInt(t[1]),end:BigInt(t[2]),path:t[5].trim()}}function j(e,t){let n=e.split(/\s+/),r=n.at(-1);if(r&&te.test(r))return{name:n.slice(0,-1).join(` `).trim(),arch:r};let i=l.basename(t);return{name:e.startsWith(i)?i:e}}function M(e,t){let n=[],r;for(let[i,a]of e.entries()){let e=a.match(/^Thread\s+(\d+)\s+Crashed:/);e?r=Number(e[1]):(a.trim().length===0||/^Thread\s+\d+/.test(a))&&(r=void 0);let o=N(a,t),s=a.match(/^\s*(\d+)/);o&&s&&n.push({...o,frameIndex:Number(s[1]),lineIndex:i,threadIndex:r})}return n}function N(e,t){let n=e.match(/^\s*\d+\s+(.+?)\s+(0x[0-9a-fA-F]+)\b/);if(!n)return null;let r=n[1].trim(),i=BigInt(n[2]),a=P(t,r,i);return a?{image:a,address:i}:null}function P(e,t,n){let r=e.filter(e=>e.name===t);return r.find(e=>F(e,n))??C(r)}function F(e,t){return e.end!==void 0&&e.base<=t&&t<=e.end}const I=1e4;async function L(e){return e.dsym&&e.searchPath?[K(e.cwd,e.dsym),...await R(K(e.cwd,e.searchPath))]:e.dsym?[K(e.cwd,e.dsym)]:e.searchPath?await R(K(e.cwd,e.searchPath)):[]}async function R(t){let n=[],r=0;async function a(o){if(n.length>=200)return;if(r+=1,r>I)throw new e(`COMMAND_FAILED`,`debug symbols search-path scan exceeded bounds.`,{searchPath:t,maxEntries:I,hint:`Pass --dsym <App.dSYM> directly or narrow --search-path to the build products directory.`});if(!(await z(o,t)).isDirectory()){o===t&&B(t);return}if(o.endsWith(`.dSYM`)){n.push(o);return}let s=await i(o,{withFileTypes:!0});for(let e of s)e.isDirectory()&&await a(l.join(o,e.name))}return await a(t),n}async function z(t,n){try{return await c(t)}catch{throw new e(`INVALID_ARGS`,`debug symbols search path does not exist: ${n}`,{hint:`Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly.`})}}function B(t){throw new e(`INVALID_ARGS`,`debug symbols search path is not a directory: ${t}`,{hint:`Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly.`})}async function V(t,n){let r=(await Promise.all(w(t).map(e=>H(e,n)))).flat();if(r.length===0)throw new e(`COMMAND_FAILED`,`No UUIDs found in dSYM bundle.`,{hint:`Verify the path points to a built .dSYM bundle with DWARF contents.`});return r}async function H(e,t){return await U(e),W(e,n(await r(t,[`--uuid`,e],{timeoutMs:15e3,allowFailure:!0}),`Failed to inspect dSYM UUIDs: ${e}`,{hint:`Verify the dSYM bundle is valid and readable.`}).stdout)}async function U(t){if(!((await c(t).catch(()=>null))?.isDirectory()&&t.endsWith(`.dSYM`)))throw new e(`INVALID_ARGS`,`Not a .dSYM bundle: ${t}`,{hint:`Pass the .dSYM bundle path, not the DWARF executable inside it.`})}function W(e,t){return t.split(`
`).flatMap(t=>{let n=t.match(/^UUID:\s+([0-9a-fA-F-]{32,36})\s+\(([^)]+)\)\s+(.+)$/),r=d(n?.[1]);return n&&r?[{dsymPath:e,uuid:r,arch:n[2],binaryPath:n[3].trim()}]:[]})}function G(t,n,r){let i=new Map;for(let e of t){let t=n.find(t=>t.uuid===e.uuid&&(e.arch===void 0||t.arch===void 0||t.arch===e.arch));t&&i.set(e.uuid,{image:e,dsym:t})}if(i.size>0)return i;let a=w(t.map(e=>e.uuid)),o=w(n.map(e=>e.uuid));throw new e(`COMMAND_FAILED`,r?`dSYM UUID does not match any Apple image in the crash artifact.`:`No matching dSYM UUID found under search path.`,{artifactUuidCount:a.length,artifactUuidSample:a.slice(0,5),dsymUuidCount:o.length,dsymUuidSample:o.slice(0,5),hint:`Use dwarfdump --uuid <App.dSYM> and compare it with the crash Binary Images or usedImages UUID, then pass the matching dSYM/search path.`})}function K(e,t){return l.resolve(e,t)}function ce(e,t){return e.format===`ips`?le(e.document,e.frameMatches,t):Se(e.lines,e.frameMatches,t)}function le(e,t,n){let r=ve(e.payload),i={format:`ips`,...ue(e),crashedThread:r,topFrames:xe(t,r,n),findings:[]};return{...i,findings:Y(i)}}function ue(e){let t=e.payload,n=_e(e.header);return{appName:de(t,n),bundleId:fe(t,n),version:pe(t,n),incident:me(t,n),timestamp:he(t,n),exceptionType:ge(t.exception),exceptionCodes:ye(t.exception),terminationReason:be(t.termination)}}function de(e,t){return h(e.procName,t?.app_name,t?.name)}function fe(e,n){return h((t(e.bundleInfo)?e.bundleInfo:void 0)?.CFBundleIdentifier,n?.bundleID)}function pe(e,n){return h((t(e.bundleInfo)?e.bundleInfo:void 0)?.CFBundleShortVersionString,n?.app_version)}function me(e,t){return h(e.incident,t?.incident_id)}function he(e,t){return h(e.captureTime,t?.timestamp)}function ge(e){return t(e)?m(e.type):void 0}function _e(e){return e?_(e):null}function ve(e){let n=v(e.faultingThread);if(n!==void 0)return n;let r=(Array.isArray(e.threads)?e.threads:[]).findIndex(e=>t(e)&&e.triggered===!0);return r===-1?void 0:r}function ye(e){return t(e)?h(e.codes,e.rawCodes):void 0}function be(e){if(t(e))return g([m(e.namespace),m(e.code),m(e.reason)])}function xe(e,t,n){return e.filter(e=>t===void 0||e.threadIndex===t).slice(0,5).map(e=>J(e.frameIndex,e.image,e.address,n))}function Se(e,t,n){let r=we(e),i={format:`text`,appName:Ce(e),bundleId:q(e,`Identifier`),version:q(e,`Version`),incident:q(e,`Incident Identifier`),timestamp:q(e,`Date/Time`),exceptionType:q(e,`Exception Type`),exceptionCodes:q(e,`Exception Codes`),terminationReason:q(e,`Termination Reason`),crashedThread:r,topFrames:Te(t,r,n),findings:[]};return{...i,findings:Y(i)}}function Ce(e){return q(e,`Process`)?.replace(/\s+\[\d+\]$/,``)}function q(e,t){let n=`${t}:`,r=e.find(e=>e.trimStart().startsWith(n));return r&&r.slice(r.indexOf(`:`)+1).trim()||void 0}function we(e){let t=q(e,`Triggered by Thread`),n=t?Number.parseInt(t,10):NaN;if(Number.isSafeInteger(n))return n;for(let t of e){let e=t.match(/^Thread\s+(\d+)\s+Crashed:/);if(e)return Number(e[1])}}function Te(e,t,n){return t===void 0?[]:e.filter(e=>e.threadIndex===t).slice(0,5).map(e=>J(e.frameIndex,e.image,e.address,n))}function J(e,t,n,r){return{index:e,image:t.name,address:p(n),symbol:r.get(f(t,n))?.text}}function Y(e){return[Ee(e),e.exceptionType?`Exception: ${e.exceptionType}`:void 0,e.terminationReason?`Termination: ${e.terminationReason}`:void 0].filter(e=>!!e).slice(0,3)}function Ee(e){let t=e.topFrames.find(e=>e.symbol);return t?`Start with ${t.symbol} in ${t.image}; it is the first symbolicated frame captured on the crashed thread.`:e.topFrames.length>0?`No symbolicated frame was found on the crashed thread; verify matching dSYMs for the top images.`:void 0}async function De(e,t,n){let r=new Map;for(let i of Oe(e,t).values())for(let e of await ke(n,i))r.set(f(e.image,e.address),e);return r}function Oe(e,t){let n=new Map;for(let r of e){let e=t.get(r.image.uuid);if(!e)continue;let i=`${r.image.uuid}:${e.dsym.binaryPath}`,a=n.get(i)??{...e,addresses:[]};a.addresses.push(r.address),n.set(i,a)}return n}async function ke(e,t){let i=w(t.addresses.map(p)),a=n(await r(e,Ae(t,i),{timeoutMs:3e4,allowFailure:!0}),`atos failed while symbolicating crash frames.`,{hint:`Verify the crash artifact and dSYM were produced from the same build and architecture.`});return X(t.image,i,a.stdout)}function Ae(e,t){return[`-arch`,e.image.arch??e.dsym.arch??`arm64`,`-o`,e.dsym.binaryPath,`-l`,p(e.image.base),...t]}function X(e,t,n){let r=je(n);return t.map((t,n)=>{let i=r[n]?.trim();return{image:e,address:BigInt(t),text:Me(i,t)?i:void 0}})}function je(e){let t=e.split(/\r?\n/);return t.at(-1)===``&&t.pop(),t}function Me(e,t){if(!e)return!1;let n=e.trim().toLowerCase();return!n||n===`??`||n===t.toLowerCase()?!1:!n.startsWith(`0x`)}async function Ne(){return{dwarfdump:await Z(`dwarfdump`),atos:await Z(`atos`)}}async function Z(t){try{let e=await r(`xcrun`,[`--find`,t],{timeoutMs:5e3,allowFailure:!0}),n=e.stdout.trim();if(e.exitCode===0&&n.length>0)return n}catch{}throw new e(`TOOL_MISSING`,`Apple symbolication tool not found: ${t}`,{hint:`Install Xcode Command Line Tools and verify xcrun --find dwarfdump and xcrun --find atos succeed.`})}const Q=67108864;async function Pe(t){if(t.action!==void 0&&t.action!==`symbols`)throw new e(`INVALID_ARGS`,`debug supports only the symbols workflow.`,{hint:`Use debug symbols --artifact <crash.ips|crash.log> --dsym <App.dSYM> or --search-path <dir> --out <path>.`});let n=t.cwd,r=$(n,t.artifact),i=$(n,t.out??Re(r)),a=ne(await Ie(r,`crash artifact`));a||Fe();let c=await L({cwd:n,dsym:t.dsym,searchPath:t.searchPath});if(c.length===0)throw new e(`INVALID_ARGS`,`debug symbols requires --dsym or --search-path.`,{hint:`Pass a matching .dSYM bundle directly, or pass --search-path <dir> so agent-device can match crash image UUIDs to local dSYMs.`});let u=await Ne(),d=await V(c,u.dwarfdump),f=G(a.images,d,!!t.dsym),p=await De(a.addresses,f,u.atos),m=a.write(p);await s(l.dirname(i)),await o(i,m);let h=[...f.values()].map(({image:e,dsym:t})=>({name:e.name,uuid:e.uuid,arch:e.arch??t.arch,dsymPath:t.dsymPath,binaryPath:t.binaryPath})),g=[...p.values()].filter(e=>e.text).length,_=a.images.length-h.length,v=_>0?[`${_} Apple image${_===1?``:`s`} had no matching dSYM and were left unchanged.`]:void 0;return{kind:`debugSymbols`,platform:`apple`,artifactPath:r,outPath:i,crash:ce(a,p),matchedImages:h,symbolicatedFrames:g,skippedImages:_,warnings:v,message:`Symbolicated ${g} frame${g===1?``:`s`} -> ${i}`}}function Fe(){throw new e(`UNSUPPORTED_OPERATION`,`debug symbols currently supports Apple crash artifacts with Binary Images or IPS usedImages.`,{hint:`For Android Java/R8 crashes, use retrace with mapping.txt. For Android native crashes, use ndk-stack or addr2line with unstripped .so symbols. Capture the crash with logs, then symbolicate externally until Android support is added.`})}async function Ie(t,n){await Le(t,n);try{return await a(t)}catch(r){let i=r instanceof Error?r.message:String(r);throw new e(`INVALID_ARGS`,`Failed to read ${n}: ${t}`,{message:i})}}async function Le(t,n){try{let r=await c(t);if(r.size<=Q)return;throw new e(`INVALID_ARGS`,`${n} is too large: ${t}`,{actualBytes:r.size,maxBytes:Q,hint:`Pass a bounded Apple .ips/.crash artifact. For very large logs, first narrow the log to the crash report, or use logs grep/tail for lead-up context.`})}catch(r){if(r instanceof e)throw r;let i=r instanceof Error?r.message:String(r);throw new e(`INVALID_ARGS`,`Failed to read ${n}: ${t}`,{message:i})}}function $(e,t){return l.resolve(e,t)}function Re(e){let t=l.extname(e);return`${t?e.slice(0,-t.length):e}-symbolicated${t||`.log`}`}export{Pe as symbolicateCrashArtifact};