agent-device 0.12.8 → 0.13.0

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 CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  # agent-device
10
10
 
11
- `agent-device` is a CLI for UI automation on iOS, tvOS, macOS, Android, and AndroidTV. It is designed for agent-driven workflows: inspect the UI, act on it deterministically, and keep that work session-aware and replayable.
11
+ `agent-device` is a CLI for UI automation and app observability on iOS, tvOS, macOS, Android, and AndroidTV. It is built for agent-driven workflows: inspect the UI, interact deterministically, collect logs/network/perf evidence when behavior breaks, and keep the whole flow session-aware and replayable.
12
12
 
13
13
  If you know Vercel's [agent-browser](https://github.com/vercel-labs/agent-browser), this project applies the same broad idea to mobile apps and devices.
14
14
 
@@ -19,6 +19,7 @@ If you know Vercel's [agent-browser](https://github.com/vercel-labs/agent-browse
19
19
  - Give agents a practical way to understand mobile UI state through structured snapshots.
20
20
  - Keep automation flows token-efficient enough for real agent loops.
21
21
  - Make common interactions reliable enough for repeated automation runs.
22
+ - Make debugging evidence easy to collect through logs, network inspection, and performance snapshots.
22
23
  - Keep automation grounded in sessions, selectors, and replayable flows instead of one-off scripts.
23
24
 
24
25
  ## Core Ideas
@@ -26,11 +27,28 @@ If you know Vercel's [agent-browser](https://github.com/vercel-labs/agent-browse
26
27
  - Sessions: open a target once, interact within that session, then close it cleanly.
27
28
  - Snapshots: inspect the current accessibility tree in a compact form and get current-screen refs for exploration.
28
29
  - Refs vs selectors: use refs for discovery, use selectors for durable replay and assertions.
30
+ - Observability: collect session logs, inspect recent HTTP traffic with `network dump`, and sample CPU/memory with `perf`.
29
31
  - Tests: run deterministic `.ad` scripts as a light e2e test suite.
30
32
  - Replay scripts: save `.ad` flows with `--save-script`, replay one script with `replay`, or run a folder/glob as a serial suite with `test`.
31
33
  `test` supports metadata-aware retries up to 3 additional attempts, per-test timeouts, flaky pass reporting, and runner-managed artifacts under `.agent-device/test-artifacts` by default. Each attempt writes `replay.ad` and `result.txt`; failed attempts also keep copied logs and artifacts when available.
32
34
  - Human docs vs agent skills: docs explain the system for people; skills provide compact operating guidance for agents.
33
35
 
36
+ ## Complementary Tooling
37
+
38
+ Use `agent-device` for on-device UI automation, screenshots/recordings, app logs, network inspection, and performance snapshots.
39
+
40
+ When the task needs the React Native component tree, props, state, hooks, or render profiling, use the bundled passthrough:
41
+
42
+ ```bash
43
+ agent-device react-devtools status
44
+ agent-device react-devtools get tree --depth 3
45
+ agent-device react-devtools profile start
46
+ agent-device react-devtools profile stop
47
+ agent-device react-devtools profile slow --limit 5
48
+ ```
49
+
50
+ `react-devtools` dynamically runs pinned `agent-react-devtools@0.4.0` commands 1:1, so `agent-device` covers both the device/app runtime layer and React component internals without making React DevTools part of the daemon.
51
+
34
52
  ## Command Flow
35
53
 
36
54
  The canonical loop is:
@@ -69,6 +87,7 @@ For people:
69
87
  For agents:
70
88
 
71
89
  - [agent-device skill](skills/agent-device/SKILL.md)
90
+ - [react-devtools skill](skills/react-devtools/SKILL.md)
72
91
  - [dogfood skill](skills/dogfood/SKILL.md)
