agent-device 0.11.7 → 0.11.9
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.
- package/README.md +2 -2
- package/dist/src/995.js +3 -0
- package/dist/src/bin.js +39 -39
- package/dist/src/daemon.js +46 -45
- package/dist/src/index.d.ts +2 -2
- package/dist/src/index.js +3 -3
- package/package.json +12 -3
- package/src/platforms/linux/atspi-dump.py +285 -0
- package/dist/src/168.js +0 -3
package/README.md
CHANGED
|
@@ -65,8 +65,8 @@ In non-JSON mode, core mutating commands print a short success acknowledgment so
|
|
|
65
65
|
|
|
66
66
|
- Startup timing is available on iOS and Android from `open` command round-trip sampling.
|
|
67
67
|
- Android app sessions also sample CPU (`adb shell dumpsys cpuinfo`) and memory (`adb shell dumpsys meminfo <package>`) when the session has an active app package context.
|
|
68
|
-
- Apple app sessions on macOS and iOS simulators
|
|
69
|
-
- Physical iOS devices
|
|
68
|
+
- Apple app sessions on macOS and iOS simulators sample CPU and memory from process snapshots resolved from the active app bundle ID.
|
|
69
|
+
- Physical iOS devices sample CPU and memory from a short `xcrun xctrace` Activity Monitor capture against the connected device, so `perf` can take a few seconds longer there than on simulators or macOS.
|
|
70
70
|
|
|
71
71
|
## Where To Go Next
|
|
72
72
|
|
package/dist/src/995.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{AsyncLocalStorage as e}from"node:async_hooks";import t from"node:crypto";import n,{constants as r}from"node:fs";import i from"node:os";import o from"node:path";import{fileURLToPath as a}from"node:url";import{access as s,stat as l}from"node:fs/promises";import{spawn as u,spawnSync as c}from"node:child_process";import{PNG as d}from"pngjs";let f=new e,p=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key)/i,m=/(bearer\s+[a-z0-9._-]+|(?:api[_-]?key|token|secret|password)\s*[=:]\s*\S+)/i;function h(){return t.randomBytes(8).toString("hex")}async function g(e,n){let r={...e,diagnosticId:`${Date.now().toString(36)}-${t.randomBytes(4).toString("hex")}`,events:[]};return await f.run(r,n)}function w(){let e=f.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug}:{}}function v(e){let t=f.getStore();if(!t)return;let r={ts:new Date().toISOString(),level:e.level??"info",phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?y(e.data):void 0};if(t.events.push(r),!t.debug)return;let i=`[agent-device][diag] ${JSON.stringify(r)}
|
|
2
|
+
`;try{t.logPath&&n.appendFile(t.logPath,i,()=>{}),t.traceLogPath&&n.appendFile(t.traceLogPath,i,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(i)}catch{}}async function S(e,t,n){let r=Date.now();try{let i=await t();return v({level:"info",phase:e,durationMs:Date.now()-r,data:n}),i}catch(t){throw v({level:"error",phase:e,durationMs:Date.now()-r,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function b(e={}){let t=f.getStore();if(!t||!e.force&&!t.debug||0===t.events.length)return null;try{let e=(t.session??"default").replace(/[^a-zA-Z0-9._-]/g,"_"),r=new Date().toISOString().slice(0,10),a=o.join(i.homedir(),".agent-device","logs",e,r);n.mkdirSync(a,{recursive:!0});let s=new Date().toISOString().replace(/[:.]/g,"-"),l=o.join(a,`${s}-${t.diagnosticId}.ndjson`),u=t.events.map(e=>JSON.stringify(y(e)));return n.writeFileSync(l,`${u.join("\n")}
|
|
3
|
+
`),t.events=[],l}catch{return null}}function y(e){return function e(t,n,r){if(null==t)return t;if("string"==typeof t){var i=t,o=r;let e=i.trim();if(!e)return i;if(o&&p.test(o)||m.test(e))return"[REDACTED]";let n=function(e){try{let t=new URL(e);return t.search&&(t.search="?REDACTED"),(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED"),t.toString()}catch{return null}}(e);return n||(e.length>400?`${e.slice(0,200)}...<truncated>`:e)}if("object"!=typeof t)return t;if(n.has(t))return"[Circular]";if(n.add(t),Array.isArray(t))return t.map(t=>e(t,n));let a={};for(let[r,i]of Object.entries(t)){if(p.test(r)){a[r]="[REDACTED]";continue}a[r]=e(i,n,r)}return a}(e,new WeakSet)}class I extends Error{code;details;cause;constructor(e,t,n,r){super(t),this.code=e,this.details=n,this.cause=r}}function x(e){return e instanceof I?e:e instanceof Error?new I("UNKNOWN",e.message,void 0,e):new I("UNKNOWN","Unknown error",{err:e})}function $(e,t={}){let n=x(e),r=n.details?y(n.details):void 0,i=r&&"string"==typeof r.hint?r.hint:void 0,o=(r&&"string"==typeof r.diagnosticId?r.diagnosticId:void 0)??t.diagnosticId,a=(r&&"string"==typeof r.logPath?r.logPath:void 0)??t.logPath,s=i??function(e){switch(e){case"INVALID_ARGS":return"Check command arguments and run --help for usage examples.";case"SESSION_NOT_FOUND":return"Run open first or pass an explicit device selector.";case"TOOL_MISSING":return"Install required platform tooling and ensure it is available in PATH.";case"DEVICE_NOT_FOUND":return"Verify the target device is booted/connected and selectors match.";case"APP_NOT_INSTALLED":return"Run apps to discover the exact installed package or bundle id, or install the app before open.";case"UNSUPPORTED_OPERATION":return"This command is not available for the selected platform/device.";case"COMMAND_FAILED":default:return"Retry with --debug and inspect diagnostics log for details.";case"UNAUTHORIZED":return"Refresh daemon metadata and retry the command."}}(n.code),l=function(e){if(!e)return;let t={...e};return delete t.hint,delete t.diagnosticId,delete t.logPath,Object.keys(t).length>0?t:void 0}(r),u=function(e,t,n){if("COMMAND_FAILED"!==e||n?.processExitError!==!0)return t;let r=function(e){let t=[/^an error was encountered processing the command/i,/^underlying error\b/i,/^simulator device failed to complete the requested operation/i];for(let n of e.split("\n")){let e=n.trim();if(e&&!t.some(t=>t.test(e)))return e.length>200?`${e.slice(0,200)}...`:e}return null}("string"==typeof n?.stderr?n.stderr:"");return r||t}(n.code,n.message,r);return{code:n.code,message:u,hint:s,diagnosticId:o,logPath:a,details:l}}let A="<wifi|airplane|location> <on|off>",N="appearance <light|dark|toggle>",E="faceid <match|nonmatch|enroll|unenroll>",D="touchid <match|nonmatch|enroll|unenroll>",M="fingerprint <match|nonmatch>",L="permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",T="permission <grant|reset> <accessibility|screen-recording|input-monitoring>",O=`macOS supports only settings ${N} and settings ${T}. wifi|airplane|location remain unsupported on macOS.`,_=`settings ${A} | settings ${N} | settings ${E} | settings ${D} | settings ${M} | settings ${L} | settings ${T}`,C=`settings requires ${A}, ${N}, ${E}, ${D}, ${M}, ${L}, or ${T}`;function k(e){let t=e.trim().toLowerCase();return"appearance"===t||"permission"===t}function R(e){return`Unsupported macOS setting: ${e}. ${O}`}let P=["app","frontmost-app","desktop","menubar"];function F(e){let t=e?.trim().toLowerCase();if("app"===t||"frontmost-app"===t||"desktop"===t||"menubar"===t)return t;throw new I("INVALID_ARGS",`Invalid surface: ${e}. Use ${P.join("|")}.`)}function B(e){var t;let n,r=j(e.label),i=j(e.value),o=j(e.identifier),a=(t=o)&&!/^[\w.]+:id\/[\w.-]+$/i.test(t)&&!/^_?NS:\d+$/i.test(t)?o:"";return(n=z(e.type??"")).includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("edittext")||n.includes("textview")||n.includes("textarea")?i||r||a:r||i||a}function j(e){return"string"==typeof e?e.trim():""}function z(e){let t=e.trim().replace(/XCUIElementType/gi,"").replace(/^AX/,"").toLowerCase(),n=Math.max(t.lastIndexOf("."),t.lastIndexOf("/"));return -1!==n&&(t=t.slice(n+1)),t}function G(e,t={}){let n=[],r=[];for(let i of e){let e=i.depth??0,o=i.label?.trim()||i.value?.trim()||i.identifier?.trim()||"",a=H(i.type??"Element");if("group"===a&&!o)continue;for(;n.length>0&&e<=n[n.length-1];)n.pop();let s=n.length;n.push(e),r.push({node:i,depth:s,type:a,text:V(i,s,!1,a,t)})}return r}function V(e,t,n,r,i={}){var o,a,s,l,u;let c,d,f=r??H(e.type??"Element"),p=(c=B(e),{text:c,isLargeSurface:d=function(e,t){if("text-view"===t||"text-field"===t||"search"===t)return!0;let n=z(e.type??""),r=`${e.role??""} ${e.subrole??""}`.toLowerCase();return n.includes("textview")||n.includes("textarea")||n.includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("edittext")||r.includes("text area")||r.includes("text field")}(e,f),shouldSummarize:d&&!!(o=c)&&(o.length>80||/[\r\n]/.test(o))}),m=(a=e,s=f,l=i,u=p,l.summarizeTextSurfaces&&u.shouldSummarize&&function(e,t,n){let r=j(e.label);if(r&&r!==n)return r;let i=j(e.identifier);if(i&&!q(i)&&i!==n)return i;switch(t){case"text":case"text-view":return"Text view";case"text-field":return"Text field";case"search":return"Search field";default:return""}}(a,s,u.text)||U(a,s)),h=" ".repeat(t),g=e.ref?`@${e.ref}`:"",w=(function(e,t,n,r){let i,o=[];if(!1===e.enabled&&o.push("disabled"),!n.summarizeTextSurfaces||(!0===e.selected&&o.push("selected"),W(t)&&o.push("editable"),function(e,t){if("scroll-area"===t)return!0;let n=(e.type??"").toLowerCase(),r=`${e.role??""} ${e.subrole??""}`.toLowerCase();return n.includes("scroll")||r.includes("scroll")}(e,t)&&o.push("scrollable"),!r.shouldSummarize))return o;return o.push(`preview:"${((i=r.text.replace(/\s+/g," ").trim()).length<=48?i:`${i.slice(0,45)}...`).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`),o.push("truncated"),[...new Set(o)]})(e,f,i,p).map(e=>` [${e}]`).join(""),v=m?` "${m}"`:"";return n?`${h}${g} [${f}]${w}`.trimEnd():`${h}${g} [${f}]${v}${w}`.trimEnd()}function U(e,t){var n,r;let i,o=e.label?.trim();if(o&&(n=t,r=o,("scroll-area"===n||"list"===n||"collection"===n||"table"===n)&&(i=r.trim().toLowerCase())&&/^(vertical|horizontal)\s+scroll\s+bar(?:,?\s*\d+\s+pages?)?$/.test(i)))return"";let a=e.value?.trim();if(W(t)){if(a)return a;if(o)return o}else if(o)return o;if(a)return a;let s=e.identifier?.trim();return!s||q(s)&&("group"===t||"image"===t||"list"===t||"collection"===t)?"":s}function H(e){let t=e.replace(/XCUIElementType/gi,"").toLowerCase(),n=e.includes(".")&&(e.startsWith("android.")||e.startsWith("androidx.")||e.startsWith("com."));switch(t.includes(".")&&(t=t.replace(/^android\.widget\./,"").replace(/^android\.view\./,"").replace(/^android\.webkit\./,"").replace(/^androidx\./,"").replace(/^com\.google\.android\./,"").replace(/^com\.android\./,""),n&&t.includes(".")&&(t=t.slice(t.lastIndexOf(".")+1))),t){case"application":return"application";case"navigationbar":return"navigation-bar";case"tabbar":return"tab-bar";case"button":case"imagebutton":return"button";case"link":return"link";case"cell":return"cell";case"statictext":case"checkedtextview":return"text";case"textfield":case"edittext":return"text-field";case"textview":return n?"text":"text-view";case"textarea":return"text-view";case"switch":return"switch";case"slider":return"slider";case"image":case"imageview":return"image";case"webview":return"webview";case"framelayout":case"linearlayout":case"relativelayout":case"constraintlayout":case"viewgroup":case"view":case"group":return"group";case"listview":case"recyclerview":return"list";case"collectionview":return"collection";case"searchfield":return"search";case"segmentedcontrol":return"segmented-control";case"window":return"window";case"checkbox":return"checkbox";case"radio":return"radio";case"menuitem":return"menu-item";case"toolbar":return"toolbar";case"scrollarea":case"scrollview":case"nestedscrollview":return"scroll-area";case"table":return"table";default:return t||"element"}}function W(e){return"text-field"===e||"text-view"===e||"search"===e}function q(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function J(e){return e.map((e,t)=>({...e,ref:`e${t+1}`}))}function K(e){let t=e.trim();return t.startsWith("@")?t.slice(1)||null:t.startsWith("e")?t:null}function X(e,t){return e.find(e=>e.ref===t)??null}function Z(e){return{x:Math.round(e.x+e.width/2),y:Math.round(e.y+e.height/2)}}function Q(e,t){let n=Z(t),r=e.filter(e=>{var t;return!!(t=e.rect)&&Number.isFinite(t.x)&&Number.isFinite(t.y)&&Number.isFinite(t.width)&&Number.isFinite(t.height)}),i=r.filter(e=>{let t=(e.type??"").toLowerCase();return t.includes("application")||t.includes("window")}),o=et(i.map(e=>e.rect).filter(e=>ee(e,n.x,n.y)));if(o)return o;let a=et(i.map(e=>e.rect));if(a)return a;let s=et(r.map(e=>e.rect).filter(e=>ee(e,n.x,n.y)));return s||null}function Y(e,t){let n=Math.max(1,t.height),r=t.y,i=t.y+n,o=r+.25*n,a=i-.25*n,s=e.y+e.height/2;return s<o?Math.ceil(o-s):s>a?Math.ceil(s-a):0}function ee(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function et(e){let t=null,n=-1;for(let r of e){let e=r.width*r.height;e>n&&(t=r,n=e)}return t}function en(e,t,n,r){return Math.max(e,n)<=Math.min(t,r)}function er(e){let t=new Map;for(let[n,r]of e.entries())t.set(r.index,n);let n=[],r=[];for(let[i,o]of e.entries()){let e=Math.max(0,o.depth??0);for(;r.length>0&&e<=r[r.length-1].depth;)r.pop();let a="number"==typeof o.parentIndex?t.get(o.parentIndex):void 0,s="number"==typeof a&&a<i?a:r[r.length-1]?.index;n.push({...o,index:i,depth:e,parentIndex:s}),r.push({depth:e,index:i})}return n}function ei(e){return new Map(e.map(e=>[e.index,e]))}function eo(e){let t=`${e??""}`.toLowerCase();return t.includes("scroll")||t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")||t.includes("collectionview")||"table"===t}function ea(e){return!!eo(e.type)||`${e.role??""} ${e.subrole??""}`.toLowerCase().includes("scroll")}function es(e){if(0===e.length)return{nodes:e,hiddenCount:0,summaryLines:[]};let t=ei(e),n=new Set,r=[];for(let i of e){if(el(i,e,t)){!function(e,t,n){let r=e,i=new Set;for(;r&&!i.has(r.index);)i.add(r.index),t.add(r.index),r="number"==typeof r.parentIndex?n.get(r.parentIndex):void 0}(i,n,t);continue}r.push(i)}let i=function(e,t,n,r){let i=new Map,o=new Set;for(let e of t){if(!e.rect)continue;let t=ef(e,n,r);if(!t?.rect)continue;let a=ec(e.rect,t.rect);if(!a)continue;let s=i.get(t.index)??new Set;s.add(a),i.set(t.index,s),o.add(e.index)}return function(e,t,n,r){for(let i of e){let e=function(e){let t=function(e,t){if(!(e?.trim().toLowerCase()??"").includes("vertical scroll bar"))return null;let n=function(e){if(!e)return null;let t=/^(\d{1,3})%$/.exec(e.trim());if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?Math.max(0,Math.min(100,n)):null}(t);return null===n?null:n<=1?{above:!1,below:!0}:n>=99?{above:!0,below:!1}:{above:!0,below:!0}}(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}(i);if(!e||0===e.size)continue;let o=ef(i,t,n);if(!o)continue;let a=r.get(o.index)??new Set;for(let t of e)a.add(t);r.set(o.index,a)}}(e,n,r,i),{directionsByContainer:i,coveredNodeIndexes:o}}(e,r,n,t),o=0===n.size?e:e.filter(e=>n.has(e.index));return{nodes:o.map(e=>(function(e,t){let n=t.get(e.index);if(!n||0===n.size)return e;let r=!!(!0===e.hiddenContentAbove||n.has("above"))||void 0,i=!!(!0===e.hiddenContentBelow||n.has("below"))||void 0;return{...e,hiddenContentAbove:r,hiddenContentBelow:i}})(e,i.directionsByContainer)),hiddenCount:0===n.size?0:e.length-o.length,summaryLines:function(e,t,n){let r=new Map;for(let i of e){let e=function(e,t,n){if(!e.rect)return null;let r=eu(e,t,n);return r?ec(e.rect,r):null}(i,t,n);if(!e)continue;let o=r.get(e)??[];o.push(i),r.set(e,o)}return["above","below"].flatMap(e=>{let t=r.get(e);if(!t||0===t.length)return[];let n=(function(e){let t=new Set,n=[];for(let r of e){let e=ed(r);!e||t.has(e)||(t.add(e),n.push(e))}return n})(t).slice(0,3).map(e=>`"${e}"`),i=1===t.length?"interactive item":"interactive items",o=n.length>0?`: ${n.join(", ")}`:"";return[`[off-screen ${e}] ${t.length} ${i}${o}`]})}(r.filter(e=>!i.coveredNodeIndexes.has(e.index)&&function(e){if(!0===e.hittable)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")||!!ed(e)}(e)),e,t)}}function el(e,t,n=ei(t)){var r;if(!e.rect)return!0;let i=eu(e,t,n);return!i||(r=e.rect,en(r.x,r.x+r.width,i.x,i.x+i.width)&&en(r.y,r.y+r.height,i.y,i.y+i.height))}function eu(e,t,n=ei(t)){let r=function(e,t){let n="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0,r=new Set;for(;n&&!r.has(n.index);){if(r.add(n.index),n.rect&&ea(n))return n.rect;n="number"==typeof n.parentIndex?t.get(n.parentIndex):void 0}return null}(e,n);return r||Q(t,e.rect??{x:0,y:0,width:0,height:0})}function ec(e,t){return e.y+e.height<=t.y?"above":e.y>=t.y+t.height?"below":null}function ed(e){return e.label?.trim()||e.value?.trim()||e.identifier?.trim()||""}function ef(e,t,n){let r="number"==typeof e.parentIndex?n.get(e.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(i.add(r.index),t.has(r.index)&&ea(r))return r;r="number"==typeof r.parentIndex?n.get(r.parentIndex):void 0}return null}function ep(){try{let e=em();return JSON.parse(n.readFileSync(o.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function em(){let e=o.dirname(a(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=o.join(t,"package.json");if(n.existsSync(e))return t;t=o.dirname(t)}return e}function eh(e){return e?{message:e}:{}}function eg(e,t){return t?{...e,message:t}:e}function ew(e){return"string"==typeof e?.message&&e.message.length>0?e.message:null}let ev=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,eS=[".com",".exe",".bat",".cmd"];async function eb(e,t,n={}){let r=eN(e);return new Promise((i,o)=>{let a=u(r,t,{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"],detached:n.detached,shell:!1}),s="",l=n.binaryStdout?Buffer.alloc(0):void 0,c="",d=!1,f=eM(n.timeoutMs),p=f?setTimeout(()=>{d=!0,a.kill("SIGKILL")},f):null;n.binaryStdout||a.stdout.setEncoding("utf8"),a.stderr.setEncoding("utf8"),void 0!==n.stdin&&a.stdin.write(n.stdin),a.stdin.end(),a.stdout.on("data",e=>{n.binaryStdout?l=Buffer.concat([l??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):s+=e}),a.stderr.on("data",e=>{c+=e}),a.on("error",n=>{(p&&clearTimeout(p),"ENOENT"===n.code)?o(new I("TOOL_MISSING",`${r} not found in PATH`,{cmd:e},n)):o(new I("COMMAND_FAILED",`Failed to run ${r}`,{cmd:e,args:t},n))}),a.on("close",a=>{p&&clearTimeout(p);let u=a??1;d&&f?o(new I("COMMAND_FAILED",`${r} timed out after ${f}ms`,{cmd:e,args:t,stdout:s,stderr:c,exitCode:u,timeoutMs:f})):0===u||n.allowFailure?i({stdout:s,stderr:c,exitCode:u,stdoutBuffer:l}):o(new I("COMMAND_FAILED",`${r} exited with code ${u}`,{cmd:e,args:t,stdout:s,stderr:c,exitCode:u,processExitError:!0}))})})}async function ey(e){let t=eE(e,{allowRelativePath:!1});if(!t)return!1;if(o.isAbsolute(t))return eD(t);let n=process.env.PATH;if(!n)return!1;let r=function(){if("win32"!==process.platform)return[""];let e=process.env.PATHEXT;if(!e)return eS;let t=e.split(";").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:eS}();for(let e of n.split(o.delimiter)){let n=e.trim();if(n){for(let e of function(e,t){if("win32"!==process.platform)return[e];let n=e.toLowerCase();return t.some(e=>n.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}(t,r))if(await eD(o.join(n,e)))return!0}}return!1}function eI(e,t,n={}){let r=eN(e),i=c(r,t,{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"],encoding:n.binaryStdout?void 0:"utf8",input:n.stdin,timeout:eM(n.timeoutMs),shell:!1});if(i.error){let o=i.error.code;if("ETIMEDOUT"===o)throw new I("COMMAND_FAILED",`${r} timed out after ${eM(n.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:eM(n.timeoutMs)},i.error);if("ENOENT"===o)throw new I("TOOL_MISSING",`${r} not found in PATH`,{cmd:e},i.error);throw new I("COMMAND_FAILED",`Failed to run ${r}`,{cmd:e,args:t},i.error)}let o=n.binaryStdout?Buffer.isBuffer(i.stdout)?i.stdout:Buffer.from(i.stdout??""):void 0,a=n.binaryStdout?"":"string"==typeof i.stdout?i.stdout:(i.stdout??"").toString(),s="string"==typeof i.stderr?i.stderr:(i.stderr??"").toString(),l=i.status??1;if(0!==l&&!n.allowFailure)throw new I("COMMAND_FAILED",`${r} exited with code ${l}`,{cmd:e,args:t,stdout:a,stderr:s,exitCode:l,processExitError:!0});return{stdout:a,stderr:s,exitCode:l,stdoutBuffer:o}}function ex(e,t,n={}){let r=u(eN(e),t,{cwd:n.cwd,env:n.env,stdio:n.stdio??"ignore",detached:!0,shell:!1});return r.unref(),r.pid??0}async function e$(e,t,n={}){let r=eN(e);return new Promise((i,o)=>{let a=u(r,t,{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"],detached:n.detached,shell:!1});n.onSpawn?.(a);let s="",l="",c=n.binaryStdout?Buffer.alloc(0):void 0,d=!1,f=eM(n.timeoutMs),p=f?setTimeout(()=>{d=!0,a.kill("SIGKILL")},f):null;n.binaryStdout||a.stdout.setEncoding("utf8"),a.stderr.setEncoding("utf8"),void 0!==n.stdin&&a.stdin.write(n.stdin),a.stdin.end(),a.stdout.on("data",e=>{if(n.binaryStdout){c=Buffer.concat([c??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]);return}let t=String(e);s+=t,n.onStdoutChunk?.(t)}),a.stderr.on("data",e=>{let t=String(e);l+=t,n.onStderrChunk?.(t)}),a.on("error",n=>{(p&&clearTimeout(p),"ENOENT"===n.code)?o(new I("TOOL_MISSING",`${r} not found in PATH`,{cmd:e},n)):o(new I("COMMAND_FAILED",`Failed to run ${r}`,{cmd:e,args:t},n))}),a.on("close",a=>{p&&clearTimeout(p);let u=a??1;d&&f?o(new I("COMMAND_FAILED",`${r} timed out after ${f}ms`,{cmd:e,args:t,stdout:s,stderr:l,exitCode:u,timeoutMs:f})):0===u||n.allowFailure?i({stdout:s,stderr:l,exitCode:u,stdoutBuffer:c}):o(new I("COMMAND_FAILED",`${r} exited with code ${u}`,{cmd:e,args:t,stdout:s,stderr:l,exitCode:u,processExitError:!0}))})})}function eA(e,t,n={}){let r=eN(e),i=u(r,t,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"],detached:n.detached,shell:!1}),o="",a="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",e=>{o+=e}),i.stderr.on("data",e=>{a+=e});let s=new Promise((s,l)=>{i.on("error",n=>{"ENOENT"===n.code?l(new I("TOOL_MISSING",`${r} not found in PATH`,{cmd:e},n)):l(new I("COMMAND_FAILED",`Failed to run ${r}`,{cmd:e,args:t},n))}),i.on("close",i=>{let u=i??1;0===u||n.allowFailure?s({stdout:o,stderr:a,exitCode:u}):l(new I("COMMAND_FAILED",`${r} exited with code ${u}`,{cmd:e,args:t,stdout:o,stderr:a,exitCode:u,processExitError:!0}))})});return{child:i,wait:s}}function eN(e){let t=eE(e,{allowRelativePath:!0});if(!t)throw new I("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e});return t}function eE(e,t){let n=e.trim();return!n||n.includes("\0")?null:o.isAbsolute(n)?n:n.includes("/")||n.includes("\\")?t.allowRelativePath?n:null:ev.test(n)?n:null}async function eD(e){try{if(!(await l(e)).isFile())return!1;return await s(e,"win32"===process.platform?r.F_OK:r.X_OK),!0}catch{return!1}}function eM(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}let eL=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function eT(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function eO(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=eI("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let n=t.stdout.trim();return n.length>0?n:null}catch{return null}}function e_(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=eI("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let n=t.stdout.trim();return n.length>0?n:null}catch{return null}}function eC(e,t){let n;if(!eT(e))return!1;if(t){let n=eO(e);if(!n||n!==t)return!1}let r=e_(e);return!!r&&!!(n=r.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&eL.some(e=>e.test(n))}function ek(e,t){try{return process.kill(e,t),!0}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return!1;throw t}}async function eR(e,t){if(!eT(e))return!0;let n=Date.now();for(;Date.now()-n<t;)if(await new Promise(e=>setTimeout(e,50)),!eT(e))return!0;return!eT(e)}async function eP(e,t){!eC(e,t.expectedStartTime)||!ek(e,"SIGTERM")||await eR(e,t.termTimeoutMs)||ek(e,"SIGKILL")&&await eR(e,t.killTimeoutMs)}function eF(e){return e?.HOME?.trim()||i.homedir()}function eB(e,t={}){return"~"===e?eF(t.env):e.startsWith("~/")?o.join(eF(t.env),e.slice(2)):e}function ej(e,t={}){let n=eB(e,t);return o.isAbsolute(n)?n:o.resolve(t.cwd??process.cwd(),n)}function ez(e){let t,n=(t=(e??"").trim())?ej(t):o.join(eB("~"),".agent-device");return{baseDir:n,infoPath:o.join(n,"daemon.json"),lockPath:o.join(n,"daemon.lock"),logPath:o.join(n,"daemon.log"),sessionsDir:o.join(n,"sessions")}}function eG(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function eV(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function eU(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function eH(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let eW=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,eq=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,eJ=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function eK(){let e=process.argv[1];return e?eX(e):"unknown"}function eX(e,r=em()){try{let i=o.resolve(r),a=[o.resolve(e)],s=new Set,l=[];for(;a.length>0;){let e=a.pop();if(!e||s.has(e))continue;s.add(e);let t=n.statSync(e);if(!t.isFile())continue;let r=o.relative(i,e)||e;l.push(`${r}:${t.size}:${Math.trunc(t.mtimeMs)}`);let u=n.readFileSync(e,"utf8");for(let t of function(e){let t=new Set;return eZ(e,eW,t),eZ(e,eq,t),[...t]}(u)){let n=function(e,t){let n=o.resolve(o.dirname(e),t),r=eQ(n);if(r)return r;for(let e of eJ){let t=eQ(`${n}${e}`);if(t)return t}for(let e of eJ){let t=eQ(o.join(n,`index${e}`));if(t)return t}return null}(e,t);n&&a.push(n)}}let u=l.sort().join("|"),c=t.createHash("sha1").update(u).digest("hex");return`graph:${l.length}:${c}`}catch{return"unknown"}}function eZ(e,t,n){t.lastIndex=0;let r=null;for(;null!==(r=t.exec(e));){let e=r[1]?.trim();e?.startsWith(".")&&n.add(e)}}function eQ(e){try{return n.statSync(e).isFile()?e:null}catch{return null}}let eY=100,e0=new Set(["batch","replay"]),e1=new Set(["command","positionals","flags","runtime"]);function e2(e){let t;try{t=JSON.parse(e)}catch{throw new I("INVALID_ARGS","Batch steps must be valid JSON.")}if(!Array.isArray(t)||0===t.length)throw new I("INVALID_ARGS","Batch steps must be a non-empty JSON array.");return t}function e8(e,t){if(!Array.isArray(e)||0===e.length)throw new I("INVALID_ARGS","batch requires a non-empty batchSteps array.");if(e.length>t)throw new I("INVALID_ARGS",`batch has ${e.length} steps; max allowed is ${t}.`);let n=[];for(let t=0;t<e.length;t+=1){let r=e[t];if(!r||"object"!=typeof r)throw new I("INVALID_ARGS",`Invalid batch step at index ${t}.`);let i=Object.keys(r).filter(e=>!e1.has(e));if(i.length>0){let e=i.map(e=>`"${e}"`).join(", ");throw new I("INVALID_ARGS",`Batch step ${t+1} has unknown field(s): ${e}. Allowed fields: command, positionals, flags, runtime.`)}let o="string"==typeof r.command?r.command.trim().toLowerCase():"";if(!o)throw new I("INVALID_ARGS",`Batch step ${t+1} requires command.`);if(e0.has(o))throw new I("INVALID_ARGS",`Batch step ${t+1} cannot run ${o}.`);if(void 0!==r.positionals&&!Array.isArray(r.positionals))throw new I("INVALID_ARGS",`Batch step ${t+1} positionals must be an array.`);let a=r.positionals??[];if(a.some(e=>"string"!=typeof e))throw new I("INVALID_ARGS",`Batch step ${t+1} positionals must contain only strings.`);if(void 0!==r.flags&&("object"!=typeof r.flags||Array.isArray(r.flags)||!r.flags))throw new I("INVALID_ARGS",`Batch step ${t+1} flags must be an object.`);if(void 0!==r.runtime&&("object"!=typeof r.runtime||Array.isArray(r.runtime)||!r.runtime))throw new I("INVALID_ARGS",`Batch step ${t+1} runtime must be an object.`);n.push({command:o,positionals:a,flags:r.flags??{},runtime:r.runtime})}return n}function e3(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function e9(e,t,n){return{deviceId:t,deviceName:n,..."android"===e?{serial:t}:"ios"===e?{udid:t}:{}}}function e4(e,t={}){let n=t.includeAndroidSerial??!0;return{platform:e.platform,target:e.target,device:e.name,id:e.id,..."ios"===e.platform?{device_udid:e.ios?.udid??e.id,ios_simulator_device_set:e.ios?.simulatorSetPath??null}:{},..."android"===e.platform&&n?{serial:e.android?.serial??e.id}:{}}}function e5(e){return{name:e.name,...e4(e.device,{includeAndroidSerial:!1}),createdAt:e.createdAt}}function e6(e){return{platform:e.platform,id:e.id,name:e.name,kind:e.kind,target:e.target,..."boolean"==typeof e.booted?{booted:e.booted}:{}}}function e7(e){let t=e.created?"Created":"Reused",n=e.booted?" (booted)":"";return eg({udid:e.udid,device:e.device,runtime:e.runtime,ios_simulator_device_set:e.iosSimulatorDeviceSet??null,created:e.created,booted:e.booted},`${t}: ${e.device} ${e.udid}${n}`)}function te(e){return e.bundleId??e.package??e.app}function tt(e){return eg({app:e.app,appPath:e.appPath,platform:e.platform,...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.package?{package:e.package}:{}},`Installed: ${te(e)}`)}function tn(e){return e.appName??e.bundleId??e.packageName??e.launchTarget}function tr(e){return eg({launchTarget:e.launchTarget,...e.appName?{appName:e.appName}:{},...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{package:e.packageName}:{},...e.installablePath?{installablePath:e.installablePath}:{},...e.archivePath?{archivePath:e.archivePath}:{},...e.materializationId?{materializationId:e.materializationId}:{},...e.materializationExpiresAt?{materializationExpiresAt:e.materializationExpiresAt}:{}},`Installed: ${tn(e)}`)}function ti(e){let t=e.appName??e.appBundleId??e.session;return eg({session:e.session,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.startup?{startup:e.startup}:{},...e.runtime?{runtime:e.runtime}:{},...e.device?e4(e.device):{}},t?`Opened: ${t}`:"Opened")}function to(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...eh(e.session?`Closed: ${e.session}`:"Closed")}}function ta(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...e.warnings&&e.warnings.length>0?{warnings:e.warnings}:{}}}function ts(e,t){try{return d.sync.read(e)}catch(e){throw new I("COMMAND_FAILED",`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}export{I as AppError,eY as DEFAULT_BATCH_MAX_STEPS,P as SESSION_SURFACES,C as SETTINGS_INVALID_ARGS_MESSAGE,_ as SETTINGS_USAGE_OVERRIDE,x as asAppError,J as attachRefs,e3 as buildAppIdentifiers,e9 as buildDeviceIdentifiers,es as buildMobileSnapshotPresentation,G as buildSnapshotDisplayLines,Z as centerOfRect,eX as computeDaemonCodeSignature,ee as containsPoint,h as createRequestId,ts as decodePng,U as displayLabel,Y as distanceFromSafeViewportBand,v as emitDiagnostic,eB as expandUserHomePath,B as extractReadableText,X as findNodeByRef,em as findProjectRoot,b as flushDiagnosticsToSessionFile,H as formatRole,V as formatSnapshotLine,w as getDiagnosticsMeta,R as getUnsupportedMacOsSettingMessage,eC as isAgentDeviceDaemonProcess,k as isMacOsSettingSupported,el as isNodeVisibleInEffectiveViewport,eT as isProcessAlive,eo as isScrollableType,$ as normalizeError,K as normalizeRef,er as normalizeSnapshotTree,eH as normalizeTenantId,e2 as parseBatchStepsJson,F as parseSessionSurface,et as pickLargestRect,ew as readCommandMessage,e_ as readProcessCommand,eO as readProcessStartTime,ep as readVersion,eK as resolveDaemonCodeSignature,ez as resolveDaemonPaths,eG as resolveDaemonServerMode,eV as resolveDaemonTransportPreference,te as resolveDeployResultTarget,eu as resolveEffectiveViewportRect,tn as resolveInstallFromSourceResultTarget,eU as resolveSessionIsolationMode,ej as resolveUserPath,Q as resolveViewportRect,eb as runCmd,eA as runCmdBackground,ex as runCmdDetached,e$ as runCmdStreaming,eI as runCmdSync,to as serializeCloseResult,tt as serializeDeployResult,e6 as serializeDevice,e7 as serializeEnsureSimulatorResult,tr as serializeInstallFromSourceResult,ti as serializeOpenResult,e5 as serializeSessionListEntry,ta as serializeSnapshotResult,eP as stopProcessForTakeover,eh as successText,e8 as validateAndNormalizeBatchSteps,ey as whichCmd,S as withDiagnosticTimer,g as withDiagnosticsScope,eg as withSuccessText};
|