agent-device 0.8.3 → 0.8.4

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.
Files changed (42) hide show
  1. package/dist/src/224.js +2 -2
  2. package/dist/src/331.js +1 -1
  3. package/dist/src/bin.js +61 -60
  4. package/dist/src/client-shared.d.ts +20 -0
  5. package/dist/src/core/dispatch-resolve.d.ts +2 -2
  6. package/dist/src/daemon/handlers/session-batch.d.ts +2 -0
  7. package/dist/src/daemon/handlers/session-close.d.ts +31 -0
  8. package/dist/src/daemon/handlers/session-deploy.d.ts +37 -0
  9. package/dist/src/daemon/handlers/session-device-utils.d.ts +25 -0
  10. package/dist/src/daemon/handlers/session-open-target.d.ts +3 -0
  11. package/dist/src/daemon/handlers/session-open.d.ts +22 -0
  12. package/dist/src/daemon/handlers/session-perf.d.ts +2 -0
  13. package/dist/src/daemon/handlers/session-runtime-command.d.ts +9 -0
  14. package/dist/src/daemon/handlers/session-runtime.d.ts +41 -0
  15. package/dist/src/daemon/handlers/session-startup-metrics.d.ts +11 -0
  16. package/dist/src/daemon/handlers/session.d.ts +4 -29
  17. package/dist/src/daemon/selectors-build.d.ts +4 -0
  18. package/dist/src/daemon/selectors-match.d.ts +5 -0
  19. package/dist/src/daemon/selectors-parse.d.ts +29 -0
  20. package/dist/src/daemon/selectors-resolve.d.ts +32 -0
  21. package/dist/src/daemon/selectors.d.ts +5 -65
  22. package/dist/src/daemon.js +36 -36
  23. package/dist/src/platforms/android/index.d.ts +2 -1
  24. package/dist/src/platforms/android/screenshot.d.ts +16 -0
  25. package/dist/src/platforms/android/snapshot.d.ts +0 -1
  26. package/dist/src/platforms/ios/config.d.ts +1 -0
  27. package/dist/src/platforms/ios/index.d.ts +1 -1
  28. package/dist/src/platforms/ios/screenshot-status-bar.d.ts +2 -0
  29. package/dist/src/platforms/ios/screenshot.d.ts +2 -1
  30. package/dist/src/utils/command-schema.d.ts +2 -0
  31. package/dist/src/utils/device.d.ts +1 -1
  32. package/dist/src/utils/interactors.d.ts +7 -0
  33. package/dist/src/utils/output.d.ts +3 -1
  34. package/dist/src/utils/path-resolution.d.ts +8 -0
  35. package/dist/src/utils/screenshot-diff.d.ts +23 -0
  36. package/package.json +5 -5
  37. package/skills/agent-device/SKILL.md +4 -0
  38. package/skills/agent-device/references/snapshot-refs.md +1 -0
  39. package/skills/dogfood/SKILL.md +12 -12
  40. package/skills/dogfood/references/issue-taxonomy.md +5 -5
  41. package/skills/dogfood/templates/dogfood-report-template.md +19 -19
  42. package/dist/src/utils/interactive.d.ts +0 -1
