agent-device 0.11.9 → 0.11.11
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 +0 -9
- package/dist/src/113.js +3 -0
- package/dist/src/320.js +1 -0
- package/dist/src/818.js +3 -0
- package/dist/src/957.js +2 -0
- package/dist/src/974.js +2 -0
- package/dist/src/995.js +1 -3
- package/dist/src/bin.js +64 -65
- package/dist/src/contracts.d.ts +79 -0
- package/dist/src/contracts.js +0 -0
- package/dist/src/daemon.js +43 -43
- package/dist/src/index.d.ts +3 -0
- package/dist/src/index.js +2 -3
- package/dist/src/metro-companion.js +1 -0
- package/dist/src/metro.d.ts +95 -0
- package/dist/src/metro.js +1 -0
- package/dist/src/remote-config.d.ts +49 -0
- package/dist/src/remote-config.js +1 -0
- package/dist/src/update-check-entry.js +1 -0
- package/package.json +13 -1
- package/skills/agent-device/SKILL.md +1 -0
- package/skills/agent-device/references/remote-tenancy.md +11 -30
package/README.md
CHANGED
|
@@ -59,15 +59,6 @@ In practice, most work follows the same pattern:
|
|
|
59
59
|
|
|
60
60
|
In non-JSON mode, core mutating commands print a short success acknowledgment so agents and humans can distinguish successful actions from dropped or silent no-ops.
|
|
61
61
|
|
|
62
|
-
## Performance Metrics
|
|
63
|
-
|
|
64
|
-
`agent-device perf --json` (alias: `metrics --json`) returns session-scoped metrics data.
|
|
65
|
-
|
|
66
|
-
- Startup timing is available on iOS and Android from `open` command round-trip sampling.
|
|
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 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
|
-
|
|
71
62
|
## Where To Go Next
|
|
72
63
|
|
|
73
64
|
For people:
|
package/dist/src/113.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import e from"node:fs";import t from"node:path";import{fileURLToPath as r}from"node:url";import{runCmdDetached as n}from"./818.js";let i="agent-device",o="--agent-device-run-update-check";function a(a){var c,p,u,m,h,f,g;let k,v,y;if(!(!(!(c=a).command||"help"===c.command||"test"===c.command||c.flags.help||c.flags.version||c.flags.json||process.env.CI?.trim()||"test"===process.env.NODE_ENV||process.env.AGENT_DEVICE_NO_UPDATE_NOTIFIER?.trim())&&process.stderr.isTTY))return;let S=Date.now(),V=t.join(a.stateDir,"update-check.json"),w=s(V);p=w,u=a.currentVersion,!p.latestVersion||0>=l(p.latestVersion,u)||!0===p.prompted||(process.stderr.write(`Update available: ${i} ${a.currentVersion} -> ${w.latestVersion}. Run \`npm install -g ${i}@latest\` to upgrade the CLI and bundled skills.
|
|
2
|
+
`),d(V,{...w,prompted:!0})),m=w,h=S,(void 0===(k=function(e){if(!e)return;let t=Date.parse(e);return Number.isNaN(t)?void 0:t}(m.checkedAt))||h-k>=12096e5)&&(f=V,g=a.currentVersion,y=(v=function(){let n=r(import.meta.url),i=t.extname(n)||".js",o=t.join(t.dirname(n),`update-check-entry${i}`);if(!e.existsSync(o))throw Error(`Update check entrypoint not found at ${o}. Rebuild the package to include the update-check worker entry.`);return o}()).endsWith(".ts")?["--experimental-strip-types"]:[],n(process.execPath,[...y,v,o,f,g]))}async function c(e){let t=Date.now(),r=s(e.cachePath);try{let n=await p()??void 0;if(!n||0>=l(n,e.currentVersion))return void d(e.cachePath,{checkedAt:new Date(t).toISOString()});d(e.cachePath,{checkedAt:new Date(t).toISOString(),latestVersion:n,prompted:r.latestVersion===n&&!0===r.prompted})}catch{d(e.cachePath,{...r,checkedAt:new Date(t).toISOString()})}}function s(t){try{let r=JSON.parse(e.readFileSync(t,"utf8"));return{checkedAt:"string"==typeof r.checkedAt?r.checkedAt:void 0,latestVersion:"string"==typeof r.latestVersion?r.latestVersion:void 0,prompted:!0===r.prompted}}catch{return{}}}function d(r,n){try{e.mkdirSync(t.dirname(r),{recursive:!0}),e.writeFileSync(r,`${JSON.stringify(n,null,2)}
|
|
3
|
+
`,"utf8")}catch{}}async function p(){let e=await fetch(`https://registry.npmjs.org/${i}/latest`,{signal:AbortSignal.timeout(3500),headers:{accept:"application/json"}});if(!e.ok)return;let t=await e.json();return"string"==typeof t.version&&t.version.trim().length>0?t.version.trim():void 0}function l(e,t){return e.localeCompare(t,void 0,{numeric:!0})}function u(e){if(e[0]!==o)return null;let t=e[1]?.trim(),r=e[2]?.trim();return t&&r?{cachePath:t,currentVersion:r}:null}export{a as maybeRunUpgradeNotifier,u as readUpdateCheckWorkerArgs,c as runUpdateCheckWorker};
|
package/dist/src/320.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let E="--agent-device-run-metro-companion",_="AGENT_DEVICE_METRO_COMPANION_SERVER_BASE_URL",N="AGENT_DEVICE_METRO_COMPANION_BEARER_TOKEN",A="AGENT_DEVICE_METRO_COMPANION_LOCAL_BASE_URL",R="AGENT_DEVICE_METRO_COMPANION_LAUNCH_URL";function O(E){let _=E.length;for(;_>0&&47===E.charCodeAt(_-1);)_-=1;return _===E.length?E:E.slice(0,_)}export{N as ENV_BEARER_TOKEN,R as ENV_LAUNCH_URL,A as ENV_LOCAL_BASE_URL,_ as ENV_SERVER_BASE_URL,E as METRO_COMPANION_RUN_ARG,O as normalizeBaseUrl};
|
package/dist/src/818.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{AsyncLocalStorage as e}from"node:async_hooks";import t from"node:crypto";import r,{constants as n}from"node:fs";import o from"node:os";import i from"node:path";import{access as s,stat as a}from"node:fs/promises";import{spawn as d,spawnSync as u}from"node:child_process";let l=new e,c=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key)/i,f=/(bearer\s+[a-z0-9._-]+|(?:api[_-]?key|token|secret|password)\s*[=:]\s*\S+)/i;function p(){return t.randomBytes(8).toString("hex")}async function m(e,r){let n={...e,diagnosticId:`${Date.now().toString(36)}-${t.randomBytes(4).toString("hex")}`,events:[]};return await l.run(n,r)}function g(){let e=l.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug}:{}}function h(e){let t=l.getStore();if(!t)return;let n={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?S(e.data):void 0};if(t.events.push(n),!t.debug)return;let o=`[agent-device][diag] ${JSON.stringify(n)}
|
|
2
|
+
`;try{t.logPath&&r.appendFile(t.logPath,o,()=>{}),t.traceLogPath&&r.appendFile(t.traceLogPath,o,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(o)}catch{}}async function w(e,t,r){let n=Date.now();try{let o=await t();return h({level:"info",phase:e,durationMs:Date.now()-n,data:r}),o}catch(t){throw h({level:"error",phase:e,durationMs:Date.now()-n,data:{...r??{},error:t instanceof Error?t.message:String(t)}}),t}}function E(e={}){let t=l.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,"_"),n=new Date().toISOString().slice(0,10),s=i.join(o.homedir(),".agent-device","logs",e,n);r.mkdirSync(s,{recursive:!0});let a=new Date().toISOString().replace(/[:.]/g,"-"),d=i.join(s,`${a}-${t.diagnosticId}.ndjson`),u=t.events.map(e=>JSON.stringify(S(e)));return r.writeFileSync(d,`${u.join("\n")}
|
|
3
|
+
`),t.events=[],d}catch{return null}}function S(e){return function e(t,r,n){if(null==t)return t;if("string"==typeof t){var o=t,i=n;let e=o.trim();if(!e)return o;if(i&&c.test(i)||f.test(e))return"[REDACTED]";let r=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 r||(e.length>400?`${e.slice(0,200)}...<truncated>`:e)}if("object"!=typeof t)return t;if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map(t=>e(t,r));let s={};for(let[n,o]of Object.entries(t)){if(c.test(n)){s[n]="[REDACTED]";continue}s[n]=e(o,r,n)}return s}(e,new WeakSet)}class D extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function A(e){return e instanceof D?e:e instanceof Error?new D("UNKNOWN",e.message,void 0,e):new D("UNKNOWN","Unknown error",{err:e})}function I(e,t={}){let r=A(e),n=r.details?S(r.details):void 0,o=n&&"string"==typeof n.hint?n.hint:void 0,i=(n&&"string"==typeof n.diagnosticId?n.diagnosticId:void 0)??t.diagnosticId,s=(n&&"string"==typeof n.logPath?n.logPath:void 0)??t.logPath,a=o??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."}}(r.code),d=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}(n),u=function(e,t,r){if("COMMAND_FAILED"!==e||r?.processExitError!==!0)return t;let n=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 r of e.split("\n")){let e=r.trim();if(e&&!t.some(t=>t.test(e)))return e.length>200?`${e.slice(0,200)}...`:e}return null}("string"==typeof r?.stderr?r.stderr:"");return n||t}(r.code,r.message,n);return{code:r.code,message:u,hint:a,diagnosticId:i,logPath:s,details:d}}let v=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,O=[".com",".exe",".bat",".cmd"];async function y(e,t,r={}){let n=L(e);return new Promise((o,i)=>{let s=d(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,shell:!1}),a="",u=r.binaryStdout?Buffer.alloc(0):void 0,l="",c=!1,f=b(r.timeoutMs),p=f?setTimeout(()=>{c=!0,s.kill("SIGKILL")},f):null;r.binaryStdout||s.stdout.setEncoding("utf8"),s.stderr.setEncoding("utf8"),void 0!==r.stdin&&s.stdin.write(r.stdin),s.stdin.end(),s.stdout.on("data",e=>{r.binaryStdout?u=Buffer.concat([u??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):a+=e}),s.stderr.on("data",e=>{l+=e}),s.on("error",r=>{(p&&clearTimeout(p),"ENOENT"===r.code)?i(new D("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):i(new D("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),s.on("close",s=>{p&&clearTimeout(p);let d=s??1;c&&f?i(new D("COMMAND_FAILED",`${n} timed out after ${f}ms`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:d,timeoutMs:f})):0===d||r.allowFailure?o({stdout:a,stderr:l,exitCode:d,stdoutBuffer:u}):i(new D("COMMAND_FAILED",`${n} exited with code ${d}`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:d,processExitError:!0}))})})}async function N(e){let t=C(e,{allowRelativePath:!1});if(!t)return!1;if(i.isAbsolute(t))return F(t);let r=process.env.PATH;if(!r)return!1;let n=function(){if("win32"!==process.platform)return[""];let e=process.env.PATHEXT;if(!e)return O;let t=e.split(";").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:O}();for(let e of r.split(i.delimiter)){let r=e.trim();if(r){for(let e of function(e,t){if("win32"!==process.platform)return[e];let r=e.toLowerCase();return t.some(e=>r.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}(t,n))if(await F(i.join(r,e)))return!0}}return!1}function M(e,t,r={}){let n=L(e),o=u(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:b(r.timeoutMs),shell:!1});if(o.error){let i=o.error.code;if("ETIMEDOUT"===i)throw new D("COMMAND_FAILED",`${n} timed out after ${b(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:b(r.timeoutMs)},o.error);if("ENOENT"===i)throw new D("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},o.error);throw new D("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},o.error)}let i=r.binaryStdout?Buffer.isBuffer(o.stdout)?o.stdout:Buffer.from(o.stdout??""):void 0,s=r.binaryStdout?"":"string"==typeof o.stdout?o.stdout:(o.stdout??"").toString(),a="string"==typeof o.stderr?o.stderr:(o.stderr??"").toString(),d=o.status??1;if(0!==d&&!r.allowFailure)throw new D("COMMAND_FAILED",`${n} exited with code ${d}`,{cmd:e,args:t,stdout:s,stderr:a,exitCode:d,processExitError:!0});return{stdout:s,stderr:a,exitCode:d,stdoutBuffer:i}}function T(e,t,r={}){let n=d(L(e),t,{cwd:r.cwd,env:r.env,stdio:r.stdio??"ignore",detached:!0,shell:!1});return n.unref(),n.pid??0}async function _(e,t,r={}){let n=L(e);return new Promise((o,i)=>{let s=d(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,shell:!1});r.onSpawn?.(s);let a="",u="",l=r.binaryStdout?Buffer.alloc(0):void 0,c=!1,f=b(r.timeoutMs),p=f?setTimeout(()=>{c=!0,s.kill("SIGKILL")},f):null;r.binaryStdout||s.stdout.setEncoding("utf8"),s.stderr.setEncoding("utf8"),void 0!==r.stdin&&s.stdin.write(r.stdin),s.stdin.end(),s.stdout.on("data",e=>{if(r.binaryStdout){l=Buffer.concat([l??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]);return}let t=String(e);a+=t,r.onStdoutChunk?.(t)}),s.stderr.on("data",e=>{let t=String(e);u+=t,r.onStderrChunk?.(t)}),s.on("error",r=>{(p&&clearTimeout(p),"ENOENT"===r.code)?i(new D("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):i(new D("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),s.on("close",s=>{p&&clearTimeout(p);let d=s??1;c&&f?i(new D("COMMAND_FAILED",`${n} timed out after ${f}ms`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:d,timeoutMs:f})):0===d||r.allowFailure?o({stdout:a,stderr:u,exitCode:d,stdoutBuffer:l}):i(new D("COMMAND_FAILED",`${n} exited with code ${d}`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:d,processExitError:!0}))})})}function $(e,t,r={}){let n=L(e),o=d(n,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached,shell:!1}),i="",s="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",e=>{i+=e}),o.stderr.on("data",e=>{s+=e});let a=new Promise((a,d)=>{o.on("error",r=>{"ENOENT"===r.code?d(new D("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):d(new D("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),o.on("close",o=>{let u=o??1;0===u||r.allowFailure?a({stdout:i,stderr:s,exitCode:u}):d(new D("COMMAND_FAILED",`${n} exited with code ${u}`,{cmd:e,args:t,stdout:i,stderr:s,exitCode:u,processExitError:!0}))})});return{child:o,wait:a}}function L(e){let t=C(e,{allowRelativePath:!0});if(!t)throw new D("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e});return t}function C(e,t){let r=e.trim();return!r||r.includes("\0")?null:i.isAbsolute(r)?r:r.includes("/")||r.includes("\\")?t.allowRelativePath?r:null:v.test(r)?r:null}async function F(e){try{if(!(await a(e)).isFile())return!1;return await s(e,"win32"===process.platform?n.F_OK:n.X_OK),!0}catch{return!1}}function b(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}export{D as AppError,A as asAppError,p as createRequestId,h as emitDiagnostic,E as flushDiagnosticsToSessionFile,g as getDiagnosticsMeta,I as normalizeError,y as runCmd,$ as runCmdBackground,T as runCmdDetached,_ as runCmdStreaming,M as runCmdSync,N as whichCmd,w as withDiagnosticTimer,m as withDiagnosticsScope};
|
package/dist/src/957.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{AsyncLocalStorage as e}from"node:async_hooks";import t from"node:crypto";import r from"node:fs";import o from"node:os";import n from"node:path";let s=new e,a=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key)/i,i=/(bearer\s+[a-z0-9._-]+|(?:api[_-]?key|token|secret|password)\s*[=:]\s*\S+)/i;function c(){return t.randomBytes(8).toString("hex")}function u(e){let t=s.getStore();if(!t)return;let o={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?function e(t,r,o){if(null==t)return t;if("string"==typeof t){var n=t,s=o;let e=n.trim();if(!e)return n;if(s&&a.test(s)||i.test(e))return"[REDACTED]";let r=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 r||(e.length>400?`${e.slice(0,200)}...<truncated>`:e)}if("object"!=typeof t)return t;if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map(t=>e(t,r));let c={};for(let[o,n]of Object.entries(t)){if(a.test(o)){c[o]="[REDACTED]";continue}c[o]=e(n,r,o)}return c}(e.data,new WeakSet):void 0};if(t.events.push(o),!t.debug)return;let n=`[agent-device][diag] ${JSON.stringify(o)}
|
|
2
|
+
`;try{t.logPath&&r.appendFile(t.logPath,n,()=>{}),t.traceLogPath&&r.appendFile(t.traceLogPath,n,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(n)}catch{}}async function d(e,t,r){let o=Date.now();try{let n=await t();return u({level:"info",phase:e,durationMs:Date.now()-o,data:r}),n}catch(t){throw u({level:"error",phase:e,durationMs:Date.now()-o,data:{...r??{},error:t instanceof Error?t.message:String(t)}}),t}}class l extends Error{code;details;cause;constructor(e,t,r,o){super(t),this.code=e,this.details=r,this.cause=o}}function f(e){return e?.HOME?.trim()||o.homedir()}function p(e,t={}){return"~"===e?f(t.env):e.startsWith("~/")?n.join(f(t.env),e.slice(2)):e}function h(e,t={}){let r=p(e,t);return n.isAbsolute(r)?r:n.resolve(t.cwd??process.cwd(),r)}export{l as AppError,c as createRequestId,u as emitDiagnostic,p as expandUserHomePath,h as resolveUserPath,d as withDiagnosticTimer};
|
package/dist/src/974.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import e from"node:fs";import"node:fs/promises";import t from"node:path";import{spawn as r,spawnSync as n}from"node:child_process";import{createHash as o}from"node:crypto";import{fileURLToPath as i}from"node:url";import{resolveUserPath as a,AppError as s}from"./957.js";let l=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/;function u(e,t,r={}){let o=m(e),i=n(o,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:d(r.timeoutMs),shell:!1});if(i.error){let n=i.error.code;if("ETIMEDOUT"===n)throw new s("COMMAND_FAILED",`${o} timed out after ${d(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:d(r.timeoutMs)},i.error);if("ENOENT"===n)throw new s("TOOL_MISSING",`${o} not found in PATH`,{cmd:e},i.error);throw new s("COMMAND_FAILED",`Failed to run ${o}`,{cmd:e,args:t},i.error)}let a=r.binaryStdout?Buffer.isBuffer(i.stdout)?i.stdout:Buffer.from(i.stdout??""):void 0,l=r.binaryStdout?"":"string"==typeof i.stdout?i.stdout:(i.stdout??"").toString(),c="string"==typeof i.stderr?i.stderr:(i.stderr??"").toString(),p=i.status??1;if(0!==p&&!r.allowFailure)throw new s("COMMAND_FAILED",`${o} exited with code ${p}`,{cmd:e,args:t,stdout:l,stderr:c,exitCode:p,processExitError:!0});return{stdout:l,stderr:c,exitCode:p,stdoutBuffer:a}}function c(e,t,n={}){let o=r(m(e),t,{cwd:n.cwd,env:n.env,stdio:n.stdio??"ignore",detached:!0,shell:!1});return o.unref(),o.pid??0}function m(e){var r;let n,o=(r={allowRelativePath:!0},!(n=e.trim())||n.includes("\0")?null:t.isAbsolute(n)?n:n.includes("/")||n.includes("\\")?r.allowRelativePath?n:null:l.test(n)?n:null);if(!o)throw new s("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e});return o}function d(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}let p=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function f(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function h(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=u("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function g(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=u("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function y(e,t){let r;if(!f(e))return!1;if(t){let r=h(e);if(!r||r!==t)return!1}let n=g(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&p.some(e=>e.test(r))}function b(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 w(e,t){if(!f(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!f(e))return!0;return!f(e)}async function E(e,t){!y(e,t.expectedStartTime)||!b(e,"SIGTERM")||await w(e,t.termTimeoutMs)||b(e,"SIGKILL")&&await w(e,t.killTimeoutMs)}let S="--agent-device-run-metro-companion",_="AGENT_DEVICE_METRO_COMPANION_LAUNCH_URL";function M(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return t===e.length?e:e.slice(0,t)}function P(e){return o("sha256").update(e).digest("hex")}function U(e){return e?.trim()?e.trim():void 0}function v(e,r){let n=t.join(e,".agent-device");if(!r)return{statePath:t.join(n,"metro-companion.json"),logPath:t.join(n,"metro-companion.log")};let o=P(r).slice(0,12),i=t.join(n,"metro-companion");return{statePath:t.join(i,`metro-companion-${o}.json`),logPath:t.join(i,`metro-companion-${o}.log`)}}function A(t){try{let r=JSON.parse(e.readFileSync(t,"utf8"));if(!Number.isInteger(r.pid)||0>=Number(r.pid)||"string"!=typeof r.serverBaseUrl||"string"!=typeof r.localBaseUrl||"string"!=typeof r.tokenHash||0===r.tokenHash.length)return null;let n=Array.isArray(r.consumers)?r.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(r.pid),startTime:"string"==typeof r.startTime?r.startTime:void 0,command:"string"==typeof r.command?r.command:void 0,serverBaseUrl:r.serverBaseUrl,localBaseUrl:r.localBaseUrl,launchUrl:U("string"==typeof r.launchUrl?r.launchUrl:void 0),tokenHash:r.tokenHash,consumers:n}}catch{return null}}function N(r,n){e.mkdirSync(t.dirname(r),{recursive:!0}),e.writeFileSync(r,`${JSON.stringify(n,null,2)}
|
|
2
|
+
`,"utf8")}function T(t){try{e.unlinkSync(t)}catch{}}function k(e){return e.includes(S)}function I(e){return U(e.consumerKey)??U(e.profileKey)??null}function R(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function $(e){if(!f(e.pid))return;let t=g(e.pid);if(t&&k(t)){try{process.kill(e.pid,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await w(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await w(e.pid,1e3)}}}async function x(r){let n=I(r),o=v(r.projectRoot,r.profileKey),a=A(o.statePath);if(a&&function(e,t){if(!f(e.pid))return!1;if(e.startTime){let t=h(e.pid);if(!t||t!==e.startTime)return!1}let r=g(e.pid);return!!r&&!!k(r)&&e.serverBaseUrl===M(t.serverBaseUrl)&&e.localBaseUrl===M(t.localBaseUrl)&&e.launchUrl===U(t.launchUrl)&&e.tokenHash===P(t.bearerToken)}(a,r)){let e=R(a,n);return e!==a&&N(o.statePath,e),{pid:a.pid,spawned:!1,statePath:o.statePath,logPath:o.logPath}}a&&(await $(a),T(o.statePath));let s=function(r,n){let o=function(){let r=i(import.meta.url),n=t.extname(r)||".js",o=t.join(t.dirname(r),`metro-companion${n}`);if(!e.existsSync(o))throw Error(`Metro companion entrypoint not found at ${o}. Rebuild the package to include the companion worker entry.`);return o}(),a=o.endsWith(".ts")?["--experimental-strip-types"]:[];e.mkdirSync(t.dirname(n),{recursive:!0});let s=e.openSync(n,"a"),l=0;try{let e;l=c(process.execPath,[...a,o,S],{env:(e={...r.env??process.env,AGENT_DEVICE_METRO_COMPANION_SERVER_BASE_URL:M(r.serverBaseUrl),AGENT_DEVICE_METRO_COMPANION_BEARER_TOKEN:r.bearerToken,AGENT_DEVICE_METRO_COMPANION_LOCAL_BASE_URL:M(r.localBaseUrl)},r.launchUrl?.trim()?e[_]=r.launchUrl.trim():delete e[_],e),stdio:["ignore",s,s]})}finally{e.closeSync(s)}if(!Number.isInteger(l)||l<=0)throw Error("Failed to start Metro companion process.");return{pid:l,startTime:h(l)??void 0,command:g(l)??void 0,serverBaseUrl:M(r.serverBaseUrl),localBaseUrl:M(r.localBaseUrl),launchUrl:U(r.launchUrl),tokenHash:P(r.bearerToken),consumers:[]}}(r,o.logPath);return N(o.statePath,R(s,n)),{pid:s.pid,spawned:!0,statePath:o.statePath,logPath:o.logPath}}async function D(e){let t=I(e),r=v(e.projectRoot,e.profileKey),n=A(r.statePath);if(!n)return T(r.statePath),{stopped:!1,statePath:r.statePath};let o=t?{...n,consumers:n.consumers.filter(e=>e!==t)}:{...n,consumers:[]};return o.consumers.length>0?(N(r.statePath,o),{stopped:!1,statePath:r.statePath}):(await $(n),T(r.statePath),{stopped:!0,statePath:r.statePath})}function O(e){return"string"==typeof e&&e.trim()?M(e.trim()):""}function C(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function B(e,t,r){return a(e,{env:t,cwd:r})}function j(t){try{return e.accessSync(t,e.constants.F_OK),!0}catch{return!1}}function L(e,t,r){if(null==e||""===e)return t;let n=Number.parseInt(String(e),10);return Number.isInteger(n)?Math.max(n,r):t}function F(e,t){let r;return{platform:t,bundleUrl:((r=new URL(`${M(e)}/index.bundle`)).searchParams.set("platform",t),r.searchParams.set("dev","true"),r.searchParams.set("minify","false"),r.toString())}}function G(e,t){return{platform:t,metroHost:C(e?.metro_host),metroPort:e?.metro_port,bundleUrl:C(e?.metro_bundle_url),launchUrl:C(e?.launch_url)}}async function H(e){await new Promise(t=>setTimeout(t,e))}async function K(e,t,r={}){try{let n=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:n.ok,status:n.status,body:await n.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function V(e,t){try{let r=await K(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}function J(e,t){let r=Error(e);return r.retryable=t,r}async function q(e){var t,r,n,o;let i;try{i=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,r=e.bearerToken,{Authorization:`Bearer ${r}`,"Content-Type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw J(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw J(t instanceof Error?t.message:String(t),!0)}let a=await i.text(),s=a?JSON.parse(a):{};if(!i.ok)throw J(`/api/metro/bridge failed (${i.status}): ${JSON.stringify(s)}`,(n=i.status,!!(n>=500||408===n||425===n||429===n||JSON.stringify(s).includes("Metro companion is not connected"))));return{enabled:(o=s.data??s).enabled,baseUrl:o.base_url,statusUrl:o.status_url,bundleUrl:o.bundle_url,iosRuntime:G(o.ios_runtime,"ios"),androidRuntime:G(o.android_runtime,"android"),upstream:{bundleUrl:o.upstream.bundle_url,host:o.upstream.host,port:o.upstream.port,statusUrl:o.upstream.status_url},probe:{reachable:o.probe.reachable,statusCode:o.probe.status_code,latencyMs:o.probe.latency_ms,detail:o.probe.detail}}}function z(e,t,r,n,o){let i=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&i.push(`bridgeError=${t}`),r?.probe.reachable===!1&&i.push(`bridgeProbe=${r.probe.detail||`unreachable (status ${r.probe.statusCode||0})`}`),n&&n!==t&&i.push(`initialBridgeError=${n}`),o&&i.push(`metroCompanionLog=${o}`),i.join(" ")}async function Z(e,t,r){let n=Date.now()+t;for(;Date.now()<n;){let t=Math.min(r,Math.max(n-Date.now(),1));if(await V(e,t))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await H(o)}return!1}async function W(e){let t=Date.now()+e.startupTimeoutMs,r=null,n=null;for(;Date.now()<t;){try{let t=await q({baseUrl:e.baseUrl,bearerToken:e.bearerToken,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==t.probe.reachable)return t;r=t,n=null}catch(e){if(n=e instanceof Error?e.message:String(e),!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable))break}let o=Math.min(1e3,Math.max(t-Date.now(),0));o>0&&await H(o)}throw Error(z(e.baseUrl,n,r,e.initialBridgeError,e.companionLogPath))}async function X(r={}){let n=r.env??process.env,o=process.cwd(),i=B(r.projectRoot??o,n,o),a=function(r,n){if("auto"!==n)return n;let o=function(r){let n=t.join(r,"package.json");if(!j(n))throw new s("INVALID_ARGS",`package.json not found at ${n}`);return JSON.parse(e.readFileSync(n,"utf8"))}(r);return"string"==typeof({...o.dependencies??{},...o.devDependencies??{}}).expo?"expo":"react-native"}(i,r.kind??"auto"),l=function(e){if(null==e||""===e)return 8081;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<1||t>65535)throw new s("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}(r.metroPort??8081),m=C(r.listenHost)??"0.0.0.0",d=C(r.statusHost)??"127.0.0.1",p=O(r.publicBaseUrl),f=L(r.startupTimeoutMs,18e4,3e4),h=L(r.probeTimeoutMs,1e4,1e3),g=r.reuseExisting??!0,y=r.installDependenciesIfNeeded??!0,b=r.runtimeFilePath?B(r.runtimeFilePath,n,o):null,w=B(r.logPath??t.join(i,".agent-device","metro.log"),n,o);if(!p)throw new s("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:E,proxyBaseUrl:S,proxyBearerToken:_}=function(e,t){if(e&&!t)throw new s("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.");if(!e&&t)throw new s("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(O(r.proxyBaseUrl),C(r.proxyBearerToken)??""),M=y?function(r,n){if(function(t){try{return e.statSync(t).isDirectory()}catch{return!1}}(t.join(r,"node_modules")))return{installed:!1};let o=j(t.join(r,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:j(t.join(r,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return u(o.command,o.installArgs,{cwd:r,env:n}),{installed:!0,packageManager:o.command}}(i,n):{installed:!1},P=`http://${d}:${l}/status`,U=!1,v=!1,A=0;if(g&&await V(P,h))v=!0;else if(U=!0,A=function(r,n,o,i,a,s){let l="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(o)]}:{command:"npx",installArgs:["react-native","start","--host",i,"--port",String(o)]};e.mkdirSync(t.dirname(a),{recursive:!0});let u=e.openSync(a,"a"),m=0;try{m=c(l.command,l.installArgs,{cwd:r,env:s,stdio:["ignore",u,u]})}finally{e.closeSync(u)}if(!Number.isInteger(m)||m<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:m}}(i,a,l,m,w,n).pid,!await Z(P,f,h))throw Error(`Metro did not become ready at ${P} within ${f}ms. Check ${w}.`);let N=F(p,"ios"),T=F(p,"android"),k=null,I=null;if(E)try{k=await q({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:N.bundleUrl},timeoutMs:h})}catch(e){I=e instanceof Error?e.message:String(e)}if(E&&(!k||!1===k.probe.reachable)){let e;try{e=(await x({projectRoot:i,serverBaseUrl:S,bearerToken:_,localBaseUrl:`http://${d}:${l}`,launchUrl:C(r.launchUrl),profileKey:C(r.companionProfileKey),consumerKey:C(r.companionConsumerKey),env:n})).logPath}catch(e){throw Error(z(S,e instanceof Error?e.message:String(e),k,I))}try{k=await W({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:N.bundleUrl},probeTimeoutMs:h,startupTimeoutMs:f,initialBridgeError:I,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}let R=k?.iosRuntime??N,$=k?.androidRuntime??T,D={projectRoot:i,kind:a,dependenciesInstalled:M.installed,packageManager:M.packageManager??null,started:U,reused:v,pid:A,logPath:w,statusUrl:P,runtimeFilePath:b,iosRuntime:R,androidRuntime:$,bridge:k};return b&&(e.mkdirSync(t.dirname(b),{recursive:!0}),e.writeFileSync(b,JSON.stringify(D,null,2))),D}export{F as buildMetroRuntimeHints,x as ensureMetroCompanion,y as isAgentDeviceDaemonProcess,X as prepareMetroRuntime,c as runCmdDetached,u as runCmdSync,D as stopMetroCompanion,E as stopProcessForTakeover};
|
package/dist/src/995.js
CHANGED
|
@@ -1,3 +1 @@
|
|
|
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};
|
|
1
|
+
import e from"node:fs";import t from"node:path";import{fileURLToPath as n}from"node:url";import r from"node:os";import i from"node:crypto";import{PNG as a}from"pngjs";import{runCmdSync as o,AppError as l}from"./818.js";let s="<wifi|airplane|location> <on|off>",u="appearance <light|dark|toggle>",c="faceid <match|nonmatch|enroll|unenroll>",d="touchid <match|nonmatch|enroll|unenroll>",f="fingerprint <match|nonmatch>",p="permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",m="permission <grant|reset> <accessibility|screen-recording|input-monitoring>",h=`macOS supports only settings ${u} and settings ${m}. wifi|airplane|location remain unsupported on macOS.`,g=`settings ${s} | settings ${u} | settings ${c} | settings ${d} | settings ${f} | settings ${p} | settings ${m}`,w=`settings requires ${s}, ${u}, ${c}, ${d}, ${f}, ${p}, or ${m}`;function b(e){let t=e.trim().toLowerCase();return"appearance"===t||"permission"===t}function x(e){return`Unsupported macOS setting: ${e}. ${h}`}let v=["app","frontmost-app","desktop","menubar"];function y(e){let t=e?.trim().toLowerCase();if("app"===t||"frontmost-app"===t||"desktop"===t||"menubar"===t)return t;throw new l("INVALID_ARGS",`Invalid surface: ${e}. Use ${v.join("|")}.`)}function S(e){var t;let n,r=I(e.label),i=I(e.value),a=I(e.identifier),o=(t=a)&&!/^[\w.]+:id\/[\w.-]+$/i.test(t)&&!/^_?NS:\d+$/i.test(t)?a:"";return(n=$(e.type??"")).includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("edittext")||n.includes("textview")||n.includes("textarea")?i||r||o:r||i||o}function I(e){return"string"==typeof e?e.trim():""}function $(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 A(e,t={}){let n=[],r=[];for(let i of e){let e=i.depth??0,a=i.label?.trim()||i.value?.trim()||i.identifier?.trim()||"",o=C(i.type??"Element");if("group"===o&&!a)continue;for(;n.length>0&&e<=n[n.length-1];)n.pop();let l=n.length;n.push(e),r.push({node:i,depth:l,type:o,text:N(i,l,!1,o,t)})}return r}function N(e,t,n,r,i={}){var a,o,l,s,u;let c,d,f=r??C(e.type??"Element"),p=(c=S(e),{text:c,isLargeSurface:d=function(e,t){if("text-view"===t||"text-field"===t||"search"===t)return!0;let n=$(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&&!!(a=c)&&(a.length>80||/[\r\n]/.test(a))}),m=(o=e,l=f,s=i,u=p,s.summarizeTextSurfaces&&u.shouldSummarize&&function(e,t,n){let r=I(e.label);if(r&&r!==n)return r;let i=I(e.identifier);if(i&&!k(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""}}(o,l,u.text)||L(o,l)),h=" ".repeat(t),g=e.ref?`@${e.ref}`:"",w=(function(e,t,n,r){let i,a=[];if(!1===e.enabled&&a.push("disabled"),!n.summarizeTextSurfaces||(!0===e.selected&&a.push("selected"),R(t)&&a.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)&&a.push("scrollable"),!r.shouldSummarize))return a;return a.push(`preview:"${((i=r.text.replace(/\s+/g," ").trim()).length<=48?i:`${i.slice(0,45)}...`).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`),a.push("truncated"),[...new Set(a)]})(e,f,i,p).map(e=>` [${e}]`).join(""),b=m?` "${m}"`:"";return n?`${h}${g} [${f}]${w}`.trimEnd():`${h}${g} [${f}]${b}${w}`.trimEnd()}function L(e,t){var n,r;let i,a=e.label?.trim();if(a&&(n=t,r=a,("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 o=e.value?.trim();if(R(t)){if(o)return o;if(a)return a}else if(a)return a;if(o)return o;let l=e.identifier?.trim();return!l||k(l)&&("group"===t||"image"===t||"list"===t||"collection"===t)?"":l}function C(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 R(e){return"text-field"===e||"text-view"===e||"search"===e}function k(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function M(e){return e.map((e,t)=>({...e,ref:`e${t+1}`}))}function _(e){let t=e.trim();return t.startsWith("@")?t.slice(1)||null:t.startsWith("e")?t:null}function E(e,t){return e.find(e=>e.ref===t)??null}function D(e){return{x:Math.round(e.x+e.width/2),y:Math.round(e.y+e.height/2)}}function P(e,t){let n=D(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")}),a=j(i.map(e=>e.rect).filter(e=>z(e,n.x,n.y)));if(a)return a;let o=j(i.map(e=>e.rect));if(o)return o;let l=j(r.map(e=>e.rect).filter(e=>z(e,n.x,n.y)));return l||null}function T(e,t){let n=Math.max(1,t.height),r=t.y,i=t.y+n,a=r+.25*n,o=i-.25*n,l=e.y+e.height/2;return l<a?Math.ceil(a-l):l>o?Math.ceil(l-o):0}function z(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function j(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 B(e,t,n,r){return Math.max(e,n)<=Math.min(t,r)}function G(e){let t=new Map;for(let[n,r]of e.entries())t.set(r.index,n);let n=[],r=[];for(let[i,a]of e.entries()){let e=Math.max(0,a.depth??0);for(;r.length>0&&e<=r[r.length-1].depth;)r.pop();let o="number"==typeof a.parentIndex?t.get(a.parentIndex):void 0,l="number"==typeof o&&o<i?o:r[r.length-1]?.index;n.push({...a,index:i,depth:e,parentIndex:l}),r.push({depth:e,index:i})}return n}function O(e){return new Map(e.map(e=>[e.index,e]))}function V(e){let t=`${e??""}`.toLowerCase();return t.includes("scroll")||t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")||t.includes("collectionview")||"table"===t}function F(e){return!!V(e.type)||`${e.role??""} ${e.subrole??""}`.toLowerCase().includes("scroll")}function U(e){if(0===e.length)return{nodes:e,hiddenCount:0,summaryLines:[]};let t=O(e),n=new Set,r=[];for(let i of e){if(W(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,a=new Set;for(let e of t){if(!e.rect)continue;let t=q(e,n,r);if(!t?.rect)continue;let o=J(e.rect,t.rect);if(!o)continue;let l=i.get(t.index)??new Set;l.add(o),i.set(t.index,l),a.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 a=q(i,t,n);if(!a)continue;let o=r.get(a.index)??new Set;for(let t of e)o.add(t);r.set(a.index,o)}}(e,n,r,i),{directionsByContainer:i,coveredNodeIndexes:a}}(e,r,n,t),a=0===n.size?e:e.filter(e=>n.has(e.index));return{nodes:a.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-a.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=H(e,t,n);return r?J(e.rect,r):null}(i,t,n);if(!e)continue;let a=r.get(e)??[];a.push(i),r.set(e,a)}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=X(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",a=n.length>0?`: ${n.join(", ")}`:"";return[`[off-screen ${e}] ${t.length} ${i}${a}`]})}(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")||!!X(e)}(e)),e,t)}}function W(e,t,n=O(t)){var r;if(!e.rect)return!0;let i=H(e,t,n);return!i||(r=e.rect,B(r.x,r.x+r.width,i.x,i.x+i.width)&&B(r.y,r.y+r.height,i.y,i.y+i.height))}function H(e,t,n=O(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&&F(n))return n.rect;n="number"==typeof n.parentIndex?t.get(n.parentIndex):void 0}return null}(e,n);return r||P(t,e.rect??{x:0,y:0,width:0,height:0})}function J(e,t){return e.y+e.height<=t.y?"above":e.y>=t.y+t.height?"below":null}function X(e){return e.label?.trim()||e.value?.trim()||e.identifier?.trim()||""}function q(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)&&F(r))return r;r="number"==typeof r.parentIndex?n.get(r.parentIndex):void 0}return null}function K(){try{let n=Z();return JSON.parse(e.readFileSync(t.join(n,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function Z(){let r=t.dirname(n(import.meta.url)),i=r;for(let n=0;n<6;n+=1){let n=t.join(i,"package.json");if(e.existsSync(n))return i;i=t.dirname(i)}return r}function Q(e){return e?{message:e}:{}}function Y(e,t){return t?{...e,message:t}:e}function ee(e){return"string"==typeof e?.message&&e.message.length>0?e.message:null}let et=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function en(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function er(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=o("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 ei(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=o("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 ea(e,t){let n;if(!en(e))return!1;if(t){let n=er(e);if(!n||n!==t)return!1}let r=ei(e);return!!r&&!!(n=r.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&et.some(e=>e.test(n))}function eo(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 el(e,t){if(!en(e))return!0;let n=Date.now();for(;Date.now()-n<t;)if(await new Promise(e=>setTimeout(e,50)),!en(e))return!0;return!en(e)}async function es(e,t){!ea(e,t.expectedStartTime)||!eo(e,"SIGTERM")||await el(e,t.termTimeoutMs)||eo(e,"SIGKILL")&&await el(e,t.killTimeoutMs)}function eu(e){return e?.HOME?.trim()||r.homedir()}function ec(e,n={}){return"~"===e?eu(n.env):e.startsWith("~/")?t.join(eu(n.env),e.slice(2)):e}function ed(e,n={}){let r=ec(e,n);return t.isAbsolute(r)?r:t.resolve(n.cwd??process.cwd(),r)}function ef(e){let n,r=(n=(e??"").trim())?ed(n):t.join(ec("~"),".agent-device");return{baseDir:r,infoPath:t.join(r,"daemon.json"),lockPath:t.join(r,"daemon.lock"),logPath:t.join(r,"daemon.log"),sessionsDir:t.join(r,"sessions")}}function ep(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function em(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function eh(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function eg(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,eb=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,ex=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function ev(){let e=process.argv[1];return e?ey(e):"unknown"}function ey(n,r=Z()){try{let a=t.resolve(r),o=[t.resolve(n)],l=new Set,s=[];for(;o.length>0;){let n=o.pop();if(!n||l.has(n))continue;l.add(n);let r=e.statSync(n);if(!r.isFile())continue;let i=t.relative(a,n)||n;s.push(`${i}:${r.size}:${Math.trunc(r.mtimeMs)}`);let u=e.readFileSync(n,"utf8");for(let e of function(e){let t=new Set;return eS(e,ew,t),eS(e,eb,t),[...t]}(u)){let r=function(e,n){let r=t.resolve(t.dirname(e),n),i=eI(r);if(i)return i;for(let e of ex){let t=eI(`${r}${e}`);if(t)return t}for(let e of ex){let n=eI(t.join(r,`index${e}`));if(n)return n}return null}(n,e);r&&o.push(r)}}let u=s.sort().join("|"),c=i.createHash("sha1").update(u).digest("hex");return`graph:${s.length}:${c}`}catch{return"unknown"}}function eS(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 eI(t){try{return e.statSync(t).isFile()?t:null}catch{return null}}let e$=100,eA=new Set(["batch","replay"]),eN=new Set(["command","positionals","flags","runtime"]);function eL(e){let t;try{t=JSON.parse(e)}catch{throw new l("INVALID_ARGS","Batch steps must be valid JSON.")}if(!Array.isArray(t)||0===t.length)throw new l("INVALID_ARGS","Batch steps must be a non-empty JSON array.");return t}function eC(e,t){if(!Array.isArray(e)||0===e.length)throw new l("INVALID_ARGS","batch requires a non-empty batchSteps array.");if(e.length>t)throw new l("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 l("INVALID_ARGS",`Invalid batch step at index ${t}.`);let i=Object.keys(r).filter(e=>!eN.has(e));if(i.length>0){let e=i.map(e=>`"${e}"`).join(", ");throw new l("INVALID_ARGS",`Batch step ${t+1} has unknown field(s): ${e}. Allowed fields: command, positionals, flags, runtime.`)}let a="string"==typeof r.command?r.command.trim().toLowerCase():"";if(!a)throw new l("INVALID_ARGS",`Batch step ${t+1} requires command.`);if(eA.has(a))throw new l("INVALID_ARGS",`Batch step ${t+1} cannot run ${a}.`);if(void 0!==r.positionals&&!Array.isArray(r.positionals))throw new l("INVALID_ARGS",`Batch step ${t+1} positionals must be an array.`);let o=r.positionals??[];if(o.some(e=>"string"!=typeof e))throw new l("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 l("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 l("INVALID_ARGS",`Batch step ${t+1} runtime must be an object.`);n.push({command:a,positionals:o,flags:r.flags??{},runtime:r.runtime})}return n}function eR(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function ek(e,t,n){return{deviceId:t,deviceName:n,..."android"===e?{serial:t}:"ios"===e?{udid:t}:{}}}function eM(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 e_(e){return{name:e.name,...eM(e.device,{includeAndroidSerial:!1}),createdAt:e.createdAt}}function eE(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 eD(e){let t=e.created?"Created":"Reused",n=e.booted?" (booted)":"";return Y({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 eP(e){return e.bundleId??e.package??e.app}function eT(e){return Y({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: ${eP(e)}`)}function ez(e){return e.appName??e.bundleId??e.packageName??e.launchTarget}function ej(e){return Y({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: ${ez(e)}`)}function eB(e){let t=e.appName??e.appBundleId??e.session;return Y({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?eM(e.device):{}},t?`Opened: ${t}`:"Opened")}function eG(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...Q(e.session?`Closed: ${e.session}`:"Closed")}}function eO(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 eV(e,t){try{return a.sync.read(e)}catch(e){throw new l("COMMAND_FAILED",`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}export{e$ as DEFAULT_BATCH_MAX_STEPS,v as SESSION_SURFACES,w as SETTINGS_INVALID_ARGS_MESSAGE,g as SETTINGS_USAGE_OVERRIDE,M as attachRefs,eR as buildAppIdentifiers,ek as buildDeviceIdentifiers,U as buildMobileSnapshotPresentation,A as buildSnapshotDisplayLines,D as centerOfRect,ey as computeDaemonCodeSignature,z as containsPoint,eV as decodePng,L as displayLabel,T as distanceFromSafeViewportBand,ec as expandUserHomePath,S as extractReadableText,E as findNodeByRef,Z as findProjectRoot,C as formatRole,N as formatSnapshotLine,x as getUnsupportedMacOsSettingMessage,ea as isAgentDeviceDaemonProcess,b as isMacOsSettingSupported,W as isNodeVisibleInEffectiveViewport,en as isProcessAlive,V as isScrollableType,_ as normalizeRef,G as normalizeSnapshotTree,eg as normalizeTenantId,eL as parseBatchStepsJson,y as parseSessionSurface,j as pickLargestRect,ee as readCommandMessage,ei as readProcessCommand,er as readProcessStartTime,K as readVersion,ev as resolveDaemonCodeSignature,ef as resolveDaemonPaths,ep as resolveDaemonServerMode,em as resolveDaemonTransportPreference,eP as resolveDeployResultTarget,H as resolveEffectiveViewportRect,ez as resolveInstallFromSourceResultTarget,eh as resolveSessionIsolationMode,ed as resolveUserPath,P as resolveViewportRect,eG as serializeCloseResult,eT as serializeDeployResult,eE as serializeDevice,eD as serializeEnsureSimulatorResult,ej as serializeInstallFromSourceResult,eB as serializeOpenResult,e_ as serializeSessionListEntry,eO as serializeSnapshotResult,es as stopProcessForTakeover,Q as successText,eC as validateAndNormalizeBatchSteps,el as waitForProcessExit,Y as withSuccessText};
|