73
92
  - [agent-device skill on ClawHub](https://clawhub.ai/okwasniewski/agent-device)
74
93
 
package/dist/src/1974.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"node:fs";import r from"node:path";import{createHash as t}from"node:crypto";import{fileURLToPath as n}from"node:url";import{runCmdDetached as o,runCmdSync as a}from"./9818.js";import{readProcessCommand as i,waitForProcessExit as s,isProcessAlive as l,readProcessStartTime as u}from"./3883.js";import{METRO_COMPANION_RUN_ARG as c,normalizeBaseUrl as d,buildBundleUrl as m,ENV_SERVER_BASE_URL as p,ENV_LOCAL_BASE_URL as f,ENV_STATE_PATH as h,ENV_LAUNCH_URL as g,ENV_SCOPE_TENANT_ID as y,ENV_SCOPE_RUN_ID as b,ENV_BEARER_TOKEN as S,ENV_SCOPE_LEASE_ID as w}from"./320.js";import{AppError as U}from"./9152.js";import{resolveUserPath as _}from"./3267.js";let I="metro-companion";function P(e){return t("sha256").update(e).digest("hex")}function E(e){return e?.trim()?e.trim():void 0}function k(e,t){let n=r.join(e,".agent-device");if(!t)return{statePath:r.join(n,"metro-companion.json"),logPath:r.join(n,"metro-companion.log")};let o=P(t).slice(0,12),a=r.join(n,I);return{statePath:r.join(a,`metro-companion-${o}.json`),logPath:r.join(a,`metro-companion-${o}.log`)}}function v(r){try{let t=JSON.parse(e.readFileSync(r,"utf8"));if(!Number.isInteger(t.pid)||0>=Number(t.pid)||"string"!=typeof t.serverBaseUrl||"string"!=typeof t.localBaseUrl||"string"!=typeof t.tokenHash||0===t.tokenHash.length)return null;let n=Array.isArray(t.consumers)?t.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(t.pid),startTime:"string"==typeof t.startTime?t.startTime:void 0,command:"string"==typeof t.command?t.command:void 0,serverBaseUrl:t.serverBaseUrl,localBaseUrl:t.localBaseUrl,launchUrl:E("string"==typeof t.launchUrl?t.launchUrl:void 0),bridgeScope:function(e){if(!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.tenantId&&"string"==typeof e.runId&&"string"==typeof e.leaseId)return{tenantId:e.tenantId,runId:e.runId,leaseId:e.leaseId}}(t.bridgeScope),tokenHash:t.tokenHash,consumers:n}}catch{return null}}function M(t,n){e.mkdirSync(r.dirname(t),{recursive:!0}),e.writeFileSync(t,`${JSON.stringify(n,null,2)}
2
- `,"utf8")}function A(r){try{let t=e.readdirSync(r);0===t.length&&e.rmdirSync(r)}catch{}}function N(t){let n=r.dirname(t.statePath),o=r.dirname(t.logPath);var a=t.statePath;try{e.unlinkSync(a)}catch{}var i=t.logPath;try{e.unlinkSync(i)}catch{}A(n),o!==n&&A(o),r.basename(n)===I&&A(r.dirname(n))}function R(e){return e.includes(c)}function $(e){return E(e.consumerKey)??E(e.profileKey)??null}function x(e,r){return!r||e.consumers.includes(r)?e:{...e,consumers:[...e.consumers,r]}}async function T(e){if(!l(e.pid))return;let r=i(e.pid);if(r&&R(r)){try{process.kill(e.pid,"SIGTERM")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}if(!await s(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await s(e.pid,1e3)}}}async function j(t){let a=$(t),s=k(t.projectRoot,t.profileKey),m=v(s.statePath);if(m&&function(e,r){var t,n;if(!l(e.pid))return!1;if(e.startTime){let r=u(e.pid);if(!r||r!==e.startTime)return!1}let o=i(e.pid);return!!o&&!!R(o)&&!!e.bridgeScope&&e.serverBaseUrl===d(r.serverBaseUrl)&&e.localBaseUrl===d(r.localBaseUrl)&&e.launchUrl===E(r.launchUrl)&&(t=e.bridgeScope,n=r.bridgeScope,t.tenantId===n.tenantId&&t.runId===n.runId&&t.leaseId===n.leaseId)&&e.tokenHash===P(r.bearerToken)}(m,t)){let e=x(m,a);return e!==m&&M(s.statePath,e),{pid:m.pid,spawned:!1,statePath:s.statePath,logPath:s.logPath}}m&&(await T(m),N(s));let U=function(t,a){let s=function(){let t=n(import.meta.url),o=r.extname(t)||".js",a=r.join(r.dirname(t),`metro-companion${o}`);if(!e.existsSync(a))throw Error(`Metro companion entrypoint not found at ${a}. Rebuild the package to include the companion worker entry.`);return a}(),l=s.endsWith(".ts")?["--experimental-strip-types"]:[];e.mkdirSync(r.dirname(a),{recursive:!0});let m=e.openSync(a,"a"),U=0;try{let e;U=o(process.execPath,[...l,s,c],{env:((e={...t.env??process.env,[p]:d(t.serverBaseUrl),[S]:t.bearerToken,[f]:d(t.localBaseUrl),[h]:k(t.projectRoot,t.profileKey).statePath})[y]=t.bridgeScope.tenantId,e[b]=t.bridgeScope.runId,e[w]=t.bridgeScope.leaseId,t.launchUrl?.trim()?e[g]=t.launchUrl.trim():delete e[g],e),stdio:["ignore",m,m]})}finally{e.closeSync(m)}if(!Number.isInteger(U)||U<=0)throw Error("Failed to start Metro companion process.");return{pid:U,startTime:u(U)??void 0,command:i(U)??void 0,serverBaseUrl:d(t.serverBaseUrl),localBaseUrl:d(t.localBaseUrl),launchUrl:E(t.launchUrl),bridgeScope:t.bridgeScope,tokenHash:P(t.bearerToken),consumers:[]}}(t,s.logPath);return M(s.statePath,x(U,a)),{pid:U.pid,spawned:!0,statePath:s.statePath,logPath:s.logPath}}async function B(e){let r=$(e),t=k(e.projectRoot,e.profileKey),n=v(t.statePath);if(!n)return N(t),{stopped:!1,statePath:t.statePath};let o=r?{...n,consumers:n.consumers.filter(e=>e!==r)}:{...n,consumers:[]};return o.consumers.length>0?(M(t.statePath,o),{stopped:!1,statePath:t.statePath}):(await T(n),N(t),{stopped:!0,statePath:t.statePath})}function C(e){return"string"==typeof e&&e.trim()?d(e.trim()):""}function K(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function H(e,r,t){return _(e,{env:r,cwd:t})}function D(r){try{return e.accessSync(r,e.constants.F_OK),!0}catch{return!1}}function O(e,r,t){if(null==e||""===e)return r;let n=Number.parseInt(String(e),10);return Number.isInteger(n)?Math.max(n,t):r}function J(e,r){return{platform:r,bundleUrl:m(e,r)}}function L(e,r){return{platform:r,metroHost:K(e?.metro_host),metroPort:e?.metro_port,bundleUrl:K(e?.metro_bundle_url),launchUrl:K(e?.launch_url)}}async function G(e){await new Promise(r=>setTimeout(r,e))}async function F(e,r,t={}){try{let n=await fetch(e,{headers:t,signal:AbortSignal.timeout(r)});return{ok:n.ok,status:n.status,body:await n.text()}}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw Error(`Timed out fetching ${e} after ${r}ms`);throw t}}async function V(e,r){try{let t=await F(e,r);return t.ok&&t.body.includes("packager-status:running")}catch{return!1}}async function q(e){if(Number.isInteger(e)&&!(e<=0)){try{process.kill(e,"SIGTERM")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}if(!await s(e,1e3)){try{process.kill(e,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await s(e,1e3)}}}function z(e,r){let t=Error(e);return t.retryable=r,t}function W(e,r){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(r).includes("Metro companion is not connected"))}function X(e){return!!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable)}async function Y(e){let r;try{var t,n;r=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,n=e.bearerToken,{Authorization:`Bearer ${n}`,"Content-Type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({...e.scope,ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw z(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw z(r instanceof Error?r.message:String(r),!0)}let o=function(e,r,t){if(!e)return{};try{let r=JSON.parse(e);if(!r||"object"!=typeof r||Array.isArray(r))throw Error("Expected a JSON object");return r}catch(a){let n=e.slice(0,200),o=a instanceof Error?a.message:String(a);throw z(`/api/metro/bridge returned invalid JSON (${r}) from ${t}: ${o}. body=${JSON.stringify(n)}`,W(r,e))}}(await r.text(),r.status,e.baseUrl);if(!r.ok)throw z(`/api/metro/bridge failed (${r.status}): ${JSON.stringify(o)}`,W(r.status,o));var a=o;let i=a.data??a;if(!i||"object"!=typeof i||Array.isArray(i))throw z("/api/metro/bridge returned malformed descriptor: Expected a JSON object.",!1);try{return{enabled:i.enabled,baseUrl:i.base_url,statusUrl:i.status_url??"",bundleUrl:i.bundle_url??"",iosRuntime:L(i.ios_runtime,"ios"),androidRuntime:L(i.android_runtime,"android"),upstream:{bundleUrl:i.upstream.bundle_url??"",host:i.upstream.host??"",port:i.upstream.port??0,statusUrl:i.upstream.status_url??""},probe:{reachable:i.probe.reachable,statusCode:i.probe.status_code,latencyMs:i.probe.latency_ms,detail:i.probe.detail}}}catch(e){throw z(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function Q(e,r,t,n,o){let a=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return r&&a.push(`bridgeError=${r}`),t?.probe.reachable===!1&&a.push(`bridgeProbe=${t.probe.detail||`unreachable (status ${t.probe.statusCode||0})`}`),n&&n!==r&&a.push(`initialBridgeError=${n}`),o&&a.push(`metroCompanionLog=${o}`),a.join(" ")}async function Z(e,r,t){let n=Date.now()+r;for(;Date.now()<n;){let r=Math.min(t,Math.max(n-Date.now(),1));if(await V(e,r))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await G(o)}return!1}async function ee(e){let r=Date.now()+e.startupTimeoutMs,t=null,n=null;for(;Date.now()<r;){try{let r=await Y({baseUrl:e.baseUrl,bearerToken:e.bearerToken,scope:e.scope,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==r.probe.reachable)return r;t=r,n=null}catch(e){if(n=e instanceof Error?e.message:String(e),!X(e))break}let o=Math.min(1e3,Math.max(r-Date.now(),0));o>0&&await G(o)}throw Error(Q(e.baseUrl,n,t,e.initialBridgeError,e.companionLogPath))}async function er(t={}){let n=t.env??process.env,i=process.cwd(),s=H(t.projectRoot??i,n,i),l=function(t,n){if("auto"!==n)return n;let o=function(t){let n=r.join(t,"package.json");if(!D(n))throw new U("INVALID_ARGS",`package.json not found at ${n}`);return JSON.parse(e.readFileSync(n,"utf8"))}(t);return"string"==typeof({...o.dependencies??{},...o.devDependencies??{}}).expo?"expo":"react-native"}(s,t.kind??"auto"),u=function(e){if(null==e||""===e)return 8081;let r=Number.parseInt(String(e),10);if(!Number.isInteger(r)||r<1||r>65535)throw new U("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return r}(t.metroPort??8081),c=K(t.listenHost)??"0.0.0.0",d=K(t.statusHost)??"127.0.0.1",m=C(t.publicBaseUrl),p=O(t.startupTimeoutMs,18e4,3e4),f=O(t.probeTimeoutMs,1e4,1e3),h=t.reuseExisting??!0,g=t.installDependenciesIfNeeded??!0,y=t.runtimeFilePath?H(t.runtimeFilePath,n,i):null,b=H(t.logPath??r.join(s,".agent-device","metro.log"),n,i);if(!m)throw new U("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:S,proxyBaseUrl:w,proxyBearerToken:_}=function(e,r){if(e&&!r)throw new U("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.");if(!e&&r)throw new U("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&r),proxyBaseUrl:e,proxyBearerToken:r}}(C(t.proxyBaseUrl),K(t.proxyBearerToken)??""),I=S?function(e){if(!e?.tenantId||!e.runId||!e.leaseId)throw new U("INVALID_ARGS","metro prepare with proxy requires tenantId, runId, and leaseId bridge scope.");return e}(t.bridgeScope):null,P=g?function(t,n){if(function(r){try{return e.statSync(r).isDirectory()}catch{return!1}}(r.join(t,"node_modules")))return{installed:!1};let o=D(r.join(t,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:D(r.join(t,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return a(o.command,o.installArgs,{cwd:t,env:n}),{installed:!0,packageManager:o.command}}(s,n):{installed:!1},E=`http://${d}:${u}/status`,k=!1,v=!1,M=0;if(h&&await V(E,f))v=!0;else if(k=!0,M=function(t,n,a,i,s,l){let u="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(a)]}:{command:"npx",installArgs:["react-native","start","--host",i,"--port",String(a)]};e.mkdirSync(r.dirname(s),{recursive:!0});let c=e.openSync(s,"a"),d=0;try{d=o(u.command,u.installArgs,{cwd:t,env:l,stdio:["ignore",c,c]})}finally{e.closeSync(c)}if(!Number.isInteger(d)||d<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:d}}(s,l,u,c,b,n).pid,!await Z(E,p,f))throw await q(M).catch(()=>{}),Error(`Metro did not become ready at ${E} within ${p}ms. Check ${b}.`);let A=J(m,"ios"),N=J(m,"android"),R=null,$=null;if(I)try{R=await Y({baseUrl:w,bearerToken:_,scope:I,runtime:{metro_bundle_url:A.bundleUrl},timeoutMs:f})}catch(e){if(!X(e))throw e;$=e instanceof Error?e.message:String(e)}if(I&&(!R||!1===R.probe.reachable)){let e;try{e=(await j({projectRoot:s,serverBaseUrl:w,bearerToken:_,bridgeScope:I,localBaseUrl:`http://${d}:${u}`,launchUrl:K(t.launchUrl),profileKey:K(t.companionProfileKey),consumerKey:K(t.companionConsumerKey),env:n})).logPath}catch(e){throw Error(Q(w,e instanceof Error?e.message:String(e),R,$))}try{R=await ee({baseUrl:w,bearerToken:_,scope:I,runtime:{metro_bundle_url:A.bundleUrl},probeTimeoutMs:f,startupTimeoutMs:p,initialBridgeError:$,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}let x=R?.iosRuntime??A,T=R?.androidRuntime??N,B={projectRoot:s,kind:l,dependenciesInstalled:P.installed,packageManager:P.packageManager??null,started:k,reused:v,pid:M,logPath:b,statusUrl:E,runtimeFilePath:y,iosRuntime:x,androidRuntime:T,bridge:R};return y&&(e.mkdirSync(r.dirname(y),{recursive:!0}),e.writeFileSync(y,JSON.stringify(B,null,2))),B}export{J as buildMetroRuntimeHints,j as ensureMetroCompanion,er as prepareMetroRuntime,B as stopMetroCompanion};
1
+ import e from"node:fs";import r from"node:path";import{createHash as t}from"node:crypto";import{fileURLToPath as n}from"node:url";import{runCmdDetached as o,runCmdSync as a}from"./9818.js";import{readProcessCommand as i,waitForProcessExit as s,isProcessAlive as l,readProcessStartTime as c}from"./3883.js";import{METRO_COMPANION_RUN_ARG as u,normalizeBaseUrl as d,buildBundleUrl as p,ENV_SERVER_BASE_URL as m,ENV_LOCAL_BASE_URL as f,ENV_STATE_PATH as h,ENV_LAUNCH_URL as g,ENV_SCOPE_TENANT_ID as y,ENV_SCOPE_RUN_ID as b,ENV_BEARER_TOKEN as S,ENV_SCOPE_LEASE_ID as w}from"./320.js";import{AppError as _}from"./9152.js";import{resolveUserPath as U}from"./3267.js";import{sleep as I}from"./4829.js";let E="metro-companion";function P(e){return t("sha256").update(e).digest("hex")}function k(e){return e?.trim()?e.trim():void 0}function v(e,t){let n=r.join(e,".agent-device");if(!t)return{statePath:r.join(n,"metro-companion.json"),logPath:r.join(n,"metro-companion.log")};let o=P(t).slice(0,12),a=r.join(n,E);return{statePath:r.join(a,`metro-companion-${o}.json`),logPath:r.join(a,`metro-companion-${o}.log`)}}function M(r){try{let t=JSON.parse(e.readFileSync(r,"utf8"));if(!Number.isInteger(t.pid)||0>=Number(t.pid)||"string"!=typeof t.serverBaseUrl||"string"!=typeof t.localBaseUrl||"string"!=typeof t.tokenHash||0===t.tokenHash.length)return null;let n=Array.isArray(t.consumers)?t.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(t.pid),startTime:"string"==typeof t.startTime?t.startTime:void 0,command:"string"==typeof t.command?t.command:void 0,serverBaseUrl:t.serverBaseUrl,localBaseUrl:t.localBaseUrl,launchUrl:k("string"==typeof t.launchUrl?t.launchUrl:void 0),bridgeScope:function(e){if(!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.tenantId&&"string"==typeof e.runId&&"string"==typeof e.leaseId)return{tenantId:e.tenantId,runId:e.runId,leaseId:e.leaseId}}(t.bridgeScope),tokenHash:t.tokenHash,consumers:n}}catch{return null}}function A(t,n){e.mkdirSync(r.dirname(t),{recursive:!0}),e.writeFileSync(t,`${JSON.stringify(n,null,2)}
2
+ `,"utf8")}function N(r){try{let t=e.readdirSync(r);0===t.length&&e.rmdirSync(r)}catch{}}function R(t){let n=r.dirname(t.statePath),o=r.dirname(t.logPath);var a=t.statePath;try{e.unlinkSync(a)}catch{}var i=t.logPath;try{e.unlinkSync(i)}catch{}N(n),o!==n&&N(o),r.basename(n)===E&&N(r.dirname(n))}function $(e){return e.includes(u)}function x(e){return k(e.consumerKey)??k(e.profileKey)??null}function j(e,r){return!r||e.consumers.includes(r)?e:{...e,consumers:[...e.consumers,r]}}async function T(e){if(!l(e.pid))return;let r=i(e.pid);if(r&&$(r)){try{process.kill(e.pid,"SIGTERM")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}if(!await s(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await s(e.pid,1e3)}}}async function B(t){let a=x(t),s=v(t.projectRoot,t.profileKey),p=M(s.statePath);if(p&&function(e,r){var t,n;if(!l(e.pid))return!1;if(e.startTime){let r=c(e.pid);if(!r||r!==e.startTime)return!1}let o=i(e.pid);return!!o&&!!$(o)&&!!e.bridgeScope&&e.serverBaseUrl===d(r.serverBaseUrl)&&e.localBaseUrl===d(r.localBaseUrl)&&e.launchUrl===k(r.launchUrl)&&(t=e.bridgeScope,n=r.bridgeScope,t.tenantId===n.tenantId&&t.runId===n.runId&&t.leaseId===n.leaseId)&&e.tokenHash===P(r.bearerToken)}(p,t)){let e=j(p,a);return e!==p&&A(s.statePath,e),{pid:p.pid,spawned:!1,statePath:s.statePath,logPath:s.logPath}}p&&(await T(p),R(s));let _=function(t,a){let s=function(){let t=n(import.meta.url),o=r.extname(t)||".js",a=r.join(r.dirname(t),`metro-companion${o}`);if(!e.existsSync(a))throw Error(`Metro companion entrypoint not found at ${a}. Rebuild the package to include the companion worker entry.`);return a}(),l=s.endsWith(".ts")?["--experimental-strip-types"]:[];e.mkdirSync(r.dirname(a),{recursive:!0});let p=e.openSync(a,"a"),_=0;try{let e;_=o(process.execPath,[...l,s,u],{env:((e={...t.env??process.env,[m]:d(t.serverBaseUrl),[S]:t.bearerToken,[f]:d(t.localBaseUrl),[h]:v(t.projectRoot,t.profileKey).statePath})[y]=t.bridgeScope.tenantId,e[b]=t.bridgeScope.runId,e[w]=t.bridgeScope.leaseId,t.launchUrl?.trim()?e[g]=t.launchUrl.trim():delete e[g],e),stdio:["ignore",p,p]})}finally{e.closeSync(p)}if(!Number.isInteger(_)||_<=0)throw Error("Failed to start Metro companion process.");return{pid:_,startTime:c(_)??void 0,command:i(_)??void 0,serverBaseUrl:d(t.serverBaseUrl),localBaseUrl:d(t.localBaseUrl),launchUrl:k(t.launchUrl),bridgeScope:t.bridgeScope,tokenHash:P(t.bearerToken),consumers:[]}}(t,s.logPath);return A(s.statePath,j(_,a)),{pid:_.pid,spawned:!0,statePath:s.statePath,logPath:s.logPath}}async function C(e){let r=x(e),t=v(e.projectRoot,e.profileKey),n=M(t.statePath);if(!n)return R(t),{stopped:!1,statePath:t.statePath};let o=r?{...n,consumers:n.consumers.filter(e=>e!==r)}:{...n,consumers:[]};return o.consumers.length>0?(A(t.statePath,o),{stopped:!1,statePath:t.statePath}):(await T(n),R(t),{stopped:!0,statePath:t.statePath})}function K(e){return"string"==typeof e&&e.trim()?d(e.trim()):""}function H(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function D(e,r,t){return U(e,{env:r,cwd:t})}function O(r){try{return e.accessSync(r,e.constants.F_OK),!0}catch{return!1}}function J(e,r,t){if(null==e||""===e)return r;let n=Number.parseInt(String(e),10);return Number.isInteger(n)?Math.max(n,t):r}function L(e,r){return{platform:r,bundleUrl:p(e,r)}}function G(e,r){return{platform:r,metroHost:H(e?.metro_host),metroPort:e?.metro_port,bundleUrl:H(e?.metro_bundle_url),launchUrl:H(e?.launch_url)}}async function F(e){await I(e)}async function V(e,r,t={}){try{let n=await fetch(e,{headers:t,signal:AbortSignal.timeout(r)});return{ok:n.ok,status:n.status,body:await n.text()}}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw Error(`Timed out fetching ${e} after ${r}ms`);throw t}}async function q(e,r){try{let t=await V(e,r);return t.ok&&t.body.includes("packager-status:running")}catch{return!1}}async function z(e){if(Number.isInteger(e)&&!(e<=0)){try{process.kill(e,"SIGTERM")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}if(!await s(e,1e3)){try{process.kill(e,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await s(e,1e3)}}}function W(e,r){let t=Error(e);return t.retryable=r,t}function X(e,r){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(r).includes("Metro companion is not connected"))}function Y(e){return!!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable)}async function Q(e){let r;try{var t,n;r=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,n=e.bearerToken,{Authorization:`Bearer ${n}`,"Content-Type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({...e.scope,...e.runtime?{ios_runtime:e.runtime}:{},timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw W(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw W(r instanceof Error?r.message:String(r),!0)}let o=function(e,r,t){if(!e)return{};try{let r=JSON.parse(e);if(!r||"object"!=typeof r||Array.isArray(r))throw Error("Expected a JSON object");return r}catch(a){let n=e.slice(0,200),o=a instanceof Error?a.message:String(a);throw W(`/api/metro/bridge returned invalid JSON (${r}) from ${t}: ${o}. body=${JSON.stringify(n)}`,X(r,e))}}(await r.text(),r.status,e.baseUrl);if(!r.ok)throw W(`/api/metro/bridge failed (${r.status}): ${JSON.stringify(o)}`,X(r.status,o));var a=o;let i=a.data??a;if(!i||"object"!=typeof i||Array.isArray(i))throw W("/api/metro/bridge returned malformed descriptor: Expected a JSON object.",!1);try{return{enabled:i.enabled,baseUrl:i.base_url,statusUrl:i.status_url??"",bundleUrl:i.bundle_url??"",iosRuntime:G(i.ios_runtime,"ios"),androidRuntime:G(i.android_runtime,"android"),upstream:{bundleUrl:i.upstream.bundle_url??"",host:i.upstream.host??"",port:i.upstream.port??0,statusUrl:i.upstream.status_url??""},probe:{reachable:i.probe.reachable,statusCode:i.probe.status_code,latencyMs:i.probe.latency_ms,detail:i.probe.detail}}}catch(e){throw W(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function Z(e,r,t,n,o){let a=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return r&&a.push(`bridgeError=${r}`),t?.probe.reachable===!1&&a.push(`bridgeProbe=${t.probe.detail||`unreachable (status ${t.probe.statusCode||0})`}`),n&&n!==r&&a.push(`initialBridgeError=${n}`),o&&a.push(`metroCompanionLog=${o}`),a.join(" ")}async function ee(e,r,t){let n=Date.now()+r;for(;Date.now()<n;){let r=Math.min(t,Math.max(n-Date.now(),1));if(await q(e,r))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await F(o)}return!1}async function er(e){let r=Date.now()+e.startupTimeoutMs,t=null,n=null;for(;Date.now()<r;){try{let r=await Q({baseUrl:e.baseUrl,bearerToken:e.bearerToken,scope:e.scope,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==r.probe.reachable)return r;t=r,n=null}catch(e){if(n=e instanceof Error?e.message:String(e),!Y(e))break}let o=Math.min(1e3,Math.max(r-Date.now(),0));o>0&&await F(o)}throw Error(Z(e.baseUrl,n,t,e.initialBridgeError,e.companionLogPath))}async function et(t={}){let n=t.env??process.env,i=process.cwd(),s=D(t.projectRoot??i,n,i),l=function(t,n){if("auto"!==n)return n;let o=function(t){let n=r.join(t,"package.json");if(!O(n))throw new _("INVALID_ARGS",`package.json not found at ${n}`);return JSON.parse(e.readFileSync(n,"utf8"))}(t);return"string"==typeof({...o.dependencies??{},...o.devDependencies??{}}).expo?"expo":"react-native"}(s,t.kind??"auto"),c=function(e){if(null==e||""===e)return 8081;let r=Number.parseInt(String(e),10);if(!Number.isInteger(r)||r<1||r>65535)throw new _("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return r}(t.metroPort??8081),u=H(t.listenHost)??"0.0.0.0",d=H(t.statusHost)??"127.0.0.1",p=K(t.publicBaseUrl),m=J(t.startupTimeoutMs,18e4,3e4),f=J(t.probeTimeoutMs,1e4,1e3),h=t.reuseExisting??!0,g=t.installDependenciesIfNeeded??!0,y=t.runtimeFilePath?D(t.runtimeFilePath,n,i):null,b=D(t.logPath??r.join(s,".agent-device","metro.log"),n,i);if(!p&&!K(t.proxyBaseUrl))throw new _("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:S,proxyBaseUrl:w,proxyBearerToken:U}=function(e,r){if(e&&!r)throw new _("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.");if(!e&&r)throw new _("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&r),proxyBaseUrl:e,proxyBearerToken:r}}(K(t.proxyBaseUrl),H(t.proxyBearerToken)??""),I=S?function(e){if(!e?.tenantId||!e.runId||!e.leaseId)throw new _("INVALID_ARGS","metro prepare with proxy requires tenantId, runId, and leaseId bridge scope.");return e}(t.bridgeScope):null,E=g?function(t,n){if(function(r){try{return e.statSync(r).isDirectory()}catch{return!1}}(r.join(t,"node_modules")))return{installed:!1};let o=O(r.join(t,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:O(r.join(t,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return a(o.command,o.installArgs,{cwd:t,env:n}),{installed:!0,packageManager:o.command}}(s,n):{installed:!1},P=`http://${d}:${c}/status`,k=!1,v=!1,M=0;if(h&&await q(P,f))v=!0;else if(k=!0,M=function(t,n,a,i,s,l){let c="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(a)]}:{command:"npx",installArgs:["react-native","start","--host",i,"--port",String(a)]};e.mkdirSync(r.dirname(s),{recursive:!0});let u=e.openSync(s,"a"),d=0;try{d=o(c.command,c.installArgs,{cwd:t,env:l,stdio:["ignore",u,u]})}finally{e.closeSync(u)}if(!Number.isInteger(d)||d<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:d}}(s,l,c,u,b,n).pid,!await ee(P,m,f))throw await z(M).catch(()=>{}),Error(`Metro did not become ready at ${P} within ${m}ms. Check ${b}.`);let A=p?L(p,"ios"):{platform:"ios"},N=p?L(p,"android"):{platform:"android"},R=null,$=null;if(I)try{R=await Q({baseUrl:w,bearerToken:U,scope:I,timeoutMs:f})}catch(e){if(!Y(e))throw e;$=e instanceof Error?e.message:String(e)}if(I&&(!R||!1===R.probe.reachable)){let e;try{e=(await B({projectRoot:s,serverBaseUrl:w,bearerToken:U,bridgeScope:I,localBaseUrl:`http://${d}:${c}`,launchUrl:H(t.launchUrl),profileKey:H(t.companionProfileKey),consumerKey:H(t.companionConsumerKey),env:n})).logPath}catch(e){throw Error(Z(w,e instanceof Error?e.message:String(e),R,$))}try{R=await er({baseUrl:w,bearerToken:U,scope:I,probeTimeoutMs:f,startupTimeoutMs:m,initialBridgeError:$,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}I&&function(e,r){if(!r?.iosRuntime.bundleUrl)throw Error(Z(e,"bridge descriptor is missing ios_runtime.metro_bundle_url",r))}(w,R);let x=R?.iosRuntime??A,j=R?.androidRuntime??N,T={projectRoot:s,kind:l,dependenciesInstalled:E.installed,packageManager:E.packageManager??null,started:k,reused:v,pid:M,logPath:b,statusUrl:P,runtimeFilePath:y,iosRuntime:x,androidRuntime:j,bridge:R};return y&&(e.mkdirSync(r.dirname(y),{recursive:!0}),e.writeFileSync(y,JSON.stringify(T,null,2))),T}export{L as buildMetroRuntimeHints,B as ensureMetroCompanion,et as prepareMetroRuntime,C as stopMetroCompanion};
package/dist/src/3883.js CHANGED
@@ -1 +1 @@
1
- import{runCmdSync as e}from"./9818.js";let t=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function r(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function n(t){if(!Number.isInteger(t)||t<=0)return null;try{let r=e("ps",["-p",String(t),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==r.exitCode)return null;let n=r.stdout.trim();return n.length>0?n:null}catch{return null}}function i(t){if(!Number.isInteger(t)||t<=0)return null;try{let r=e("ps",["-p",String(t),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==r.exitCode)return null;let n=r.stdout.trim();return n.length>0?n:null}catch{return null}}function o(e,o){let s;if(!r(e))return!1;if(o){let t=n(e);if(!t||t!==o)return!1}let u=i(e);return!!u&&!!(s=u.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&t.some(e=>e.test(s))}function s(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 u(e,t){if(!r(e))return!0;let n=Date.now();for(;Date.now()-n<t;)if(await new Promise(e=>setTimeout(e,50)),!r(e))return!0;return!r(e)}async function l(e,t){!o(e,t.expectedStartTime)||!s(e,"SIGTERM")||await u(e,t.termTimeoutMs)||s(e,"SIGKILL")&&await u(e,t.killTimeoutMs)}export{o as isAgentDeviceDaemonProcess,r as isProcessAlive,i as readProcessCommand,n as readProcessStartTime,l as stopProcessForTakeover,u as waitForProcessExit};
1
+ import{runCmdSync as e}from"./9818.js";import{sleep as t}from"./4829.js";let r=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function n(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function i(t){if(!Number.isInteger(t)||t<=0)return null;try{let r=e("ps",["-p",String(t),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==r.exitCode)return null;let n=r.stdout.trim();return n.length>0?n:null}catch{return null}}function o(t){if(!Number.isInteger(t)||t<=0)return null;try{let r=e("ps",["-p",String(t),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==r.exitCode)return null;let n=r.stdout.trim();return n.length>0?n:null}catch{return null}}function l(e,t){let l;if(!n(e))return!1;if(t){let r=i(e);if(!r||r!==t)return!1}let s=o(e);return!!s&&!!(l=s.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&r.some(e=>e.test(l))}function s(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 u(e,r){if(!n(e))return!0;let i=Date.now();for(;Date.now()-i<r;)if(await t(50),!n(e))return!0;return!n(e)}async function c(e,t){!l(e,t.expectedStartTime)||!s(e,"SIGTERM")||await u(e,t.termTimeoutMs)||s(e,"SIGKILL")&&await u(e,t.killTimeoutMs)}export{l as isAgentDeviceDaemonProcess,n as isProcessAlive,o as readProcessCommand,i as readProcessStartTime,c as stopProcessForTakeover,u as waitForProcessExit};