package/dist/src/224.js CHANGED
@@ -1,2 +1,2 @@
1
- import{createRequestId as e,node_path as t,isAgentDeviceDaemonProcess as r,runCmdDetached as a,readVersion as n,findProjectRoot as o,node_https as i,runCmdSync as s,withDiagnosticTimer as d,resolveDaemonTransportPreference as l,emitDiagnostic as c,spawn as u,AppError as m,node_fs as p,resolveDaemonPaths as h,node_net as f,resolveDaemonServerMode as I,stopProcessForTakeover as w,node_http as A}from"./331.js";async function g(e){let{localPath:r,baseUrl:a,token:n}=e,o=p.statSync(r).isDirectory(),s=t.basename(r),d=new URL("upload",a.endsWith("/")?a:`${a}/`),l="https:"===d.protocol?i:A,c={"x-artifact-type":o?"app-bundle":"file","x-artifact-filename":s,"transfer-encoding":"chunked"};return n&&(c.authorization=`Bearer ${n}`,c["x-agent-device-token"]=n),new Promise((e,a)=>{let n=l.request({protocol:d.protocol,host:d.hostname,port:d.port,method:"POST",path:d.pathname+d.search,headers:c},t=>{let r="";t.setEncoding("utf8"),t.on("data",e=>{r+=e}),t.on("end",()=>{clearTimeout(i);try{let t=JSON.parse(r);if(!t.ok||!t.uploadId)return void a(new m("COMMAND_FAILED",`Upload failed: ${r}`));e(t.uploadId)}catch{a(new m("COMMAND_FAILED",`Invalid upload response: ${r}`))}})}),i=setTimeout(()=>{n.destroy(),a(new m("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(n.on("error",e=>{clearTimeout(i),a(new m("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),o){let e=u("tar",["cf","-","-C",t.dirname(r),t.basename(r)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(n),e.on("error",e=>{n.destroy(),a(new m("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(n.destroy(),a(new m("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=p.createReadStream(r);e.pipe(n),e.on("error",e=>{n.destroy(),a(new m("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}let D=function(e=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if(!e)return 9e4;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):9e4}(),v=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS){if(!e)return 15e3;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):15e3}(),y=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_ATTEMPTS){if(!e)return 2;let t=Number(e);return Number.isFinite(t)?Math.min(5,Math.max(1,Math.floor(t))):2}(),E=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];async function P(t){let r=t.meta?.requestId??e(),a=!!(t.meta?.debug||t.flags?.verbose),n=function(e){let t=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,r=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new m("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new m("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(e.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),a=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN,n=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,o=l(n);if(r&&"socket"===o)throw new m("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:r});let i=I(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===n?"dual":void 0));return{paths:h(t),transportPreference:o,serverMode:i,remoteBaseUrl:r,remoteAuthToken:a}}(t),o=await d("daemon_startup",async()=>await S(n),{requestId:r,session:t.session}),i=await _(t,o),s={...t,positionals:i.positionals,flags:i.flags,token:o.token,meta:{...t.meta??{},requestId:r,debug:a,cwd:t.meta?.cwd,tenantId:t.meta?.tenantId??t.flags?.tenant,runId:t.meta?.runId??t.flags?.runId,leaseId:t.meta?.leaseId??t.flags?.leaseId,sessionIsolation:t.meta?.sessionIsolation??t.flags?.sessionIsolation,lockPolicy:t.meta?.lockPolicy,lockPlatform:t.meta?.lockPlatform,...i.uploadedArtifactId?{uploadedArtifactId:i.uploadedArtifactId}:{},...i.clientArtifactPaths?{clientArtifactPaths:i.clientArtifactPaths}:{},...i.installSource?{installSource:i.installSource}:{}}};return c({level:"info",phase:"daemon_request_prepare",data:{requestId:r,command:t.command,session:t.session}}),await d("daemon_request",async()=>await z(o,s,n.transportPreference),{requestId:r,command:t.command})}async function _(e,r){let a,n=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,i=e.meta?.installSource,s={};if(W(r)){let d=function(e,r){if("screenshot"===e.command){let t=b(e,"path",".png");return r[0]?{field:"path",localPath:t,positionalIndex:0,positionalPath:T("screenshot",".png")}:{field:"path",localPath:t,positionalIndex:0,flagPath:T("screenshot",".png")}}if("record"===e.command&&"start"===(r[0]??"").toLowerCase()){let r=b(e,"outPath",".mp4",1);return{field:"outPath",localPath:r,positionalIndex:1,positionalPath:T("recording",t.extname(r)||".mp4")}}return null}(e,n);d&&(void 0!==d.positionalPath&&(n[d.positionalIndex]=d.positionalPath),void 0!==d.flagPath&&((o??={}).out=d.flagPath),s[d.field]=d.localPath);let l=await M(e,r);l&&(i=l.installSource,a=l.uploadedArtifactId??a)}if(!W(r)||"install"!==e.command&&"reinstall"!==e.command||n.length<2)return{positionals:n,flags:o,installSource:i,uploadedArtifactId:a,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}};let d=n[1];if(d.startsWith("remote:"))return n[1]=d.slice(7),{positionals:n,flags:o,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}};let l=t.isAbsolute(d)?d:t.resolve(e.meta?.cwd??process.cwd(),d);return p.existsSync(l)?{positionals:n,flags:o,installSource:i,uploadedArtifactId:a=await g({localPath:l,baseUrl:r.baseUrl,token:r.token}),...Object.keys(s).length>0?{clientArtifactPaths:s}:{}}:{positionals:n,flags:o,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}}}async function M(e,r){let a=e.meta?.installSource;if("install_source"!==e.command||!a||"path"!==a.kind)return null;let n=a.path.trim();if(!n)return{installSource:a};if(n.startsWith("remote:"))return{installSource:{...a,path:n.slice(7)}};let o=t.isAbsolute(n)?n:t.resolve(e.meta?.cwd??process.cwd(),n);if(!p.existsSync(o))return{installSource:{...a,path:o}};let i=await g({localPath:o,baseUrl:r.baseUrl,token:r.token});return{installSource:{...a,path:o},uploadedArtifactId:i}}function b(e,r,a,n=0){let o=e.positionals?.[n]??e.flags?.out,i=`${"path"===r?"screenshot":"recording"}-${Date.now()}${a}`,s=o&&o.trim().length>0?o:i;return t.isAbsolute(s)?s:t.resolve(e.meta?.cwd??process.cwd(),s)}function T(e,r){let a=r.startsWith(".")?r:`.${r}`;return t.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${a}`)}async function S(e){let a;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await x(t,"http"))return t;throw new m("COMMAND_FAILED","Remote daemon is unavailable",{daemonBaseUrl:e.remoteBaseUrl,hint:"Verify AGENT_DEVICE_DAEMON_BASE_URL points to a reachable daemon with GET /health and POST /rpc."})}let i=R(e.paths.infoPath),s=n(),d=function(e,r=o()){try{let a=p.statSync(e),n=t.relative(r,e)||e;return`${n}:${a.size}:${Math.trunc(a.mtimeMs)}`}catch{return"unknown"}}((a=B()).useSrc?a.srcPath:a.distPath,a.root),l=!!i&&await x(i,e.transportPreference);if(i&&i.version===s&&i.codeSignature===d&&l)return i;i&&(i.version!==s||i.codeSignature!==d||!l)&&(await C(i),F(e.paths.infoPath)),function(e){let t=L(e);if(!t.hasLock||t.hasInfo)return;let a=U(e.lockPath);if(!a)return F(e.lockPath);r(a.pid,a.processStartTime)||F(e.lockPath)}(e.paths);let c=0;for(let t=1;t<=y;t+=1){await $(e);let r=await N(v,e);if(r)return r;if(await O(e.paths)){c+=1;continue}let a=L(e.paths);if(!(t<y))break;if(!a.hasInfo&&!a.hasLock){await k(150);continue}}let u=L(e.paths);throw new m("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:v,startupAttempts:y,lockRecoveryCount:c,metadataState:u,hint:function(e,t=h(process.env.AGENT_DEVICE_STATE_DIR)){return e.hasLock&&!e.hasInfo?`Detected ${t.lockPath} without ${t.infoPath}. If no agent-device daemon process is running, delete ${t.lockPath} and retry.`:e.hasLock&&e.hasInfo?`Daemon metadata may be stale. If no agent-device daemon process is running, delete ${t.infoPath} and ${t.lockPath}, then retry.`:`Daemon metadata is missing or stale. Delete ${t.infoPath} if present and retry.`}(u,e.paths)})}async function N(e,t){let r=Date.now();for(;Date.now()-r<e;){let e=R(t.paths.infoPath);if(e&&await x(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function k(e){await new Promise(t=>setTimeout(t,e))}async function O(e){let t=L(e);if(!t.hasLock||t.hasInfo)return!1;let a=U(e.lockPath);return a&&r(a.pid,a.processStartTime)&&await w(a.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:a.processStartTime}),F(e.lockPath),!0}async function C(e){await w(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function R(e){let t=q(e);if(!t||"string"!=typeof t.token||0===t.token.length)return null;let r=Number.isInteger(t.port)&&Number(t.port)>0,a=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;return r||a?{...t,port:r?Number(t.port):void 0,httpPort:a?Number(t.httpPort):void 0,pid:Number.isInteger(t.pid)&&t.pid>0?t.pid:0}:null}function U(e){let t=q(e);return t&&Number.isInteger(t.pid)&&!(t.pid<=0)?t:null}function L(e){return{hasInfo:p.existsSync(e.infoPath),hasLock:p.existsSync(e.lockPath)}}function q(e){if(!p.existsSync(e))return null;try{return JSON.parse(p.readFileSync(e,"utf8"))}catch{return null}}function F(e){try{p.existsSync(e)&&p.unlinkSync(e)}catch{}}async function x(e,t){var r;return"http"===G(e,t)?await function(e){let t=e.baseUrl?J(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!t)return Promise.resolve(!1);let r=new URL(t),a="https:"===r.protocol?i:A,n=e.baseUrl?3e3:500;return new Promise(e=>{let t=a.request({protocol:r.protocol,host:r.hostname,port:r.port,path:r.pathname+r.search,method:"GET",timeout:n},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(e):await ((r=e.port)?new Promise(e=>{let t=f.createConnection({host:"127.0.0.1",port:r},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function $(e){let t=B(),r=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};a(process.execPath,r,{env:n})}function B(){let e=o(),r=t.join(e,"dist","src","daemon.js"),a=t.join(e,"src","daemon.ts"),n=p.existsSync(r),i=p.existsSync(a);if(!n&&!i)throw new m("COMMAND_FAILED","Daemon entry not found",{distPath:r,srcPath:a});return{root:e,distPath:r,srcPath:a,useSrc:process.execArgv.includes("--experimental-strip-types")?i:!n&&i}}async function z(e,t,r){return"http"===G(e,r)?await j(e,t):await V(e,t)}function G(e,t){if(e.baseUrl){if("socket"===t)throw new m("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t){if(!e.httpPort)throw new m("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");return"http"}if("socket"===t){if(!e.port)throw new m("COMMAND_FAILED","Daemon socket endpoint is unavailable");return"socket"}let r=e.transport;if("http"===r&&e.httpPort)return"http";if(("socket"===r||"dual"===r)&&e.port)return"socket";if(e.httpPort)return"http";if(e.port)return"socket";throw new m("COMMAND_FAILED","Daemon metadata has no reachable transport")}async function V(e,t){let r=e.port;if(!r)throw new m("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((a,n)=>{let o=f.createConnection({host:"127.0.0.1",port:r},()=>{o.write(`${JSON.stringify(t)}
2
- `)}),i=setTimeout(()=>{o.destroy();let r=H(),a=K(e,h(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR));c({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:D,requestId:t.meta?.requestId,command:t.command,timedOutRunnerPidsTerminated:r.terminated,timedOutRunnerCleanupError:r.error,daemonPidReset:e.pid,daemonPidForceKilled:a.forcedKill}}),n(new m("COMMAND_FAILED","Daemon request timed out",{timeoutMs:D,requestId:t.meta?.requestId,hint:"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},D),s="";o.setEncoding("utf8"),o.on("data",e=>{let r=(s+=e).indexOf("\n");if(-1===r)return;let d=s.slice(0,r).trim();if(d)try{let e=JSON.parse(d);o.end(),clearTimeout(i),a(e)}catch(e){clearTimeout(i),n(new m("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:d},e instanceof Error?e:void 0))}}),o.on("error",e=>{clearTimeout(i),c({level:"error",phase:"daemon_request_socket_error",data:{requestId:t.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),n(new m("COMMAND_FAILED","Failed to communicate with daemon",{requestId:t.meta?.requestId,hint:"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e))})})}async function j(t,r){let a=t.baseUrl?new URL(J(t.baseUrl,"rpc")):t.httpPort?new URL(`http://127.0.0.1:${t.httpPort}/rpc`):null;if(!a)throw new m("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let n=JSON.stringify({jsonrpc:"2.0",id:r.meta?.requestId??e(),method:"agent_device.command",params:r}),o={"content-type":"application/json","content-length":Buffer.byteLength(n)};return t.baseUrl&&t.token&&(o.authorization=`Bearer ${t.token}`,o["x-agent-device-token"]=t.token),await new Promise((e,s)=>{let d=h(r.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l=("https:"===a.protocol?i:A).request({protocol:a.protocol,host:a.hostname,port:a.port,method:"POST",path:a.pathname+a.search,headers:o},a=>{let n="";a.setEncoding("utf8"),a.on("data",e=>{n+=e}),a.on("end",()=>{clearTimeout(u);try{let a=JSON.parse(n);if(a.error){let e=a.error.data??{};s(new m(String(e.code??"COMMAND_FAILED"),String(e.message??a.error.message??"Daemon RPC request failed"),{..."object"==typeof e.details&&e.details?e.details:{},hint:"string"==typeof e.hint?e.hint:void 0,diagnosticId:"string"==typeof e.diagnosticId?e.diagnosticId:void 0,logPath:"string"==typeof e.logPath?e.logPath:void 0,requestId:r.meta?.requestId}));return}if(!a.result||"object"!=typeof a.result)return void s(new m("COMMAND_FAILED","Invalid daemon RPC response",{requestId:r.meta?.requestId}));if(t.baseUrl&&a.result.ok)return void Q(t,r,a.result).then(e).catch(s);e(a.result)}catch(e){clearTimeout(u),s(new m("COMMAND_FAILED","Invalid daemon response",{requestId:r.meta?.requestId,line:n},e instanceof Error?e:void 0))}})}),u=setTimeout(()=>{l.destroy();let e=W(t)?{terminated:0}:H(),a=W(t)?{forcedKill:!1}:K(t,d);c({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:D,requestId:r.meta?.requestId,command:r.command,timedOutRunnerPidsTerminated:e.terminated,timedOutRunnerCleanupError:e.error,daemonPidReset:W(t)?void 0:t.pid,daemonPidForceKilled:W(t)?void 0:a.forcedKill,daemonBaseUrl:t.baseUrl}}),s(new m("COMMAND_FAILED","Daemon request timed out",{timeoutMs:D,requestId:r.meta?.requestId,hint:W(t)?"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.":"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},D);l.on("error",e=>{clearTimeout(u),c({level:"error",phase:"daemon_request_socket_error",data:{requestId:r.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),s(new m("COMMAND_FAILED","Failed to communicate with daemon",{requestId:r.meta?.requestId,hint:W(t)?"Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.":"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e))}),l.write(n),l.end()})}function H(){let e=0;try{for(let t of E){let r=s("pkill",["-f",t],{allowFailure:!0});0===r.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}function K(e,t){let a=!1;try{r(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),a=!0)}catch{w(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{F(t.infoPath),F(t.lockPath)}return{forcedKill:a}}function W(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function J(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function Q(e,r,a){let n=Array.isArray(a.data?.artifacts)?a.data.artifacts:[];if(0===n.length||!e.baseUrl)return a;let o=a.data?{...a.data}:{},i=[];for(let a of n){if(!a||"object"!=typeof a||"string"!=typeof a.artifactId){i.push(a);continue}let n=function(e,r){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let a=e.fileName?.trim()||`${e.field}-${Date.now()}`;return t.resolve(r.meta?.cwd??process.cwd(),a)}(a,r);await X({baseUrl:e.baseUrl,token:e.token,artifactId:a.artifactId,destinationPath:n,requestId:r.meta?.requestId}),o[a.field]=n,i.push({...a,localPath:n})}return o.artifacts=i,{ok:!0,data:o}}async function X(e){var r,a;let n,o=new URL((r=e.baseUrl,a=e.artifactId,n=r.endsWith("/")?r:`${r}/`,new URL(`upload/${encodeURIComponent(a)}`,n).toString())),s="https:"===o.protocol?i:A;await p.promises.mkdir(t.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,r)=>{let a=!1,n=e.timeoutMs??D,i=n=>{if(!a){if(a=!0,clearTimeout(l),n)return void p.promises.rm(e.destinationPath,{force:!0}).finally(()=>r(n));t()}},d=s.request({protocol:o.protocol,host:o.hostname,port:o.port,method:"GET",path:o.pathname+o.search,headers:e.token?{authorization:`Bearer ${e.token}`,"x-agent-device-token":e.token}:void 0},t=>{if((t.statusCode??500)>=400){let r="";t.setEncoding("utf8"),t.on("data",e=>{r+=e}),t.on("end",()=>{i(new m("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:r}))});return}let r=p.createWriteStream(e.destinationPath);r.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{i(new m("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),r.on("finish",()=>{r.close(()=>i())}),t.pipe(r)}),l=setTimeout(()=>{d.destroy(new m("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n}))},n);d.on("error",t=>{t instanceof m?i(t):i(new m("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n},t instanceof Error?t:void 0))}),d.end()})}function Y(e,t){let r=ed(e,"bundleId"),a=ed(e,"package"),n=r??a;return{app:es(e,"app"),appPath:es(e,"appPath"),platform:ec(e,"platform"),appId:n,bundleId:r,package:a,identifiers:{session:t,appId:n,appBundleId:r,package:a}}}function Z(e,t){return{session:t,configured:!0===e.configured,cleared:!0===e.cleared||void 0,runtime:er(e.runtime),identifiers:{session:t}}}function ee(e){let t=eo(e),r=ec(t,"platform"),a=es(t,"id");return{platform:r,target:eu(t,"target"),kind:function(e,t){let r=e[t];if("simulator"===r||"emulator"===r||"device"===r)return r;throw new m("COMMAND_FAILED",`Daemon response has invalid "${t}".`,{response:e})}(t,"kind"),id:a,name:es(t,"name"),booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:{deviceId:a,deviceName:es(t,"name"),..."ios"===r?{udid:a}:{serial:a}},ios:"ios"===r?{udid:a}:void 0,android:"android"===r?{serial:a}:void 0}}function et(e){let t=eo(e),r=ec(t,"platform"),a=es(t,"id"),n=es(t,"name"),o=eu(t,"target"),i=es(t,"device"),s={session:n,deviceId:a,deviceName:i,..."ios"===r?{udid:a}:{serial:a}};return{name:n,createdAt:function(e,t){let r=e[t];if("number"!=typeof r||!Number.isFinite(r))throw new m("COMMAND_FAILED",`Daemon response is missing numeric "${t}".`,{response:e});return r}(t,"createdAt"),device:{platform:r,target:o,id:a,name:i,identifiers:s,ios:"ios"===r?{udid:a,simulatorSetPath:el(t,"ios_simulator_device_set")}:void 0,android:"android"===r?{serial:a}:void 0},identifiers:s}}function er(e){if(!ei(e))return;let t=e.platform,r=ed(e,"metroHost"),a="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:a,bundleUrl:ed(e,"bundleUrl"),launchUrl:ed(e,"launchUrl")}}function ea(e,t){return t??e??"default"}function en(e){let t={};for(let[r,a]of Object.entries(e))void 0!==a&&(t[r]=a);return t}function eo(e){if(!ei(e))throw new m("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function ei(e){return"object"==typeof e&&null!==e}function es(e,t){let r=e[t];if("string"!=typeof r||0===r.length)throw new m("COMMAND_FAILED",`Daemon response is missing "${t}".`,{response:e});return r}function ed(e,t){let r=e[t];return"string"==typeof r&&r.length>0?r:void 0}function el(e,t){let r=e[t];return null===r?null:"string"==typeof r&&r.length>0?r:void 0}function ec(e,t){let r=e[t];if("ios"===r||"android"===r)return r;throw new m("COMMAND_FAILED",`Daemon response has invalid "${t}".`,{response:e})}function eu(e,t){return"tv"===e[t]?"tv":"mobile"}function em(e={},t={}){let r=t.transport??P,a=async(t,a=[],n={})=>{let o={...e,...n},i=await r({session:ea(e.session,n.session),command:t,positionals:a,flags:en({stateDir:o.stateDir,daemonBaseUrl:o.daemonBaseUrl,daemonAuthToken:o.daemonAuthToken,daemonTransport:o.daemonTransport,daemonServerMode:o.daemonServerMode,tenant:o.tenant,sessionIsolation:o.sessionIsolation,runId:o.runId,leaseId:o.leaseId,platform:o.platform,target:o.target,device:o.device,udid:o.udid,serial:o.serial,iosSimulatorDeviceSet:o.iosSimulatorDeviceSet,androidDeviceAllowlist:o.androidDeviceAllowlist,runtime:o.simulatorRuntimeId,boot:o.boot,reuseExisting:o.reuseExisting,activity:o.activity,relaunch:o.relaunch,shutdown:o.shutdown,saveScript:o.saveScript,noRecord:o.noRecord,metroHost:o.metroHost,metroPort:o.metroPort,bundleUrl:o.bundleUrl,launchUrl:o.launchUrl,snapshotInteractiveOnly:o.interactiveOnly,snapshotCompact:o.compact,snapshotDepth:o.depth,snapshotScope:o.scope,snapshotRaw:o.raw,verbose:o.debug}),runtime:o.runtime,meta:en({requestId:o.requestId,cwd:o.cwd,debug:o.debug,lockPolicy:o.lockPolicy,lockPlatform:o.lockPlatform,tenantId:o.tenant,runId:o.runId,leaseId:o.leaseId,sessionIsolation:o.sessionIsolation,installSource:o.installSource,retainMaterializedPaths:o.retainMaterializedPaths,materializedPathRetentionMs:o.materializedPathRetentionMs,materializationId:o.materializationId})});if(!i.ok)throw new m(i.error.code,i.error.message,{...i.error.details??{},hint:i.error.hint,diagnosticId:i.error.diagnosticId,logPath:i.error.logPath});return i.data??{}},n=async(e={})=>{let t=await a("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(et)};return{devices:{list:async(e={})=>{let t=await a("devices",[],e);return(Array.isArray(t.devices)?t.devices:[]).map(ee)}},sessions:{list:async(e={})=>await n(e),close:async(t={})=>{let r=ea(e.session,t.session),n=(await a("close",[],t)).shutdown;return{session:r,shutdown:"object"==typeof n&&null!==n?n:void 0,identifiers:{session:r}}}},simulators:{ensure:async e=>{let{runtime:t,...r}=e,n=await a("ensure-simulator",[],{...r,simulatorRuntimeId:t}),o=es(n,"udid"),i=es(n,"device");return{udid:o,device:i,runtime:es(n,"runtime"),created:!0===n.created,booted:!0===n.booted,iosSimulatorDeviceSet:el(n,"ios_simulator_device_set"),identifiers:{deviceId:o,deviceName:i,udid:o}}}},apps:{install:async t=>Y(await a("install",[t.app,t.appPath],t),ea(e.session,t.session)),reinstall:async t=>Y(await a("reinstall",[t.app,t.appPath],t),ea(e.session,t.session)),installFromSource:async t=>(function(e,t){let r=ed(e,"bundleId"),a=ed(e,"packageName"),n=r??a??ed(e,"appId"),o=ed(e,"launchTarget")??a??r??n;if(!o)throw new m("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:ed(e,"appName"),appId:n,bundleId:r,packageName:a,launchTarget:o,installablePath:ed(e,"installablePath"),archivePath:ed(e,"archivePath"),materializationId:ed(e,"materializationId"),materializationExpiresAt:ed(e,"materializationExpiresAt"),identifiers:{session:t,appId:n,appBundleId:r,package:a}}})(await a("install_source",[],{...t,installSource:t.source,retainMaterializedPaths:t.retainPaths,materializedPathRetentionMs:t.retentionMs}),ea(e.session,t.session)),open:async t=>{let r=ea(e.session,t.session),n=t.url?[t.app,t.url]:[t.app],o=await a("open",n,t),i=function(e){let t=e.platform,r=ed(e,"id"),a=ed(e,"device");if("ios"!==t&&"android"!==t||!r||!a)return;let n=eu(e,"target"),o={deviceId:r,deviceName:a,..."ios"===t?{udid:r}:{serial:r}};return{platform:t,target:n,id:r,name:a,identifiers:o,ios:"ios"===t?{udid:ed(e,"device_udid")??r,simulatorSetPath:el(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:ed(e,"serial")??r}:void 0}}(o),s=ed(o,"appBundleId");return{session:r,appName:ed(o,"appName"),appBundleId:s,appId:s,startup:function(e){if(ei(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:ed(e,"appTarget"),appBundleId:ed(e,"appBundleId")}}(o.startup),runtime:er(o.runtime),device:i,identifiers:{session:r,deviceId:i?.id,deviceName:i?.name,udid:i?.ios?.udid,serial:i?.android?.serial,appId:s,appBundleId:s}}},close:async(t={})=>{let r=ea(e.session,t.session),n=(await a("close",t.app?[t.app]:[],t)).shutdown;return{session:r,closedApp:t.app,shutdown:"object"==typeof n&&null!==n?n:void 0,identifiers:{session:r}}}},materializations:{release:async e=>{var t;return{released:!0===(t=await a("release_materialized_paths",[],{...e,materializationId:e.materializationId})).released,materializationId:es(t,"materializationId"),identifiers:{}}}},runtime:{set:async t=>Z(await a("runtime",["set"],t),ea(e.session,t.session)),show:async(t={})=>Z(await a("runtime",["show"],t),ea(e.session,t.session))},capture:{snapshot:async(t={})=>{var r;let n=ea(e.session,t.session),o=await a("snapshot",[],t),i=ed(o,"appBundleId");return{nodes:Array.isArray(r=o.nodes)?r:[],truncated:!0===o.truncated,appName:ed(o,"appName"),appBundleId:i,identifiers:{session:n,appId:i,appBundleId:i}}},screenshot:async(t={})=>{let r=ea(e.session,t.session);return{path:es(await a("screenshot",t.path?[t.path]:[],t),"path"),identifiers:{session:r}}}}}}export{em as createAgentDeviceClient,P as sendToDaemon};
1
+ import{createRequestId as e,node_path as t,isAgentDeviceDaemonProcess as r,runCmdDetached as a,readVersion as n,findProjectRoot as o,node_https as i,runCmdSync as s,withDiagnosticTimer as d,resolveDaemonTransportPreference as l,emitDiagnostic as u,spawn as c,AppError as p,node_fs as m,resolveDaemonPaths as f,node_net as h,resolveDaemonServerMode as I,stopProcessForTakeover as v,node_http as w}from"./331.js";async function g(e){let{localPath:r,baseUrl:a,token:n}=e,o=m.statSync(r).isDirectory(),s=t.basename(r),d=new URL("upload",a.endsWith("/")?a:`${a}/`),l="https:"===d.protocol?i:w,u={"x-artifact-type":o?"app-bundle":"file","x-artifact-filename":s,"transfer-encoding":"chunked"};return n&&(u.authorization=`Bearer ${n}`,u["x-agent-device-token"]=n),new Promise((e,a)=>{let n=l.request({protocol:d.protocol,host:d.hostname,port:d.port,method:"POST",path:d.pathname+d.search,headers:u},t=>{let r="";t.setEncoding("utf8"),t.on("data",e=>{r+=e}),t.on("end",()=>{clearTimeout(i);try{let t=JSON.parse(r);if(!t.ok||!t.uploadId)return void a(new p("COMMAND_FAILED",`Upload failed: ${r}`));e(t.uploadId)}catch{a(new p("COMMAND_FAILED",`Invalid upload response: ${r}`))}})}),i=setTimeout(()=>{n.destroy(),a(new p("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(n.on("error",e=>{clearTimeout(i),a(new p("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),o){let e=c("tar",["cf","-","-C",t.dirname(r),t.basename(r)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(n),e.on("error",e=>{n.destroy(),a(new p("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(n.destroy(),a(new p("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=m.createReadStream(r);e.pipe(n),e.on("error",e=>{n.destroy(),a(new p("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}let A=function(e=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if(!e)return 9e4;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):9e4}(),y=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS){if(!e)return 15e3;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):15e3}(),D=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_ATTEMPTS){if(!e)return 2;let t=Number(e);return Number.isFinite(t)?Math.min(5,Math.max(1,Math.floor(t))):2}(),_=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];async function b(t){let r=t.meta?.requestId??e(),a=!!(t.meta?.debug||t.flags?.verbose),n=function(e){let t=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,r=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new p("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new p("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(e.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),a=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN,n=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,o=l(n);if(r&&"socket"===o)throw new p("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:r});let i=I(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===n?"dual":void 0));return{paths:f(t),transportPreference:o,serverMode:i,remoteBaseUrl:r,remoteAuthToken:a}}(t),o=await d("daemon_startup",async()=>await T(n),{requestId:r,session:t.session}),i=await P(t,o),s={...t,positionals:i.positionals,flags:i.flags,token:o.token,meta:{...t.meta??{},requestId:r,debug:a,cwd:t.meta?.cwd,tenantId:t.meta?.tenantId??t.flags?.tenant,runId:t.meta?.runId??t.flags?.runId,leaseId:t.meta?.leaseId??t.flags?.leaseId,sessionIsolation:t.meta?.sessionIsolation??t.flags?.sessionIsolation,lockPolicy:t.meta?.lockPolicy,lockPlatform:t.meta?.lockPlatform,...i.uploadedArtifactId?{uploadedArtifactId:i.uploadedArtifactId}:{},...i.clientArtifactPaths?{clientArtifactPaths:i.clientArtifactPaths}:{},...i.installSource?{installSource:i.installSource}:{}}};return u({level:"info",phase:"daemon_request_prepare",data:{requestId:r,command:t.command,session:t.session}}),await d("daemon_request",async()=>await B(o,s,n.transportPreference),{requestId:r,command:t.command})}async function P(e,r){let a,n=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,i=e.meta?.installSource,s={};if(J(r)){let d=function(e,r){if("screenshot"===e.command){let t=S(e,"path",".png");return r[0]?{field:"path",localPath:t,positionalIndex:0,positionalPath:M("screenshot",".png")}:{field:"path",localPath:t,positionalIndex:0,flagPath:M("screenshot",".png")}}if("record"===e.command&&"start"===(r[0]??"").toLowerCase()){let r=S(e,"outPath",".mp4",1);return{field:"outPath",localPath:r,positionalIndex:1,positionalPath:M("recording",t.extname(r)||".mp4")}}return null}(e,n);d&&(void 0!==d.positionalPath&&(n[d.positionalIndex]=d.positionalPath),void 0!==d.flagPath&&((o??={}).out=d.flagPath),s[d.field]=d.localPath);let l=await E(e,r);l&&(i=l.installSource,a=l.uploadedArtifactId??a)}if(!J(r)||"install"!==e.command&&"reinstall"!==e.command||n.length<2)return{positionals:n,flags:o,installSource:i,uploadedArtifactId:a,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}};let d=n[1];if(d.startsWith("remote:"))return n[1]=d.slice(7),{positionals:n,flags:o,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}};let l=t.isAbsolute(d)?d:t.resolve(e.meta?.cwd??process.cwd(),d);return m.existsSync(l)?{positionals:n,flags:o,installSource:i,uploadedArtifactId:a=await g({localPath:l,baseUrl:r.baseUrl,token:r.token}),...Object.keys(s).length>0?{clientArtifactPaths:s}:{}}:{positionals:n,flags:o,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}}}async function E(e,r){let a=e.meta?.installSource;if("install_source"!==e.command||!a||"path"!==a.kind)return null;let n=a.path.trim();if(!n)return{installSource:a};if(n.startsWith("remote:"))return{installSource:{...a,path:n.slice(7)}};let o=t.isAbsolute(n)?n:t.resolve(e.meta?.cwd??process.cwd(),n);if(!m.existsSync(o))return{installSource:{...a,path:o}};let i=await g({localPath:o,baseUrl:r.baseUrl,token:r.token});return{installSource:{...a,path:o},uploadedArtifactId:i}}function S(e,r,a,n=0){let o=e.positionals?.[n]??e.flags?.out,i=`${"path"===r?"screenshot":"recording"}-${Date.now()}${a}`,s=o&&o.trim().length>0?o:i;return t.isAbsolute(s)?s:t.resolve(e.meta?.cwd??process.cwd(),s)}function M(e,r){let a=r.startsWith(".")?r:`.${r}`;return t.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${a}`)}async function T(e){let a;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await x(t,"http"))return t;throw new p("COMMAND_FAILED","Remote daemon is unavailable",{daemonBaseUrl:e.remoteBaseUrl,hint:"Verify AGENT_DEVICE_DAEMON_BASE_URL points to a reachable daemon with GET /health and POST /rpc."})}let i=U(e.paths.infoPath),s=n(),d=function(e,r=o()){try{let a=m.statSync(e),n=t.relative(r,e)||e;return`${n}:${a.size}:${Math.trunc(a.mtimeMs)}`}catch{return"unknown"}}((a=z()).useSrc?a.srcPath:a.distPath,a.root),l=!!i&&await x(i,e.transportPreference);if(i&&i.version===s&&i.codeSignature===d&&l)return i;i&&(i.version!==s||i.codeSignature!==d||!l)&&(await O(i),F(e.paths.infoPath)),function(e){let t=L(e);if(!t.hasLock||t.hasInfo)return;let a=C(e.lockPath);if(!a)return F(e.lockPath);r(a.pid,a.processStartTime)||F(e.lockPath)}(e.paths);let u=0;for(let t=1;t<=D;t+=1){await $(e);let r=await N(y,e);if(r)return r;if(await R(e.paths)){u+=1;continue}let a=L(e.paths);if(!(t<D))break;if(!a.hasInfo&&!a.hasLock){await k(150);continue}}let c=L(e.paths);throw new p("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:y,startupAttempts:D,lockRecoveryCount:u,metadataState:c,hint:function(e,t=f(process.env.AGENT_DEVICE_STATE_DIR)){return e.hasLock&&!e.hasInfo?`Detected ${t.lockPath} without ${t.infoPath}. If no agent-device daemon process is running, delete ${t.lockPath} and retry.`:e.hasLock&&e.hasInfo?`Daemon metadata may be stale. If no agent-device daemon process is running, delete ${t.infoPath} and ${t.lockPath}, then retry.`:`Daemon metadata is missing or stale. Delete ${t.infoPath} if present and retry.`}(c,e.paths)})}async function N(e,t){let r=Date.now();for(;Date.now()-r<e;){let e=U(t.paths.infoPath);if(e&&await x(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function k(e){await new Promise(t=>setTimeout(t,e))}async function R(e){let t=L(e);if(!t.hasLock||t.hasInfo)return!1;let a=C(e.lockPath);return a&&r(a.pid,a.processStartTime)&&await v(a.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:a.processStartTime}),F(e.lockPath),!0}async function O(e){await v(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function U(e){let t=q(e);if(!t||"object"!=typeof t)return null;let r="string"==typeof t.token&&t.token.length>0?t.token:null;if(!r)return null;let a=Number.isInteger(t.port)&&Number(t.port)>0,n=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;if(!a&&!n)return null;let o=t.transport,i="string"==typeof t.version?t.version:void 0,s="string"==typeof t.codeSignature?t.codeSignature:void 0,d="string"==typeof t.processStartTime?t.processStartTime:void 0,l=Number.isInteger(t.pid)&&Number(t.pid)>0;return{token:r,port:a?Number(t.port):void 0,httpPort:n?Number(t.httpPort):void 0,transport:"socket"===o||"http"===o||"dual"===o?o:void 0,pid:l?Number(t.pid):0,version:i,codeSignature:s,processStartTime:d}}function C(e){let t=q(e);return t&&"object"==typeof t&&Number.isInteger(t.pid)&&Number(t.pid)>0?{pid:Number(t.pid),processStartTime:"string"==typeof t.processStartTime?t.processStartTime:void 0,startedAt:"number"==typeof t.startedAt?t.startedAt:void 0}:null}function L(e){return{hasInfo:m.existsSync(e.infoPath),hasLock:m.existsSync(e.lockPath)}}function q(e){if(!m.existsSync(e))return null;try{return JSON.parse(m.readFileSync(e,"utf8"))}catch{return null}}function F(e){try{m.existsSync(e)&&m.unlinkSync(e)}catch{}}async function x(e,t){var r;return"http"===G(e,t)?await function(e){let t=e.baseUrl?Q(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!t)return Promise.resolve(!1);let r=new URL(t),a="https:"===r.protocol?i:w,n=e.baseUrl?3e3:500;return new Promise(e=>{let t=a.request({protocol:r.protocol,host:r.hostname,port:r.port,path:r.pathname+r.search,method:"GET",timeout:n},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(e):await ((r=e.port)?new Promise(e=>{let t=h.createConnection({host:"127.0.0.1",port:r},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function $(e){let t=z(),r=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};a(process.execPath,r,{env:n})}function z(){let e=o(),r=t.join(e,"dist","src","daemon.js"),a=t.join(e,"src","daemon.ts"),n=m.existsSync(r),i=m.existsSync(a);if(!n&&!i)throw new p("COMMAND_FAILED","Daemon entry not found",{distPath:r,srcPath:a});return{root:e,distPath:r,srcPath:a,useSrc:process.execArgv.includes("--experimental-strip-types")?i:!n&&i}}async function B(e,t,r){return"http"===G(e,r)?await H(e,t):await j(e,t)}function G(e,t){if(e.baseUrl){if("socket"===t)throw new p("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var r=e,a=t;if(V(r,a))return a;throw new p("COMMAND_FAILED","http"===a?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let n=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>V(e,t));if(n)return n;throw new p("COMMAND_FAILED","Daemon metadata has no reachable transport")}function V(e,t){return"http"===t?!!e.httpPort:!!e.port}async function j(e,t){let r=e.port;if(!r)throw new p("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((a,n)=>{let o=h.createConnection({host:"127.0.0.1",port:r},()=>{o.write(`${JSON.stringify(t)}
2
+ `)}),i=setTimeout(()=>{o.destroy();let r=K(),a=W(e,f(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR));u({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:A,requestId:t.meta?.requestId,command:t.command,timedOutRunnerPidsTerminated:r.terminated,timedOutRunnerCleanupError:r.error,daemonPidReset:e.pid,daemonPidForceKilled:a.forcedKill}}),n(new p("COMMAND_FAILED","Daemon request timed out",{timeoutMs:A,requestId:t.meta?.requestId,hint:"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},A),s="";o.setEncoding("utf8"),o.on("data",e=>{let r=(s+=e).indexOf("\n");if(-1===r)return;let d=s.slice(0,r).trim();if(d)try{let e=JSON.parse(d);o.end(),clearTimeout(i),a(e)}catch(e){clearTimeout(i),n(new p("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:d},e instanceof Error?e:void 0))}}),o.on("error",e=>{clearTimeout(i),u({level:"error",phase:"daemon_request_socket_error",data:{requestId:t.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),n(new p("COMMAND_FAILED","Failed to communicate with daemon",{requestId:t.meta?.requestId,hint:"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e))})})}async function H(t,r){let a=t.baseUrl?new URL(Q(t.baseUrl,"rpc")):t.httpPort?new URL(`http://127.0.0.1:${t.httpPort}/rpc`):null;if(!a)throw new p("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let n=JSON.stringify({jsonrpc:"2.0",id:r.meta?.requestId??e(),method:"agent_device.command",params:r}),o={"content-type":"application/json","content-length":Buffer.byteLength(n)};return t.baseUrl&&t.token&&(o.authorization=`Bearer ${t.token}`,o["x-agent-device-token"]=t.token),await new Promise((e,s)=>{let d=f(r.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l=("https:"===a.protocol?i:w).request({protocol:a.protocol,host:a.hostname,port:a.port,method:"POST",path:a.pathname+a.search,headers:o},a=>{let n="";a.setEncoding("utf8"),a.on("data",e=>{n+=e}),a.on("end",()=>{clearTimeout(c);try{let a=JSON.parse(n);if(a.error){let e=a.error.data??{};s(new p(String(e.code??"COMMAND_FAILED"),String(e.message??a.error.message??"Daemon RPC request failed"),{..."object"==typeof e.details&&e.details?e.details:{},hint:"string"==typeof e.hint?e.hint:void 0,diagnosticId:"string"==typeof e.diagnosticId?e.diagnosticId:void 0,logPath:"string"==typeof e.logPath?e.logPath:void 0,requestId:r.meta?.requestId}));return}if(!a.result||"object"!=typeof a.result)return void s(new p("COMMAND_FAILED","Invalid daemon RPC response",{requestId:r.meta?.requestId}));if(t.baseUrl&&a.result.ok)return void X(t,r,a.result).then(e).catch(s);e(a.result)}catch(e){clearTimeout(c),s(new p("COMMAND_FAILED","Invalid daemon response",{requestId:r.meta?.requestId,line:n},e instanceof Error?e:void 0))}})}),c=setTimeout(()=>{l.destroy();let e=J(t)?{terminated:0}:K(),a=J(t)?{forcedKill:!1}:W(t,d);u({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:A,requestId:r.meta?.requestId,command:r.command,timedOutRunnerPidsTerminated:e.terminated,timedOutRunnerCleanupError:e.error,daemonPidReset:J(t)?void 0:t.pid,daemonPidForceKilled:J(t)?void 0:a.forcedKill,daemonBaseUrl:t.baseUrl}}),s(new p("COMMAND_FAILED","Daemon request timed out",{timeoutMs:A,requestId:r.meta?.requestId,hint:J(t)?"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.":"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},A);l.on("error",e=>{clearTimeout(c),u({level:"error",phase:"daemon_request_socket_error",data:{requestId:r.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),s(new p("COMMAND_FAILED","Failed to communicate with daemon",{requestId:r.meta?.requestId,hint:J(t)?"Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.":"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e))}),l.write(n),l.end()})}function K(){let e=0;try{for(let t of _){let r=s("pkill",["-f",t],{allowFailure:!0});0===r.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}function W(e,t){let a=!1;try{r(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),a=!0)}catch{v(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{F(t.infoPath),F(t.lockPath)}return{forcedKill:a}}function J(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function Q(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function X(e,r,a){let n=Array.isArray(a.data?.artifacts)?a.data.artifacts:[];if(0===n.length||!e.baseUrl)return a;let o=a.data?{...a.data}:{},i=[];for(let a of n){if(!a||"object"!=typeof a||"string"!=typeof a.artifactId){i.push(a);continue}let n=function(e,r){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let a=e.fileName?.trim()||`${e.field}-${Date.now()}`;return t.resolve(r.meta?.cwd??process.cwd(),a)}(a,r);await Y({baseUrl:e.baseUrl,token:e.token,artifactId:a.artifactId,destinationPath:n,requestId:r.meta?.requestId}),o[a.field]=n,i.push({...a,localPath:n})}return o.artifacts=i,{ok:!0,data:o}}async function Y(e){var r,a;let n,o=new URL((r=e.baseUrl,a=e.artifactId,n=r.endsWith("/")?r:`${r}/`,new URL(`upload/${encodeURIComponent(a)}`,n).toString())),s="https:"===o.protocol?i:w;await m.promises.mkdir(t.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,r)=>{let a=!1,n=e.timeoutMs??A,i=n=>{if(!a){if(a=!0,clearTimeout(l),n)return void m.promises.rm(e.destinationPath,{force:!0}).finally(()=>r(n));t()}},d=s.request({protocol:o.protocol,host:o.hostname,port:o.port,method:"GET",path:o.pathname+o.search,headers:e.token?{authorization:`Bearer ${e.token}`,"x-agent-device-token":e.token}:void 0},t=>{if((t.statusCode??500)>=400){let r="";t.setEncoding("utf8"),t.on("data",e=>{r+=e}),t.on("end",()=>{i(new p("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:r}))});return}let r=m.createWriteStream(e.destinationPath);r.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{i(new p("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),r.on("finish",()=>{r.close(()=>i())}),t.pipe(r)}),l=setTimeout(()=>{d.destroy(new p("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n}))},n);d.on("error",t=>{t instanceof p?i(t):i(new p("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n},t instanceof Error?t:void 0))}),d.end()})}function Z(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function ee(e,t,r){return{deviceId:t,deviceName:r,..."ios"===e?{udid:t}:{serial:t}}}function et(e,t={}){let r=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&&r?{serial:e.android?.serial??e.id}:{}}}function er(e){return{name:e.name,...et(e.device,{includeAndroidSerial:!1}),createdAt:e.createdAt}}function ea(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 en(e){return{udid:e.udid,device:e.device,runtime:e.runtime,ios_simulator_device_set:e.iosSimulatorDeviceSet??null,created:e.created,booted:e.booted}}function eo(e){return{session:e.session,configured:e.configured,...e.cleared?{cleared:!0}:{},...e.runtime?{runtime:e.runtime}:{}}}function ei(e){return{app:e.app,appPath:e.appPath,platform:e.platform,...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.package?{package:e.package}:{}}}function es(e){return{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?et(e.device):{}}}function ed(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{}}}function el(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{}}}function eu(e,t){let r=eA(e,"bundleId"),a=eA(e,"package");return{app:eg(e,"app"),appPath:eg(e,"appPath"),platform:ey(e,"platform"),appId:r??a,bundleId:r,package:a,identifiers:Z({session:t,bundleId:r,packageName:a})}}function ec(e,t){return{session:t,configured:!0===e.configured,cleared:!0===e.cleared||void 0,runtime:ef(e.runtime),identifiers:{session:t}}}function ep(e){var t;let r=ev(e),a=ey(r,"platform"),n=eg(r,"id"),o=eg(r,"name");return{platform:a,target:eD(r,"target"),kind:e_(r,t="kind",eM,`Daemon response has invalid "${t}".`),id:n,name:o,booted:"boolean"==typeof r.booted?r.booted:void 0,identifiers:ee(a,n,o),ios:"ios"===a?{udid:n}:void 0,android:"android"===a?{serial:n}:void 0}}function em(e){var t;let r=ev(e),a=ey(r,"platform"),n=eg(r,"id"),o=eg(r,"name"),i=eD(r,"target"),s=eg(r,"device"),d={session:o,...ee(a,n,s)};return{name:o,createdAt:e_(r,t="createdAt",eE,`Daemon response is missing numeric "${t}".`),device:{platform:a,target:i,id:n,name:s,identifiers:d,ios:"ios"===a?{udid:n,simulatorSetPath:eb(r,"ios_simulator_device_set",eP)}:void 0,android:"android"===a?{serial:n}:void 0},identifiers:d}}function ef(e){if(!ew(e))return;let t=e.platform,r=eA(e,"metroHost"),a="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:a,bundleUrl:eA(e,"bundleUrl"),launchUrl:eA(e,"launchUrl")}}function eh(e,t){return t??e??"default"}function eI(e){let t={};for(let[r,a]of Object.entries(e))void 0!==a&&(t[r]=a);return t}function ev(e){if(!ew(e))throw new p("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function ew(e){return"object"==typeof e&&null!==e}function eg(e,t){return e_(e,t,eP,`Daemon response is missing "${t}".`)}function eA(e,t){return eP(e[t])}function ey(e,t){return e_(e,t,eS,`Daemon response has invalid "${t}".`)}function eD(e,t){return eT(e[t])??"mobile"}function e_(e,t,r,a){let n=r(e[t]);if(void 0===n)throw new p("COMMAND_FAILED",a,{response:e});return n}function eb(e,t,r){let a=e[t];return null===a?null:r(a)}function eP(e){return"string"==typeof e&&e.length>0?e:void 0}function eE(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function eS(e){return"ios"===e||"android"===e?e:void 0}function eM(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function eT(e){return"tv"===e?"tv":"mobile"===e?"mobile":void 0}function eN(e={},t={}){let r=t.transport??b,a=async(t,a=[],n={})=>{let o={...e,...n},i=await r({session:eh(e.session,n.session),command:t,positionals:a,flags:eI({stateDir:o.stateDir,daemonBaseUrl:o.daemonBaseUrl,daemonAuthToken:o.daemonAuthToken,daemonTransport:o.daemonTransport,daemonServerMode:o.daemonServerMode,tenant:o.tenant,sessionIsolation:o.sessionIsolation,runId:o.runId,leaseId:o.leaseId,platform:o.platform,target:o.target,device:o.device,udid:o.udid,serial:o.serial,iosSimulatorDeviceSet:o.iosSimulatorDeviceSet,androidDeviceAllowlist:o.androidDeviceAllowlist,runtime:o.simulatorRuntimeId,boot:o.boot,reuseExisting:o.reuseExisting,activity:o.activity,relaunch:o.relaunch,shutdown:o.shutdown,saveScript:o.saveScript,noRecord:o.noRecord,metroHost:o.metroHost,metroPort:o.metroPort,bundleUrl:o.bundleUrl,launchUrl:o.launchUrl,snapshotInteractiveOnly:o.interactiveOnly,snapshotCompact:o.compact,snapshotDepth:o.depth,snapshotScope:o.scope,snapshotRaw:o.raw,verbose:o.debug}),runtime:o.runtime,meta:eI({requestId:o.requestId,cwd:o.cwd,debug:o.debug,lockPolicy:o.lockPolicy,lockPlatform:o.lockPlatform,tenantId:o.tenant,runId:o.runId,leaseId:o.leaseId,sessionIsolation:o.sessionIsolation,installSource:o.installSource,retainMaterializedPaths:o.retainMaterializedPaths,materializedPathRetentionMs:o.materializedPathRetentionMs,materializationId:o.materializationId})});if(!i.ok)throw new p(i.error.code,i.error.message,{...i.error.details??{},hint:i.error.hint,diagnosticId:i.error.diagnosticId,logPath:i.error.logPath});return i.data??{}},n=async(e={})=>{let t=await a("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(em)};return{devices:{list:async(e={})=>{let t=await a("devices",[],e);return(Array.isArray(t.devices)?t.devices:[]).map(ep)}},sessions:{list:async(e={})=>await n(e),close:async(t={})=>{let r=eh(e.session,t.session),n=(await a("close",[],t)).shutdown;return{session:r,shutdown:"object"==typeof n&&null!==n?n:void 0,identifiers:{session:r}}}},simulators:{ensure:async e=>{let{runtime:t,...r}=e,n=await a("ensure-simulator",[],{...r,simulatorRuntimeId:t}),o=eg(n,"udid"),i=eg(n,"device");return{udid:o,device:i,runtime:eg(n,"runtime"),created:!0===n.created,booted:!0===n.booted,iosSimulatorDeviceSet:eb(n,"ios_simulator_device_set",eP),identifiers:{deviceId:o,deviceName:i,udid:o}}}},apps:{install:async t=>eu(await a("install",[t.app,t.appPath],t),eh(e.session,t.session)),reinstall:async t=>eu(await a("reinstall",[t.app,t.appPath],t),eh(e.session,t.session)),installFromSource:async t=>(function(e,t){let r=eA(e,"bundleId"),a=eA(e,"packageName"),n=r??a??eA(e,"appId"),o=eA(e,"launchTarget")??a??r??n;if(!o)throw new p("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:eA(e,"appName"),appId:n,bundleId:r,packageName:a,launchTarget:o,installablePath:eA(e,"installablePath"),archivePath:eA(e,"archivePath"),materializationId:eA(e,"materializationId"),materializationExpiresAt:eA(e,"materializationExpiresAt"),identifiers:Z({session:t,bundleId:r,packageName:a,appId:n})}})(await a("install_source",[],{...t,installSource:t.source,retainMaterializedPaths:t.retainPaths,materializedPathRetentionMs:t.retentionMs}),eh(e.session,t.session)),open:async t=>{let r=eh(e.session,t.session),n=t.url?[t.app,t.url]:[t.app],o=await a("open",n,t),i=function(e){let t=e.platform,r=eA(e,"id"),a=eA(e,"device");if("ios"!==t&&"android"!==t||!r||!a)return;let n=eD(e,"target"),o=ee(t,r,a);return{platform:t,target:n,id:r,name:a,identifiers:o,ios:"ios"===t?{udid:eA(e,"device_udid")??r,simulatorSetPath:eb(e,"ios_simulator_device_set",eP)}:void 0,android:"android"===t?{serial:eA(e,"serial")??r}:void 0}}(o),s=eA(o,"appBundleId");return{session:r,appName:eA(o,"appName"),appBundleId:s,appId:s,startup:function(e){if(ew(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:eA(e,"appTarget"),appBundleId:eA(e,"appBundleId")}}(o.startup),runtime:ef(o.runtime),device:i,identifiers:{session:r,deviceId:i?.id,deviceName:i?.name,udid:i?.ios?.udid,serial:i?.android?.serial,appId:s,appBundleId:s}}},close:async(t={})=>{let r=eh(e.session,t.session),n=(await a("close",t.app?[t.app]:[],t)).shutdown;return{session:r,closedApp:t.app,shutdown:"object"==typeof n&&null!==n?n:void 0,identifiers:{session:r}}}},materializations:{release:async e=>{var t;return{released:!0===(t=await a("release_materialized_paths",[],{...e,materializationId:e.materializationId})).released,materializationId:eg(t,"materializationId"),identifiers:{}}}},runtime:{set:async t=>ec(await a("runtime",["set"],t),eh(e.session,t.session)),show:async(t={})=>ec(await a("runtime",["show"],t),eh(e.session,t.session))},capture:{snapshot:async(t={})=>{var r;let n=eh(e.session,t.session),o=await a("snapshot",[],t),i=eA(o,"appBundleId");return{nodes:Array.isArray(r=o.nodes)?r:[],truncated:!0===o.truncated,appName:eA(o,"appName"),appBundleId:i,identifiers:{session:n,appId:i,appBundleId:i}}},screenshot:async(t={})=>{let r=eh(e.session,t.session);return{path:eg(await a("screenshot",t.path?[t.path]:[],t),"path"),identifiers:{session:r}}}}}}export{eN as createAgentDeviceClient,b as sendToDaemon,ed as serializeCloseResult,ei as serializeDeployResult,ea as serializeDevice,en as serializeEnsureSimulatorResult,es as serializeOpenResult,eo as serializeRuntimeResult,er as serializeSessionListEntry,el as serializeSnapshotResult};
package/dist/src/331.js CHANGED
@@ -1,3 +1,3 @@
1
1
  import{URL as e,fileURLToPath as t,pathToFileURL as r}from"node:url";import{spawn as n,spawnSync as o}from"node:child_process";import i from"node:os";import s,{promises as a}from"node:fs";import d from"node:path";import{AsyncLocalStorage as u}from"node:async_hooks";import c from"node:crypto";let l=new u,f=/(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 p(){return c.randomBytes(8).toString("hex")}async function h(e,t){let r={...e,diagnosticId:`${Date.now().toString(36)}-${c.randomBytes(4).toString("hex")}`,events:[]};return await l.run(r,t)}function g(){let e=l.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug}:{}}function w(e){let t=l.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?D(e.data):void 0};if(t.events.push(r),!t.debug)return;let n=`[agent-device][diag] ${JSON.stringify(r)}
2
2
  `;try{t.logPath&&s.appendFile(t.logPath,n,()=>{}),t.traceLogPath&&s.appendFile(t.traceLogPath,n,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(n)}catch{}}async function S(e,t,r){let n=Date.now();try{let o=await t();return w({level:"info",phase:e,durationMs:Date.now()-n,data:r}),o}catch(t){throw w({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,"_"),r=new Date().toISOString().slice(0,10),n=d.join(i.homedir(),".agent-device","logs",e,r);s.mkdirSync(n,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),a=d.join(n,`${o}-${t.diagnosticId}.ndjson`),u=t.events.map(e=>JSON.stringify(D(e)));return s.writeFileSync(a,`${u.join("\n")}
3
- `),t.events=[],a}catch{return null}}function D(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&&f.test(i)||m.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(f.test(n)){s[n]="[REDACTED]";continue}s[n]=e(o,r,n)}return s}(e,new WeakSet)}class v extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function y(e){return e instanceof v?e:e instanceof Error?new v("UNKNOWN",e.message,void 0,e):new v("UNKNOWN","Unknown error",{err:e})}function I(e,t={}){let r=y(e),n=r.details?D(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"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}}async function M(e,t,r={}){return new Promise((o,i)=>{let s=n(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached}),a="",d=r.binaryStdout?Buffer.alloc(0):void 0,u="",c=!1,l=C(r.timeoutMs),f=l?setTimeout(()=>{c=!0,s.kill("SIGKILL")},l):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?d=Buffer.concat([d??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):a+=e}),s.stderr.on("data",e=>{u+=e}),s.on("error",r=>{(f&&clearTimeout(f),"ENOENT"===r.code)?i(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):i(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),s.on("close",n=>{f&&clearTimeout(f);let s=n??1;c&&l?i(new v("COMMAND_FAILED",`${e} timed out after ${l}ms`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:s,timeoutMs:l})):0===s||r.allowFailure?o({stdout:a,stderr:u,exitCode:s,stdoutBuffer:d}):i(new v("COMMAND_FAILED",`${e} exited with code ${s}`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:s,processExitError:!0}))})})}async function A(e){try{var t;let{shell:r,args:n}=(t=e,"win32"===process.platform?{shell:"cmd.exe",args:["/c","where",t]}:{shell:"bash",args:["-lc",`command -v ${t}`]}),o=await M(r,n,{allowFailure:!0});return 0===o.exitCode&&o.stdout.trim().length>0}catch{return!1}}function N(e,t,r={}){let n=o(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:C(r.timeoutMs)});if(n.error){let o=n.error.code;if("ETIMEDOUT"===o)throw new v("COMMAND_FAILED",`${e} timed out after ${C(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:C(r.timeoutMs)},n.error);if("ENOENT"===o)throw new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},n.error);throw new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},n.error)}let i=r.binaryStdout?Buffer.isBuffer(n.stdout)?n.stdout:Buffer.from(n.stdout??""):void 0,s=r.binaryStdout?"":"string"==typeof n.stdout?n.stdout:(n.stdout??"").toString(),a="string"==typeof n.stderr?n.stderr:(n.stderr??"").toString(),d=n.status??1;if(0!==d&&!r.allowFailure)throw new v("COMMAND_FAILED",`${e} 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 O(e,t,r={}){n(e,t,{cwd:r.cwd,env:r.env,stdio:"ignore",detached:!0}).unref()}async function T(e,t,r={}){return new Promise((o,i)=>{let s=n(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached});r.onSpawn?.(s);let a="",d="",u=r.binaryStdout?Buffer.alloc(0):void 0;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){u=Buffer.concat([u??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);d+=t,r.onStderrChunk?.(t)}),s.on("error",r=>{"ENOENT"===r.code?i(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):i(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),s.on("close",n=>{let s=n??1;0===s||r.allowFailure?o({stdout:a,stderr:d,exitCode:s,stdoutBuffer:u}):i(new v("COMMAND_FAILED",`${e} exited with code ${s}`,{cmd:e,args:t,stdout:a,stderr:d,exitCode:s,processExitError:!0}))})})}function _(e,t,r={}){let o=n(e,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached}),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((n,a)=>{o.on("error",r=>{"ENOENT"===r.code?a(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):a(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),o.on("close",o=>{let d=o??1;0===d||r.allowFailure?n({stdout:i,stderr:s,exitCode:d}):a(new v("COMMAND_FAILED",`${e} exited with code ${d}`,{cmd:e,args:t,stdout:i,stderr:s,exitCode:d,processExitError:!0}))})});return{child:o,wait:a}}function C(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function P(){try{let e=L();return JSON.parse(s.readFileSync(d.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function L(){let e=d.dirname(t(import.meta.url)),r=e;for(let e=0;e<6;e+=1){let e=d.join(r,"package.json");if(s.existsSync(e))return r;r=d.dirname(r)}return e}let F=[/(^|[\/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[\/\s"'=])src\/daemon\.ts($|[\s"'])/];function $(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function k(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=N("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 b(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=N("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 x(e,t){let r;if(!$(e))return!1;if(t){let r=k(e);if(!r||r!==t)return!1}let n=b(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&F.some(e=>e.test(r))}function R(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 j(e,t){if(!$(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!$(e))return!0;return!$(e)}async function B(e,t){!x(e,t.expectedStartTime)||!R(e,"SIGTERM")||await j(e,t.termTimeoutMs)||R(e,"SIGKILL")&&await j(e,t.killTimeoutMs)}function U(e){let t,r=(t=(e??"").trim())?"~"===t?i.homedir():t.startsWith("~/")?d.join(i.homedir(),t.slice(2)):d.resolve(t):d.join(i.homedir(),".agent-device");return{baseDir:r,infoPath:d.join(r,"daemon.json"),lockPath:d.join(r,"daemon.lock"),logPath:d.join(r,"daemon.log"),sessionsDir:d.join(r,"sessions")}}function G(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function q(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function H(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function z(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}export{default as node_net}from"node:net";export{default as node_http}from"node:http";export{default as node_https}from"node:https";export{v as AppError,y as asAppError,p as createRequestId,w as emitDiagnostic,e as external_node_url_URL,t as fileURLToPath,L as findProjectRoot,E as flushDiagnosticsToSessionFile,g as getDiagnosticsMeta,x as isAgentDeviceDaemonProcess,$ as isProcessAlive,c as node_crypto,s as node_fs,i as node_os,d as node_path,I as normalizeError,z as normalizeTenantId,r as pathToFileURL,a as promises,b as readProcessCommand,k as readProcessStartTime,P as readVersion,U as resolveDaemonPaths,G as resolveDaemonServerMode,q as resolveDaemonTransportPreference,H as resolveSessionIsolationMode,M as runCmd,_ as runCmdBackground,O as runCmdDetached,T as runCmdStreaming,N as runCmdSync,n as spawn,B as stopProcessForTakeover,A as whichCmd,S as withDiagnosticTimer,h as withDiagnosticsScope};
3
+ `),t.events=[],a}catch{return null}}function D(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&&f.test(i)||m.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(f.test(n)){s[n]="[REDACTED]";continue}s[n]=e(o,r,n)}return s}(e,new WeakSet)}class v extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function y(e){return e instanceof v?e:e instanceof Error?new v("UNKNOWN",e.message,void 0,e):new v("UNKNOWN","Unknown error",{err:e})}function I(e,t={}){let r=y(e),n=r.details?D(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"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}}async function M(e,t,r={}){return new Promise((o,i)=>{let s=n(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached}),a="",d=r.binaryStdout?Buffer.alloc(0):void 0,u="",c=!1,l=P(r.timeoutMs),f=l?setTimeout(()=>{c=!0,s.kill("SIGKILL")},l):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?d=Buffer.concat([d??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):a+=e}),s.stderr.on("data",e=>{u+=e}),s.on("error",r=>{(f&&clearTimeout(f),"ENOENT"===r.code)?i(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):i(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),s.on("close",n=>{f&&clearTimeout(f);let s=n??1;c&&l?i(new v("COMMAND_FAILED",`${e} timed out after ${l}ms`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:s,timeoutMs:l})):0===s||r.allowFailure?o({stdout:a,stderr:u,exitCode:s,stdoutBuffer:d}):i(new v("COMMAND_FAILED",`${e} exited with code ${s}`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:s,processExitError:!0}))})})}async function A(e){try{var t;let{shell:r,args:n}=(t=e,"win32"===process.platform?{shell:"cmd.exe",args:["/c","where",t]}:{shell:"bash",args:["-lc",`command -v ${t}`]}),o=await M(r,n,{allowFailure:!0});return 0===o.exitCode&&o.stdout.trim().length>0}catch{return!1}}function N(e,t,r={}){let n=o(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:P(r.timeoutMs)});if(n.error){let o=n.error.code;if("ETIMEDOUT"===o)throw new v("COMMAND_FAILED",`${e} timed out after ${P(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:P(r.timeoutMs)},n.error);if("ENOENT"===o)throw new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},n.error);throw new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},n.error)}let i=r.binaryStdout?Buffer.isBuffer(n.stdout)?n.stdout:Buffer.from(n.stdout??""):void 0,s=r.binaryStdout?"":"string"==typeof n.stdout?n.stdout:(n.stdout??"").toString(),a="string"==typeof n.stderr?n.stderr:(n.stderr??"").toString(),d=n.status??1;if(0!==d&&!r.allowFailure)throw new v("COMMAND_FAILED",`${e} 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 O(e,t,r={}){n(e,t,{cwd:r.cwd,env:r.env,stdio:"ignore",detached:!0}).unref()}async function T(e,t,r={}){return new Promise((o,i)=>{let s=n(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached});r.onSpawn?.(s);let a="",d="",u=r.binaryStdout?Buffer.alloc(0):void 0;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){u=Buffer.concat([u??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);d+=t,r.onStderrChunk?.(t)}),s.on("error",r=>{"ENOENT"===r.code?i(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):i(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),s.on("close",n=>{let s=n??1;0===s||r.allowFailure?o({stdout:a,stderr:d,exitCode:s,stdoutBuffer:u}):i(new v("COMMAND_FAILED",`${e} exited with code ${s}`,{cmd:e,args:t,stdout:a,stderr:d,exitCode:s,processExitError:!0}))})})}function _(e,t,r={}){let o=n(e,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached}),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((n,a)=>{o.on("error",r=>{"ENOENT"===r.code?a(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):a(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),o.on("close",o=>{let d=o??1;0===d||r.allowFailure?n({stdout:i,stderr:s,exitCode:d}):a(new v("COMMAND_FAILED",`${e} exited with code ${d}`,{cmd:e,args:t,stdout:i,stderr:s,exitCode:d,processExitError:!0}))})});return{child:o,wait:a}}function P(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function C(){try{let e=L();return JSON.parse(s.readFileSync(d.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function L(){let e=d.dirname(t(import.meta.url)),r=e;for(let e=0;e<6;e+=1){let e=d.join(r,"package.json");if(s.existsSync(e))return r;r=d.dirname(r)}return e}let F=[/(^|[\/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[\/\s"'=])src\/daemon\.ts($|[\s"'])/];function $(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function b(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=N("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 k(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=N("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 x(e,t){let r;if(!$(e))return!1;if(t){let r=b(e);if(!r||r!==t)return!1}let n=k(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&F.some(e=>e.test(r))}function R(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 j(e,t){if(!$(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!$(e))return!0;return!$(e)}async function B(e,t){!x(e,t.expectedStartTime)||!R(e,"SIGTERM")||await j(e,t.termTimeoutMs)||R(e,"SIGKILL")&&await j(e,t.killTimeoutMs)}function U(e){return e?.HOME?.trim()||i.homedir()}function G(e,t={}){return"~"===e?U(t.env):e.startsWith("~/")?d.join(U(t.env),e.slice(2)):e}function H(e,t={}){let r=G(e,t);return d.isAbsolute(r)?r:d.resolve(t.cwd??process.cwd(),r)}function q(e){let t,r=(t=(e??"").trim())?H(t):d.join(G("~"),".agent-device");return{baseDir:r,infoPath:d.join(r,"daemon.json"),lockPath:d.join(r,"daemon.lock"),logPath:d.join(r,"daemon.log"),sessionsDir:d.join(r,"sessions")}}function z(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function K(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function V(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function W(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}export{default as node_net}from"node:net";export{default as node_http}from"node:http";export{default as node_https}from"node:https";export{v as AppError,y as asAppError,p as createRequestId,w as emitDiagnostic,G as expandUserHomePath,e as external_node_url_URL,t as fileURLToPath,L as findProjectRoot,E as flushDiagnosticsToSessionFile,g as getDiagnosticsMeta,x as isAgentDeviceDaemonProcess,$ as isProcessAlive,c as node_crypto,s as node_fs,i as node_os,d as node_path,I as normalizeError,W as normalizeTenantId,r as pathToFileURL,a as promises,k as readProcessCommand,b as readProcessStartTime,C as readVersion,q as resolveDaemonPaths,z as resolveDaemonServerMode,K as resolveDaemonTransportPreference,V as resolveSessionIsolationMode,H as resolveUserPath,M as runCmd,_ as runCmdBackground,O as runCmdDetached,T as runCmdStreaming,N as runCmdSync,n as spawn,B as stopProcessForTakeover,A as whichCmd,S as withDiagnosticTimer,h as withDiagnosticsScope};