agent-device 0.17.1 → 0.17.3

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 (97) hide show
  1. package/README.md +3 -3
  2. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.1.apk → agent-device-android-multitouch-helper-0.17.3.apk} +0 -0
  3. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.3.apk.sha256 +1 -0
  4. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.1.manifest.json → agent-device-android-multitouch-helper-0.17.3.manifest.json} +4 -4
  5. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.1.apk → agent-device-android-snapshot-helper-0.17.3.apk} +0 -0
  6. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.3.apk.sha256 +1 -0
  7. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.1.manifest.json → agent-device-android-snapshot-helper-0.17.3.manifest.json} +6 -6
  8. package/dist/src/123.js +1 -0
  9. package/dist/src/1231.js +1 -1
  10. package/dist/src/1352.js +1 -1
  11. package/dist/src/221.js +2 -2
  12. package/dist/src/2403.js +3 -0
  13. package/dist/src/2415.js +36 -30
  14. package/dist/src/4778.js +1 -1
  15. package/dist/src/5611.js +1 -0
  16. package/dist/src/5827.js +1 -0
  17. package/dist/src/6088.js +1 -0
  18. package/dist/src/6133.js +1 -0
  19. package/dist/src/7556.js +1 -1
  20. package/dist/src/7847.js +1 -1
  21. package/dist/src/8806.js +3 -3
  22. package/dist/src/9010.js +1 -0
  23. package/dist/src/9238.js +3 -3
  24. package/dist/src/9471.js +1 -1
  25. package/dist/src/9542.js +6 -3
  26. package/dist/src/9616.js +2 -0
  27. package/dist/src/9818.js +1 -1
  28. package/dist/src/android-adb.d.ts +12 -6
  29. package/dist/src/android-adb.js +1 -1
  30. package/dist/src/android-snapshot-helper.d.ts +15 -8
  31. package/dist/src/android.js +5 -5
  32. package/dist/src/apple.js +1 -1
  33. package/dist/src/apps.js +10 -10
  34. package/dist/src/args.js +53 -14
  35. package/dist/src/batch.d.ts +16 -4
  36. package/dist/src/batch.js +1 -1
  37. package/dist/src/cli-output.js +29 -0
  38. package/dist/src/cli.js +17 -42
  39. package/dist/src/command-surface.js +1 -1
  40. package/dist/src/contracts.d.ts +80 -4
  41. package/dist/src/contracts.js +1 -1
  42. package/dist/src/find.js +1 -1
  43. package/dist/src/finders.d.ts +3 -1
  44. package/dist/src/generic.js +7 -7
  45. package/dist/src/index.d.ts +250 -79
  46. package/dist/src/index.js +1 -1
  47. package/dist/src/input-actions.js +1 -1
  48. package/dist/src/interaction.js +1 -1
  49. package/dist/src/internal/png-worker.d.ts +26 -0
  50. package/dist/src/internal/png-worker.js +1 -0
  51. package/dist/src/metro.d.ts +3 -1
  52. package/dist/src/react-native.js +1 -1
  53. package/dist/src/record-trace-recording.js +3 -3
  54. package/dist/src/remote-config.d.ts +33 -7
  55. package/dist/src/selector-runtime.js +1 -1
  56. package/dist/src/selectors.d.ts +17 -3
  57. package/dist/src/selectors.js +1 -1
  58. package/dist/src/server.js +2 -2
  59. package/dist/src/session.js +8 -11
  60. package/dist/src/snapshot.js +2 -2
  61. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h +1 -0
  62. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +14 -0
  63. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +297 -0
  64. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +328 -0
  65. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +121 -172
  66. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +153 -5
  67. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +171 -0
  68. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +0 -10
  69. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +64 -18
  70. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +200 -0
  71. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +406 -0
  72. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +82 -169
  73. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +425 -0
  74. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +77 -6
  75. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +10 -1
  76. package/ios-runner/README.md +5 -5
  77. package/ios-runner/RUNNER_PROTOCOL.md +0 -1
  78. package/package.json +8 -5
  79. package/server.json +2 -2
  80. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.1.apk.sha256 +0 -1
  81. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.1.apk.sha256 +0 -1
  82. package/dist/src/1998.js +0 -1
  83. package/dist/src/2805.js +0 -1
  84. package/dist/src/4057.js +0 -1
  85. package/dist/src/5310.js +0 -1
  86. package/dist/src/5792.js +0 -1
  87. package/dist/src/6085.js +0 -1
  88. package/dist/src/6232.js +0 -1
  89. package/dist/src/7455.js +0 -1
  90. package/dist/src/8020.js +0 -1
  91. package/dist/src/8502.js +0 -1
  92. package/dist/src/8699.js +0 -1
  93. package/dist/src/940.js +0 -1
  94. package/dist/src/9404.js +0 -1
  95. package/dist/src/9533.js +0 -1
  96. package/dist/src/command-metadata.js +0 -1
  97. /package/dist/src/{1393.js → 3675.js} +0 -0
package/dist/src/8806.js CHANGED
@@ -1,7 +1,7 @@
1
- import{promises as t}from"node:fs";import e from"node:os";import a from"node:path";import{asAppError as n,AppError as i}from"./9152.js";import{emitDiagnostic as r}from"./7599.js";import{runCmd as o,resolveFileOverridePath as s,whichCmd as l,runCmdDetached as d}from"./9818.js";import{ensureAndroidSdkPathConfigured as u,resolveAndroidArchivePackageName as c}from"./7651.js";import{sleep as p}from"./4829.js";import{createAndroidPortReverseManager as f,resolveAndroidAdbProvider as m,installAndroidAdbPackage as w,resolveAndroidAdbExecutor as h}from"./9639.js";import{materializeInstallablePath as A,isTrustedInstallSourceUrl as y}from"./989.js";let g=["mCurrentFocus=Window{","mFocusedApp=AppWindowToken{","mResumedActivity:","ResumedActivity:"],v=/\bApplication Not Responding:\s*([A-Za-z0-9_.]+)/i,_=/([^{}]*\bis(?:n't| not)\s+responding[^{}]*)/i,M=/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\b/;function b(t){let e=new Set;for(let a of t.split("\n")){let t=a.trim();if(!t)continue;let n=t.split(/\s+/)[0]??"";if(!n.includes("/"))continue;let i=n.split("/")[0]??"";i.includes(".")&&i&&e.add(i)}return Array.from(e)}function I(t){return t.split("\n").map(t=>{let e=t.trim();return e.startsWith("package:")?e.slice(8):e}).filter(Boolean)}function N(t){return O(t,t=>(function(t){for(let e of t.trim().split(/\s+/)){let t=e.indexOf("/");if(t<=0)continue;let a=D(e.slice(0,t),!1),n=D(e.slice(t+1),!0);if(a&&n&&a.length===t)return{package:a,activity:n}}return null})(t))}function O(t,e){let a=t.split("\n");for(let t of g)for(let n of a){let a=n.indexOf(t);if(-1===a)continue;let i=n.trim(),r=e(n.slice(a+t.length),i);if(r)return r}return null}function D(t,e){let a=0;for(;a<t.length&&function(t,e){if(!t)return!1;let a=t.charCodeAt(0);return a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||"_"===t||"."===t||e&&"$"===t}(t[a],e);)a+=1;return t.slice(0,a)}function C(t){let e=t.trim();if(!e||/\s/.test(e))return!1;let a=/^([A-Za-z][A-Za-z0-9+.-]*):(.+)$/.exec(e);if(!a)return!1;let n=a[1]?.toLowerCase(),i=a[2]??"";return"http"!==n&&"https"!==n&&"ws"!==n&&"wss"!==n&&"ftp"!==n&&"ftps"!==n||i.startsWith("//")}function E(t){let e=t.trim().split(":")[0]?.toLowerCase();return"http"===e||"https"===e}function T(t,e){let a=t?.trim();return a||(E(e)?"com.apple.mobilesafari":void 0)}function L(t={}){let e=t.ttlMs??3e4,a=t.nowMs??Date.now,n=new Map,i=t=>{var e;let a=[(e=t).platform,e.deviceId,""].join("\0");for(let t of n.keys())t.startsWith(a)&&n.delete(t)};return{get(t,e){let i=k(t,e),r=n.get(i);if(r)return r.expiresAtMs<=a()?void n.delete(i):r.value},set:(t,i,r)=>(n.set(k(t,i),{value:r,expiresAtMs:a()+e}),r),clear(t){i(t)},async invalidateWhile(t,e){i(t);try{return await e()}finally{i(t)}}}}function k(t,e){return[t.platform,t.deviceId,t.variant??"",e.trim().toLowerCase()].join("\0")}function S(t){return["1","true","yes","on"].includes((t??"").trim().toLowerCase())}class R{startedAtMs;expiresAtMs;constructor(t,e){this.startedAtMs=t,this.expiresAtMs=t+Math.max(0,e)}static fromTimeoutMs(t,e=Date.now()){return new R(e,t)}remainingMs(t=Date.now()){return Math.max(0,this.expiresAtMs-t)}elapsedMs(t=Date.now()){return Math.max(0,t-this.startedAtMs)}isExpired(t=Date.now()){return 0>=this.remainingMs(t)}}async function x(t,e={},a={}){let n,r={maxAttempts:e.maxAttempts??3,baseDelayMs:e.baseDelayMs??200,maxDelayMs:e.maxDelayMs??2e3,jitter:e.jitter??.2,shouldRetry:e.shouldRetry};for(let e=1;e<=r.maxAttempts;e+=1){if(a.signal?.aborted)throw new i("COMMAND_FAILED","request canceled",{reason:"request_canceled"});if(a.deadline?.isExpired()&&e>1)break;try{let n=await t({attempt:e,maxAttempts:r.maxAttempts,deadline:a.deadline});return a.onEvent?.({phase:a.phase,event:"succeeded",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),P({phase:a.phase,event:"succeeded",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),n}catch(d){n=d;let t=a.classifyReason?.(d),i={phase:a.phase,event:"attempt_failed",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:t};if(a.onEvent?.(i),P(i),e>=r.maxAttempts||r.shouldRetry&&!r.shouldRetry(d,e))break;let o=function(t,e,a,n){let i=Math.min(e,t*2**(n-1));return Math.max(0,i+i*a*(2*Math.random()-1))}(r.baseDelayMs,r.maxDelayMs,r.jitter,e),s=a.deadline?Math.min(o,a.deadline.remainingMs()):o;if(s<=0)break;let l={phase:a.phase,event:"retry_scheduled",attempt:e,maxAttempts:r.maxAttempts,delayMs:s,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:t};a.onEvent?.(l),P(l),await function(t,e){return new Promise(a=>{if(e?.aborted)return void a();let n=!1,i=()=>{n||(n=!0,e&&e.removeEventListener("abort",o),a())},r=setTimeout(i,t);function o(){clearTimeout(r),i()}e&&e.addEventListener("abort",o,{once:!0})})}(s,a.signal)}}let o={phase:a.phase,event:"exhausted",attempt:r.maxAttempts,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:a.classifyReason?.(n)};if(a.onEvent?.(o),P(o),n)throw n;throw new i("COMMAND_FAILED","retry failed")}async function U(t,e={}){return x(()=>t(),{maxAttempts:e.attempts,baseDelayMs:e.baseDelayMs,maxDelayMs:e.maxDelayMs,jitter:e.jitter,shouldRetry:e.shouldRetry})}function P(t){r({level:"attempt_failed"===t.event||"exhausted"===t.event?"warn":"debug",phase:"retry",data:{...t}})}function F(t){return t?.trim()||void 0}function B(t){return F(t)}function $(t){return new Set(t.split(/[\s,]+/).map(t=>t.trim()).filter(Boolean))}function V(t,e=process.env){let a=F(t)??F(e.AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST);if(a)return $(a)}let W=new Set(["IOS_BOOT_TIMEOUT","IOS_RUNNER_CONNECT_TIMEOUT","IOS_TOOL_MISSING","ANDROID_BOOT_TIMEOUT","ADB_TRANSPORT_UNAVAILABLE","CI_RESOURCE_STARVATION_SUSPECTED"]);function G(t){return W.has(t.toUpperCase())}function j(t){let e=t.error?n(t.error):null,a=t.context?.platform,i=t.context?.phase;if(e?.code==="TOOL_MISSING")return"android"===a?"ADB_TRANSPORT_UNAVAILABLE":"IOS_TOOL_MISSING";let r=e?.details??{},o="string"==typeof r.message?r.message:void 0,s="string"==typeof r.stdout?r.stdout:void 0,l="string"==typeof r.stderr?r.stderr:void 0,d=r.boot&&"object"==typeof r.boot?r.boot:null,u=r.bootstatus&&"object"==typeof r.bootstatus?r.bootstatus:null,c=[t.message,e?.message,t.stdout,t.stderr,o,s,l,"string"==typeof d?.stdout?d.stdout:void 0,"string"==typeof d?.stderr?d.stderr:void 0,"string"==typeof u?.stdout?u.stdout:void 0,"string"==typeof u?.stderr?u.stderr:void 0].filter(Boolean).join("\n").toLowerCase();return"ios"===a&&(c.includes("runner did not accept connection")||"connect"===i&&(c.includes("timed out")||c.includes("timeout")||c.includes("econnrefused")||c.includes("connection refused")||c.includes("fetch failed")||c.includes("socket hang up")))?"IOS_RUNNER_CONNECT_TIMEOUT":"ios"===a&&"boot"===i&&(c.includes("timed out")||c.includes("timeout"))?"IOS_BOOT_TIMEOUT":"android"===a&&"boot"===i&&(c.includes("timed out")||c.includes("timeout"))?"ANDROID_BOOT_TIMEOUT":c.includes("resource temporarily unavailable")||c.includes("killed: 9")||c.includes("cannot allocate memory")||c.includes("system is low on memory")?"CI_RESOURCE_STARVATION_SUSPECTED":"android"===a&&(c.includes("device not found")||c.includes("no devices")||c.includes("device offline")||c.includes("offline")||c.includes("unauthorized")||c.includes("not authorized")||c.includes("unable to locate device")||c.includes("invalid device"))?"ADB_TRANSPORT_UNAVAILABLE":e?.code==="COMMAND_FAILED"||c.length>0?"BOOT_COMMAND_FAILED":"UNKNOWN"}function H(t){switch(t){case"IOS_BOOT_TIMEOUT":return"Retry simulator boot and inspect simctl bootstatus logs; in CI reduce parallel jobs or use a larger runner.";case"IOS_RUNNER_CONNECT_TIMEOUT":return"Retry runner startup, inspect xcodebuild logs, and verify simulator responsiveness before command execution.";case"ANDROID_BOOT_TIMEOUT":return"Retry emulator startup and verify sys.boot_completed reaches 1; consider increasing startup budget in CI.";case"ADB_TRANSPORT_UNAVAILABLE":return"Check adb server/device transport (adb devices -l), restart adb, and ensure the target device is online and authorized.";case"CI_RESOURCE_STARVATION_SUSPECTED":return"CI machine may be resource constrained; reduce parallel jobs or use a larger runner.";case"IOS_TOOL_MISSING":return"Xcode command-line tools are missing or not in PATH; run xcode-select --install and verify xcrun works.";case"BOOT_COMMAND_FAILED":return"Inspect command stderr/stdout for the failing boot phase and retry after environment validation.";default:return"Retry once and inspect verbose logs for the failing phase."}}let K=["android.software.leanback","android.software.leanback_only","android.hardware.type.television"];async function z(t,e,a){let n=Array(t.length),i=0,r=Math.min(e,t.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<t.length;){let e=i;i+=1,n[e]=await a(t[e])}})),n}function q(t){return`${t.stdout}
1
+ import{promises as t}from"node:fs";import e from"node:os";import a from"node:path";import{asAppError as n,AppError as i}from"./9152.js";import{emitDiagnostic as r}from"./7599.js";import{runCmd as o,resolveFileOverridePath as s,whichCmd as l,runCmdDetached as d}from"./9818.js";import{ensureAndroidSdkPathConfigured as u,resolveAndroidArchivePackageName as c}from"./7651.js";import{sleep as p}from"./4829.js";import{createAndroidPortReverseManager as f,resolveAndroidAdbProvider as m,installAndroidAdbPackage as w,resolveAndroidAdbExecutor as h}from"./9639.js";import{materializeInstallablePath as A,isTrustedInstallSourceUrl as y}from"./989.js";let g=["mCurrentFocus=Window{","mFocusedApp=AppWindowToken{","mResumedActivity:","ResumedActivity:"],v=/\bApplication Not Responding:\s*([A-Za-z0-9_.]+)/i,_=/([^{}]*\bis(?:n't| not)\s+responding[^{}]*)/i,M=/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\b/;function b(t){let e=new Set;for(let a of t.split("\n")){let t=a.trim();if(!t)continue;let n=t.split(/\s+/)[0]??"";if(!n.includes("/"))continue;let i=n.split("/")[0]??"";i.includes(".")&&i&&e.add(i)}return Array.from(e)}function I(t){return t.split("\n").map(t=>{let e=t.trim();return e.startsWith("package:")?e.slice(8):e}).filter(Boolean)}function N(t){return O(t,t=>(function(t){for(let e of t.trim().split(/\s+/)){let t=e.indexOf("/");if(t<=0)continue;let a=D(e.slice(0,t),!1),n=D(e.slice(t+1),!0);if(a&&n&&a.length===t)return{package:a,activity:n}}return null})(t))}function O(t,e){let a=t.split("\n");for(let t of g)for(let n of a){let a=n.indexOf(t);if(-1===a)continue;let i=n.trim(),r=e(n.slice(a+t.length),i);if(r)return r}return null}function D(t,e){let a=0;for(;a<t.length&&function(t,e){if(!t)return!1;let a=t.charCodeAt(0);return a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||"_"===t||"."===t||e&&"$"===t}(t[a],e);)a+=1;return t.slice(0,a)}function E(t){let e=t.trim();if(!e||/\s/.test(e))return!1;let a=/^([A-Za-z][A-Za-z0-9+.-]*):(.+)$/.exec(e);if(!a)return!1;let n=a[1]?.toLowerCase(),i=a[2]??"";return"http"!==n&&"https"!==n&&"ws"!==n&&"wss"!==n&&"ftp"!==n&&"ftps"!==n||i.startsWith("//")}function C(t){let e=t.trim().split(":")[0]?.toLowerCase();return"http"===e||"https"===e}function T(t,e){let a=t?.trim();return a||(C(e)?"com.apple.mobilesafari":void 0)}function L(t={}){let e=t.ttlMs??3e4,a=t.nowMs??Date.now,n=new Map,i=t=>{var e;let a=[(e=t).platform,e.deviceId,""].join("\0");for(let t of n.keys())t.startsWith(a)&&n.delete(t)};return{get(t,e){let i=k(t,e),r=n.get(i);if(r)return r.expiresAtMs<=a()?void n.delete(i):r.value},set:(t,i,r)=>(n.set(k(t,i),{value:r,expiresAtMs:a()+e}),r),clear(t){i(t)},async invalidateWhile(t,e){i(t);try{return await e()}finally{i(t)}}}}function k(t,e){return[t.platform,t.deviceId,t.variant??"",e.trim().toLowerCase()].join("\0")}function S(t){return["1","true","yes","on"].includes((t??"").trim().toLowerCase())}class R{startedAtMs;expiresAtMs;constructor(t,e){this.startedAtMs=t,this.expiresAtMs=t+Math.max(0,e)}static fromTimeoutMs(t,e=Date.now()){return new R(e,t)}remainingMs(t=Date.now()){return Math.max(0,this.expiresAtMs-t)}elapsedMs(t=Date.now()){return Math.max(0,t-this.startedAtMs)}isExpired(t=Date.now()){return 0>=this.remainingMs(t)}}async function x(t,e={},a={}){let n,r={maxAttempts:e.maxAttempts??3,baseDelayMs:e.baseDelayMs??200,maxDelayMs:e.maxDelayMs??2e3,jitter:e.jitter??.2,shouldRetry:e.shouldRetry};for(let e=1;e<=r.maxAttempts;e+=1){if(a.signal?.aborted)throw new i("COMMAND_FAILED","request canceled",{reason:"request_canceled"});if(a.deadline?.isExpired()&&e>1)break;try{let n=await t({attempt:e,maxAttempts:r.maxAttempts,deadline:a.deadline});return a.onEvent?.({phase:a.phase,event:"succeeded",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),P({phase:a.phase,event:"succeeded",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),n}catch(d){n=d;let t=a.classifyReason?.(d),i={phase:a.phase,event:"attempt_failed",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:t};if(a.onEvent?.(i),P(i),e>=r.maxAttempts||r.shouldRetry&&!r.shouldRetry(d,e))break;let o=function(t,e,a,n){let i=Math.min(e,t*2**(n-1));return Math.max(0,i+i*a*(2*Math.random()-1))}(r.baseDelayMs,r.maxDelayMs,r.jitter,e),s=a.deadline?Math.min(o,a.deadline.remainingMs()):o;if(s<=0)break;let l={phase:a.phase,event:"retry_scheduled",attempt:e,maxAttempts:r.maxAttempts,delayMs:s,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:t};a.onEvent?.(l),P(l),await function(t,e){return new Promise(a=>{if(e?.aborted)return void a();let n=!1,i=()=>{n||(n=!0,e&&e.removeEventListener("abort",o),a())},r=setTimeout(i,t);function o(){clearTimeout(r),i()}e&&e.addEventListener("abort",o,{once:!0})})}(s,a.signal)}}let o={phase:a.phase,event:"exhausted",attempt:r.maxAttempts,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:a.classifyReason?.(n)};if(a.onEvent?.(o),P(o),n)throw n;throw new i("COMMAND_FAILED","retry failed")}async function U(t,e={}){return x(()=>t(),{maxAttempts:e.attempts,baseDelayMs:e.baseDelayMs,maxDelayMs:e.maxDelayMs,jitter:e.jitter,shouldRetry:e.shouldRetry})}function P(t){r({level:"attempt_failed"===t.event||"exhausted"===t.event?"warn":"debug",phase:"retry",data:{...t}})}function F(t){return t?.trim()||void 0}function B(t){return F(t)}function $(t){return new Set(t.split(/[\s,]+/).map(t=>t.trim()).filter(Boolean))}function V(t,e=process.env){let a=F(t)??F(e.AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST);if(a)return $(a)}let W=new Set(["IOS_BOOT_TIMEOUT","IOS_RUNNER_CONNECT_TIMEOUT","IOS_TOOL_MISSING","ANDROID_BOOT_TIMEOUT","ADB_TRANSPORT_UNAVAILABLE","CI_RESOURCE_STARVATION_SUSPECTED"]);function G(t){return W.has(t.toUpperCase())}function j(t){let e=t.error?n(t.error):null,a=t.context?.platform,i=t.context?.phase;if(e?.code==="TOOL_MISSING")return"android"===a?"ADB_TRANSPORT_UNAVAILABLE":"IOS_TOOL_MISSING";let r=e?.details??{},o="string"==typeof r.message?r.message:void 0,s="string"==typeof r.stdout?r.stdout:void 0,l="string"==typeof r.stderr?r.stderr:void 0,d=r.boot&&"object"==typeof r.boot?r.boot:null,u=r.bootstatus&&"object"==typeof r.bootstatus?r.bootstatus:null,c=[t.message,e?.message,t.stdout,t.stderr,o,s,l,"string"==typeof d?.stdout?d.stdout:void 0,"string"==typeof d?.stderr?d.stderr:void 0,"string"==typeof u?.stdout?u.stdout:void 0,"string"==typeof u?.stderr?u.stderr:void 0].filter(Boolean).join("\n").toLowerCase();return"ios"===a&&(c.includes("runner did not accept connection")||"connect"===i&&(c.includes("timed out")||c.includes("timeout")||c.includes("econnrefused")||c.includes("connection refused")||c.includes("fetch failed")||c.includes("socket hang up")))?"IOS_RUNNER_CONNECT_TIMEOUT":"ios"===a&&"boot"===i&&(c.includes("timed out")||c.includes("timeout"))?"IOS_BOOT_TIMEOUT":"android"===a&&"boot"===i&&(c.includes("timed out")||c.includes("timeout"))?"ANDROID_BOOT_TIMEOUT":c.includes("resource temporarily unavailable")||c.includes("killed: 9")||c.includes("cannot allocate memory")||c.includes("system is low on memory")?"CI_RESOURCE_STARVATION_SUSPECTED":"android"===a&&(c.includes("device not found")||c.includes("no devices")||c.includes("device offline")||c.includes("offline")||c.includes("unauthorized")||c.includes("not authorized")||c.includes("unable to locate device")||c.includes("invalid device"))?"ADB_TRANSPORT_UNAVAILABLE":e?.code==="COMMAND_FAILED"||c.length>0?"BOOT_COMMAND_FAILED":"UNKNOWN"}function H(t){switch(t){case"IOS_BOOT_TIMEOUT":return"Retry simulator boot and inspect simctl bootstatus logs; in CI reduce parallel jobs or use a larger runner.";case"IOS_RUNNER_CONNECT_TIMEOUT":return"Retry runner startup, inspect xcodebuild logs, and verify simulator responsiveness before command execution.";case"ANDROID_BOOT_TIMEOUT":return"Retry emulator startup and verify sys.boot_completed reaches 1; consider increasing startup budget in CI.";case"ADB_TRANSPORT_UNAVAILABLE":return"Check adb server/device transport (adb devices -l), restart adb, and ensure the target device is online and authorized.";case"CI_RESOURCE_STARVATION_SUSPECTED":return"CI machine may be resource constrained; reduce parallel jobs or use a larger runner.";case"IOS_TOOL_MISSING":return"Xcode command-line tools are missing or not in PATH; run xcode-select --install and verify xcrun works.";case"BOOT_COMMAND_FAILED":return"Inspect command stderr/stdout for the failing boot phase and retry after environment validation.";default:return"Retry once and inspect verbose logs for the failing phase."}}let K=["android.software.leanback","android.software.leanback_only","android.hardware.type.television"];async function z(t,e,a){let n=Array(t.length),i=0,r=Math.min(e,t.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<t.length;){let e=i;i+=1,n[e]=await a(t[e])}})),n}function q(t){return`${t.stdout}
2
2
  ${t.stderr}`}function Z(t,e){return["-s",t,...e]}function J(t){return t.startsWith("emulator-")}function X(t){return t.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}async function Q(t,e=1e4){return o("adb",Z(t,["shell","getprop","sys.boot_completed"]),{allowFailure:!0,timeoutMs:e})}async function Y(t,e){let a=e.replace(/_/g," ").trim();if(!J(t))return a||t;let n=await te(t);return n?n.replace(/_/g," "):a||t}async function tt(t,e,a){try{return await a("adb",Z(t,e),{allowFailure:!0,timeoutMs:1e4})}catch(t){var i;if("COMMAND_FAILED"===(i=n(t)).code&&"number"==typeof i.details?.timeoutMs)return;throw t}}async function te(t,e=o){for(let a of["ro.boot.qemu.avd_name","persist.sys.avd_name"]){let n=await tt(t,["shell","getprop",a],e);if(!n)continue;let i=n.stdout.trim();if(0===n.exitCode&&i.length>0)return i}let a=await tt(t,["emu","avd","name"],e);if(!a)return;let n=function(t){let e=t.split("\n").map(t=>t.trim()).filter(t=>t.length>0);if(0!==e.length)return"OK"===e.at(-1)&&e.pop(),e.join("\n").trim()||void 0}(a.stdout);if(0===a.exitCode&&n)return n}async function ta(t,e){let a=q(await o("adb",Z(t,["shell","cmd","package","has-feature",e]),{allowFailure:!0,timeoutMs:1e4})).toLowerCase();return!!a.includes("true")||!a.includes("false")&&null}async function tn(t){return(await z(K,2,async e=>await ta(t,e))).some(t=>!0===t)}async function ti(t){var e;let a;return"tv"===((a=q(await o("adb",Z(t,["shell","getprop","ro.build.characteristics"]),{allowFailure:!0,timeoutMs:1e4})).toLowerCase()).includes("tv")||a.includes("leanback")?"tv":null)||await tn(t)?"tv":(e=q(await o("adb",Z(t,["shell","pm","list","features"]),{allowFailure:!0,timeoutMs:1e4})),/feature:android\.(software\.leanback(_only)?|hardware\.type\.television)\b/i.test(e))?"tv":"mobile"}async function tr(t={}){if(await u(),!await l("adb"))throw new i("TOOL_MISSING","adb not found in PATH");let e=t.serialAllowlist??V(void 0),a=(await to()).filter(t=>!e||e.has(t.serial));return await z(a,3,async({serial:t,rawModel:e})=>{let[a,n,i]=await Promise.all([Y(t,e),tu(t),ti(t)]);return{platform:"android",id:t,name:a,kind:J(t)?"emulator":"device",target:i,booted:n}})}async function to(){return(await o("adb",["devices","-l"],{timeoutMs:1e4})).stdout.split("\n").map(t=>t.trim()).filter(t=>t.length>0&&!t.startsWith("List of devices")).map(t=>t.split(/\s+/)).flatMap(t=>{let e=t[0];return void 0===e||"device"!==t[1]?[]:[{serial:e,rawModel:(t.find(t=>t.startsWith("model:"))??"").replace("model:","")}]})}async function ts(){let t=await o("emulator",["-list-avds"],{allowFailure:!0,timeoutMs:1e4});if(0!==t.exitCode)throw new i("COMMAND_FAILED","Failed to list Android emulator AVDs",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode,hint:"Verify Android emulator tooling is installed and available in PATH."});return t.stdout.split("\n").map(t=>t.trim()).filter(t=>t.length>0)}async function tl(t){let e=Date.now();for(;Date.now()-e<t.timeoutMs;){try{let e=await td(t.avdName,t.serial);if(e)return{platform:"android",id:e,name:t.avdName,kind:"emulator",target:"mobile",booted:!1}}catch{}await p(1e3)}throw new i("COMMAND_FAILED","Android emulator did not appear in time",{avdName:t.avdName,serial:t.serial,timeoutMs:t.timeoutMs,hint:"Check emulator logs and verify the AVD can start from command line."})}async function td(t,e){let a=X(t);for(let t of(await to()).filter(t=>(!e||t.serial===e)&&J(t.serial)))if(X(t.rawModel)===a||X(await Y(t.serial,t.rawModel))===a)return t.serial}async function tu(t){try{let e=await Q(t);return"1"===e.stdout.trim()}catch{return!1}}async function tc(t){var e,a;let n;await u();let r=t.avdName.trim();if(!r)throw new i("INVALID_ARGS","Android emulator boot requires a non-empty AVD name.");let o=t.timeoutMs??12e4;if(!await l("adb"))throw new i("TOOL_MISSING","adb not found in PATH");if(!await l("emulator"))throw new i("TOOL_MISSING","emulator not found in PATH");let s=await ts(),c=function(t,e){let a=t.find(t=>t===e);if(a)return a;let n=X(e);return t.find(t=>X(t)===n)}(s,r);if(!c)throw new i("DEVICE_NOT_FOUND",`No Android emulator AVD named ${t.avdName}`,{requestedAvdName:r,availableAvds:s,hint:"Run `emulator -list-avds` and pass an existing AVD name to --device."});let p=Date.now(),f=(e=await tr(),a=t.serial,n=X(c),e.find(t=>"android"===t.platform&&"emulator"===t.kind&&(!a||t.id===a)&&X(t.name)===n));if(!f){let e=["-avd",c];t.headless&&e.push("-no-window","-no-audio"),d("emulator",e)}let m=f??await tl({avdName:c,serial:t.serial,timeoutMs:o}),w=Math.max(1e3,o-(Date.now()-p));await tp(m.id,w);let h=(await tr()).find(t=>t.id===m.id);return h?{...h,name:c,booted:!0}:{...m,name:c,booted:!0}}async function tp(t,e=6e4){let a,r=R.fromTimeoutMs(e),o=Math.max(1,Math.ceil(e/1e3)),s=!1;try{await x(async({deadline:n})=>{if(n?.isExpired())throw s=!0,new i("COMMAND_FAILED","Android boot deadline exceeded",{serial:t,timeoutMs:e,elapsedMs:r.elapsedMs(),message:"timeout"});let o=Math.max(1e3,n?.remainingMs()??e),l=await Q(t,Math.min(o,1e4));if(a=l,"1"!==l.stdout.trim())throw new i("COMMAND_FAILED","Android device is still booting",{serial:t,stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode})},{maxAttempts:o,baseDelayMs:1e3,maxDelayMs:1e3,jitter:0,shouldRetry:t=>{let e=j({error:t,stdout:a?.stdout,stderr:a?.stderr,context:{platform:"android",phase:"boot"}});return"ADB_TRANSPORT_UNAVAILABLE"!==e&&"ANDROID_BOOT_TIMEOUT"!==e}},{deadline:r,phase:"boot",classifyReason:t=>j({error:t,stdout:a?.stdout,stderr:a?.stderr,context:{platform:"android",phase:"boot"}})})}catch(f){let o=n(f),l=a?.stdout,d=a?.stderr,u=a?.exitCode,c=j({error:f,stdout:l,stderr:d,context:{platform:"android",phase:"boot"}});"BOOT_COMMAND_FAILED"===c&&"Android device is still booting"===o.message&&(c="ANDROID_BOOT_TIMEOUT");let p={serial:t,timeoutMs:e,elapsedMs:r.elapsedMs(),reason:c,hint:H(c),stdout:l,stderr:d,exitCode:u};if(s||"ANDROID_BOOT_TIMEOUT"===c)throw new i("COMMAND_FAILED","Android device did not finish booting in time",p);if("TOOL_MISSING"===o.code)throw new i("TOOL_MISSING",o.message,{...p,...o.details??{}});if("ADB_TRANSPORT_UNAVAILABLE"===c)throw new i("COMMAND_FAILED",o.message,{...p,...o.details??{}});throw new i(o.code,o.message,{...p,...o.details??{}},o.cause)}}async function tf(t,e,a){return await h(t)(e,a)}function tm(t){return{platform:"android",id:t,name:t,kind:t.startsWith("emulator-")?"emulator":"device",booted:!0}}function tw(t,e){let a=`${t}
3
- ${e}`.toLowerCase();return a.includes("no shell command implementation")||a.includes("unknown command")}let th=/\.(?:apk|aab)$/i,tA=/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)+$/;function ty(t){var e,a;let n=t.trim();return 0===n.length?"other":th.test(n)?n.includes("/")||n.includes("\\")||n.startsWith(".")||n.startsWith("~")||(e=n,!tA.test(e))?"binary":"package":(a=n,tA.test(a))?"package":"other"}function tg(t){return`Android runtime hints require an installed package name, not "${t}". Install or reinstall the app first, then relaunch by package.`}async function tv(t,e){let n="url"===t.kind&&y(t.url),i=await A({source:t,isInstallablePath:(t,e)=>{var n;let i;return e.isFile()&&(n=t,".apk"===(i=a.extname(n).toLowerCase())||".aab"===i)},installableLabel:"Android installable (.apk or .aab)",allowArchiveExtraction:"url"!==t.kind||n,signal:e?.signal});try{let t=e?.resolveIdentity===!1?{}:await t_(i.installablePath);return{archivePath:i.archivePath,installablePath:i.installablePath,packageName:t.packageName,cleanup:i.cleanup}}catch(t){throw await i.cleanup(),t}}async function t_(t){let e=a.extname(t).toLowerCase();return".apk"!==e&&".aab"!==e?{}:{packageName:await c(t)}}let tM={settings:{type:"intent",value:"android.settings.SETTINGS"}},tb="android.intent.category.LAUNCHER",tI="android.intent.category.LEANBACK_LAUNCHER",tN="android.intent.category.DEFAULT",tO="Run agent-device apps --platform android to discover the installed package name, then retry open with that exact package.",tD=new Set(["localhost","127.0.0.1","::1","[::1]"]),tC=L();function tE(t){return{platform:"android",deviceId:t.id,variant:t.target??""}}async function tT(t,e){let a=e.trim();if("package"===ty(a))return{type:"package",value:a};let n=tM[a.toLowerCase()];if(n)return n;let r=tE(t),o=tC.get(r,a);if(o)return o;let s=(await tf(t,["shell","pm","list","packages"])).stdout.split("\n").map(t=>t.replace("package:","").trim()).filter(Boolean).filter(t=>t.toLowerCase().includes(a.toLowerCase())),l=s[0];if(void 0!==l&&1===s.length)return tC.set(r,a,{type:"package",value:l});if(s.length>1)throw new i("INVALID_ARGS",`Multiple packages matched "${e}"`,{matches:s,hint:"Run agent-device apps --platform android to see the exact installed package names before retrying open."});throw new i("APP_NOT_INSTALLED",`No package found matching "${e}"`,{hint:tO})}async function tL(t,e){let a=await tk(t);return("user-installed"===e?(await tR(t)).filter(t=>a.has(t)):Array.from(a)).sort((t,e)=>t.localeCompare(e)).map(t=>({package:t,name:tx(t)}))}async function tk(t){let e=new Set;for(let a of tS(t,{includeFallbackWhenUnknown:!0})){let n=await tf(t,["shell","cmd","package","query-activities","--brief","-a","android.intent.action.MAIN","-c",a],{allowFailure:!0});if(0===n.exitCode&&0!==n.stdout.trim().length)for(let t of b(n.stdout))e.add(t)}return e}function tS(t,e={}){return"tv"===t.target?[tI]:"mobile"===t.target?[tb]:e.includeFallbackWhenUnknown?[tb,tI]:[tb]}async function tR(t){return I((await tf(t,["shell","pm","list","packages","-3"])).stdout)}function tx(t){let e=new Set(["com","android","google","app","apps","service","services","mobile","client"]),a=t.split(".").flatMap(t=>t.split(/[_-]+/)).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0),n=a[a.length-1]??t;for(let t=a.length-1;t>=0;t-=1){let i=a[t];if(i&&!e.has(i)){n=i;break}}return n.split(/[^a-z0-9]+/i).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async function tU(t){let e=await tF(t,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]]);if(e)return e;let a=await tF(t,[["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]);return a||{}}async function tP(t){return await tB(t,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]])}async function tF(t,e){for(let a of e){let e=N((await tf(t,a,{allowFailure:!0})).stdout??"");if(e)return e}return null}async function tB(t,e){for(let a of e){let e=O((await tf(t,a,{allowFailure:!0})).stdout??"",(t,e)=>(function(t,e){let a=t.split("}")[0]?.trim()??t.trim(),n=v.exec(a);if(n){let t=n[1];return{package:t,focusedWindow:`Application Not Responding: ${t}`,raw:e}}let i=_.exec(a);if(!i)return null;let r=i[1];if(void 0===r)return null;let o=r.trim().replace(/\s+/g," "),s=M.exec(o)?.[1];return{...s?{package:s}:{},focusedWindow:o,raw:e}})(t,e));if(e)return e}return null}async function t$(t,e){let a=function(t){let e;try{e=new URL(t)}catch{return null}let a=e.hostname.toLowerCase();if(!tD.has(a)||!e.port)return null;let n=Number(e.port);return Number.isInteger(n)?`tcp:${n}`:null}(e);if(!a)return;let n=f(m(t));try{await n.ensure({local:a,remote:a})}catch(e){let t={localPort:a.replace("tcp:",""),operation:`adb reverse ${a} ${a}`};throw e instanceof i&&Object.assign(t,{hint:e.details?.hint,diagnosticId:e.details?.diagnosticId,logPath:e.details?.logPath}),new i("COMMAND_FAILED",`Failed to ensure Android port reverse ${a} before opening localhost URL`,t,e)}}function tV(t){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function tW(t){return(t.launchArgs??[]).map(tV)}async function tG(t,e,a){var n;t.booted||await tp(t.id);let i="string"==typeof(n=a)?{activity:n}:n??{},r=i.activity,o=e.trim();if(C(o))return void await tj(t,o,i);if(void 0!==i.url)return void await tH(t,e,i);let s=await tT(t,e),l=tS(t)[0]??tb;"intent"===s.type?await tK(t,s.value,i):r?await tz(t,s.value,r,l,i):await tq(t,s.value,l,i)}async function tj(t,e,a){var n;let r;if(a.activity)throw new i("INVALID_ARGS","Activity override is not supported when opening a deep link URL");await t$(t,e),await tf(t,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",e,...(n=a.appBundleId,(r=n?.trim())?["-p",r]:[]),...tW(a)])}async function tH(t,e,a){if(a.activity)throw new i("INVALID_ARGS","Activity override is not supported when opening an app-bound deep link URL");let n=a.url?.trim()??"";if(!C(n))throw new i("INVALID_ARGS","Android app-bound open requires a valid URL target");let r=await tJ(t,e,"app-bound open");await tf(t,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",n,"-p",r,...tW(a)])}async function tK(t,e,a){if(a.activity)throw new i("INVALID_ARGS","Activity override requires a package name, not an intent");await tf(t,["shell","am","start","-W","-a",e,...tW(a)])}async function tz(t,e,a,n,i){let r=a.includes("/")?a:`${e}/${a.startsWith(".")?a:`.${a}`}`;try{await tf(t,tZ(r,n,i))}catch(a){throw await tY(t,e,a),a}}async function tq(t,e,a,n){let r=await tf(t,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",tN,"-c",a,"-p",e,...tW(n)],{allowFailure:!0});if(0===r.exitCode&&!t9(r.stdout,r.stderr))return;let o=await t1(t,e);if(!o){if(!await tQ(t,e))throw tX(e);throw new i("COMMAND_FAILED",`Failed to launch ${e}`,{stdout:r.stdout,stderr:r.stderr})}await tf(t,tZ(o,a,n))}function tZ(t,e,a){return["shell","am","start","-W","-a","android.intent.action.MAIN","-c",tN,"-c",e,"-n",t,...tW(a)]}async function tJ(t,e,a){let n=await tT(t,e);if("intent"===n.type)throw new i("INVALID_ARGS",`Android ${a} requires a package name, not an intent`);return n.value}function tX(t){return new i("APP_NOT_INSTALLED",`No package found matching "${t}"`,{package:t,hint:tO})}async function tQ(t,e){let a=await tf(t,["shell","pm","path",e],{allowFailure:!0}),n=`${a.stdout}
3
+ ${e}`.toLowerCase();return a.includes("no shell command implementation")||a.includes("unknown command")}let th=/\.(?:apk|aab)$/i,tA=/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)+$/;function ty(t){var e,a;let n=t.trim();return 0===n.length?"other":th.test(n)?n.includes("/")||n.includes("\\")||n.startsWith(".")||n.startsWith("~")||(e=n,!tA.test(e))?"binary":"package":(a=n,tA.test(a))?"package":"other"}function tg(t){return`Android runtime hints require an installed package name, not "${t}". Install or reinstall the app first, then relaunch by package.`}async function tv(t,e){let n="url"===t.kind&&y(t.url),i=await A({source:t,isInstallablePath:(t,e)=>{var n;let i;return e.isFile()&&(n=t,".apk"===(i=a.extname(n).toLowerCase())||".aab"===i)},installableLabel:"Android installable (.apk or .aab)",allowArchiveExtraction:"url"!==t.kind||n,signal:e?.signal});try{let t=e?.resolveIdentity===!1?{}:await t_(i.installablePath);return{archivePath:i.archivePath,installablePath:i.installablePath,packageName:t.packageName,cleanup:i.cleanup}}catch(t){throw await i.cleanup(),t}}async function t_(t){let e=a.extname(t).toLowerCase();return".apk"!==e&&".aab"!==e?{}:{packageName:await c(t)}}let tM={settings:{type:"intent",value:"android.settings.SETTINGS"}},tb="android.intent.category.LAUNCHER",tI="android.intent.category.LEANBACK_LAUNCHER",tN="android.intent.category.DEFAULT",tO="Run agent-device apps --platform android to discover the installed package name, then retry open with that exact package.",tD=new Set(["localhost","127.0.0.1","::1","[::1]"]),tE=L();function tC(t){return{platform:"android",deviceId:t.id,variant:t.target??""}}async function tT(t,e){let a=e.trim();if("package"===ty(a))return{type:"package",value:a};let n=tM[a.toLowerCase()];if(n)return n;let r=tC(t),o=tE.get(r,a);if(o)return o;let s=(await tf(t,["shell","pm","list","packages"])).stdout.split("\n").map(t=>t.replace("package:","").trim()).filter(Boolean).filter(t=>t.toLowerCase().includes(a.toLowerCase())),l=s[0];if(void 0!==l&&1===s.length)return tE.set(r,a,{type:"package",value:l});if(s.length>1)throw new i("INVALID_ARGS",`Multiple packages matched "${e}"`,{matches:s,hint:"Run agent-device apps --platform android to see the exact installed package names before retrying open."});throw new i("APP_NOT_INSTALLED",`No package found matching "${e}"`,{hint:tO})}async function tL(t,e){let a=await tk(t);return("user-installed"===e?(await tR(t)).filter(t=>a.has(t)):Array.from(a)).sort((t,e)=>t.localeCompare(e)).map(t=>({package:t,name:tx(t)}))}async function tk(t){let e=new Set;for(let a of tS(t,{includeFallbackWhenUnknown:!0})){let n=await tf(t,["shell","cmd","package","query-activities","--brief","-a","android.intent.action.MAIN","-c",a],{allowFailure:!0});if(0===n.exitCode&&0!==n.stdout.trim().length)for(let t of b(n.stdout))e.add(t)}return e}function tS(t,e={}){return"tv"===t.target?[tI]:"mobile"===t.target?[tb]:e.includeFallbackWhenUnknown?[tb,tI]:[tb]}async function tR(t){return I((await tf(t,["shell","pm","list","packages","-3"])).stdout)}function tx(t){let e=new Set(["com","android","google","app","apps","service","services","mobile","client"]),a=t.split(".").flatMap(t=>t.split(/[_-]+/)).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0),n=a[a.length-1]??t;for(let t=a.length-1;t>=0;t-=1){let i=a[t];if(i&&!e.has(i)){n=i;break}}return n.split(/[^a-z0-9]+/i).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async function tU(t){let e=await tF(t,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]]);if(e)return e;let a=await tF(t,[["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]);return a||{}}async function tP(t){return await tB(t,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]])}async function tF(t,e){for(let a of e){let e=N((await tf(t,a,{allowFailure:!0})).stdout??"");if(e)return e}return null}async function tB(t,e){for(let a of e){let e=O((await tf(t,a,{allowFailure:!0})).stdout??"",(t,e)=>(function(t,e){let a=t.split("}")[0]?.trim()??t.trim(),n=v.exec(a);if(n){let t=n[1];return{package:t,focusedWindow:`Application Not Responding: ${t}`,raw:e}}let i=_.exec(a);if(!i)return null;let r=i[1];if(void 0===r)return null;let o=r.trim().replace(/\s+/g," "),s=M.exec(o)?.[1];return{...s?{package:s}:{},focusedWindow:o,raw:e}})(t,e));if(e)return e}return null}async function t$(t,e){let a=function(t){let e;try{e=new URL(t)}catch{return null}let a=e.hostname.toLowerCase();if(!tD.has(a)||!e.port)return null;let n=Number(e.port);return Number.isInteger(n)?`tcp:${n}`:null}(e);if(!a)return;let n=f(m(t));try{await n.ensure({local:a,remote:a})}catch(e){let t={localPort:a.replace("tcp:",""),operation:`adb reverse ${a} ${a}`};throw e instanceof i&&Object.assign(t,{hint:e.details?.hint,diagnosticId:e.details?.diagnosticId,logPath:e.details?.logPath}),new i("COMMAND_FAILED",`Failed to ensure Android port reverse ${a} before opening localhost URL`,t,e)}}function tV(t){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function tW(t){return(t.launchArgs??[]).map(tV)}async function tG(t,e,a){var n;t.booted||await tp(t.id);let i="string"==typeof(n=a)?{activity:n}:n??{},r=i.activity,o=e.trim();if(E(o))return void await tj(t,o,i);if(void 0!==i.url)return void await tH(t,e,i);let s=await tT(t,e),l=tS(t)[0]??tb;"intent"===s.type?await tK(t,s.value,i):r?await tz(t,s.value,r,l,i):await tq(t,s.value,l,i)}async function tj(t,e,a){var n;let r;if(a.activity)throw new i("INVALID_ARGS","Activity override is not supported when opening a deep link URL");await t$(t,e),await tf(t,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",e,...(n=a.appBundleId,(r=n?.trim())?["-p",r]:[]),...tW(a)])}async function tH(t,e,a){if(a.activity)throw new i("INVALID_ARGS","Activity override is not supported when opening an app-bound deep link URL");let n=a.url?.trim()??"";if(!E(n))throw new i("INVALID_ARGS","Android app-bound open requires a valid URL target");let r=await tJ(t,e,"app-bound open");await tf(t,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",n,"-p",r,...tW(a)])}async function tK(t,e,a){if(a.activity)throw new i("INVALID_ARGS","Activity override requires a package name, not an intent");await tf(t,["shell","am","start","-W","-a",e,...tW(a)])}async function tz(t,e,a,n,i){let r=a.includes("/")?a:`${e}/${a.startsWith(".")?a:`.${a}`}`;try{await tf(t,tZ(r,n,i))}catch(a){throw await tY(t,e,a),a}}async function tq(t,e,a,n){let r=await tf(t,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",tN,"-c",a,"-p",e,...tW(n)],{allowFailure:!0});if(0===r.exitCode&&!t9(r.stdout,r.stderr))return;let o=await t1(t,e);if(!o){if(!await tQ(t,e))throw tX(e);throw new i("COMMAND_FAILED",`Failed to launch ${e}`,{stdout:r.stdout,stderr:r.stderr})}await tf(t,tZ(o,a,n))}function tZ(t,e,a){return["shell","am","start","-W","-a","android.intent.action.MAIN","-c",tN,"-c",e,"-n",t,...tW(a)]}async function tJ(t,e,a){let n=await tT(t,e);if("intent"===n.type)throw new i("INVALID_ARGS",`Android ${a} requires a package name, not an intent`);return n.value}function tX(t){return new i("APP_NOT_INSTALLED",`No package found matching "${t}"`,{package:t,hint:tO})}async function tQ(t,e){let a=await tf(t,["shell","pm","path",e],{allowFailure:!0}),n=`${a.stdout}
4
4
  ${a.stderr}`;return!!(0===a.exitCode&&/\bpackage:/i.test(n))||(t0(n),!1)}async function tY(t,e,a){if(t0(a instanceof i?`${String(a.details?.stdout??"")}
5
5
  ${String(a.details?.stderr??"")}`:"")||!await tQ(t,e))throw tX(e)}function t0(t){return/\bunknown package\b/i.test(t)||/\bpackage .* (?:was|is) not found\b/i.test(t)||/\bpackage .* does not exist\b/i.test(t)||/\bcould not find package\b/i.test(t)}async function t1(t,e){for(let a of Array.from(new Set(tS(t,{includeFallbackWhenUnknown:!0})))){let n=await tf(t,["shell","cmd","package","resolve-activity","--brief","-a","android.intent.action.MAIN","-c",a,e],{allowFailure:!0});if(0!==n.exitCode)continue;let i=t2(n.stdout);if(i)return i}return null}function t9(t,e){let a=`${t}
6
6
  ${e}`;return/Error:.*(?:Activity not started|unable to resolve Intent)/i.test(a)}function t2(t){let e=t.split("\n").map(t=>t.trim()).filter(Boolean);for(let t=e.length-1;t>=0;t-=1){let a=e[t];if(void 0===a||!a.includes("/"))continue;let n=a.split(/\s+/)[0];if(void 0!==n)return n}return null}async function t3(t){t.booted||await tp(t.id)}async function t4(t,e){if("settings"===e.trim().toLowerCase()){await tf(t,["shell","am","force-stop","com.android.settings"]),await t5(t,"com.android.settings");return}let a=await tT(t,e);if("intent"===a.type)throw new i("INVALID_ARGS","Close requires a package name, not an intent");await tf(t,["shell","am","force-stop",a.value]),await t5(t,a.value)}async function t5(t,e){await t8(t,e),await t6(t,e)}async function t8(t,e){let a=Date.now()+2e3;for(;Date.now()<a;){let a=await t7(t);if(a?.package!==e)return;await p(50)}}async function t7(t){for(let e of[["shell","dumpsys","window","windows"],["shell","dumpsys","window"],["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]){let a=N((await tf(t,e,{allowFailure:!0})).stdout??"");if(a)return a}return null}async function t6(t,e){let a=Date.now()+2e3;for(;Date.now()<a;){if(!await et(t,e)&&(await p(150),!await et(t,e)))return;await p(50)}}async function et(t,e){return((await tf(t,["shell","pidof",e],{allowFailure:!0})).stdout??"").trim().length>0}async function ee(t,e){let a=await tT(t,e);if("intent"===a.type)throw new i("INVALID_ARGS","App uninstall requires a package name, not an intent");let n=await tf(t,["uninstall",a.value],{allowFailure:!0});if(0!==n.exitCode){let t=`${n.stdout}
7
- ${n.stderr}`.toLowerCase();if(!t.includes("unknown package")&&!t.includes("not installed"))throw new i("COMMAND_FAILED",`adb uninstall failed for ${a.value}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}return{package:a.value}}let ea=null;async function en(){let t=`${process.env.PATH??""}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR??""}`;if(ea?.key===t)return ea.invocation;if(await l("bundletool")){let e={cmd:"bundletool",prefixArgs:[]};return ea={key:t,invocation:e},e}let e=await s(process.env.AGENT_DEVICE_BUNDLETOOL_JAR,"AGENT_DEVICE_BUNDLETOOL_JAR");if(!e)throw new i("TOOL_MISSING","bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.");let a={cmd:"java",prefixArgs:["-jar",e]};return ea={key:t,invocation:a},a}async function ei(t){let e=await en();await o(e.cmd,[...e.prefixArgs,...t])}async function er(n,i){let r=m(n),o="universal";if(r.installBundle)return void await r.installBundle(i,{mode:o});let s=await t.mkdtemp(a.join(e.tmpdir(),"agent-device-aab-")),l=a.join(s,"bundle.apks");try{await ei(["build-apks","--bundle",i,"--output",l,"--mode",o]),await ei(["install-apks","--apks",l,"--device-id",n.id])}finally{await t.rm(s,{recursive:!0,force:!0})}}async function eo(t,e){".aab"===a.extname(e).toLowerCase()?await er(t,e):await w(e,{device:t,replace:!0})}async function es(t){return new Set((await tf(t,["shell","pm","list","packages"])).stdout.split("\n").map(t=>t.replace("package:","").trim()).filter(Boolean))}async function el(t,e){let a=Array.from(await es(t)).filter(t=>!e.has(t));if(1===a.length)return a[0]}async function ed(t,e){await tC.invalidateWhile(tE(t),async()=>{t.booted||await tp(t.id),await eo(t,e)})}async function eu(t,e,a){let n=a?void 0:await es(t);return await ed(t,e),a??(n?await el(t,n):void 0)}async function ec(t,e){t.booted||await tp(t.id);let a=await tv({kind:"path",path:e});try{let e=await eu(t,a.installablePath,a.packageName),n=e?tx(e):void 0;return{archivePath:a.archivePath,installablePath:a.installablePath,packageName:e,appName:n,launchTarget:e}}finally{await a.cleanup()}}async function ep(t,e,a){return await tC.invalidateWhile(tE(t),async()=>{t.booted||await tp(t.id);let{package:n}=await ee(t,e),i=await tv({kind:"path",path:a},{resolveIdentity:!1});try{await ed(t,i.installablePath)}finally{await i.cleanup()}return{package:n}})}async function ef(t,e={}){let a=["logcat","-d","-v","time"];void 0!==e.lines&&a.push("-t",String(Math.max(1,Math.floor(e.lines))));let n=await t(a,{allowFailure:!0,timeoutMs:e.timeoutMs,signal:e.signal});if(0!==n.exitCode)throw new i("COMMAND_FAILED","Failed to capture Android logcat",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});return n.stdout}function em(t,e={}){if(!t.spawn)throw new i("UNSUPPORTED_OPERATION","Android ADB provider does not support streams",{capability:"adb.spawn"});let a=["logcat","-v","time"];e.pid&&a.push("--pid",e.pid);let n=t.spawn(a,{stdio:["ignore","pipe","pipe"],signal:e.signal});return e.output&&n.stdout&&n.stdout.pipe(e.output,{end:!1}),n}export{R as Deadline,tm as androidDeviceForSerial,H as bootFailureHint,ef as captureAndroidLogcatWithAdb,ty as classifyAndroidAppTarget,j as classifyBootFailure,t4 as closeAndroidApp,L as createAppResolutionCache,tc as ensureAndroidEmulatorBooted,tg as formatAndroidInstalledPackageRequiredMessage,tU as getAndroidAppState,tP as getAndroidBlockingDialogFocus,tx as inferAndroidAppName,ec as installAndroidApp,eu as installAndroidInstallablePathAndResolvePackageName,t9 as isAmStartError,tw as isClipboardShellUnsupported,C as isDeepLinkTarget,S as isEnvTruthy,G as isInfrastructureBootFailureReason,E as isWebUrl,tL as listAndroidApps,tr as listAndroidDevices,tG as openAndroidApp,t3 as openAndroidDevice,N as parseAndroidForegroundApp,t2 as parseAndroidLaunchComponent,b as parseAndroidLaunchablePackages,I as parseAndroidUserInstalledPackages,$ as parseSerialAllowlist,tv as prepareAndroidInstallArtifact,ep as reinstallAndroidApp,tT as resolveAndroidApp,V as resolveAndroidSerialAllowlist,T as resolveIosDeviceDeepLinkBundleId,B as resolveIosSimulatorDeviceSetPath,x as retryWithPolicy,tf as runAndroidAdb,em as streamAndroidLogcatWithAdb,tp as waitForAndroidBoot,U as withRetry};
7
+ ${n.stderr}`.toLowerCase();if(!t.includes("unknown package")&&!t.includes("not installed"))throw new i("COMMAND_FAILED",`adb uninstall failed for ${a.value}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}return{package:a.value}}let ea=null;async function en(){let t=`${process.env.PATH??""}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR??""}`;if(ea?.key===t)return ea.invocation;if(await l("bundletool")){let e={cmd:"bundletool",prefixArgs:[]};return ea={key:t,invocation:e},e}let e=await s(process.env.AGENT_DEVICE_BUNDLETOOL_JAR,"AGENT_DEVICE_BUNDLETOOL_JAR");if(!e)throw new i("TOOL_MISSING","bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.");let a={cmd:"java",prefixArgs:["-jar",e]};return ea={key:t,invocation:a},a}async function ei(t){let e=await en();await o(e.cmd,[...e.prefixArgs,...t])}async function er(n,i){let r=m(n),o="universal";if(r.installBundle)return void await r.installBundle(i,{mode:o});let s=await t.mkdtemp(a.join(e.tmpdir(),"agent-device-aab-")),l=a.join(s,"bundle.apks");try{await ei(["build-apks","--bundle",i,"--output",l,"--mode",o]),await ei(["install-apks","--apks",l,"--device-id",n.id])}finally{await t.rm(s,{recursive:!0,force:!0})}}async function eo(t,e){".aab"===a.extname(e).toLowerCase()?await er(t,e):await w(e,{device:t,replace:!0})}async function es(t){return new Set((await tf(t,["shell","pm","list","packages"])).stdout.split("\n").map(t=>t.replace("package:","").trim()).filter(Boolean))}async function el(t,e){let a=Array.from(await es(t)).filter(t=>!e.has(t));if(1===a.length)return a[0]}async function ed(t,e){await tE.invalidateWhile(tC(t),async()=>{t.booted||await tp(t.id),await eo(t,e)})}async function eu(t,e,a){let n=a?void 0:await es(t);return await ed(t,e),a??(n?await el(t,n):void 0)}async function ec(t,e){t.booted||await tp(t.id);let a=await tv({kind:"path",path:e});try{let e=await eu(t,a.installablePath,a.packageName),n=e?tx(e):void 0;return{archivePath:a.archivePath,installablePath:a.installablePath,packageName:e,appName:n,launchTarget:e}}finally{await a.cleanup()}}async function ep(t,e,a){return await tE.invalidateWhile(tC(t),async()=>{t.booted||await tp(t.id);let{package:n}=await ee(t,e),i=await tv({kind:"path",path:a},{resolveIdentity:!1});try{await ed(t,i.installablePath)}finally{await i.cleanup()}return{package:n}})}async function ef(t,e={}){let a=["logcat","-d","-v","time"];void 0!==e.lines&&a.push("-t",String(Math.max(1,Math.floor(e.lines))));let n=await t(a,{allowFailure:!0,timeoutMs:e.timeoutMs,signal:e.signal});if(0!==n.exitCode)throw new i("COMMAND_FAILED","Failed to capture Android logcat",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});return n.stdout}function em(t,e={}){if(!t.spawn)throw new i("UNSUPPORTED_OPERATION","Android ADB provider does not support streams",{capability:"adb.spawn"});let a=["logcat","-v","time"];e.pid&&a.push("--pid",e.pid);let n=t.spawn(a,{stdio:["ignore","pipe","pipe"],signal:e.signal});return e.output&&n.stdout&&n.stdout.pipe(e.output,{end:!1}),n}export{R as Deadline,tm as androidDeviceForSerial,H as bootFailureHint,ef as captureAndroidLogcatWithAdb,ty as classifyAndroidAppTarget,j as classifyBootFailure,t4 as closeAndroidApp,L as createAppResolutionCache,tc as ensureAndroidEmulatorBooted,tg as formatAndroidInstalledPackageRequiredMessage,tU as getAndroidAppState,tP as getAndroidBlockingDialogFocus,tx as inferAndroidAppName,ec as installAndroidApp,eu as installAndroidInstallablePathAndResolvePackageName,t9 as isAmStartError,tw as isClipboardShellUnsupported,E as isDeepLinkTarget,S as isEnvTruthy,G as isInfrastructureBootFailureReason,C as isWebUrl,tL as listAndroidApps,tr as listAndroidDevices,tG as openAndroidApp,t3 as openAndroidDevice,N as parseAndroidForegroundApp,t2 as parseAndroidLaunchComponent,b as parseAndroidLaunchablePackages,I as parseAndroidUserInstalledPackages,$ as parseSerialAllowlist,tv as prepareAndroidInstallArtifact,ep as reinstallAndroidApp,tT as resolveAndroidApp,V as resolveAndroidSerialAllowlist,T as resolveIosDeviceDeepLinkBundleId,B as resolveIosSimulatorDeviceSetPath,x as retryWithPolicy,tf as runAndroidAdb,em as streamAndroidLogcatWithAdb,tp as waitForAndroidBoot,U as withRetry};
@@ -0,0 +1 @@
1
+ import{deflateSync as t,inflateSync as e}from"node:zlib";import{AppError as r}from"./9152.js";let n=Buffer.from([137,80,78,71,13,10,26,10]),i=new Map([[0,1],[2,3],[3,1],[4,2],[6,4]]),o=new Map([[0,new Set([1,2,4,8,16])],[2,new Set([8,16])],[3,new Set([1,2,4,8])],[4,new Set([8,16])],[6,new Set([8,16])]]),f=[{x:0,y:0,dx:8,dy:8},{x:4,y:0,dx:8,dy:8},{x:0,y:4,dx:4,dy:8},{x:2,y:0,dx:4,dy:4},{x:0,y:2,dx:2,dy:4},{x:1,y:0,dx:2,dy:2},{x:0,y:1,dx:1,dy:2}];class a{width;height;data;static sync={read:h,write:l};constructor(t){this.width=E(t.width,"width"),this.height=E(t.height,"height");let e=this.width*this.height*4;if(this.data=t.data?Buffer.from(t.data):Buffer.alloc(e),this.data.length!==e)throw Error(`PNG data length must be ${e} bytes`)}}function h(t){var r;let{metadata:h,idatChunks:l}=function(t){let e,r=[];for(let f of function*(t){if(!t.subarray(0,n.length).equals(n))throw Error("Invalid PNG signature");let e=n.length;for(;e<t.length;){if(e+12>t.length)throw Error("Truncated PNG chunk");let r=t.readUInt32BE(e),n=t.toString("ascii",e+4,e+8),i=e+8,o=i+r;if(o+4>t.length)throw Error(`Truncated PNG ${n} chunk`);let f=t.subarray(i,o),a=t.readUInt32BE(o);if(g(t.subarray(e+4,o))!==a)throw Error(`Invalid PNG ${n} chunk CRC`);e=o+4,yield{type:n,data:f}}}(t))if("IHDR"===f.type?e=function(t){var e;if(13!==t.length)throw Error("Invalid PNG IHDR length");let r=t.readUInt32BE(0),n=t.readUInt32BE(4),f=t[8],a=t[9],h=t[10],l=t[11],u=t[12];if(e=a,!i.has(e))throw Error(`Unsupported PNG color type ${a}`);let c=o.get(a);if(!c?.has(f))throw Error(`Unsupported PNG color type ${a} with bit depth ${f}`);if(0!==h)throw Error(`Unsupported PNG compression method ${h}`);if(0!==l)throw Error(`Unsupported PNG filter method ${l}`);if(0!==u&&1!==u)throw Error(`Unsupported PNG interlace method ${u}`);return{width:E(r,"width"),height:E(n,"height"),bitDepth:f,colorType:a,interlace:u}}(f.data):"IDAT"===f.type?r.push(Buffer.from(f.data)):e=function(t,e){if("PLTE"===t.type){if(!e)throw Error("PNG PLTE appeared before IHDR");e.palette=Buffer.from(t.data)}else if("tRNS"===t.type){if(!e)throw Error("PNG tRNS appeared before IHDR");e.transparency=Buffer.from(t.data)}return e}(f,e),"IEND"===f.type)break;return{metadata:e,idatChunks:r}}(t);if(!h)throw Error("PNG is missing IHDR");if(0===l.length)throw Error("PNG is missing IDAT");let s=function(t,r){let n=function(t){if(0===t.interlace)return function(t,e){return(p(t)+1)*e}(t,t.height);let e=0;for(let r of f){let n=c(t.width,r.x,r.dx),i=c(t.height,r.y,r.dy);0!==n&&0!==i&&(e+=function(t,e){return(p(t)+1)*e}({...t,width:n,height:i},i))}return e}(r);try{let r=e(Buffer.concat(t),{maxOutputLength:n});if(r.length!==n)throw Error("PNG pixel data is truncated");return r}catch(t){var i;if((i=t)instanceof Error&&"code"in i&&"ERR_BUFFER_TOO_LARGE"===i.code)throw Error(`PNG pixel data exceeds expected length ${n}`);throw t}}(l,h);return new a({width:h.width,height:h.height,data:1===h.interlace?function(t,e){let r=Buffer.alloc(e.width*e.height*4),n=0;for(let i of f){let o=c(e.width,i.x,i.dx),f=c(e.height,i.y,i.dy);if(0===o||0===f)continue;let a={...e,width:o,height:f,interlace:0},h=u({inflated:t,offset:n,scanlineLength:p(a),height:f,bytesPerPixel:y(a)});n=h.offset;let l=p(a);for(let t=0;t<f;t+=1){let n=h.raw.subarray(t*l,(t+1)*l);for(let f=0;f<o;f+=1){let o=i.x+f*i.dx,h=((i.y+t*i.dy)*e.width+o)*4,[l,u,c,s]=d(n,f,a);r[h]=l,r[h+1]=u,r[h+2]=c,r[h+3]=s}}}return r}(s,h):function(t,e){let r=Buffer.alloc(e.width*e.height*4),n=p(e);for(let i=0;i<e.height;i+=1){let o=t.subarray(i*n,(i+1)*n);for(let t=0;t<e.width;t+=1){let n=(i*e.width+t)*4,[f,a,h,l]=d(o,t,e);r[n]=f,r[n+1]=a,r[n+2]=h,r[n+3]=l}}return r}(u({inflated:s,offset:0,scanlineLength:p(r=h),height:r.height,bytesPerPixel:y(r)}).raw,h)})}function l(e){let r=4*e.width,i=Buffer.alloc((r+1)*e.height);for(let t=0;t<e.height;t+=1){let n=t*(r+1);i[n]=0,e.data.copy(i,n+1,t*r,(t+1)*r)}let o=Buffer.alloc(13);return o.writeUInt32BE(e.width,0),o.writeUInt32BE(e.height,4),o[8]=8,o[9]=6,o[10]=0,o[11]=0,o[12]=0,Buffer.concat([n,w("IHDR",o),w("IDAT",t(i)),w("IEND",Buffer.alloc(0))])}function u(t){let{inflated:e,offset:r,scanlineLength:n,height:i,bytesPerPixel:o}=t,f=r+(n+1)*i;if(e.length<f)throw Error("PNG pixel data is truncated");let a=Buffer.alloc(n*i);for(let t=0;t<i;t+=1){let i=r+t*(n+1),f=t*n,h=e[i];for(let r=0;r<n;r+=1){let l=e[i+1+r],u=r>=o?a[f+r-o]:0,c=t>0?a[f+r-n]:0,d=t>0&&r>=o?a[f+r-n-o]:0;a[f+r]=function(t,e,r,n,i){if(0===t)return e;if(1===t)return e+r&255;if(2===t)return e+n&255;if(3===t)return e+Math.floor((r+n)/2)&255;if(4===t)return e+function(t,e,r){let n=t+e-r,i=Math.abs(n-t),o=Math.abs(n-e),f=Math.abs(n-r);return i<=o&&i<=f?t:o<=f?e:r}(r,n,i)&255;throw Error(`Unsupported PNG filter type ${t}`)}(h,l,u,c,d)}}return{raw:a,offset:f}}function c(t,e,r){return t<=e?0:Math.floor((t-e+r-1)/r)}function d(t,e,r){if(3===r.colorType){var n,o,f,a,h,l,u,c=t,d=e,p=r;if(!p.palette)throw Error("Indexed PNG is missing PLTE");let i=s(c,d,p.bitDepth),y=3*i;if(y+2>=p.palette.length)throw Error("Indexed PNG palette is invalid");return[p.palette[y],p.palette[y+1],p.palette[y+2],p.transparency?.[i]??255]}if(r.bitDepth<8){let i,o;return[o=Math.round((i=s(t,e,(n=r).bitDepth))/((1<<n.bitDepth)-1)*255),o,o,255*!(n.transparency&&n.transparency.length>=2&&i===n.transparency.readUInt16BE(0))]}let y=16===r.bitDepth?2:1,w=e*i.get(r.colorType)*y,g=e=>16===r.bitDepth?t.readUInt16BE(w+2*e):t[w+e*y],E=t=>{var e;return e=g(t),16===r.bitDepth?Math.round(e/65535*255):e};if(0===r.colorType){let t=E(0);return[t,t,t,255*(o=g(0),!(f=r).transparency||!!(f.transparency.length<2)||o!==f.transparency.readUInt16BE(0))]}if(2===r.colorType){return[E(0),E(1),E(2),255*(a=g(0),h=g(1),l=g(2),!(u=r).transparency||!!(u.transparency.length<6)||a!==u.transparency.readUInt16BE(0)||h!==u.transparency.readUInt16BE(2)||l!==u.transparency.readUInt16BE(4))]}if(4===r.colorType){let t=E(0);return[t,t,t,E(1)]}return[E(0),E(1),E(2),E(3)]}function s(t,e,r){let n=e*r;return t[Math.floor(n/8)]>>8-r-n%8&(1<<r)-1}function p(t){let e=i.get(t.colorType);return Math.ceil(t.width*e*t.bitDepth/8)}function y(t){return Math.max(1,Math.ceil(i.get(t.colorType)*t.bitDepth/8))}function w(t,e){let r=Buffer.from(t,"ascii"),n=Buffer.alloc(8+e.length+4);return n.writeUInt32BE(e.length,0),r.copy(n,4),e.copy(n,8),n.writeUInt32BE(g(Buffer.concat([r,e])),8+e.length),n}function g(t){let e=0xffffffff;for(let r of t){e^=r;for(let t=0;t<8;t+=1)e=1&e?0xedb88320^e>>>1:e>>>1}return(0xffffffff^e)>>>0}function E(t,e){if(!Number.isInteger(t)||t<1)throw Error(`PNG ${e} must be positive`);return t}function x(t,e){try{return a.sync.read(t)}catch(t){throw new r("COMMAND_FAILED",`Failed to decode ${e} as PNG`,{label:e,reason:t instanceof Error?t.message:String(t)})}}function B(t){let{baselineData:e,currentData:r,maxColorDistance:n}=t,i=t.width*t.height,o=Buffer.alloc(4*i),f=new Uint8Array(i),a=0;for(let t=0,i=0;t<e.length;t+=4,i+=1){if(Math.sqrt((e[t]-r[t])**2+(e[t+1]-r[t+1])**2+(e[t+2]-r[t+2])**2)>n){a+=1,f[i]=1;let e=P(r,t);o[t]=b(e,220,.78),o[t+1]=b(e,0,.78),o[t+2]=b(e,0,.78),o[t+3]=255;continue}let h=P(r,t);o[t]=h,o[t+1]=h,o[t+2]=h,o[t+3]=255}return{diffData:o,diffMask:f,differentPixels:a}}function P(t,e){return b(Math.round(.299*t[e]+.587*t[e+1]+.114*t[e+2]),255,.72)}function b(t,e,r){return Math.round(t*(1-r)+e*r)}function I(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}export{a as PNG,B as computeScreenshotDiffPixels,x as decodePng,I as toBuffer};
package/dist/src/9238.js CHANGED
@@ -1,4 +1,4 @@
1
- import e from"node:path";import t from"node:crypto";import n from"node:fs";import{resolveUserPath as o,expandUserHomePath as r}from"./3267.js";import{findProjectRoot as s}from"./9671.js";function i(e,t){let n=[],o=e+t.toString(),r=o.indexOf("\n");for(;-1!==r;){let e=o.slice(0,r).trim();o=o.slice(r+1),e&&n.push(e),r=o.indexOf("\n")}return{lines:n,buffer:o}}function l(t){let n,s=(n=(t??"").trim())?o(n):e.join(r("~"),".agent-device");return{baseDir:s,infoPath:e.join(s,"daemon.json"),lockPath:e.join(s,"daemon.lock"),logPath:e.join(s,"daemon.log"),sessionsDir:e.join(s,"sessions")}}function u(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function a(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function f(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function c(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let p=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,m=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,d=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function h(){let e=process.argv[1];return e?g(e):"unknown"}function g(o,r=s()){try{let s=e.resolve(r),i=[e.resolve(o)],l=new Set,u=[];for(;i.length>0;){let t=i.pop();if(!t||l.has(t))continue;l.add(t);let o=n.statSync(t);if(!o.isFile())continue;let r=e.relative(s,t)||t;u.push(`${r}:${o.size}:${Math.trunc(o.mtimeMs)}`);let a=n.readFileSync(t,"utf8");for(let n of function(e){let t=new Set;return v(e,p,t),v(e,m,t),[...t]}(a)){let o=function(t,n){let o=e.resolve(e.dirname(t),n),r=y(o);if(r)return r;for(let e of d){let t=y(`${o}${e}`);if(t)return t}for(let t of d){let n=y(e.join(o,`index${t}`));if(n)return n}return null}(t,n);o&&i.push(o)}}let a=u.sort().join("|"),f=t.createHash("sha1").update(a).digest("hex");return`graph:${u.length}:${f}`}catch{return"unknown"}}function v(e,t,n){t.lastIndex=0;let o=null;for(;null!==(o=t.exec(e));){let e=o[1]?.trim();e?.startsWith(".")&&n.add(e)}}function y(e){try{return n.statSync(e).isFile()?e:null}catch{return null}}let S=/^[A-Za-z0-9_@%+=:,./-]+$/;function $(e){return`'${e.replaceAll("'","'\\''")}'`}function j(e){return S.test(e)?e:$(e)}function _(e){return e.meta?.requestProgress==="replay-test"}function x(e){return!!e&&"object"==typeof e&&"progress"===e.type&&!!e.event}function D(e){return!!e&&"object"==typeof e&&"response"===e.type&&!!e.response}function P(e){return`${JSON.stringify({type:"progress",event:e})}
1
+ import e from"node:crypto";import t from"node:fs";import n from"node:path";import{resolveUserPath as r,expandUserHomePath as o}from"./3267.js";import{findProjectRoot as s}from"./9671.js";function i(l,a={}){var u,c;let f,p=(u=l,c=a,(f=(u??"").trim())?r(f,{env:c.env}):function(r={}){var i;let l,a,u,c=n.join(o("~",{env:r.env}),".agent-device"),f=r.projectRoot??s();return(i=f,t.existsSync(n.join(i,"package.json"))&&t.existsSync(n.join(i,"src","daemon.ts")))?n.join(c,"dev",(l=function(e){try{return t.realpathSync.native(e)}catch{return n.resolve(e)}}(f),a=n.basename(l).replaceAll(/[^a-zA-Z0-9._-]+/g,"-"),u=e.createHash("sha1").update(l).digest("hex").slice(0,12),`${a||"agent-device"}-${u}`)):c}(c));return{baseDir:p,infoPath:n.join(p,"daemon.json"),lockPath:n.join(p,"daemon.lock"),logPath:n.join(p,"daemon.log"),sessionsDir:n.join(p,"sessions")}}function l(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function a(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function u(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function c(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let f=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,p=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,m=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function d(){let e=process.argv[1];return e?h(e):"unknown"}function h(r,o=s()){try{let s=n.resolve(o),i=[n.resolve(r)],l=new Set,a=[];for(;i.length>0;){let e=i.pop();if(!e||l.has(e))continue;l.add(e);let r=t.statSync(e);if(!r.isFile())continue;let o=n.relative(s,e)||e;a.push(`${o}:${r.size}:${Math.trunc(r.mtimeMs)}`);let u=t.readFileSync(e,"utf8");for(let t of function(e){let t=new Set;return v(e,f,t),v(e,p,t),[...t]}(u)){let r=function(e,t){let r=n.resolve(n.dirname(e),t),o=g(r);if(o)return o;for(let e of m){let t=g(`${r}${e}`);if(t)return t}for(let e of m){let t=g(n.join(r,`index${e}`));if(t)return t}return null}(e,t);r&&i.push(r)}}let u=a.sort().join("|"),c=e.createHash("sha1").update(u).digest("hex");return`graph:${a.length}:${c}`}catch{return"unknown"}}function v(e,t,n){t.lastIndex=0;let r=null;for(;null!==(r=t.exec(e));){let e=r[1]?.trim();e?.startsWith(".")&&n.add(e)}}function g(e){try{return t.statSync(e).isFile()?e:null}catch{return null}}let y=/^[A-Za-z0-9_@%+=:,./-]+$/;function S(e){return`'${e.replaceAll("'","'\\''")}'`}function j(e){return y.test(e)?e:S(e)}function $(e,t){let n=[],r=e+t.toString(),o=r.indexOf("\n");for(;-1!==o;){let e=r.slice(0,o).trim();r=r.slice(o+1),e&&n.push(e),o=r.indexOf("\n")}return{lines:n,buffer:r}}function x(e){return e.meta?.requestProgress==="replay-test"}function _(e){return!!e&&"object"==typeof e&&"progress"===e.type&&!!e.event}function D(e){return!!e&&"object"==typeof e&&"response"===e.type&&!!e.response}function P(e){return`${JSON.stringify({type:"progress",event:e})}
2
2
  `}function C(e){return`${JSON.stringify({type:"response",response:e})}
3
- `}function w(e){return`${JSON.stringify({type:"response",response:e})}
4
- `}export{g as computeDaemonCodeSignature,i as consumeTextLines,x as isDaemonProgressEnvelope,D as isDaemonResponseEnvelope,c as normalizeTenantId,h as resolveDaemonCodeSignature,l as resolveDaemonPaths,u as resolveDaemonServerMode,a as resolveDaemonTransportPreference,f as resolveSessionIsolationMode,P as serializeDaemonProgressEnvelope,C as serializeDaemonResponseEnvelope,w as serializeDaemonRpcResponseEnvelope,$ as shellQuote,j as shellQuoteIfNeeded,_ as shouldStreamRequestProgress};
3
+ `}function k(e){return`${JSON.stringify({type:"response",response:e})}
4
+ `}export{h as computeDaemonCodeSignature,$ as consumeTextLines,_ as isDaemonProgressEnvelope,D as isDaemonResponseEnvelope,c as normalizeTenantId,d as resolveDaemonCodeSignature,i as resolveDaemonPaths,l as resolveDaemonServerMode,a as resolveDaemonTransportPreference,u as resolveSessionIsolationMode,P as serializeDaemonProgressEnvelope,C as serializeDaemonResponseEnvelope,k as serializeDaemonRpcResponseEnvelope,S as shellQuote,j as shellQuoteIfNeeded,x as shouldStreamRequestProgress};
package/dist/src/9471.js CHANGED
@@ -1 +1 @@
1
- import{setSessionSnapshot as e,captureSnapshot as r,isNavigationSensitiveAction as t,markPendingInteractionOutcome as n,markPostGestureStabilization as o,getSnapshotReferenceFrame as i,recordTouchVisualizationEvent as a,markAndroidSnapshotFreshness as c,stripInternalInteractionFlags as s}from"./2415.js";import{successText as d}from"./1998.js";import{getAndroidScreenSize as f}from"./input-actions.js";import{emitDiagnostic as u}from"./7599.js";async function l(t,n,o,i,a){let c={...n??{},snapshotInteractiveOnly:a.interactiveOnly,snapshotCompact:a.interactiveOnly},s=i(c,t.appBundleId,t.trace?.outPath),{snapshot:d}=await r({device:t.device,session:t,flags:c,outPath:c.out,logPath:s.logPath??"",androidFreshnessMode:a.androidFreshnessMode});return e(t,d),o.set(t.name,t),d}function p(e){var r,t,n;let o,i,a,{data:c,fallbackX:s,fallbackY:f,referenceFrame:u,extra:l}=e,p=(r=l,t=s,n=f,o="string"==typeof r?.ref?r.ref:void 0,i="string"==typeof r?.button?r.button:void 0,a="string"==typeof r?.gesture?r.gesture:void 0,("string"==typeof r?.text?`Filled ${Array.from(r.text).length} chars`:o?"longpress"===a?`Long pressed @${o} (${t}, ${n})`:i&&"primary"!==i?`Clicked ${i} @${o} (${t}, ${n})`:`Tapped @${o} (${t}, ${n})`:void 0)??("string"==typeof c?.message?c.message:void 0));return{x:s,y:f,...u??{},...l??{},...c??{},...d(p)}}function h(e){let{session:r,sessionStore:i,command:d,positionals:f,retryPositionals:u,flags:l,result:p,responseData:h,actionStartedAt:g,actionFinishedAt:m,androidFreshnessBaseline:_}=e,v=s(l);return i.recordAction(r,{command:d,positionals:f,flags:v??{},result:p}),n({session:r,command:d,positionals:u??f,flags:l,preSnapshot:r.snapshot}),t(d)&&c(r,d,_??r.snapshot),o(r,d,u??f,l),a(r,d,f,p,v??{},g,m),{ok:!0,data:h}}async function g(e){let{session:r,flags:t,sessionStore:n,contextFromFlags:o,captureSnapshotForSession:a}=e;if(!r.recording)return;if(r.recording.touchReferenceFrame)return r.recording.touchReferenceFrame;if("android"===r.device.platform){let e=await f(r.device),t={referenceWidth:e.width,referenceHeight:e.height};return r.recording&&(r.recording.touchReferenceFrame=t),t}let c=i(r.snapshot);if(c)return r.recording&&(r.recording.touchReferenceFrame=c),c;if(!r.recording)return;let s=i(await a(r,t,n,o,{interactiveOnly:!0}));return s&&r.recording&&(r.recording.touchReferenceFrame=s),s}async function m(e){try{return await g(e)}catch(r){u({level:"warn",phase:"touch_reference_frame_resolve_failed",data:{platform:e.session.device.platform,error:r instanceof Error?r.message:String(r)}});return}}function _(e){return i({nodes:e,createdAt:0})}export{p as buildTouchVisualizationResult,h as finalizeTouchInteraction,l as interaction_snapshot_captureSnapshotForSession,_ as readSnapshotNodesReferenceFrame,m as resolveDirectTouchReferenceFrameSafely};
1
+ import{setSessionSnapshot as e,captureSnapshot as r,isNavigationSensitiveAction as t,markPendingInteractionOutcome as n,markPostGestureStabilization as o,getSnapshotReferenceFrame as i,recordTouchVisualizationEvent as a,markAndroidSnapshotFreshness as c,stripInternalInteractionFlags as s}from"./2415.js";import{isSparseSnapshotQualityVerdict as d,successText as f}from"./6133.js";import{getAndroidScreenSize as u}from"./input-actions.js";import{emitDiagnostic as l}from"./7599.js";async function h(t,n,o,i,a){let c={...n??{},snapshotInteractiveOnly:a.interactiveOnly},s=i(c,t.appBundleId,t.trace?.outPath),{snapshot:f}=await r({device:t.device,session:t,flags:c,outPath:c.out,logPath:s.logPath??"",androidFreshnessMode:a.androidFreshnessMode});return d(f.snapshotQuality)||(e(t,f),o.set(t.name,t)),f}function p(e){var r,t,n;let o,i,a,{data:c,fallbackX:s,fallbackY:d,referenceFrame:u,extra:l}=e,h=(r=l,t=s,n=d,o="string"==typeof r?.ref?r.ref:void 0,i="string"==typeof r?.button?r.button:void 0,a="string"==typeof r?.gesture?r.gesture:void 0,("string"==typeof r?.text?`Filled ${Array.from(r.text).length} chars`:o?"longpress"===a?`Long pressed @${o} (${t}, ${n})`:i&&"primary"!==i?`Clicked ${i} @${o} (${t}, ${n})`:`Tapped @${o} (${t}, ${n})`:void 0)??("string"==typeof c?.message?c.message:void 0));return{x:s,y:d,...u??{},...l??{},...c??{},...f(h)}}function g(e){let{session:r,sessionStore:i,command:d,positionals:f,retryPositionals:u,flags:l,result:h,responseData:p,actionStartedAt:g,actionFinishedAt:_,androidFreshnessBaseline:m}=e,v=s(l);return i.recordAction(r,{command:d,positionals:f,flags:v??{},result:h}),n({session:r,command:d,positionals:u??f,flags:l,preSnapshot:r.snapshot}),t(d)&&c(r,d,m??r.snapshot),o(r,d,u??f,l),a(r,d,f,h,v??{},g,_),{ok:!0,data:p}}async function _(e){let{session:r,flags:t,sessionStore:n,contextFromFlags:o,captureSnapshotForSession:a}=e;if(!r.recording)return;if(r.recording.touchReferenceFrame)return r.recording.touchReferenceFrame;if("android"===r.device.platform){let e=await u(r.device),t={referenceWidth:e.width,referenceHeight:e.height};return r.recording&&(r.recording.touchReferenceFrame=t),t}let c=i(r.snapshot);if(c)return r.recording&&(r.recording.touchReferenceFrame=c),c;if(!r.recording)return;let s=i(await a(r,t,n,o,{interactiveOnly:!0}));return s&&r.recording&&(r.recording.touchReferenceFrame=s),s}async function m(e){try{return await _(e)}catch(r){l({level:"warn",phase:"touch_reference_frame_resolve_failed",data:{platform:e.session.device.platform,error:r instanceof Error?r.message:String(r)}});return}}function v(e){return i({nodes:e,createdAt:0})}export{p as buildTouchVisualizationResult,g as finalizeTouchInteraction,h as interaction_snapshot_captureSnapshotForSession,v as readSnapshotNodesReferenceFrame,m as resolveDirectTouchReferenceFrameSafely};
package/dist/src/9542.js CHANGED
@@ -1,3 +1,6 @@
1
- import e from"node:net";import t from"node:http";import a from"node:https";import r from"node:fs";import n from"node:os";import o from"node:path";import{pipeline as i}from"node:stream/promises";import{createHash as s,randomUUID as l}from"node:crypto";import{Writable as c}from"node:stream";import{toAppErrorCode as d,AppError as u}from"./9152.js";import{runCmdSync as p,runCmd as m,runCmdDetached as f}from"./9818.js";import{consumeTextLines as h,shellQuote as y,shouldStreamRequestProgress as w,isDaemonResponseEnvelope as g,resolveDaemonPaths as I,isDaemonProgressEnvelope as v,resolveDaemonServerMode as A,computeDaemonCodeSignature as _,resolveDaemonTransportPreference as P}from"./9238.js";import{readVersion as k,findProjectRoot as S}from"./9671.js";import{createRequestId as b,withDiagnosticTimer as D,emitDiagnostic as E}from"./7599.js";import{isAgentDeviceDaemonProcess as M,stopProcessForTakeover as T}from"./8656.js";import{INTERNAL_COMMANDS as N,PUBLIC_COMMANDS as C}from"./5792.js";import{sleep as L}from"./4829.js";import{reloadMetro as U,prepareMetroRuntime as R}from"./1974.js";import{normalizeSession as x,resolveSessionName as O,buildFlags as $,normalizeStartupSample as F,normalizeInstallFromSourceResult as B,normalizeMaterializationReleaseResult as q,prepareDaemonCommandRequest as j,readSnapshotNodes as K,normalizeRuntimeHints as H,normalizeDeployResult as G,normalizeOpenDevice as z,readScreenshotOverlayRefs as V,buildMeta as J,normalizeDevice as W}from"./8699.js";import{readRequiredString as Y,readOptionalString as Q}from"./7455.js";function X(e){return new Promise((t,a)=>{let r="";e.setEncoding("utf8"),e.on("data",e=>{r+=e}),e.on("end",()=>t(r)),e.on("error",a)})}let Z="sha256";async function ee(e){let t=await et(e.localPath,e.platform),a=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;try{let r=await eo({normalizedBase:a,token:e.token,artifact:t});if(r?.kind==="cache-hit")return r.uploadId;if(r?.kind==="direct-upload")try{return await ei(t.payloadPath,r),await el({normalizedBase:a,token:e.token,uploadId:r.uploadId})}catch{}return await en({normalizedBase:a,token:e.token,artifact:t})}finally{t.cleanup()}}async function et(e,t){var a,n,i;let s,l=r.statSync(e),c=o.basename(e),d=l.isDirectory(),u=("ios"===(a=t)||"android"===a?a:void 0)??(n=e,i=l,s=n.toLowerCase(),i.isDirectory()&&s.endsWith(".app")||s.endsWith(".ipa")?"ios":s.endsWith(".apk")||s.endsWith(".aab")?"android":void 0),p=[];try{let t=d?await ea(e,p):e,a=r.statSync(t);return{payloadPath:t,fileName:c,artifactType:d?"app-bundle":"file",platform:u,contentType:d?"application/gzip":"application/octet-stream",sha256:await ec(t),sizeBytes:a.size,cleanup:()=>er(p)}}catch(e){throw er(p),e}}async function ea(e,t){let a=r.mkdtempSync(o.join(n.tmpdir(),`agent-device-upload-${l()}-`));t.push(a);let i=o.join(a,`${o.basename(e)}.tar.gz`);return await m("tar",["czf",i,"-C",o.dirname(e),o.basename(e)],{env:{...process.env,COPYFILE_DISABLE:"1"}}),i}function er(e){for(let t of e)r.rmSync(t,{recursive:!0,force:!0})}async function en(e){let{normalizedBase:t,token:a,artifact:r}=e,n=new URL("upload",t),o={"content-type":r.contentType,"x-artifact-type":r.artifactType,"x-artifact-filename":r.fileName,"x-artifact-hash":r.sha256,"x-artifact-hash-algorithm":Z,"transfer-encoding":"chunked"};a&&(o.authorization=`Bearer ${a}`,o["x-agent-device-token"]=a);let i=await es({url:n,method:"POST",headers:o,payloadPath:r.payloadPath,timeoutMessage:"Artifact upload timed out",timeoutHint:"The upload to the remote daemon exceeded the 5-minute timeout.",errorMessage:"Failed to upload artifact to remote daemon",errorHint:"Verify the remote daemon is reachable and supports artifact uploads."});try{let e=JSON.parse(i.body);if(!e.ok||!e.uploadId)throw new u("COMMAND_FAILED",`Upload failed: ${i.body}`);return e.uploadId}catch(e){if(e instanceof u)throw e;throw new u("COMMAND_FAILED",`Invalid upload response: ${i.body}`)}}async function eo(e){let t=new URL("upload/preflight",e.normalizedBase),a={"content-type":"application/json"};e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token);let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({sha256:e.artifact.sha256,fileName:e.artifact.fileName,sizeBytes:e.artifact.sizeBytes,artifactType:e.artifact.artifactType,...e.artifact.platform?{platform:e.artifact.platform}:{},contentType:e.artifact.contentType})}).catch(()=>void 0);if(r?.ok)return function(e){var t;if(!e||"object"!=typeof e||!0!==e.ok||"string"!=typeof e.uploadId)return;if(!0===e.cacheHit)return{kind:"cache-hit",uploadId:e.uploadId};let a=e.upload;if(!a||"string"!=typeof a.url)return;let r=a.headers??{};if(!(!(t=r)||"object"!=typeof t||Array.isArray(t))&&Object.values(t).every(e=>"string"==typeof e))return{kind:"direct-upload",uploadId:e.uploadId,url:a.url,headers:r}}(await r.json().catch(()=>void 0))}async function ei(e,t){let a=await es({url:new URL(t.url),method:"PUT",headers:t.headers,payloadPath:e,timeoutMessage:"Direct artifact upload timed out",timeoutHint:"The direct upload ticket did not accept the artifact within the timeout.",errorMessage:"Failed to upload artifact with direct upload ticket"});if(a.statusCode<200||a.statusCode>=300)throw new u("COMMAND_FAILED","Direct artifact upload failed",{statusCode:a.statusCode,statusMessage:a.statusMessage})}async function es(e){let n="https:"===e.url.protocol?a:t;return await new Promise((t,a)=>{let o=n.request({protocol:e.url.protocol,host:e.url.hostname,port:e.url.port,method:e.method,path:e.url.pathname+e.url.search,headers:e.headers},e=>{X(e).then(a=>{clearTimeout(s),t({statusCode:e.statusCode??500,statusMessage:e.statusMessage,body:a})}).catch(a)}),s=setTimeout(()=>{o.destroy(),a(new u("COMMAND_FAILED",e.timeoutMessage,{timeoutMs:3e5,...e.timeoutHint?{hint:e.timeoutHint}:{}}))},3e5);o.on("error",t=>{clearTimeout(s),a(new u("COMMAND_FAILED",e.errorMessage,e.errorHint?{hint:e.errorHint}:{},t))}),o.on("close",()=>clearTimeout(s)),i(r.createReadStream(e.payloadPath),o).catch(e=>{o.destroy(),a(new u("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:Error(String(e))))})})}async function el(e){let t=new URL("upload/finalize",e.normalizedBase),a={"content-type":"application/json"};e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token);let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({uploadId:e.uploadId})}).catch(e=>{throw new u("COMMAND_FAILED","Failed to finalize direct artifact upload",{},e)});if(!r.ok)throw new u("COMMAND_FAILED","Direct artifact upload finalize failed",{status:r.status,statusText:r.statusText});let n=await r.json().catch(()=>void 0);if(!n?.ok||!n.uploadId)throw new u("COMMAND_FAILED","Invalid upload finalize response");return n.uploadId}async function ec(e){let t=s(Z),a=new c({write(e,a,r){t.update(e),r()}});return await i(r.createReadStream(e),a).catch(e=>{throw new u("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:void 0)}),t.digest("hex")}function ed(e){let t=Math.max(0,e)/1e3;return t>=10?`${t.toFixed(1)}s`:t>=1?`${t.toFixed(2)}s`:`${t.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}s`}function eu(e){let t=function(e){var t,a,r;let n,i;if("replay-test"!==e.type||"pass"===e.status||"fail"===e.status&&!e.retrying)return;let s=(t=e,(n=t.title?.trim())?JSON.stringify(n):o.basename(t.file)),l=void 0!==e.durationMs?` (${i=ed((a=e).durationMs??0),a.attempt&&a.attempt>1&&!a.retrying?`total ${i}`:i})`:"",c=void 0===(r=e).attempt?"":"fail"===r.status&&r.retrying&&void 0!==r.maxAttempts?` attempt ${r.attempt}/${r.maxAttempts} retrying`:r.attempt>1?` after ${r.attempt} attempts`:"",d=e.message?.replace(/\s+/g," ").trim();return"skip"===e.status?[`SKIP ${s}`,d?` ${d}`:""].filter(Boolean).join("\n"):[`FAIL ${s}${c}${l}`,d?` ${d}`:"",e.artifactsDir?` artifacts: ${e.artifactsDir}`:""].filter(Boolean).join("\n")}(e);t&&process.stderr.write(`${t}
2
- `)}let ep=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"],em=new e.BlockList;async function ef(t){var a,i,s,l,c,d;let p,m,f,h,y,w,g,v=t.meta?.requestId??b(),_=!!(t.meta?.debug||t.flags?.verbose),k=(h=(i=a=t,i.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),y=(s=a,m=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new u("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new u("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(p=s.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),function(t,a){let r;if(!(!t||"localhost"===(r=new URL(t).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(e.isIPv4(r)?em.check(r,"ipv4"):!!e.isIPv6(r)&&em.check(r,"ipv6")))&&("string"!=typeof a||!(a.trim().length>0)))throw new u("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:t,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."})}(m,f=s.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN),{rawBaseUrl:p,remoteBaseUrl:m,authToken:f}),w=function(e,t){let a=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,r=P(a);if(t&&"socket"===r)throw new u("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:t});return{preference:r,serverMode:A(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===a?"dual":void 0))}}(a,y.remoteBaseUrl),{paths:I((g=(l=a,c=h,d=y.rawBaseUrl,eb(l.command)&&!c&&!d))?r.mkdtempSync(o.join(n.tmpdir(),"agent-device-replay-daemon-")):h),transportPreference:w.preference,serverMode:w.serverMode,ownedStateDir:g,remoteBaseUrl:y.remoteBaseUrl,remoteAuthToken:y.authToken}),S=function(e){if(e.command!==C.test){var t;return"number"==typeof e.flags?.timeoutMs&&((t=e.command)===C.prepare||t===C.replay||t===C.snapshot)?e.flags.timeoutMs:e.command===C.prepare?24e4:9e4}}(t),M=await D("daemon_startup",async()=>await eA(k),{requestId:v,session:t.session}),T=M.info,N=await eh(t,T),L={...t,positionals:N.positionals,flags:N.flags,token:T.token,meta:{...t.meta??{},requestId:v,debug:_,cwd:t.meta?.cwd,sessionExplicit:t.meta?.sessionExplicit,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,...N.uploadedArtifactId?{uploadedArtifactId:N.uploadedArtifactId}:{},...N.clientArtifactPaths?{clientArtifactPaths:N.clientArtifactPaths}:{},...N.installSource?{installSource:N.installSource}:{}}};E({level:"info",phase:"daemon_request_prepare",data:{requestId:v,command:t.command,session:t.session}});try{return await D("daemon_request",async()=>await eq(T,L,k.transportPreference,S),{requestId:v,command:t.command})}finally{await eS(t,M,k)}}async function eh(e,t){let a,r=[...e.positionals??[]],n=e.flags?{...e.flags}:void 0,i=e.meta?.installSource,s={};if(!eY(t))return ew({positionals:r,flags:n,installSource:i,uploadedArtifactId:a,clientArtifactPaths:s});n=function(e,t,a,r){var n,i;let s=function(e,t){if("screenshot"===e.command){let a=eI(e,"path",".png");return t[0]?{field:"path",localPath:a,positionalIndex:0,positionalPath:ev("screenshot",".png")}:{field:"path",localPath:a,positionalIndex:0,flagPath:ev("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=eI(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:ev("recording",o.extname(t)||".mp4")}}return null}(e,t);if(!s)return a;void 0!==s.positionalPath&&(t[s.positionalIndex]=s.positionalPath);let l=(n=a,void 0===(i=s.flagPath)?n:{...n??{},out:i});return r[s.field]=s.localPath,l}(e,r,n,s);let l=await eg(e,t);l&&(i=l.installSource,a=l.uploadedArtifactId??a);let c=()=>ew({positionals:r,flags:n,installSource:i,uploadedArtifactId:a,clientArtifactPaths:s});return"install"!==e.command&&"reinstall"!==e.command||(a=await ey(e,t,r)??a),c()}async function ey(e,t,a){var n,i;let s,l=a[1];if(void 0===l)return;if(l.startsWith("remote:")){a[1]=l.slice(7);return}let c=(n=l,i=e.meta?.cwd,s=o.isAbsolute(n)?n:o.resolve(i??process.cwd(),n),r.existsSync(s)?s:void 0);if(c)return await ee({localPath:c,baseUrl:t.baseUrl,token:t.token,platform:e.flags?.platform})}function ew(e){return{positionals:e.positionals,flags:e.flags,installSource:e.installSource,uploadedArtifactId:e.uploadedArtifactId,...Object.keys(e.clientArtifactPaths).length>0?{clientArtifactPaths:e.clientArtifactPaths}:{}}}async function eg(e,t){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 i=o.isAbsolute(n)?n:o.resolve(e.meta?.cwd??process.cwd(),n);if(!r.existsSync(i))return{installSource:{...a,path:i}};let s=await ee({localPath:i,baseUrl:t.baseUrl,token:t.token,platform:e.flags?.platform});return{installSource:{...a,path:i},uploadedArtifactId:s}}function eI(e,t,a,r=0){let n=e.positionals?.[r]??e.flags?.out,i=`${"path"===t?"screenshot":"recording"}-${Date.now()}${a}`,s=n&&n.trim().length>0?n:i;return o.isAbsolute(s)?s:o.resolve(e.meta?.cwd??process.cwd(),s)}function ev(e,t){let a=t.startsWith(".")?t:`.${t}`;return o.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${a}`)}async function eA(e){if(e.remoteBaseUrl)return await e_(e);let t=await eP(e);return t?{info:t,startedByClient:!1}:(function(e){let t=eR(e);if(!t.hasLock||t.hasInfo)return;let a=eL(e.lockPath);if(!a)return eO(e.lockPath);M(a.pid,a.processStartTime)||eO(e.lockPath)}(e.paths),await ek(e))}async function e_(e){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await e$(t,"http"))return{info:t,startedByClient:!1};throw new u("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."})}async function eP(e){var t,a;let r,n=eT(e.paths.infoPath);if(!n)return null;let o=await e$(n,e.transportPreference);return(t=n,a=o,t.version===k()&&t.codeSignature===_((r=eB()).useSrc?r.srcPath:r.distPath,r.root)&&a)?n:(await eM(n),eO(e.paths.infoPath),null)}async function ek(e){let t,a=0,r=[];for(let n=1;n<=2;n+=1){try{await eF(e)}catch(a){if(t=a instanceof Error?a.message:String(a),r.push(await eU(e.paths,"start_error")),n<2){await L(150);continue}break}let o=await eD(15e3,e);if(o)return{info:o,startedByClient:!0};if(await eE(e.paths)){a+=1;continue}let i=eR(e.paths),s=n<2,l=await eU(e.paths,"startup_timeout",{stopLiveProcesses:!1});if(r.push(l),l.retainedInfoProcess||l.retainedLockProcess){let t=await eD(15e3,e);if(t)return{info:t,startedByClient:!0};break}if(!s)break;i.hasInfo||i.hasLock||await L(150)}let n=eR(e.paths);throw new u("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:15e3,startupAttempts:2,lockRecoveryCount:a,cleanupResults:r,startError:t,metadataState:n,hint:function(e,t=I(process.env.AGENT_DEVICE_STATE_DIR)){var a;let r=(a=t,`rm -f ${y(a.infoPath)} ${y(a.lockPath)}`);return e.hasLock&&!e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.lockPath} still exists without ${t.infoPath}. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasLock&&e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.infoPath} and ${t.lockPath} still remain. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasInfo?`agent-device did not observe reachable daemon metadata after retrying, and ${t.infoPath} still remains. Stale metadata was cleaned automatically when safe; retry with --debug. If this persists after confirming no agent-device daemon process is running, run: ${r}`:`agent-device did not observe reachable daemon metadata after retrying. Stale metadata was cleaned automatically when safe; retry with --debug and check daemon diagnostics logs. If stale metadata returns after confirming no agent-device daemon process is running, run: ${r}`}(n,e.paths)})}async function eS(e,t,a){if(!eb(e.command)||!t.startedByClient&&!a.ownedStateDir||eY(t.info))return;let n={pid:t.info.pid,removedInfo:!1,removedLock:!1,removedStateDir:!1,error:void 0};try{await eM(t.info)}catch(e){n.error=e instanceof Error?e.message:String(e)}finally{let e=r.existsSync(a.paths.infoPath);eO(a.paths.infoPath),n.removedInfo=e&&!r.existsSync(a.paths.infoPath);let t=r.existsSync(a.paths.lockPath);eO(a.paths.lockPath),n.removedLock=t&&!r.existsSync(a.paths.lockPath),a.ownedStateDir&&(r.rmSync(a.paths.baseDir,{recursive:!0,force:!0}),n.removedStateDir=!r.existsSync(a.paths.baseDir))}E({level:n.error?"warn":"info",phase:"daemon_replay_cleanup",data:n})}function eb(e){return e===C.replay||e===C.test}async function eD(e,t){let a=Date.now();for(;Date.now()-a<e;){let e=eT(t.paths.infoPath);if(e&&await e$(e,t.transportPreference))return e;await L(100)}return null}async function eE(e){let t=eR(e);if(!t.hasLock||t.hasInfo)return!1;let a=eL(e.lockPath);return!(a&&M(a.pid,a.processStartTime))&&(eO(e.lockPath),!0)}async function eM(e){await T(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function eT(e){var t,a,r;let n,o,i=ex(e);if(!i||"object"!=typeof i)return null;let s="string"==typeof(t=i).token&&t.token.length>0?t.token:null;if(!s)return null;let l=(n=eC((a=i).port),o=eC(a.httpPort),void 0===n&&void 0===o?null:{port:n,httpPort:o});return l?{token:s,...l,transport:"socket"===(r=i.transport)||"http"===r||"dual"===r?r:void 0,pid:eC(i.pid)??0,version:eN(i.version),codeSignature:eN(i.codeSignature),processStartTime:eN(i.processStartTime)}:null}function eN(e){return"string"==typeof e?e:void 0}function eC(e){return Number.isInteger(e)&&Number(e)>0?Number(e):void 0}function eL(e){let t=ex(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}em.addSubnet("127.0.0.0",8,"ipv4"),em.addAddress("::1","ipv6"),em.addSubnet("::ffff:127.0.0.0",104,"ipv6");async function eU(e,t,a={}){let n=a.stopLiveProcesses??!0,o={reason:t,removedInfo:!1,removedLock:!1,stoppedInfoProcess:!1,stoppedLockProcess:!1};try{var i,s,l,c;let t=r.existsSync(e.infoPath),a=eT(e.infoPath);if(a){let t=M(a.pid,a.processStartTime);t&&!n?o.retainedInfoProcess=!0:(t&&(await eM(a),o.stoppedInfoProcess=!0),i=e.infoPath,eO(i),o.removedInfo=!0)}else t&&(s=e.infoPath,eO(s),o.removedInfo=!0);let d=r.existsSync(e.lockPath),u=eL(e.lockPath);if(u){let t=M(u.pid,u.processStartTime);t&&!n?o.retainedLockProcess=!0:(t&&(await T(u.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:u.processStartTime}),o.stoppedLockProcess=!0),l=e.lockPath,eO(l),o.removedLock=!0)}else d&&(c=e.lockPath,eO(c),o.removedLock=!0)}catch(e){o.error=e instanceof Error?e.message:String(e)}return E({level:o.error?"warn":"info",phase:"daemon_startup_metadata_cleanup",data:o}),o}function eR(e){return{hasInfo:r.existsSync(e.infoPath),hasLock:r.existsSync(e.lockPath)}}function ex(e){if(!r.existsSync(e))return null;try{return JSON.parse(r.readFileSync(e,"utf8"))}catch{return null}}function eO(e){try{r.existsSync(e)&&r.unlinkSync(e)}catch{}}async function e$(r,n){var o;return"http"===ej(r,n)?await function(e){let r=e.baseUrl?eQ(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!r)return Promise.resolve(!1);let n=new URL(r),o="https:"===n.protocol?a:t,i=e.baseUrl?3e3:500;return new Promise(e=>{let t=o.request({protocol:n.protocol,host:n.hostname,port:n.port,path:n.pathname+n.search,method:"GET",timeout:i},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(r):await ((o=r.port)?new Promise(t=>{let a=!1,r=e.createConnection({host:"127.0.0.1",port:o},()=>{n(!0)}),n=e=>{a||(a=!0,r.destroy(),t(e))};r.setTimeout(500),r.on("timeout",()=>{n(!1)}),r.on("error",()=>{n(!1)})}):Promise.resolve(!1))}async function eF(e){let t=eB(),a=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],r={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};f(process.execPath,a,{env:r})}function eB(){let e=S(),t=[o.join(e,"dist","src","internal","daemon.js"),o.join(e,"dist","src","daemon.js")],a=t[0];if(void 0===a)throw new u("COMMAND_FAILED","Daemon dist path list is empty");let n=t.find(e=>r.existsSync(e))??a,i=o.join(e,"src","daemon.ts"),s=t.some(e=>r.existsSync(e)),l=r.existsSync(i);if(!s&&!l)throw new u("COMMAND_FAILED","Daemon entry not found",{distPaths:t,srcPath:i});return{root:e,distPath:n,distPaths:t,srcPath:i,useSrc:process.execArgv.includes("--experimental-strip-types")?l:!s&&l}}async function eq(e,t,a,r){return"http"===ej(e,a)?await eV(e,t,r):await ez(e,t,r)}function ej(e,t){if(e.baseUrl){if("socket"===t)throw new u("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var a=e,r=t;if(eK(a,r))return r;throw new u("COMMAND_FAILED","http"===r?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let n=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>eK(e,t));if(n)return n;throw new u("COMMAND_FAILED","Daemon metadata has no reachable transport")}function eK(e,t){return"http"===t?!!e.httpPort:!!e.port}function eH(e,t,a,r,n,o){let i=n?{terminated:0}:function(){let e=0;try{for(let t of ep){let a=p("pkill",["-f",t],{allowFailure:!0});0===a.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}(),s=!n&&"snapshot"!==r,l=s?function(e,t){let a=!1;try{M(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),a=!0)}catch{T(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{eO(t.infoPath),eO(t.lockPath)}return{forcedKill:a}}(e,t):{forcedKill:!1};return E({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:o,requestId:a,command:r,timedOutRunnerPidsTerminated:i.terminated,timedOutRunnerCleanupError:i.error,daemonPidReset:s?e.pid:void 0,daemonPidForceKilled:s?l.forcedKill:void 0,daemonPreservedAfterTimeout:!n&&!s,daemonBaseUrl:e.baseUrl}}),new u("COMMAND_FAILED","Daemon request timed out",{timeoutMs:o,requestId:a,hint:function(e){let{remote:t,resetDaemon:a,command:r}=e;if(t)return"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.";if(!a){let e=r===C.snapshot?" If this was the first Apple-platform snapshot on the device, run agent-device prepare ios-runner with the same --platform before snapshot/test so runner startup is handled explicitly.":"";return`Retry with --debug and check daemon diagnostics logs. The timed-out ${r??"request"} request was canceled and Apple runner work was aborted when detected; the daemon was kept alive so the session can still be closed or inspected.${e}`}return"Retry with --debug and check daemon diagnostics logs. Timed-out Apple runner xcodebuild processes were terminated when detected."}({remote:n,resetDaemon:s,command:r})})}function eG(e,t,a){return E({level:"error",phase:"daemon_request_socket_error",data:{requestId:t,message:e instanceof Error?e.message:String(e)}}),new u("COMMAND_FAILED","Failed to communicate with daemon",{requestId:t,hint:a?"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 instanceof Error?e:void 0)}async function ez(t,a,r){let n=t.port;if(!n)throw new u("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((o,i)=>{let s=e.createConnection({host:"127.0.0.1",port:n},()=>{s.write(`${JSON.stringify(a)}
3
- `)}),l=I(a.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),c=!1,d="number"==typeof r?setTimeout(()=>{c=!0,s.destroy(),i(eH(t,l,a.meta?.requestId,a.command,!1,r))},r):void 0,p="";s.setEncoding("utf8"),s.on("data",e=>{if(c)return;let t=h(p,e);for(let e of(p=t.buffer,t.lines))try{let t=JSON.parse(e);if(v(t)){eu(t.event);continue}let a=g(t)?t.response:t;c=!0,s.end(),d&&clearTimeout(d),o(a);return}catch(t){c=!0,d&&clearTimeout(d),i(new u("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e},t instanceof Error?t:void 0));return}}),s.on("error",e=>{c||(c=!0,d&&clearTimeout(d),i(eG(e,a.meta?.requestId,!1)))})})}async function eV(e,r,n){var o,i,s;let l,c=e.baseUrl?new URL(eQ(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!c)throw new u("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let d=JSON.stringify((o=r,i={includeTokenParam:!e.baseUrl},l=o.meta?.requestId??b(),"lease_allocate"!==(s=o.command)&&"lease_heartbeat"!==s&&"lease_release"!==s?{jsonrpc:"2.0",id:l,method:"agent_device.command",params:o}:{jsonrpc:"2.0",id:l,method:function(e){switch(e){case"lease_allocate":return"agent_device.lease.allocate";case"lease_heartbeat":return"agent_device.lease.heartbeat";case"lease_release":return"agent_device.lease.release"}}(o.command),params:function(e,t,a){let r={...a.includeTokenParam?{token:e.token}:{},session:e.session,tenantId:e.meta?.tenantId,runId:e.meta?.runId};switch(t){case"lease_allocate":return{...r,ttlMs:e.meta?.leaseTtlMs,backend:e.meta?.leaseBackend};case"lease_heartbeat":return{...r,leaseId:e.meta?.leaseId,ttlMs:e.meta?.leaseTtlMs};case"lease_release":return{...r,leaseId:e.meta?.leaseId}}}(o,o.command,i)})),p={"content-type":"application/json","content-length":Buffer.byteLength(d)};return e.baseUrl&&e.token&&(p.authorization=`Bearer ${e.token}`,p["x-agent-device-token"]=e.token),await new Promise((o,i)=>{let s=I(r.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l=("https:"===c.protocol?a:t).request({protocol:c.protocol,host:c.hostname,port:c.port,method:"POST",path:c.pathname+c.search,headers:p},t=>{var a;(a=t.headers?.["content-type"],w(r)&&String(Array.isArray(a)?a.join(","):a??"").includes("application/x-ndjson"))?function(e,t){let{req:a,handleResponseBody:r,reject:n,clearTimeout:o}=t,i="",s=!1,l=e=>{try{let t=JSON.parse(e);if(v(t))return eu(t.event),!1;if(g(t))return s=!0,o(),r(JSON.stringify(t.response)),!0;throw Error("Missing daemon progress response envelope")}catch(t){return s=!0,o(),n(new u("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e},t instanceof Error?t:void 0)),!0}};e.setEncoding("utf8"),e.on("data",e=>{if(s)return;let t=h(i,e);for(let e of(i=t.buffer,t.lines))if(e&&l(e))return}),e.on("end",()=>{if(s)return;let e=i.trim();e&&l(e)||(s=!0,o(),n(new u("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e})))}),e.on("error",e=>{s||(s=!0,o(),n(new u("COMMAND_FAILED","Failed to read daemon response",{requestId:a.meta?.requestId},e instanceof Error?e:void 0)))})}(t,{req:r,reject:i,clearTimeout:()=>{f&&clearTimeout(f)},handleResponseBody:t=>eJ(t,{info:e,req:r,resolve:o,reject:i})}):X(t).then(t=>{f&&clearTimeout(f),eJ(t,{info:e,req:r,resolve:o,reject:i})}).catch(e=>{f&&clearTimeout(f),i(new u("COMMAND_FAILED","Failed to read daemon response",{requestId:r.meta?.requestId},e instanceof Error?e:void 0))})}),m=eY(e),f="number"==typeof n?setTimeout(()=>{l.destroy(),i(eH(e,s,r.meta?.requestId,r.command,m,n))},n):void 0;l.on("error",e=>{f&&clearTimeout(f),i(eG(e,r.meta?.requestId,m))}),l.write(d),l.end()})}function eJ(e,t){let{info:a,req:r,resolve:n,reject:o}=t;try{var i,s,l;let t=(i=e,JSON.parse(i));if(t.error){let e;return void o((s=t.error,l=r.meta?.requestId,e=s.data??{},new u(d(null!=e.code?String(e.code):void 0,"COMMAND_FAILED"),String(e.message??s.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:l})))}if(!t.result||"object"!=typeof t.result)return void o(new u("COMMAND_FAILED","Invalid daemon RPC response",{requestId:r.meta?.requestId}));eW(a,r,t.result,n,o)}catch(t){o(new u("COMMAND_FAILED","Invalid daemon response",{requestId:r.meta?.requestId,line:e},t instanceof Error?t:void 0))}}async function eW(e,t,a,r,n){try{r(e.baseUrl&&a.ok?await eX(e,t,a):a)}catch(e){n(e)}}function eY(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function eQ(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function eX(e,t,a){let r=Array.isArray(a.data?.artifacts)?a.data.artifacts:[];if(0===r.length||!e.baseUrl)return a;let n=a.data?{...a.data}:{},i=[];for(let a of r){if(!a||"object"!=typeof a||"string"!=typeof a.artifactId){i.push(a);continue}let r=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let a=t.meta?.clientArtifactPaths?.[e.field];if(a&&a.trim().length>0)return a;let r=e.fileName?.trim()||`${e.field}-${Date.now()}`;return o.resolve(t.meta?.cwd??process.cwd(),r)}(a,t);await eZ({baseUrl:e.baseUrl,token:e.token,artifactId:a.artifactId,destinationPath:r,requestId:t.meta?.requestId}),n[a.field]=r,i.push({...a,localPath:r})}return n.artifacts=i,{ok:!0,data:n}}async function eZ(e){var n,s;let l,c=new URL((n=e.baseUrl,s=e.artifactId,l=n.endsWith("/")?n:`${n}/`,new URL(`artifacts/${encodeURIComponent(s)}`,l).toString())),d="https:"===c.protocol?a:t;await r.promises.mkdir(o.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,a)=>{let n=!1,o=e.timeoutMs??9e4,s=o=>{if(!n){if(n=!0,clearTimeout(p),o)return void r.promises.rm(e.destinationPath,{force:!0}).finally(()=>a(o));t()}},l=d.request({protocol:c.protocol,host:c.hostname,port:c.port,method:"GET",path:c.pathname+c.search,headers:e.token?{authorization:`Bearer ${e.token}`,"x-agent-device-token":e.token}:void 0},t=>{if((t.statusCode??500)>=400){let a="";t.setEncoding("utf8"),t.on("data",e=>{a+=e}),t.on("end",()=>{s(new u("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:a}))});return}t.on("aborted",()=>{s(new u("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),i(t,r.createWriteStream(e.destinationPath)).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}),p=setTimeout(()=>{let t=new u("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:o});s(t),l.destroy(t)},o);l.on("error",t=>{t instanceof u?s(t):s(new u("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:o},t instanceof Error?t:void 0))}),l.end()})}function e0(e={},t={}){let a=t.transport??ef,r=async(t,r=[],n={})=>{var o,i;let s=(o=e,i=n,{...o,...i}),l=await a({session:O(s.session),command:t,positionals:r,flags:$(s),runtime:s.runtime,meta:J(s)});return l.ok||function(e){throw new u(d(e.code),e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(l.error),l.data??{}},n=async(e={})=>{let t=await r(N.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(x)},o=async(e,t={})=>{let a=j(e,t);return await r(a.command,a.positionals,a.options)},i=(t={})=>{var a,r;return O((a=e,r=t,{...a,...r}).session)};return{command:{wait:async e=>await o("wait",e),alert:async(e={})=>await o("alert",e),appState:async(e={})=>await o("appstate",e),back:async(e={})=>await o("back",e),home:async(e={})=>await o("home",e),rotate:async e=>await o("rotate",e),appSwitcher:async(e={})=>await o("app-switcher",e),keyboard:async(e={})=>await o("keyboard",e),clipboard:async e=>await o("clipboard",e),reactNative:async e=>await o("react-native",e),prepare:async e=>await o("prepare",e)},devices:{list:async(e={})=>{let t=await o("devices",e);return(Array.isArray(t.devices)?t.devices:[]).map(W)},boot:async(e={})=>await o("boot",e)},sessions:{list:async(e={})=>await n(e),close:async(e={})=>{let t=i(e),a=(await o("close",e)).shutdown;return{session:t,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}}},apps:{install:async e=>G(await o("install",e),i(e)),reinstall:async e=>G(await o("reinstall",e),i(e)),installFromSource:async e=>B(await o("install-from-source",e),i(e)),list:async(e={})=>{let t=await o("apps",e);return Array.isArray(t.apps)?t.apps.filter(e=>"string"==typeof e):[]},open:async e=>{let t=i(e),a=await o("open",e),r=z(a),n=Q(a,"appBundleId");return{session:t,sessionStateDir:Q(a,"sessionStateDir"),appName:Q(a,"appName"),appBundleId:n,appId:n,startup:F(a.startup),runtime:H(a.runtime),device:r,identifiers:{session:t,deviceId:r?.id,deviceName:r?.name,udid:r?.ios?.udid,serial:r?.android?.serial,appId:n,appBundleId:n}}},close:async(e={})=>{let t=i(e),a=(await o("close",e)).shutdown;return{session:t,closedApp:e.app,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}},push:async e=>await o("push",e),triggerEvent:async e=>await o("trigger-app-event",e)},materializations:{release:async e=>q(await r(N.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:{allocate:async e=>e2(await r(N.leaseAllocate,[],{...e,leaseId:void 0,leaseTtlMs:e.ttlMs})),heartbeat:async e=>e2(await r(N.leaseHeartbeat,[],{...e,leaseTtlMs:e.ttlMs})),release:async e=>({released:!0===(await r(N.leaseRelease,[],e)).released})},metro:{prepare:async t=>await R({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,bridgeScope:t.bridgeScope,launchUrl:t.launchUrl,companionProfileKey:t.companionProfileKey,companionConsumerKey:t.companionConsumerKey,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath}),reload:async(t={})=>await U({metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,runtime:e.runtime,timeoutMs:t.timeoutMs})},capture:{snapshot:async(e={})=>{var t,a,r;let n,s,l,c,d,u=i(e);return t=await o("snapshot",e),a=u,n=Q(t,"appBundleId"),{nodes:K(t.nodes),truncated:!0===t.truncated,appName:Q(t,"appName"),appBundleId:n,...(s=e1((r=t).visibility),l=e1(r.androidSnapshot),c=e1(r.unchanged),d=Array.isArray(r.warnings)?r.warnings.filter(e=>"string"==typeof e):void 0,{...s?{visibility:s}:{},...l?{androidSnapshot:l}:{},...c?{unchanged:c}:{},...d?{warnings:d}:{}}),identifiers:{session:a,appId:n,appBundleId:n}}},screenshot:async(e={})=>{let t=i(e),a=await o("screenshot",e);return{path:Y(a,"path"),overlayRefs:V(a),identifiers:{session:t}}},diff:async e=>await o("diff",e)},interactions:{click:async e=>await o("click",e),press:async e=>await o("press",e),longPress:async e=>await o("longpress",e),swipe:async e=>await o("swipe",e),pan:async e=>await o("gesture-pan",e),fling:async e=>await o("gesture-fling",e),swipeGesture:async e=>await o("gesture-swipe",e),focus:async e=>await o("focus",e),type:async e=>await o("type",e),fill:async e=>await o("fill",e),scroll:async e=>await o("scroll",e),pinch:async e=>await o("gesture-pinch",e),rotateGesture:async e=>await o("gesture-rotate",e),transformGesture:async e=>await o("gesture-transform",e),get:async e=>await o("get",e),is:async e=>await o("is",e),find:async e=>await o("find",e)},replay:{run:async e=>await o("replay",e),test:async e=>await o("test",e)},batch:{run:async e=>await o("batch",e)},observability:{perf:async(e={})=>await o("perf",e),logs:async(e={})=>await o("logs",e),network:async(e={})=>await o("network",e)},recording:{record:async e=>await o("record",e),trace:async e=>await o("trace",e)},settings:{update:async e=>await o("settings",e)}}}function e1(e){return"object"==typeof e&&null!==e?e:void 0}function e2(e){let t=e.lease;if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Invalid lease response from daemon");return{leaseId:Y(t,"leaseId"),tenantId:Y(t,"tenantId"),runId:Y(t,"runId"),backend:Y(t,"backend"),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,heartbeatAt:"number"==typeof t.heartbeatAt?t.heartbeatAt:void 0,expiresAt:"number"==typeof t.expiresAt?t.expiresAt:void 0}}export{e0 as createAgentDeviceClient,ed as formatDurationSeconds,ef as sendToDaemon};
1
+ import e from"node:fs";import t from"node:http";import a from"node:https";import r from"node:path";import{pipeline as n}from"node:stream/promises";import i from"node:os";import{createHash as o,randomUUID as s}from"node:crypto";import{Writable as d}from"node:stream";import l from"node:net";import c from"node:fs/promises";import{toAppErrorCode as u,AppError as f}from"./9152.js";import{runCmdDetachedMonitored as p,runCmd as m,runCmdSync as h}from"./9818.js";import{createRequestId as y,withDiagnosticTimer as w,emitDiagnostic as g}from"./7599.js";import{isAgentDeviceDaemonProcess as I,stopProcessForTakeover as v}from"./8656.js";import{consumeTextLines as b,shellQuote as A,shouldStreamRequestProgress as S,isDaemonResponseEnvelope as M,isDaemonProgressEnvelope as P,resolveDaemonPaths as _,resolveDaemonServerMode as D,computeDaemonCodeSignature as k,resolveDaemonTransportPreference as E}from"./9238.js";import{INTERNAL_COMMANDS as x,PUBLIC_COMMANDS as N}from"./6088.js";import{readVersion as $,findProjectRoot as T}from"./9671.js";import{sleep as C}from"./4829.js";import{normalizeSession as U,readRequiredString as L,readSerializedSnapshotCaptureAnnotations as R,readOptionalString as O,normalizeMaterializationReleaseResult as F,readSnapshotNodes as B,normalizeDeployResult as q,appDaemonWriters as j,observabilityDaemonWriters as V,normalizeOpenDevice as G,replayDaemonWriters as H,buildMeta as K,systemDaemonWriters as z,resolveSessionName as Y,buildFlags as W,reactNativeDaemonWriters as J,interactionDaemonWriters as X,captureDaemonWriters as Q,perfDaemonWriters as Z,gestureDaemonWriters as ee,selectorDaemonWriters as et,createBatchDaemonWriter as ea,normalizeRuntimeHints as er,normalizeDevice as en,recordingDaemonWriters as ei,readScreenshotOverlayRefs as eo,normalizeStartupSample as es,normalizeInstallFromSourceResult as ed}from"./6133.js";import{reloadMetro as el,prepareMetroRuntime as ec}from"./1974.js";function eu(e){return new Promise((t,a)=>{let r="";e.setEncoding("utf8"),e.on("data",e=>{r+=e}),e.on("end",()=>t(r)),e.on("error",a)})}let ef="sha256";async function ep(e){let t=await em(e.localPath,e.platform),a=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;try{let r=await eg({normalizedBase:a,token:e.token,artifact:t});if(r?.kind==="cache-hit")return r.uploadId;if(r?.kind==="direct-upload")try{return await eI(t.payloadPath,r),await eS({normalizedBase:a,token:e.token,uploadId:r.uploadId})}catch{}return await ew({normalizedBase:a,token:e.token,artifact:t})}finally{t.cleanup()}}async function em(t,a){var n,i,o;let s,d=e.statSync(t),l=r.basename(t),c=d.isDirectory(),u=("ios"===(n=a)||"android"===n?n:void 0)??(i=t,o=d,s=i.toLowerCase(),o.isDirectory()&&s.endsWith(".app")||s.endsWith(".ipa")?"ios":s.endsWith(".apk")||s.endsWith(".aab")?"android":void 0),f=[];try{let a=c?await eh(t,f):t,r=e.statSync(a);return{payloadPath:a,fileName:l,artifactType:c?"app-bundle":"file",platform:u,contentType:c?"application/gzip":"application/octet-stream",sha256:await eM(a),sizeBytes:r.size,cleanup:()=>ey(f)}}catch(e){throw ey(f),e}}async function eh(t,a){let n=e.mkdtempSync(r.join(i.tmpdir(),`agent-device-upload-${s()}-`));a.push(n);let o=r.join(n,`${r.basename(t)}.tar.gz`);return await m("tar",["czf",o,"-C",r.dirname(t),r.basename(t)],{env:{...process.env,COPYFILE_DISABLE:"1"}}),o}function ey(t){for(let a of t)e.rmSync(a,{recursive:!0,force:!0})}async function ew(e){let{normalizedBase:t,token:a,artifact:r}=e,n=new URL("upload",t),i={"content-type":r.contentType,"x-artifact-type":r.artifactType,"x-artifact-filename":r.fileName,"x-artifact-hash":r.sha256,"x-artifact-hash-algorithm":ef,"transfer-encoding":"chunked"};a&&(i.authorization=`Bearer ${a}`,i["x-agent-device-token"]=a);let o=await ev({url:n,method:"POST",headers:i,payloadPath:r.payloadPath,timeoutMessage:"Artifact upload timed out",timeoutHint:"The upload to the remote daemon exceeded the 5-minute timeout.",errorMessage:"Failed to upload artifact to remote daemon",errorHint:"Verify the remote daemon is reachable and supports artifact uploads."});try{let e=JSON.parse(o.body);if(!e.ok||!e.uploadId)throw new f("COMMAND_FAILED",`Upload failed: ${o.body}`);return e.uploadId}catch(e){if(e instanceof f)throw e;throw new f("COMMAND_FAILED",`Invalid upload response: ${o.body}`)}}async function eg(e){let t=new URL("upload/preflight",e.normalizedBase),a={"content-type":"application/json"};e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token);let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({sha256:e.artifact.sha256,fileName:e.artifact.fileName,sizeBytes:e.artifact.sizeBytes,artifactType:e.artifact.artifactType,...e.artifact.platform?{platform:e.artifact.platform}:{},contentType:e.artifact.contentType})}).catch(()=>void 0);if(r?.ok)return function(e){var t;if(!e||"object"!=typeof e||!0!==e.ok||"string"!=typeof e.uploadId)return;if(!0===e.cacheHit)return{kind:"cache-hit",uploadId:e.uploadId};let a=e.upload;if(!a||"string"!=typeof a.url)return;let r=a.headers??{};if(!(!(t=r)||"object"!=typeof t||Array.isArray(t))&&Object.values(t).every(e=>"string"==typeof e))return{kind:"direct-upload",uploadId:e.uploadId,url:a.url,headers:r}}(await r.json().catch(()=>void 0))}async function eI(e,t){let a=await ev({url:new URL(t.url),method:"PUT",headers:t.headers,payloadPath:e,timeoutMessage:"Direct artifact upload timed out",timeoutHint:"The direct upload ticket did not accept the artifact within the timeout.",errorMessage:"Failed to upload artifact with direct upload ticket"});if(a.statusCode<200||a.statusCode>=300)throw new f("COMMAND_FAILED","Direct artifact upload failed",{statusCode:a.statusCode,statusMessage:a.statusMessage})}async function ev(e){return await eb({...e,url:e.url,redirectCount:0,startOffset:0})}async function eb(r){var i,o,s;let d="https:"===r.url.protocol?a:t,l=e.statSync(r.payloadPath).size,c=(i=r.headers,o=r.startOffset,s=l,o<=0?i:{...i,"content-length":Math.max(s-o,0),"content-range":`bytes ${o}-${s-1}/${s}`});return await new Promise((t,a)=>{let i=!1,o=d.request({protocol:r.url.protocol,host:r.url.hostname,port:r.url.port,method:r.method,path:r.url.pathname+r.url.search,headers:c},e=>{i=!0,eu(e).then(n=>{clearTimeout(s);let i=e.statusCode??500,o=e.headers.location;if(o&&[301,302,303,307,308].includes(i)){if(r.redirectCount>=5)return void a(new f("COMMAND_FAILED","Artifact upload exceeded redirect limit",{maxRedirects:5,url:r.url.toString()}));let e=new URL(o,r.url);return void eb({...r,url:e,redirectCount:r.redirectCount+1}).then(t,a)}let d=308===i?function(e,t){let a=function(e){let t=eA(e);if(void 0===t)return;let a=Number(t);return Number.isSafeInteger(a)&&a>=0?a:void 0}(e["x-upload-offset"]??e["upload-offset"]);if(void 0!==a)return Math.min(a,t);let r=eA(e.range),n=r?.match(/^bytes=0-(\d+)$/);if(!n)return;let i=Number(n[1]);if(Number.isSafeInteger(i)&&!(i<0))return Math.min(i+1,t)}(e.headers,l):void 0;void 0!==d?d>=l?t({statusCode:200,statusMessage:"Upload already complete",body:""}):d<=r.startOffset?a(new f("COMMAND_FAILED","Artifact upload resume did not advance",{offset:d,previousOffset:r.startOffset,url:r.url.toString()})):eb({...r,startOffset:d}).then(t,a):t({statusCode:i,statusMessage:e.statusMessage,body:n})}).catch(a)}),s=setTimeout(()=>{o.destroy(),a(new f("COMMAND_FAILED",r.timeoutMessage,{timeoutMs:3e5,...r.timeoutHint?{hint:r.timeoutHint}:{}}))},3e5);o.on("error",e=>{i||(clearTimeout(s),a(new f("COMMAND_FAILED",r.errorMessage,r.errorHint?{hint:r.errorHint}:{},e)))}),o.on("close",()=>clearTimeout(s)),n(e.createReadStream(r.payloadPath,{start:r.startOffset}),o).catch(e=>{i||(o.destroy(),a(new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:Error(String(e)))))})})}function eA(e){return Array.isArray(e)?e[0]:e}async function eS(e){let t=new URL("upload/finalize",e.normalizedBase),a={"content-type":"application/json"};e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token);let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({uploadId:e.uploadId})}).catch(e=>{throw new f("COMMAND_FAILED","Failed to finalize direct artifact upload",{},e)});if(!r.ok)throw new f("COMMAND_FAILED","Direct artifact upload finalize failed",{status:r.status,statusText:r.statusText});let n=await r.json().catch(()=>void 0);if(!n?.ok||!n.uploadId)throw new f("COMMAND_FAILED","Invalid upload finalize response");return n.uploadId}async function eM(t){let a=o(ef),r=new d({write(e,t,r){a.update(e),r()}});return await n(e.createReadStream(t),r).catch(e=>{throw new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:void 0)}),a.digest("hex")}async function eP(e,t){var a;let n,i=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,s=e.meta?.installSource,d={};if(!("string"==typeof(a=t).baseUrl&&a.baseUrl.length>0))return eD({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:d});o=function(e,t,a,n){var i,o;let s=function(e,t){if("screenshot"===e.command){let a=eE(e,"path",".png");return t[0]?{field:"path",localPath:a,positionalIndex:0,positionalPath:ex("screenshot",".png")}:{field:"path",localPath:a,positionalIndex:0,flagPath:ex("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=eE(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:ex("recording",r.extname(t)||".mp4")}}return null}(e,t);if(!s)return a;void 0!==s.positionalPath&&(t[s.positionalIndex]=s.positionalPath);let d=(i=a,void 0===(o=s.flagPath)?i:{...i??{},out:o});return n[s.field]=s.localPath,d}(e,i,o,d);let l=await ek(e,t);l&&(s=l.installSource,n=l.uploadedArtifactId??n);let c=()=>eD({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:d});return"install"!==e.command&&"reinstall"!==e.command||(n=await e_(e,t,i)??n),c()}async function e_(t,a,n){var i,o;let s,d=n[1];if(void 0===d)return;if(d.startsWith("remote:")){n[1]=d.slice(7);return}let l=(i=d,o=t.meta?.cwd,s=r.isAbsolute(i)?i:r.resolve(o??process.cwd(),i),e.existsSync(s)?s:void 0);if(l)return await ep({localPath:l,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform})}function eD(e){return{positionals:e.positionals,flags:e.flags,installSource:e.installSource,uploadedArtifactId:e.uploadedArtifactId,...Object.keys(e.clientArtifactPaths).length>0?{clientArtifactPaths:e.clientArtifactPaths}:{}}}async function ek(t,a){let n=t.meta?.installSource;if("install_source"!==t.command||!n||"path"!==n.kind)return null;let i=n.path.trim();if(!i)return{installSource:n};if(i.startsWith("remote:"))return{installSource:{...n,path:i.slice(7)}};let o=r.isAbsolute(i)?i:r.resolve(t.meta?.cwd??process.cwd(),i);if(!e.existsSync(o))return{installSource:{...n,path:o}};let s=await ep({localPath:o,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform});return{installSource:{...n,path:o},uploadedArtifactId:s}}function eE(e,t,a,n=0){let i=e.positionals?.[n]??e.flags?.out,o=`${"path"===t?"screenshot":"recording"}-${Date.now()}${a}`,s=i&&i.trim().length>0?i:o;return r.isAbsolute(s)?s:r.resolve(e.meta?.cwd??process.cwd(),s)}function ex(e,t){let a=t.startsWith(".")?t:`.${t}`;return r.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${a}`)}async function eN(e,t,a){let n=Array.isArray(a.data?.artifacts)?a.data.artifacts:[];if(0===n.length||!e.baseUrl)return a;let i=a.data?{...a.data}:{},o=[];for(let a of n){if(!a||"object"!=typeof a||"string"!=typeof a.artifactId){o.push(a);continue}let n=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let a=t.meta?.clientArtifactPaths?.[e.field];if(a&&a.trim().length>0)return a;let n=e.fileName?.trim()||`${e.field}-${Date.now()}`;return r.resolve(t.meta?.cwd??process.cwd(),n)}(a,t);await e$({baseUrl:e.baseUrl,token:e.token,artifactId:a.artifactId,destinationPath:n,requestId:t.meta?.requestId}),i[a.field]=n,o.push({...a,localPath:n})}return i.artifacts=o,{ok:!0,data:i}}async function e$(i){var o,s;let d,l=new URL((o=i.baseUrl,s=i.artifactId,d=o.endsWith("/")?o:`${o}/`,new URL(`artifacts/${encodeURIComponent(s)}`,d).toString())),c="https:"===l.protocol?a:t;await e.promises.mkdir(r.dirname(i.destinationPath),{recursive:!0}),await new Promise((t,a)=>{let r=!1,o=i.timeoutMs??9e4,s=n=>{if(!r){if(r=!0,clearTimeout(u),n)return void e.promises.rm(i.destinationPath,{force:!0}).finally(()=>a(n));t()}},d=c.request({protocol:l.protocol,host:l.hostname,port:l.port,method:"GET",path:l.pathname+l.search,headers:i.token?{authorization:`Bearer ${i.token}`,"x-agent-device-token":i.token}:void 0},t=>{if((t.statusCode??500)>=400){let e="";t.setEncoding("utf8"),t.on("data",t=>{e+=t}),t.on("end",()=>{s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,statusCode:t.statusCode,requestId:i.requestId,body:e}))});return}t.on("aborted",()=>{s(new f("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:i.artifactId,requestId:i.requestId}))}),n(t,e.createWriteStream(i.destinationPath)).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}),u=setTimeout(()=>{let e=new f("COMMAND_FAILED","Remote artifact download timed out",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o});s(e),d.destroy(e)},o);d.on("error",e=>{e instanceof f?s(e):s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o},e instanceof Error?e:void 0))}),d.end()})}function eT(e){var t,a,r;let n,i,o=ej(e);if(!o||"object"!=typeof o)return null;let s="string"==typeof(t=o).token&&t.token.length>0?t.token:null;if(!s)return null;let d=(n=eU((a=o).port),i=eU(a.httpPort),void 0===n&&void 0===i?null:{port:n,httpPort:i});return d?{token:s,...d,transport:"socket"===(r=o.transport)||"http"===r||"dual"===r?r:void 0,pid:eU(o.pid)??0,version:eC(o.version),codeSignature:eC(o.codeSignature),processStartTime:eC(o.processStartTime)}:null}function eC(e){return"string"==typeof e?e:void 0}function eU(e){return Number.isInteger(e)&&Number(e)>0?Number(e):void 0}function eL(e){let t=ej(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}async function eR(t,a,r={}){let n=r.stopLiveProcesses??!0,i={reason:a,removedInfo:!1,removedLock:!1,stoppedInfoProcess:!1,stoppedLockProcess:!1};try{var o,s,d,l;let a=e.existsSync(t.infoPath),r=eT(t.infoPath);if(r){let e=I(r.pid,r.processStartTime);e&&!n?i.retainedInfoProcess=!0:(e&&(await eB(r),i.stoppedInfoProcess=!0),o=t.infoPath,eV(o),i.removedInfo=!0)}else a&&(s=t.infoPath,eV(s),i.removedInfo=!0);let c=e.existsSync(t.lockPath),u=eL(t.lockPath);if(u){let e=I(u.pid,u.processStartTime);e&&!n?i.retainedLockProcess=!0:(e&&(await v(u.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:u.processStartTime}),i.stoppedLockProcess=!0),d=t.lockPath,eV(d),i.removedLock=!0)}else c&&(l=t.lockPath,eV(l),i.removedLock=!0)}catch(e){i.error=e instanceof Error?e.message:String(e)}return g({level:i.error?"warn":"info",phase:"daemon_startup_metadata_cleanup",data:i}),i}function eO(t){return{hasInfo:e.existsSync(t.infoPath),hasLock:e.existsSync(t.lockPath)}}async function eF(e){let t=eO(e);if(!t.hasLock||t.hasInfo)return!1;let a=eL(e.lockPath);return!(a&&I(a.pid,a.processStartTime))&&(eV(e.lockPath),!0)}async function eB(e){await v(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function eq(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function ej(t){if(!e.existsSync(t))return null;try{return JSON.parse(e.readFileSync(t,"utf8"))}catch{return null}}function eV(t){try{e.existsSync(t)&&e.unlinkSync(t)}catch{}}function eG(e){let t=Math.max(0,e)/1e3;return t>=10?`${t.toFixed(1)}s`:t>=1?`${t.toFixed(2)}s`:`${t.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}s`}let eH={start:"START",pass:"PASS",fail:"FAIL",skip:"SKIP"};function eK(e){var t,a,n,i,o,s,d;let l,c,u,f,p,m,h,y,w,g,I,v="replay-test-suite"===e.type?(t=e,l=[`Running replay suite: ${t.total} ${1===t.total?"file":"files"}`],t.shardMode&&t.shardCount&&t.shardCount>1&&l.push(` sharding: ${t.shardMode} across ${t.shardCount} devices`),l.push(` artifacts: ${t.artifactsDir}`),l.join("\n")):"replay-test"===e.type?(function(e,t){if("start"===t.status){t.session&&e.push(` session: ${t.session}`),t.artifactsDir&&e.push(` artifacts: ${t.artifactsDir}`);return}let a=t.message?.replace(/\s+/g," ").trim();a&&e.push(` ${a}`),"fail"===t.status&&!t.retrying&&(t.session&&e.push(` session: ${t.session}`),t.artifactsDir&&e.push(` artifacts: ${t.artifactsDir}`))}(I=[(n=a=e,p=`[${n.index}/${n.total}]`,m=(i=n).retrying?"RETRY":eH[i.status],h=(o=n,c=o.title?.trim(),u=r.basename(o.file),c?`${JSON.stringify(c)} in ${u}`:u),y=function(e){if("number"!=typeof e.shardIndex)return"";let t="number"==typeof e.shardCount?e.shardCount:"?",a="string"==typeof e.deviceId?` ${e.deviceId}`:"";return` [shard ${e.shardIndex+1}/${t}${a}]`}(n),w=void 0===(s=n).attempt||"start"===s.status?"":"fail"===s.status&&s.retrying&&void 0!==s.maxAttempts?` attempt ${s.attempt}/${s.maxAttempts}`:s.attempt>1?` after ${s.attempt} attempts`:"",g=void 0!==n.durationMs?` (${f=eG((d=n).durationMs??0),d.attempt&&d.attempt>1&&!d.retrying?`total ${f}`:f})`:"",`${p} ${m} ${h}${y}${w}${g}`)],a),I.join("\n")):void 0;v&&process.stderr.write(`${v}
2
+ `)}function ez(e,t){let{info:a,req:r,resolve:n,reject:i}=t;try{var o,s,d;let t=(o=e,JSON.parse(o));if(t.error){let e;return void i((s=t.error,d=r.meta?.requestId,e=s.data??{},new f(u(null!=e.code?String(e.code):void 0,"COMMAND_FAILED"),String(e.message??s.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:d})))}if(!t.result||"object"!=typeof t.result)return void i(new f("COMMAND_FAILED","Invalid daemon RPC response",{requestId:r.meta?.requestId}));eY(a,r,t.result,n,i)}catch(t){i(new f("COMMAND_FAILED","Invalid daemon response",{requestId:r.meta?.requestId,line:e},t instanceof Error?t:void 0))}}async function eY(e,t,a,r,n){try{r(e.baseUrl&&a.ok?await eN(e,t,a):a)}catch(e){n(e)}}let eW=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];function eJ(e,t,a,r,n,i){let o=n?{terminated:0}:function(){let e=0;try{for(let t of eW){let a=h("pkill",["-f",t],{allowFailure:!0});0===a.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}(),s=!n&&"snapshot"!==r,d=s?function(e,t){let a=!1;try{I(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),a=!0)}catch{eB(e)}finally{eV(t.infoPath),eV(t.lockPath)}return{forcedKill:a}}(e,t):{forcedKill:!1};return g({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:i,requestId:a,command:r,timedOutRunnerPidsTerminated:o.terminated,timedOutRunnerCleanupError:o.error,daemonPidReset:s?e.pid:void 0,daemonPidForceKilled:s?d.forcedKill:void 0,daemonPreservedAfterTimeout:!n&&!s,daemonBaseUrl:e.baseUrl}}),new f("COMMAND_FAILED","Daemon request timed out",{timeoutMs:i,requestId:a,hint:function(e){let{remote:t,resetDaemon:a,command:r}=e;if(t)return"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.";if(!a){let e=r===N.snapshot?" If this was the first Apple-platform snapshot on the device, run agent-device prepare ios-runner with the same --platform before snapshot/test so runner startup is handled explicitly.":"";return`Retry with --debug and check daemon diagnostics logs. The timed-out ${r??"request"} request was canceled and Apple runner work was aborted when detected; the daemon was kept alive so the session can still be closed or inspected.${e}`}return"Retry with --debug and check daemon diagnostics logs. Timed-out Apple runner xcodebuild processes were terminated when detected."}({remote:n,resetDaemon:s,command:r})})}async function eX(e,t){let a=e1(e,t);if(await eQ(e,a))return!0;let r=e2(e,t,a);return!!r&&await eQ(e,r)}async function eQ(e,r){var n;return"http"===r?await function(e){let r=e.baseUrl?e8(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!r)return Promise.resolve(!1);let n=new URL(r),i="https:"===n.protocol?a:t,o=e.baseUrl?3e3:500;return new Promise(e=>{let t=i.request({protocol:n.protocol,host:n.hostname,port:n.port,path:n.pathname+n.search,method:"GET",timeout:o},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(e):await ((n=e.port)?new Promise(e=>{let t=!1,a=l.createConnection({host:"127.0.0.1",port:n},()=>{r(!0)}),r=r=>{t||(t=!0,a.destroy(),e(r))};a.setTimeout(500),a.on("timeout",()=>{r(!1)}),a.on("error",()=>{r(!1)})}):Promise.resolve(!1))}async function eZ(e,t,a,r,n){let i=e1(e,a);try{return await e0(e,t,r,n,i)}catch(d){var o;let s=e2(e,a,i);if(!s||(o=d,"socket"!==i||!(o instanceof f)||"COMMAND_FAILED"!==o.code||"Failed to communicate with daemon"!==o.message||o.details?.daemonSocketRequestWritten!==!1))throw d;return await e0(e,t,r,n,s)}}async function e0(e,t,a,r,n){return"http"===n?await e4(e,t,a,r):await e6(e,t,a,r)}function e1(e,t){if(e.baseUrl){if("socket"===t)throw new f("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var a=e,r=t;if(e3(a,r))return r;throw new f("COMMAND_FAILED","http"===r?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let n=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>e3(e,t));if(n)return n;throw new f("COMMAND_FAILED","Daemon metadata has no reachable transport")}function e3(e,t){return"http"===t?!!e.httpPort:!!e.port}function e2(e,t,a){if("auto"!==t||e.baseUrl)return null;let r="socket"===a?"http":"socket";return e3(e,r)?r:null}function e5(e,t,a,r={}){return g({level:"error",phase:"daemon_request_socket_error",data:{requestId:t,message:e instanceof Error?e.message:String(e)}}),new f("COMMAND_FAILED","Failed to communicate with daemon",{...r,requestId:t,hint:a?"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 instanceof Error?e:void 0)}async function e6(e,t,a,r){let n=e.port;if(!n)throw new f("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((i,o)=>{let s=!1,d=l.createConnection({host:"127.0.0.1",port:n},()=>{s=!0,d.write(`${JSON.stringify(t)}
3
+ `)}),c=!1,u="number"==typeof r?setTimeout(()=>{c=!0,d.destroy(),o(eJ(e,a,t.meta?.requestId,t.command,!1,r))},r):void 0;!function(e,t){let{req:a,isSettled:r,resolve:n,reject:i,clearTimeout:o}=t,s="",d=(e,t)=>{o(),i(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e},t instanceof Error?t:void 0))};e.setEncoding("utf8"),e.on("data",t=>{if(r())return;let a=b(s,t);for(let t of(s=a.buffer,a.lines))try{let a=JSON.parse(t);if(P(a)){eK(a.event);continue}let r=M(a)?a.response:a;o(),n(r),e.end();return}catch(e){d(t,e);return}})}(d,{req:t,isSettled:()=>c,clearTimeout:()=>{u&&clearTimeout(u)},resolve:e=>{c=!0,i(e)},reject:e=>{c=!0,o(e)}}),d.on("error",e=>{c||(c=!0,u&&clearTimeout(u),o(e5(e,t.meta?.requestId,!1,{daemonSocketRequestWritten:s})))})})}async function e4(e,r,n,i){var o,s;let d,l=e.baseUrl?new URL(e8(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!l)throw new f("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let c=JSON.stringify((o={includeTokenParam:!e.baseUrl},d=r.meta?.requestId??y(),"lease_allocate"!==(s=r.command)&&"lease_heartbeat"!==s&&"lease_release"!==s?{jsonrpc:"2.0",id:d,method:"agent_device.command",params:r}:{jsonrpc:"2.0",id:d,method:function(e){switch(e){case"lease_allocate":return"agent_device.lease.allocate";case"lease_heartbeat":return"agent_device.lease.heartbeat";case"lease_release":return"agent_device.lease.release"}}(r.command),params:function(e,t,a){let r={...a.includeTokenParam?{token:e.token}:{},session:e.session,tenantId:e.meta?.tenantId,runId:e.meta?.runId};switch(t){case"lease_allocate":return{...r,ttlMs:e.meta?.leaseTtlMs,backend:e.meta?.leaseBackend};case"lease_heartbeat":return{...r,leaseId:e.meta?.leaseId,ttlMs:e.meta?.leaseTtlMs};case"lease_release":return{...r,leaseId:e.meta?.leaseId}}}(r,r.command,o)})),u={"content-type":"application/json","content-length":Buffer.byteLength(c)};return e.baseUrl&&e.token&&(u.authorization=`Bearer ${e.token}`,u["x-agent-device-token"]=e.token),await new Promise((o,s)=>{let d=("https:"===l.protocol?a:t).request({protocol:l.protocol,host:l.hostname,port:l.port,method:"POST",path:l.pathname+l.search,headers:u},t=>{var a;(a=t.headers?.["content-type"],S(r)&&String(Array.isArray(a)?a.join(","):a??"").includes("application/x-ndjson"))?function(e,t){let{req:a,handleResponseBody:r,reject:n,clearTimeout:i}=t,o="",s=!1,d=e=>{try{let t=JSON.parse(e);if(P(t))return eK(t.event),!1;if(M(t))return s=!0,i(),r(JSON.stringify(t.response)),!0;throw Error("Missing daemon progress response envelope")}catch(t){return s=!0,i(),n(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e},t instanceof Error?t:void 0)),!0}};e.setEncoding("utf8"),e.on("data",e=>{if(s)return;let t=b(o,e);for(let e of(o=t.buffer,t.lines))if(e&&d(e))return}),e.on("end",()=>{if(s)return;let e=o.trim();e&&d(e)||(s=!0,i(),n(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e})))}),e.on("error",e=>{s||(s=!0,i(),n(new f("COMMAND_FAILED","Failed to read daemon response",{requestId:a.meta?.requestId},e instanceof Error?e:void 0)))})}(t,{req:r,reject:s,clearTimeout:()=>{m&&clearTimeout(m)},handleResponseBody:t=>ez(t,{info:e,req:r,resolve:o,reject:s})}):eu(t).then(t=>{m&&clearTimeout(m),ez(t,{info:e,req:r,resolve:o,reject:s})}).catch(e=>{m&&clearTimeout(m),s(new f("COMMAND_FAILED","Failed to read daemon response",{requestId:r.meta?.requestId},e instanceof Error?e:void 0))})}),p=eq(e),m="number"==typeof i?setTimeout(()=>{d.destroy(),s(eJ(e,n,r.meta?.requestId,r.command,p,i))},i):void 0;d.on("error",e=>{m&&clearTimeout(m),s(e5(e,r.meta?.requestId,p))}),d.write(c),d.end()})}function e8(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}let e9=new l.BlockList;async function e7(e){if(e.remoteBaseUrl)return await te(e);let t=await tt(e);return t?{info:t,startedByClient:!1}:(!function(e){let t=eO(e);if(!t.hasLock||t.hasInfo)return;let a=eL(e.lockPath);if(!a)return eV(e.lockPath);I(a.pid,a.processStartTime)||eV(e.lockPath)}(e.paths),await ta(e))}async function te(e){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await eX(t,"http"))return{info:t,startedByClient:!1};throw new f("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."})}async function tt(e){var t,a;let r=eT(e.paths.infoPath);if(!r)return null;let n=await eX(r,e.transportPreference);return(t=r,a=n,t.version===$()&&t.codeSignature===ts()&&a)?r:(function(e,t,a){try{var r,n;let i=e.version?`pid ${e.pid}, v${e.version}`:`pid ${e.pid}`,o=(r=e,n=t,r.version!==$()?`version mismatch (client v${$()})`:r.codeSignature!==ts()?"code-signature mismatch":n?"not reusable":"unreachable");process.stderr.write(`Replacing daemon (${i}) in ${a}: ${o}
4
+ `)}catch{}}(r,n,e.paths.baseDir),await eB(r),eV(e.paths.infoPath),null)}async function ta(t){let a,r,n=0,i=[];for(let o=1;o<=2;o+=1){let s;try{r={pid:(s=function(t){let a=to(),r=a.useSrc?["--experimental-strip-types",a.srcPath]:[a.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:t.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:t.serverMode};e.mkdirSync(t.paths.baseDir,{recursive:!0});let i=e.openSync(t.paths.logPath,"a"),o=e.openSync(t.paths.logPath,"a");try{return p(process.execPath,r,{env:n,stdio:["ignore",i,o]})}finally{e.closeSync(i),e.closeSync(o)}}(t)).pid}}catch(e){if(a=e instanceof Error?e.message:String(e),i.push(await eR(t.paths,"start_error")),o<2){await C(150);continue}break}let d=await ti(15e3,t,s);if("ready"===d.kind)return{info:d.info,startedByClient:!0};if("early_exit"===d.kind){if(r=d.exit,a=td(d.exit),i.push(await eR(t.paths,"start_error")),o<2){await C(150);continue}break}if(await eF(t.paths)){n+=1;continue}let l=eO(t.paths),c=o<2,u=await eR(t.paths,"startup_timeout",{stopLiveProcesses:!1});if(i.push(u),u.retainedInfoProcess||u.retainedLockProcess){let e=await ti(15e3,t,s);if("ready"===e.kind)return{info:e.info,startedByClient:!0};"early_exit"===e.kind&&(r=e.exit,a=td(e.exit));break}if(!c)break;l.hasInfo||l.hasLock||await C(150)}let o=eO(t.paths),s=function(t){try{if(!e.existsSync(t))return;let a=e.statSync(t);if(a.size<=0)return;let r=Math.min(a.size,64e3),n=e.openSync(t,"r");try{let t=Buffer.alloc(r);e.readSync(n,t,0,r,a.size-r);let i=t.toString("utf8").trim();return i.length>0?i:void 0}finally{e.closeSync(n)}}catch{return}}(t.paths.logPath);throw new f("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",stateDir:t.paths.baseDir,infoPath:t.paths.infoPath,lockPath:t.paths.lockPath,logPath:t.paths.logPath,startupTimeoutMs:15e3,startupAttempts:2,lockRecoveryCount:n,cleanupResults:i,startError:a,daemonProcess:r,...s?{daemonLogTail:s}:{},metadataState:o,hint:function(e,t=_(process.env.AGENT_DEVICE_STATE_DIR)){var a;let r=(a=t,`rm -f ${A(a.infoPath)} ${A(a.lockPath)}`);return e.hasLock&&!e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.lockPath} still exists without ${t.infoPath}. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasLock&&e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.infoPath} and ${t.lockPath} still remain. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasInfo?`agent-device did not observe reachable daemon metadata after retrying, and ${t.infoPath} still remains. Stale metadata was cleaned automatically when safe; retry with --debug. If this persists after confirming no agent-device daemon process is running, run: ${r}`:`agent-device did not observe reachable daemon metadata after retrying. Stale metadata was cleaned automatically when safe; retry with --debug and check daemon diagnostics logs. If stale metadata returns after confirming no agent-device daemon process is running, run: ${r}`}(o,t.paths)})}async function tr(t,a,r){if(!tn(t.command)||!a.startedByClient&&!r.ownedStateDir||eq(a.info))return;let n={pid:a.info.pid,removedInfo:!1,removedLock:!1,removedStateDir:!1,error:void 0};try{await eB(a.info)}catch(e){n.error=e instanceof Error?e.message:String(e)}finally{let t=e.existsSync(r.paths.infoPath);eV(r.paths.infoPath),n.removedInfo=t&&!e.existsSync(r.paths.infoPath);let a=e.existsSync(r.paths.lockPath);eV(r.paths.lockPath),n.removedLock=a&&!e.existsSync(r.paths.lockPath),r.ownedStateDir&&(e.rmSync(r.paths.baseDir,{recursive:!0,force:!0}),n.removedStateDir=!e.existsSync(r.paths.baseDir))}g({level:n.error?"warn":"info",phase:"daemon_replay_cleanup",data:n})}function tn(e){return e===N.replay||e===N.test}async function ti(e,t,a){let r,n=Date.now();for(a.exited.then(e=>{r=e});Date.now()-n<e;){if(r)return{kind:"early_exit",exit:r};let e=eT(t.paths.infoPath);if(e&&await eX(e,t.transportPreference))return{kind:"ready",info:e};if(r)return{kind:"early_exit",exit:r};await C(100)}return{kind:"timeout"}}function to(){let t=T(),a=[r.join(t,"dist","src","internal","daemon.js"),r.join(t,"dist","src","daemon.js")],n=a[0];if(void 0===n)throw new f("COMMAND_FAILED","Daemon dist path list is empty");let i=a.find(t=>e.existsSync(t))??n,o=r.join(t,"src","daemon.ts"),s=a.some(t=>e.existsSync(t)),d=e.existsSync(o);if(!s&&!d)throw new f("COMMAND_FAILED","Daemon entry not found",{distPaths:a,srcPath:o});return{root:t,distPath:i,distPaths:a,srcPath:o,useSrc:process.execArgv.includes("--experimental-strip-types")?d:!s&&d}}function ts(){let e=to();return k(e.useSrc?e.srcPath:e.distPath,e.root)}function td(e){return e.error?`daemon process ${e.pid} failed to start: ${e.error}`:e.signal?`daemon process ${e.pid} exited before readiness with signal ${e.signal}`:`daemon process ${e.pid} exited before readiness with code ${e.exitCode??0}`}async function tl(t){var a,n,o,s,d;let c,u,p,m,h,I,v,b=t.meta?.requestId??y(),A=!!(t.meta?.debug||t.flags?.verbose),S=(a=t,m=a.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,n=t,function(e,t){let a;if(!(!e||"localhost"===(a=new URL(e).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(l.isIPv4(a)?e9.check(a,"ipv4"):!!l.isIPv6(a)&&e9.check(a,"ipv6")))&&("string"!=typeof t||!(t.trim().length>0)))throw new f("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:e,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."})}(u=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new f("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new f("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(c=n.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),p=n.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN),I=function(e,t){let a=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,r=E(a);if(t&&"socket"===r)throw new f("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:t});return{preference:r,serverMode:D(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===a?"dual":void 0))}}(t,(h={rawBaseUrl:c,remoteBaseUrl:u,authToken:p}).remoteBaseUrl),o=t,s=m,d=h.rawBaseUrl,{paths:_((v=tn(o.command)&&!s&&!d)?e.mkdtempSync(r.join(i.tmpdir(),"agent-device-replay-daemon-")):m),transportPreference:I.preference,serverMode:I.serverMode,ownedStateDir:v,remoteBaseUrl:h.remoteBaseUrl,remoteAuthToken:h.authToken}),M=function(e){if(e.command!==N.test){var t;return"number"==typeof e.flags?.timeoutMs&&((t=e.command)===N.prepare||t===N.replay||t===N.snapshot)?e.flags.timeoutMs:e.command===N.prepare?24e4:9e4}}(t),P=await w("daemon_startup",async()=>await e7(S),{requestId:b,session:t.session}),k=P.info,x=await eP(t,k),$={...t,positionals:x.positionals,flags:x.flags,token:k.token,meta:{...t.meta??{},requestId:b,debug:A,cwd:t.meta?.cwd,sessionExplicit:t.meta?.sessionExplicit,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,...x.uploadedArtifactId?{uploadedArtifactId:x.uploadedArtifactId}:{},...x.clientArtifactPaths?{clientArtifactPaths:x.clientArtifactPaths}:{},...x.installSource?{installSource:x.installSource}:{}}};g({level:"info",phase:"daemon_request_prepare",data:{requestId:b,command:t.command,session:t.session}});try{return await w("daemon_request",async()=>await eZ(k,$,S.transportPreference,S.paths,M),{requestId:b,command:t.command})}finally{await tr(t,P,S)}}e9.addSubnet("127.0.0.0",8,"ipv4"),e9.addAddress("::1","ipv6"),e9.addSubnet("::ffff:127.0.0.0",104,"ipv6");let tc=/^[0-9a-fA-F-]{32,36}$/;function tu(e){if(e&&tc.test(e))return e.replaceAll("-","").toUpperCase()}function tf(e,t){return`${e.uuid}:${tp(t)}`}function tp(e){return`0x${e.toString(16)}`}function tm(e){return"string"==typeof e&&e.length>0?e:void 0}function th(...e){for(let t of e){let e=tm(t);if(e)return e}}function ty(e){return"object"==typeof e&&null!==e}function tw(e){return ty(e)?e:void 0}function tg(e){try{let t=JSON.parse(e);return ty(t)?t:null}catch{return null}}function tI(e){if("number"==typeof e&&Number.isSafeInteger(e))return e;if("string"==typeof e){let t=e.startsWith("0x")?Number.parseInt(e,16):Number(e);return Number.isSafeInteger(t)?t:void 0}}function tv(e,t,a){var r;if(!Object.hasOwn(e,t))return;let n="bigint"==typeof(r=e[t])?r:"number"==typeof r&&Number.isSafeInteger(r)?BigInt(r):"string"!=typeof r?void 0:/^(?:0x[0-9a-fA-F]+|\d+)$/.test(r)?BigInt(r):void 0;if(void 0!==n)return n;tb(a,t)}function tb(e,t){throw new f("INVALID_ARGS",`Invalid ${e} numeric field: ${t}`,{hint:"Crash artifact numeric fields must be integer numbers or integer numeric strings."})}function tA(e){return[...new Set(e)]}let tS=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;async function tM(e){return e.dsym&&e.searchPath?[tx(e.cwd,e.dsym),...await tP(tx(e.cwd,e.searchPath))]:e.dsym?[tx(e.cwd,e.dsym)]:e.searchPath?await tP(tx(e.cwd,e.searchPath)):[]}async function tP(e){let t=[],a=0;async function n(i){if(!(t.length>=200)){if((a+=1)>1e4)throw new f("COMMAND_FAILED","debug symbols search-path scan exceeded bounds.",{searchPath:e,maxEntries:1e4,hint:"Pass --dsym <App.dSYM> directly or narrow --search-path to the build products directory."});if(!(await t_(i,e)).isDirectory()){i===e&&function(e){throw new f("INVALID_ARGS",`debug symbols search path is not a directory: ${e}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}(e);return}if(i.endsWith(".dSYM"))return void t.push(i);for(let e of(await c.readdir(i,{withFileTypes:!0})))e.isDirectory()&&await n(r.join(i,e.name))}}return await n(e),t}async function t_(e,t){try{return await c.stat(e)}catch{throw new f("INVALID_ARGS",`debug symbols search path does not exist: ${t}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}}async function tD(e,t){let a=(await Promise.all(tA(e).map(e=>tk(e,t)))).flat();if(0===a.length)throw new f("COMMAND_FAILED","No UUIDs found in dSYM bundle.",{hint:"Verify the path points to a built .dSYM bundle with DWARF contents."});return a}async function tk(e,t){var a;await tE(e);let r=await m(t,["--uuid",e],{timeoutMs:15e3,allowFailure:!0});if(0!==r.exitCode)throw new f("COMMAND_FAILED",`Failed to inspect dSYM UUIDs: ${e}`,{stderr:r.stderr,hint:"Verify the dSYM bundle is valid and readable."});return a=e,r.stdout.split("\n").flatMap(e=>{let t=e.match(/^UUID:\s+([0-9a-fA-F-]{32,36})\s+\(([^)]+)\)\s+(.+)$/),r=tu(t?.[1]);return t&&r?[{dsymPath:a,uuid:r,arch:t[2],binaryPath:t[3].trim()}]:[]})}async function tE(e){let t=await c.stat(e).catch(()=>null);if(!(t?.isDirectory()&&e.endsWith(".dSYM")))throw new f("INVALID_ARGS",`Not a .dSYM bundle: ${e}`,{hint:"Pass the .dSYM bundle path, not the DWARF executable inside it."})}function tx(e,t){return r.resolve(e,t)}function tN(e,t){let a=`${t}:`,r=e.find(e=>e.trimStart().startsWith(a));return r&&r.slice(r.indexOf(":")+1).trim()||void 0}function t$(e,t,a,r){return{index:e,image:t.name,address:tp(a),symbol:r.get(tf(t,a))?.text}}function tT(e){var t;let a;return[(a=(t=e).topFrames.find(e=>e.symbol))?`Start with ${a.symbol} in ${a.image}; it is the first symbolicated frame captured on the crashed thread.`:t.topFrames.length>0?"No symbolicated frame was found on the crashed thread; verify matching dSYMs for the top images.":void 0,e.exceptionType?`Exception: ${e.exceptionType}`:void 0,e.terminationReason?`Termination: ${e.terminationReason}`:void 0].filter(e=>!!e).slice(0,3)}async function tC(e,t,a){let r=new Map;for(let n of(function(e,t){let a=new Map;for(let r of e){let e=t.get(r.image.uuid);if(!e)continue;let n=`${r.image.uuid}:${e.dsym.binaryPath}`,i=a.get(n)??{...e,addresses:[]};i.addresses.push(r.address),a.set(n,i)}return a})(e,t).values())for(let e of(await tU(a,n)))r.set(tf(e.image,e.address),e);return r}async function tU(e,t){var a,r,n,i;let o,s,d=tA(t.addresses.map(tp)),l=await m(e,(a=t,r=d,["-arch",a.image.arch??a.dsym.arch??"arm64","-o",a.dsym.binaryPath,"-l",tp(a.image.base),...r]),{timeoutMs:3e4,allowFailure:!0});return 0!==l.exitCode&&function(e){throw new f("COMMAND_FAILED","atos failed while symbolicating crash frames.",{stderr:e,hint:"Verify the crash artifact and dSYM were produced from the same build and architecture."})}(l.stderr),n=t.image,i=d,s=(""===(o=l.stdout.split(/\r?\n/)).at(-1)&&o.pop(),o),i.map((e,t)=>{let a=s[t]?.trim();return{image:n,address:BigInt(e),text:!function(e,t){if(!e)return!1;let a=e.trim().toLowerCase();return!!a&&"??"!==a&&a!==t.toLowerCase()&&!a.startsWith("0x")}(a,e)?void 0:a}})}async function tL(){return{dwarfdump:await tR("dwarfdump"),atos:await tR("atos")}}async function tR(e){try{let t=await m("xcrun",["--find",e],{timeoutMs:5e3,allowFailure:!0}),a=t.stdout.trim();if(0===t.exitCode&&a.length>0)return a}catch{}throw new f("TOOL_MISSING",`Apple symbolication tool not found: ${e}`,{hint:"Install Xcode Command Line Tools and verify xcrun --find dwarfdump and xcrun --find atos succeed."})}async function tO(e){var t,a,n,i,o,s,d,l,u,p,m,h,y,w,g,I,v,b,A,S,M,P,_,D,k,E,x;let N,$,T,C,U,L,R,O,F;if(void 0!==e.action&&"symbols"!==e.action)throw new f("INVALID_ARGS","debug supports only the symbols workflow.",{hint:"Use debug symbols --artifact <crash.ips|crash.log> --dsym <App.dSYM> or --search-path <dir> --out <path>."});let B=e.cwd??process.cwd(),q=tq(B,e.artifact),j=tq(B,e.out??(a=q,$=(N=r.extname(a))?a.slice(0,-N.length):a,`${$}-symbolicated${N||".log"}`)),V=function(e){var t;let a,n=function(e){let t=tg(e);if(t)return{payload:t};let a=e.indexOf("\n");if(-1===a)return null;let r=e.slice(0,a),n=tg(e.slice(a+1));return n?{header:r,payload:n}:null}(e);if(!n)return null;let i=(Array.isArray(n.payload.usedImages)?n.payload.usedImages:[]).flatMap((e,t)=>(function(e,t){if(!e||"object"!=typeof e)return[];let a=tu(tm(e.uuid)),n=tv(e,"base","IPS usedImages");if(!a||void 0===n)return[];let i=tm(e.path);return[{index:t,name:tm(e.name)??(i?r.basename(i):`image-${t}`),uuid:a,arch:tm(e.arch),base:n,path:i}]})(e,t));if(0===i.length)return null;let o=(t=Array.isArray(n.payload.threads)?n.payload.threads:[],a=new Map(i.map(e=>[e.index,e])),t.flatMap((e,t)=>(function(e){if(!e||"object"!=typeof e)return[];let t=e.frames;return Array.isArray(t)?t.filter(e=>ty(e)):[]})(e).flatMap((e,r)=>(function(e,t,a,r){let n=function(e,t,a){if(!Object.hasOwn(e,t))return;let r=tI(e[t]);if(void 0!==r)return r;tb(a,t)}(e,"imageIndex","IPS frame"),i=tv(e,"imageOffset","IPS frame");if(void 0===n||void 0===i)return[];let o=t.get(n);return o?[{frame:e,frameIndex:r,threadIndex:a,image:o,address:o.base+i}]:[]})(e,a,t,r))));return{format:"ips",images:i,addresses:o.map(({frame:e,...t})=>t),document:n,frameMatches:o,write:e=>(function(e,t,a){for(let e of t){let t=a.get(tf(e.image,e.address))?.text;t&&function(e,t){let a,r=(a=t.match(/^(.*) \+ (\d+)$/))?{symbol:a[1],location:Number(a[2])}:{symbol:t};e.symbol=r.symbol,void 0!==r.location&&(e.symbolLocation=r.location)}(e.frame,t)}e.payload.agentDeviceSymbolication={tool:"agent-device debug symbols",symbolicatedFrames:[...a.values()].filter(e=>e.text).length};let r=`${JSON.stringify(e.payload,null,2)}
5
+ `;return e.header?`${e.header}
6
+ ${r}`:r})(n,o,e)}}(t=await tF(q,"crash artifact"))??function(e){let t=e.split("\n"),a=function(e){let t=[],a=e.findIndex(e=>/^Binary Images:/i.test(e.trim()));if(-1===a)return t;for(let n of e.slice(a+1)){let e=function(e){let t=e.match(/^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+\+?(.+?)\s+<([0-9a-fA-F-]{32,36})>\s+(.+)$/);if(!t)return null;let a=tu(t[4]);if(!a)return null;let n=function(e,t){let a=e.split(/\s+/),n=a.at(-1);if(n&&tS.test(n))return{name:a.slice(0,-1).join(" ").trim(),arch:n};let i=r.basename(t);return{name:e.startsWith(i)?i:e}}(t[3].trim(),t[5].trim());return{name:n.name,arch:n.arch,uuid:a,base:BigInt(t[1]),end:BigInt(t[2]),path:t[5].trim()}}(n);e&&t.push(e)}return t}(t);if(0===a.length)return null;let n=function(e,t){let a,r=[];for(let[n,i]of e.entries()){let e=i.match(/^Thread\s+(\d+)\s+Crashed:/);e?a=Number(e[1]):(0===i.trim().length||/^Thread\s+\d+/.test(i))&&(a=void 0);let o=function(e,t){let a=e.match(/^\s*\d+\s+(.+?)\s+(0x[0-9a-fA-F]+)\b/);if(!a)return null;let r=a[1].trim(),n=BigInt(a[2]),i=function(e,t,a){let r=e.filter(e=>e.name===t);return r.find(e=>{var t,r;return t=e,r=a,void 0!==t.end&&t.base<=r&&r<=t.end})??(1===r.length?r[0]:void 0)}(t,r,n);return i?{image:i,address:n}:null}(i,t),s=i.match(/^\s*(\d+)/);o&&s&&r.push({...o,frameIndex:Number(s[1]),lineIndex:n,threadIndex:a})}return r}(t,a);return{format:"text",images:a,addresses:n,lines:t,frameMatches:n,write(e){let a=new Map(n.map(e=>[e.lineIndex,e]));return t.map((t,r)=>{let n=a.get(r);if(!n)return t;let i=e.get(tf(n.image,n.address))?.text;return!i||t.includes(i)?t:`${t} // ${i}`}).join("\n")}}}(t);V||function(){throw new f("UNSUPPORTED_OPERATION","debug symbols currently supports Apple crash artifacts with Binary Images or IPS usedImages.",{hint:"For Android Java/R8 crashes, use retrace with mapping.txt. For Android native crashes, use ndk-stack or addr2line with unstripped .so symbols. Capture the crash with logs, then symbolicate externally until Android support is added."})}();let G=await tM({cwd:B,dsym:e.dsym,searchPath:e.searchPath});if(0===G.length)throw new f("INVALID_ARGS","debug symbols requires --dsym or --search-path.",{hint:"Pass a matching .dSYM bundle directly, or pass --search-path <dir> so agent-device can match crash image UUIDs to local dSYMs."});let H=await tL(),K=await tD(G,H.dwarfdump),z=function(e,t,a){let r=new Map;for(let a of e){let e=t.find(e=>e.uuid===a.uuid&&(void 0===a.arch||void 0===e.arch||e.arch===a.arch));e&&r.set(a.uuid,{image:a,dsym:e})}if(r.size>0)return r;let n=tA(e.map(e=>e.uuid)),i=tA(t.map(e=>e.uuid));throw new f("COMMAND_FAILED",a?"dSYM UUID does not match any Apple image in the crash artifact.":"No matching dSYM UUID found under search path.",{artifactUuidCount:n.length,artifactUuidSample:n.slice(0,5),dsymUuidCount:i.length,dsymUuidSample:i.slice(0,5),hint:"Use dwarfdump --uuid <App.dSYM> and compare it with the crash Binary Images or usedImages UUID, then pass the matching dSYM/search path."})}(V.images,K,!!e.dsym),Y=await tC(V.addresses,z,H.atos),W=V.write(Y);await c.mkdir(r.dirname(j),{recursive:!0}),await c.writeFile(j,W,"utf8");let J=[...z.values()].map(({image:e,dsym:t})=>({name:e.name,uuid:e.uuid,arch:e.arch??t.arch,dsymPath:t.dsymPath,binaryPath:t.binaryPath})),X=[...Y.values()].filter(e=>e.text).length,Q=V.images.length-J.length,Z=Q>0?[`${Q} Apple image${1===Q?"":"s"} had no matching dSYM and were left unchanged.`]:void 0;return{kind:"debugSymbols",platform:"apple",artifactPath:q,outPath:j,crash:"ips"===V.format?(n=V.document,i=V.frameMatches,o=Y,U=function(e){let t=tI(e.faultingThread);if(void 0!==t)return t;let a=(Array.isArray(e.threads)?e.threads:[]).findIndex(e=>tw(e)?.triggered===!0);return -1===a?void 0:a}(n.payload),{...L={format:"ips",...(T=(s=n).payload,C=(d=s.header)?tg(d):null,{appName:(l=T,u=C,th(l.procName,u?.app_name,u?.name)),bundleId:(p=T,m=C,th(tw(p.bundleInfo)?.CFBundleIdentifier,m?.bundleID)),version:(h=T,y=C,th(tw(h.bundleInfo)?.CFBundleShortVersionString,y?.app_version)),incident:(w=T,g=C,th(w.incident,g?.incident_id)),timestamp:(I=T,v=C,th(I.captureTime,v?.timestamp)),exceptionType:(b=T.exception,tm(tw(b)?.type)),exceptionCodes:function(e){let t=tw(e);if(t)return th(t.codes,t.rawCodes)}(T.exception),terminationReason:function(e){let t=tw(e);if(t){let e;return(e=[tm(t.namespace),tm(t.code),tm(t.reason)].filter(e=>!!e)).length>0?e.join(" "):void 0}}(T.termination)}),crashedThread:U,topFrames:(A=i,S=U,M=o,A.filter(e=>void 0===S||e.threadIndex===S).slice(0,5).map(e=>t$(e.frameIndex,e.image,e.address,M))),findings:[]},findings:tT(L)}):(P=V.lines,_=V.frameMatches,D=Y,O=function(e){let t=tN(e,"Triggered by Thread"),a=t?Number.parseInt(t,10):NaN;if(Number.isSafeInteger(a))return a;for(let t of e){let e=t.match(/^Thread\s+(\d+)\s+Crashed:/);if(e)return Number(e[1])}}(P),{...F={format:"text",appName:(R=tN(P,"Process"),R?.replace(/\s+\[\d+\]$/,"")),bundleId:tN(P,"Identifier"),version:tN(P,"Version"),incident:tN(P,"Incident Identifier"),timestamp:tN(P,"Date/Time"),exceptionType:tN(P,"Exception Type"),exceptionCodes:tN(P,"Exception Codes"),terminationReason:tN(P,"Termination Reason"),crashedThread:O,topFrames:(k=_,E=O,x=D,void 0===E?[]:k.filter(e=>e.threadIndex===E).slice(0,5).map(e=>t$(e.frameIndex,e.image,e.address,x))),findings:[]},findings:tT(F)}),matchedImages:J,symbolicatedFrames:X,skippedImages:Q,warnings:Z,message:`Symbolicated ${X} frame${1===X?"":"s"} -> ${j}`}}async function tF(e,t){await tB(e,t);try{return await c.readFile(e,"utf8")}catch(a){throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}async function tB(e,t){try{let a=await c.stat(e);if(a.size<=0x4000000)return;throw new f("INVALID_ARGS",`${t} is too large: ${e}`,{actualBytes:a.size,maxBytes:0x4000000,hint:"Pass a bounded Apple .ips/.crash artifact. For very large logs, first narrow the log to the crash report, or use logs grep/tail for lead-up context."})}catch(a){if(a instanceof f)throw a;throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}function tq(e,t){return r.resolve(e,t)}let tj={...j,...Q,...X,...ee,...et,...V,...Z,...J,...ei,...H,...z,batch:ea(function(e,t){let a=tj[e];if(!a)throw Error(`Missing daemon writer for batch command: ${e}`);return a(t)})};function tV(e={},t={}){let a=t.transport??tl,r=async(t,r=[],n={})=>{let i=tH(e,n),o=await a({session:Y(i.session),command:t,positionals:r,flags:W(i),runtime:i.runtime,meta:K(i)});return o.ok||function(e){throw new f(u(e.code),e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(o.error),o.data??{}},n=async(e={})=>{let t=await r(x.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(U)},i=async(e,t={})=>{let a=tj[e](t);return await r(a.command,a.positionals,a.options)},o=(t={})=>Y(tH(e,t).session);return{command:{wait:async e=>await i("wait",e),alert:async(e={})=>await i("alert",e),appState:async(e={})=>await i("appstate",e),back:async(e={})=>await i("back",e),home:async(e={})=>await i("home",e),rotate:async e=>await i("rotate",e),appSwitcher:async(e={})=>await i("app-switcher",e),keyboard:async(e={})=>await i("keyboard",e),clipboard:async e=>await i("clipboard",e),reactNative:async e=>await i("react-native",e),prepare:async e=>await i("prepare",e)},devices:{list:async(e={})=>{let t=await i("devices",e);return(Array.isArray(t.devices)?t.devices:[]).map(en)},boot:async(e={})=>await i("boot",e),shutdown:async(e={})=>await i("shutdown",e)},sessions:{list:async(e={})=>await n(e),stateDir:async(t={})=>_(tH(e,t).stateDir??process.env.AGENT_DEVICE_STATE_DIR).baseDir,close:async(e={})=>{let t=o(e),a=(await i("close",e)).shutdown;return{session:t,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}}},apps:{install:async e=>q(await i("install",e),o(e)),reinstall:async e=>q(await i("reinstall",e),o(e)),installFromSource:async e=>ed(await i("install-from-source",e),o(e)),list:async(e={})=>{let t=await i("apps",e);return Array.isArray(t.apps)?t.apps.filter(e=>"string"==typeof e):[]},open:async e=>{let t=o(e),a=await i("open",e),r=G(a),n=O(a,"appBundleId");return{session:t,sessionStateDir:O(a,"sessionStateDir"),appName:O(a,"appName"),appBundleId:n,appId:n,startup:es(a.startup),runtime:er(a.runtime),device:r,identifiers:{session:t,deviceId:r?.id,deviceName:r?.name,udid:r?.ios?.udid,serial:r?.android?.serial,appId:n,appBundleId:n}}},close:async(e={})=>{let t=o(e),a=(await i("close",e)).shutdown;return{session:t,closedApp:e.app,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}},push:async e=>await i("push",e),triggerEvent:async e=>await i("trigger-app-event",e)},materializations:{release:async e=>F(await r(x.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:{allocate:async e=>tK(await r(x.leaseAllocate,[],{...e,leaseId:void 0,leaseTtlMs:e.ttlMs})),heartbeat:async e=>tK(await r(x.leaseHeartbeat,[],{...e,leaseTtlMs:e.ttlMs})),release:async e=>({released:!0===(await r(x.leaseRelease,[],e)).released})},metro:{prepare:async t=>await ec({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,bridgeScope:t.bridgeScope,launchUrl:t.launchUrl,companionProfileKey:t.companionProfileKey,companionConsumerKey:t.companionConsumerKey,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath}),reload:async(t={})=>await el({metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,runtime:e.runtime,timeoutMs:t.timeoutMs})},capture:{snapshot:async(e={})=>{var t,a,r;let n,s,d,l=o(e);return t=await i("snapshot",e),a=l,n=O(t,"appBundleId"),{nodes:B(t.nodes),truncated:!0===t.truncated,appName:O(t,"appName"),appBundleId:n,...(s=tG((r=t).visibility),d=tG(r.unchanged),{...s?{visibility:s}:{},...R(r),...d?{unchanged:d}:{}}),identifiers:{session:a,appId:n,appBundleId:n}}},screenshot:async(e={})=>{let t=o(e),a=await i("screenshot",e);return{path:L(a,"path"),overlayRefs:eo(a),identifiers:{session:t}}},diff:async e=>await i("diff",e)},interactions:{click:async e=>await i("click",e),press:async e=>await i("press",e),longPress:async e=>await i("longpress",e),swipe:async e=>await i("swipe",e),pan:async e=>await i("gesture-pan",e),fling:async e=>await i("gesture-fling",e),swipeGesture:async e=>await i("gesture-swipe",e),focus:async e=>await i("focus",e),type:async e=>await i("type",e),fill:async e=>await i("fill",e),scroll:async e=>await i("scroll",e),pinch:async e=>await i("gesture-pinch",e),rotateGesture:async e=>await i("gesture-rotate",e),transformGesture:async e=>await i("gesture-transform",e),get:async e=>await i("get",e),is:async e=>await i("is",e),find:async e=>await i("find",e)},replay:{run:async e=>await i("replay",e),test:async e=>await i("test",e)},batch:{run:async e=>await i("batch",e)},observability:{perf:async(e={})=>await i("perf",e),logs:async(e={})=>await i("logs",e),network:async(e={})=>await i("network",e)},debug:{symbols:async t=>await tO({cwd:t.cwd??e.cwd,...t})},recording:{record:async e=>await i("record",e),trace:async e=>await i("trace",e)},settings:{update:async e=>await i("settings",e)}}}function tG(e){return"object"==typeof e&&null!==e?e:void 0}function tH(e,t){return{...e,...t}}function tK(e){let t=e.lease;if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Invalid lease response from daemon");return{leaseId:L(t,"leaseId"),tenantId:L(t,"tenantId"),runId:L(t,"runId"),backend:L(t,"backend"),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,heartbeatAt:"number"==typeof t.heartbeatAt?t.heartbeatAt:void 0,expiresAt:"number"==typeof t.expiresAt?t.expiresAt:void 0}}export{tV as createAgentDeviceClient,eG as formatDurationSeconds,tl as sendToDaemon};
@@ -0,0 +1,2 @@
1
+ import{AppError as e}from"./9152.js";let t=["ios","macos","android","linux","apple"],r=["mobile","tv","desktop"];function a(e){return e}function n(e){return"apple"===e||"ios"===e||"macos"===e}function i(e,t){return!t||("apple"===t?n(e):e===t)}function o(e){return"macos"===e||"desktop"===e?"macOS":"tv"===e?"tvOS":"iOS"}function l(e){let{simulatorSetPath:t,platform:r,target:a}=e;if(t&&"macos"!==r&&"desktop"!==a)return t}async function s(t,r,a={}){let o=t,l=e=>e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim();if(r.platform&&(o=o.filter(e=>i(e.platform,r.platform))),r.target&&(o=o.filter(e=>(e.target??"mobile")===r.target)),r.udid){let t=o.find(e=>e.id===r.udid&&n(e.platform));if(!t)throw new e("DEVICE_NOT_FOUND",`No Apple device with UDID ${r.udid}`);return t}if(r.serial){let t=o.find(e=>e.id===r.serial&&"android"===e.platform);if(!t)throw new e("DEVICE_NOT_FOUND",`No Android device with serial ${r.serial}`);return t}if(r.deviceName){let t=l(r.deviceName),a=o.find(e=>l(e.name)===t);if(!a)throw new e("DEVICE_NOT_FOUND",`No device named ${r.deviceName}`);return a}let d=o[0];if(void 0!==d&&1===o.length)return d;if(0===o.length){var c;let t=a.simulatorSetPath;if(t&&(!(c=r.platform)||"apple"===c||"ios"===c))throw new e("DEVICE_NOT_FOUND","No devices found in the scoped simulator set",{simulatorSetPath:t,hint:`The simulator set at "${t}" appears to be empty. Create a simulator first:
2
+ xcrun simctl --set "${t}" create "iPhone 16" com.apple.CoreSimulator.SimDeviceType.iPhone-16 com.apple.CoreSimulator.SimRuntime.iOS-18-0`,selector:r});throw new e("DEVICE_NOT_FOUND","No devices found",{selector:r})}let u=o.filter(e=>"device"!==e.kind);u.length>0&&(o=u);let m=o.filter(e=>e.booted),f=m[0];if(void 0!==f&&1===m.length)return f;let p=m[0]??o[0];if(void 0===p)throw new e("DEVICE_NOT_FOUND","No devices found",{selector:r});return p}function d(e){return e.map((e,t)=>({...e,ref:`e${t+1}`}))}function c(e){let t=e.trim();return t.startsWith("@")?t.slice(1)||null:t.startsWith("e")?t:null}function u(e,t){return e.find(e=>e.ref===t)??null}function m(e){return JSON.stringify({interactiveOnly:e?.interactiveOnly===!0,depth:"number"==typeof e?.depth?e.depth:null,scope:e?.scope?.trim()||null,raw:e?.raw===!0})}function f(e){if(e)return{depth:e.snapshotDepth,interactiveOnly:e.snapshotInteractiveOnly,raw:e.snapshotRaw,scope:e.snapshotScope}}function p(e){return{x:Math.round(e.x+e.width/2),y:Math.round(e.y+e.height/2)}}let h=["reject","strip"],$=["ios-simulator","ios-instance","android-instance"],E=["socket","http","dual"],I=["auto","socket","http"],v=["none","tenant"],S=["summary","headers","body","all"];function N(e){return{parse:t=>e(t,"$")}}function O(e,t){throw Error(`${e}: ${t}`)}function _(e,t){return(!e||"object"!=typeof e||Array.isArray(e))&&O(t,"Expected an object"),e}function g(e,t){return"string"!=typeof e&&O(t,"Expected a string"),e}function y(e,t){let r=g(e,t).trim();return r||O(t,"Expected a non-empty string"),r}function P(e,t){return Number.isInteger(e)||O(t,"Expected an integer"),e}function b(e,t,r){let a=e[t];return void 0===a?void 0:g(a,`${r}.${t}`)}function w(e,t,r){let a=e[t];if(void 0!==a)return"boolean"!=typeof a&&O(`${r}.${t}`,"Expected a boolean"),a}function A(e,t,r){let a=e[t];return void 0===a?void 0:P(a,`${r}.${t}`)}function D(e,t,r){let a=e[t];return void 0===a?void 0:_(a,`${r}.${t}`)}function M(e,t,r,a){let n=e[t];if(void 0!==n)return"string"==typeof n&&r.includes(n)||O(`${a}.${t}`,`Expected one of: ${r.join(", ")}`),n}function R(e,t){let r=_(e,t),a={};for(let[e,n]of Object.entries(r))a[e]=g(n,`${t}.${e}`);return a}let k=N((e,t)=>{let r=_(e,t);return{platform:M(r,"platform",["ios","android"],t),metroHost:b(r,"metroHost",t),metroPort:A(r,"metroPort",t),bundleUrl:b(r,"bundleUrl",t),launchUrl:b(r,"launchUrl",t)}}),x=N((e,r)=>{var a,n;let i=_(e,r),o=(a=i.positionals,n=`${r}.positionals`,Array.isArray(a)||O(n,"Expected an array"),a),l=D(i,"meta",r);return{token:b(i,"token",r),session:b(i,"session",r),command:g(i.command,`${r}.command`),positionals:o.map((e,t)=>g(e,`${r}.positionals[${String(t)}]`)),flags:D(i,"flags",r),runtime:void 0===i.runtime?void 0:k.parse(i.runtime),meta:void 0===l?void 0:{requestId:b(l,"requestId",`${r}.meta`),debug:w(l,"debug",`${r}.meta`),cwd:b(l,"cwd",`${r}.meta`),sessionExplicit:w(l,"sessionExplicit",`${r}.meta`),tenantId:b(l,"tenantId",`${r}.meta`),runId:b(l,"runId",`${r}.meta`),leaseId:b(l,"leaseId",`${r}.meta`),leaseTtlMs:A(l,"leaseTtlMs",`${r}.meta`),leaseBackend:M(l,"leaseBackend",$,`${r}.meta`),sessionIsolation:M(l,"sessionIsolation",v,`${r}.meta`),uploadedArtifactId:b(l,"uploadedArtifactId",`${r}.meta`),clientArtifactPaths:void 0===l.clientArtifactPaths?void 0:R(l.clientArtifactPaths,`${r}.meta.clientArtifactPaths`),installSource:void 0===l.installSource?void 0:function(e,t){let r=_(e,t),a=g(r.kind,`${t}.kind`);if("url"===a){let e=g(r.url,`${t}.url`),n=void 0===r.headers?void 0:R(r.headers,`${t}.headers`);return n?{kind:a,url:e,headers:n}:{kind:a,url:e}}if("path"===a)return{kind:a,path:g(r.path,`${t}.path`)};if("github-actions-artifact"===a){let e,a,n,i,o;return e=y(r.owner,`${t}.owner`),a=y(r.repo,`${t}.repo`),n=void 0!==r.artifactId,i=void 0!==r.runId,o=void 0!==r.artifactName,(n&&(i||o)&&O(`${t}`,"Expected either artifactId or artifactName, not both"),n||!i||o||O(`${t}`,"Expected artifactName when runId is specified"),n||o||O(`${t}`,"Expected artifactId or artifactName"),n)?{kind:"github-actions-artifact",owner:e,repo:a,artifactId:P(r.artifactId,`${t}.artifactId`)}:{kind:"github-actions-artifact",owner:e,repo:a,...i?{runId:P(r.runId,`${t}.runId`)}:{},artifactName:y(r.artifactName,`${t}.artifactName`)}}O(`${t}.kind`,'Expected "url", "path", or "github-actions-artifact"')}(l.installSource,`${r}.meta.installSource`),retainMaterializedPaths:w(l,"retainMaterializedPaths",`${r}.meta`),materializedPathRetentionMs:A(l,"materializedPathRetentionMs",`${r}.meta`),materializationId:b(l,"materializationId",`${r}.meta`),lockPolicy:M(l,"lockPolicy",h,`${r}.meta`),lockPlatform:M(l,"lockPlatform",t,`${r}.meta`)}}});function C(e,t){return{token:b(e,"token",t),session:b(e,"session",t),tenantId:b(e,"tenantId",t),tenant:b(e,"tenant",t),runId:b(e,"runId",t)}}let T=N((e,t)=>{let r=_(e,t);return{...C(r,t),ttlMs:A(r,"ttlMs",t),backend:M(r,"backend",$,t)}}),U=N((e,t)=>{let r,a={record:r=_(e,t),leaseId:b(r,"leaseId",t),ttlMs:A(r,"ttlMs",t)};return{...C(a.record,t),leaseId:a.leaseId,ttlMs:a.ttlMs}}),F=N((e,t)=>{let r=_(e,t);return void 0!==r.ttlMs&&O(`${t}.ttlMs`,"Unexpected field"),{...C(r,t),leaseId:b(r,"leaseId",t)}}),j=N((e,t)=>{let r,a=_(e,t);return{jsonrpc:b(a,"jsonrpc",t),id:(null==(r=a.id)||"string"!=typeof r&&"number"!=typeof r&&O(`${t}.id`,"Expected a string, number, or null"),r),method:b(a,"method",t),params:a.params}});export{h as DAEMON_LOCK_POLICIES,E as DAEMON_SERVER_MODES,I as DAEMON_TRANSPORT_PREFERENCES,r as DEVICE_TARGETS,$ as LEASE_BACKENDS,S as NETWORK_INCLUDE_MODES,t as PLATFORM_SELECTORS,v as SESSION_ISOLATION_MODES,d as attachRefs,m as buildSnapshotPresentationKey,p as centerOfRect,x as daemonCommandRequestSchema,k as daemonRuntimeSchema,u as findNodeByRef,n as isApplePlatform,j as jsonRpcRequestSchema,T as leaseAllocateSchema,U as leaseHeartbeatSchema,F as leaseReleaseSchema,i as matchesPlatformSelector,a as normalizePlatformSelector,c as normalizeRef,o as resolveApplePlatformName,l as resolveAppleSimulatorSetPathForSelector,s as resolveDevice,f as snapshotPresentationOptionsFromFlags};
package/dist/src/9818.js CHANGED
@@ -1 +1 @@
1
- import{AsyncLocalStorage as t}from"node:async_hooks";import{constants as e}from"node:fs";import{access as r,stat as n}from"node:fs/promises";import i from"node:path";import{spawn as o,spawnSync as u}from"node:child_process";import{Readable as d}from"node:stream";import{pipeline as s}from"node:stream/promises";import{AppError as a}from"./9152.js";let f=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,c=[".com",".exe",".bat",".cmd"],l=new t;async function m(t,e){return t?await l.run(t,e):await e()}async function p(t){return await l.run(void 0,t)}async function w(t,e,r={}){let n=l.getStore()?.(t,e,r);return n?await n:await v(t,e,r)}async function h(t,e,r={}){let n=l.getStore()?.(t,e,r);return n?await n:await v(t,e,r)}function v(t,e,r={}){let n=O(t);return new Promise((i,u)=>{let d=o(n,e,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0,shell:!1});r.onSpawn?.(d);let s="",f=r.binaryStdout?[]:void 0,c="",l=!1,m=T(r.timeoutMs),p=m?setTimeout(()=>{l=!0,P(d,r.detached)},m):null,w=B(d,r);r.binaryStdout||d.stdout.setEncoding("utf8"),d.stderr.setEncoding("utf8"),H(d,r.stdin).catch(i=>{var o,s,f,c;w.didAbort||l||(o=i)instanceof Error&&"code"in o&&"EPIPE"===o.code||(u((s=n,f=t,new a("COMMAND_FAILED",`Failed to write stdin for ${s}`,{cmd:f,args:e},(c=i)instanceof Error?c:void 0))),P(d,r.detached))}),d.stdout.on("data",t=>{if(r.binaryStdout)return void f?.push(Buffer.isBuffer(t)?t:Buffer.from(t));let e=String(t);s+=e,r.onStdoutChunk?.(e)}),d.stderr.on("data",t=>{let e=String(t);c+=e,r.onStderrChunk?.(e)}),d.on("error",r=>{p&&clearTimeout(p),w.dispose(),u($(w,n,t,e,r))}),d.on("close",o=>{p&&clearTimeout(p),w.dispose();let d=o??1;if(!w.didAbort&&l&&m){var h,v,A,S,E,b;return void u((h=n,v=t,A=e,S=m,E=d,b=s,new a("COMMAND_FAILED",`${h} timed out after ${S}ms`,{cmd:v,args:A,stdout:b,stderr:c,exitCode:E,timeoutMs:S})))}let g=L(w,n,t,e,d,r.allowFailure,s,c);g?u(g):i({stdout:s,stderr:c,exitCode:d,stdoutBuffer:f?Buffer.concat(f):void 0})})})}async function A(t){let e=D(t);if(!e)return!1;if(i.isAbsolute(e))return x(e);let r=process.env.PATH;if(!r)return!1;let n=function(){if("win32"!==process.platform)return[""];let t=process.env.PATHEXT;if(!t)return c;let e=t.split(";").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0);return e.length>0?e:c}();for(let t of r.split(i.delimiter)){let r=t.trim();if(r){for(let t of function(t,e){if("win32"!==process.platform)return[t];let r=t.toLowerCase();return e.some(t=>r.endsWith(t))?[t]:e.map(e=>`${t}${e}`)}(e,n))if(await x(i.join(r,t)))return!0}}return!1}async function S(t,e){let r=N(t,e,"executable");if(r){if(!await x(r))throw new a("TOOL_MISSING",`${e} points to a missing or non-executable file: ${r}`,{envName:e,path:r});return r}}async function E(t,e){let r=N(t,e,"file");if(r){if(!await F(r))throw new a("TOOL_MISSING",`${e} points to a missing or non-file path: ${r}`,{envName:e,path:r});return r}}function b(t,e,r={}){let n=O(t),i=u(n,e,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:T(r.timeoutMs),windowsHide:!0,shell:!1,...void 0!==r.maxBuffer?{maxBuffer:r.maxBuffer}:{}});if(i.error){let o=i.error.code;if("ETIMEDOUT"===o)throw new a("COMMAND_FAILED",`${n} timed out after ${T(r.timeoutMs)}ms`,{cmd:t,args:e,timeoutMs:T(r.timeoutMs)},i.error);if("ENOENT"===o)throw I(n,t,i.error);throw M(n,t,e,i.error)}let o=r.binaryStdout?Buffer.isBuffer(i.stdout)?i.stdout:Buffer.from(i.stdout??""):void 0,d=r.binaryStdout?"":"string"==typeof i.stdout?i.stdout:(i.stdout??"").toString(),s="string"==typeof i.stderr?i.stderr:(i.stderr??"").toString(),f=i.status??1;if(0!==f&&!r.allowFailure)throw C(n,t,e,f,d,s);return{stdout:d,stderr:s,exitCode:f,stdoutBuffer:o}}function g(t,e,r={}){let n=o(O(t),e,{cwd:r.cwd,env:r.env,stdio:r.stdio??"ignore",detached:!0,windowsHide:!0,shell:!1});return n.unref(),n.pid??0}function y(t,e,r={}){let n=O(t),i=o(n,e,{cwd:r.cwd,env:r.env,stdio:r.stdio??["ignore","pipe","pipe"],detached:r.detached,windowsHide:!0,shell:!1}),u="",d="",s=r.captureOutput??!0,a=B(i,r);s&&(i.stdout?.setEncoding("utf8"),i.stderr?.setEncoding("utf8"),i.stdout?.on("data",t=>{u+=t}),i.stderr?.on("data",t=>{d+=t}));let f=new Promise((o,s)=>{i.on("error",r=>{a.dispose(),s($(a,n,t,e,r))}),i.on("close",i=>{a.dispose();let f=i??1,c=L(a,n,t,e,f,r.allowFailure,u,d);c?s(c):o({stdout:u,stderr:d,exitCode:f})})});return{child:i,wait:f}}function O(t){let e=D(t);if(!e)throw new a("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(t)}`,{cmd:t,hint:"Use a bare command name from PATH or an absolute executable path."});return e}function I(t,e,r){return new a("TOOL_MISSING",`${t} not found in PATH`,{cmd:e},r)}function M(t,e,r,n){return new a("COMMAND_FAILED",`Failed to run ${t}`,{cmd:e,args:r},n)}function _(t,e,r){return new a("COMMAND_FAILED","request canceled",{cmd:e,args:r,executable:t,reason:"request_canceled"})}function C(t,e,r,n,i,o){return new a("COMMAND_FAILED",`${t} exited with code ${n}`,{cmd:e,args:r,stdout:i,stderr:o,exitCode:n,processExitError:!0})}function $(t,e,r,n,i){return t.didAbort?_(e,r,n):"ENOENT"===i.code?I(e,r,i):M(e,r,n,i)}function L(t,e,r,n,i,o,u,d){return t.didAbort?_(e,r,n):0===i||o?null:C(e,r,n,i,u,d)}function N(t,e,r){let n=t?.trim();if(n){if(!i.isAbsolute(n)||n.includes("\0"))throw new a("INVALID_ARGS",`${e} must be an absolute ${r} path, not ${JSON.stringify(t)}`,{envName:e,path:t});return n}}function D(t){let e=t.trim();return!e||e.includes("\0")?null:i.isAbsolute(e)?e:e.includes("/")||e.includes("\\")?null:f.test(e)?e:null}async function x(t){try{if(!await F(t))return!1;return await r(t,"win32"===process.platform?e.F_OK:e.X_OK),!0}catch{return!1}}async function F(t){try{return(await n(t)).isFile()}catch{return!1}}function T(t){if(!Number.isFinite(t))return;let e=Math.floor(t);if(!(e<=0))return e}function B(t,e){let r=!1,n=()=>{r=!0,P(t,e.detached)};return e.signal?.aborted?n():e.signal?.addEventListener("abort",n,{once:!0}),{get didAbort(){return r},dispose:()=>{e.signal?.removeEventListener("abort",n)}}}function P(t,e){if(e&&t.pid&&"win32"!==process.platform)try{process.kill(-t.pid,"SIGKILL");return}catch{}t.kill("SIGKILL")}async function H(t,e){if(t.stdin){if(void 0===e)return void t.stdin?.end();await s(d.from([e]),t.stdin)}}export{x as isExecutablePath,S as resolveExecutableOverridePath,E as resolveFileOverridePath,w as runCmd,y as runCmdBackground,g as runCmdDetached,h as runCmdStreaming,b as runCmdSync,A as whichCmd,m as withCommandExecutorOverride,p as withoutCommandExecutorOverride};
1
+ import{AsyncLocalStorage as t}from"node:async_hooks";import{constants as e}from"node:fs";import{access as r,stat as n}from"node:fs/promises";import o from"node:path";import{spawn as i,spawnSync as u}from"node:child_process";import{Readable as d}from"node:stream";import{pipeline as s}from"node:stream/promises";import{AppError as a}from"./9152.js";let f=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,c=[".com",".exe",".bat",".cmd"],l=new t;async function m(t,e){return t?await l.run(t,e):await e()}async function p(t){return await l.run(void 0,t)}async function w(t,e,r={}){let n=l.getStore()?.(t,e,r);return n?await n:await v(t,e,r)}async function h(t,e,r={}){let n=l.getStore()?.(t,e,r);return n?await n:await v(t,e,r)}function v(t,e,r={}){let n=O(t);return new Promise((o,u)=>{let d=i(n,e,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0,shell:!1});r.onSpawn?.(d);let s="",f=r.binaryStdout?[]:void 0,c="",l=!1,m=P(r.timeoutMs),p=m?setTimeout(()=>{l=!0,H(d,r.detached)},m):null,w=B(d,r);r.binaryStdout||d.stdout.setEncoding("utf8"),d.stderr.setEncoding("utf8"),G(d,r.stdin).catch(o=>{var i,s,f,c;w.didAbort||l||(i=o)instanceof Error&&"code"in i&&"EPIPE"===i.code||(u((s=n,f=t,new a("COMMAND_FAILED",`Failed to write stdin for ${s}`,{cmd:f,args:e},(c=o)instanceof Error?c:void 0))),H(d,r.detached))}),d.stdout.on("data",t=>{if(r.binaryStdout)return void f?.push(Buffer.isBuffer(t)?t:Buffer.from(t));let e=String(t);s+=e,r.onStdoutChunk?.(e)}),d.stderr.on("data",t=>{let e=String(t);c+=e,r.onStderrChunk?.(e)}),d.on("error",r=>{p&&clearTimeout(p),w.dispose(),u(L(w,n,t,e,r))}),d.on("close",i=>{p&&clearTimeout(p),w.dispose();let d=i??1;if(!w.didAbort&&l&&m){var h,v,A,S,b,E;return void u((h=n,v=t,A=e,S=m,b=d,E=s,new a("COMMAND_FAILED",`${h} timed out after ${S}ms`,{cmd:v,args:A,stdout:E,stderr:c,exitCode:b,timeoutMs:S})))}let g=N(w,n,t,e,d,r.allowFailure,s,c);g?u(g):o({stdout:s,stderr:c,exitCode:d,stdoutBuffer:f?Buffer.concat(f):void 0})})})}async function A(t){let e=D(t);if(!e)return!1;if(o.isAbsolute(e))return F(e);let r=process.env.PATH;if(!r)return!1;let n=function(){if("win32"!==process.platform)return[""];let t=process.env.PATHEXT;if(!t)return c;let e=t.split(";").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0);return e.length>0?e:c}();for(let t of r.split(o.delimiter)){let r=t.trim();if(r){for(let t of function(t,e){if("win32"!==process.platform)return[t];let r=t.toLowerCase();return e.some(t=>r.endsWith(t))?[t]:e.map(e=>`${t}${e}`)}(e,n))if(await F(o.join(r,t)))return!0}}return!1}async function S(t,e){let r=x(t,e,"executable");if(r){if(!await F(r))throw new a("TOOL_MISSING",`${e} points to a missing or non-executable file: ${r}`,{envName:e,path:r});return r}}async function b(t,e){let r=x(t,e,"file");if(r){if(!await T(r))throw new a("TOOL_MISSING",`${e} points to a missing or non-file path: ${r}`,{envName:e,path:r});return r}}function E(t,e,r={}){let n=O(t),o=u(n,e,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:P(r.timeoutMs),windowsHide:!0,shell:!1,...void 0!==r.maxBuffer?{maxBuffer:r.maxBuffer}:{}});if(o.error){let i=o.error.code;if("ETIMEDOUT"===i)throw new a("COMMAND_FAILED",`${n} timed out after ${P(r.timeoutMs)}ms`,{cmd:t,args:e,timeoutMs:P(r.timeoutMs)},o.error);if("ENOENT"===i)throw I(n,t,o.error);throw C(n,t,e,o.error)}let i=r.binaryStdout?Buffer.isBuffer(o.stdout)?o.stdout:Buffer.from(o.stdout??""):void 0,d=r.binaryStdout?"":"string"==typeof o.stdout?o.stdout:(o.stdout??"").toString(),s="string"==typeof o.stderr?o.stderr:(o.stderr??"").toString(),f=o.status??1;if(0!==f&&!r.allowFailure)throw $(n,t,e,f,d,s);return{stdout:d,stderr:s,exitCode:f,stdoutBuffer:i}}function g(t,e,r={}){return y(t,e,r).pid}function y(t,e,r={}){let n=i(O(t),e,{cwd:r.cwd,env:r.env,stdio:r.stdio??"ignore",detached:!0,windowsHide:!0,shell:!1}),o=n.pid??0,u=new Promise(t=>{n.once("error",e=>{t({pid:o,error:e.message})}),n.once("exit",(e,r)=>{t({pid:o,..."number"==typeof e?{exitCode:e}:{},...r?{signal:r}:{}})})});return n.unref(),{pid:o,exited:u}}function M(t,e,r={}){let n=O(t),o=i(n,e,{cwd:r.cwd,env:r.env,stdio:r.stdio??["ignore","pipe","pipe"],detached:r.detached,windowsHide:!0,shell:!1}),u="",d="",s=r.captureOutput??!0,a=B(o,r);s&&(o.stdout?.setEncoding("utf8"),o.stderr?.setEncoding("utf8"),o.stdout?.on("data",t=>{u+=t}),o.stderr?.on("data",t=>{d+=t}));let f=new Promise((i,s)=>{o.on("error",r=>{a.dispose(),s(L(a,n,t,e,r))}),o.on("close",o=>{a.dispose();let f=o??1,c=N(a,n,t,e,f,r.allowFailure,u,d);c?s(c):i({stdout:u,stderr:d,exitCode:f})})});return{child:o,wait:f}}function O(t){let e=D(t);if(!e)throw new a("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(t)}`,{cmd:t,hint:"Use a bare command name from PATH or an absolute executable path."});return e}function I(t,e,r){return new a("TOOL_MISSING",`${t} not found in PATH`,{cmd:e},r)}function C(t,e,r,n){return new a("COMMAND_FAILED",`Failed to run ${t}`,{cmd:e,args:r},n)}function _(t,e,r){return new a("COMMAND_FAILED","request canceled",{cmd:e,args:r,executable:t,reason:"request_canceled"})}function $(t,e,r,n,o,i){return new a("COMMAND_FAILED",`${t} exited with code ${n}`,{cmd:e,args:r,stdout:o,stderr:i,exitCode:n,processExitError:!0})}function L(t,e,r,n,o){return t.didAbort?_(e,r,n):"ENOENT"===o.code?I(e,r,o):C(e,r,n,o)}function N(t,e,r,n,o,i,u,d){return t.didAbort?_(e,r,n):0===o||i?null:$(e,r,n,o,u,d)}function x(t,e,r){let n=t?.trim();if(n){if(!o.isAbsolute(n)||n.includes("\0"))throw new a("INVALID_ARGS",`${e} must be an absolute ${r} path, not ${JSON.stringify(t)}`,{envName:e,path:t});return n}}function D(t){let e=t.trim();return!e||e.includes("\0")?null:o.isAbsolute(e)?e:e.includes("/")||e.includes("\\")?null:f.test(e)?e:null}async function F(t){try{if(!await T(t))return!1;return await r(t,"win32"===process.platform?e.F_OK:e.X_OK),!0}catch{return!1}}async function T(t){try{return(await n(t)).isFile()}catch{return!1}}function P(t){if(!Number.isFinite(t))return;let e=Math.floor(t);if(!(e<=0))return e}function B(t,e){let r=!1,n=()=>{r=!0,H(t,e.detached)};return e.signal?.aborted?n():e.signal?.addEventListener("abort",n,{once:!0}),{get didAbort(){return r},dispose:()=>{e.signal?.removeEventListener("abort",n)}}}function H(t,e){if(e&&t.pid&&"win32"!==process.platform)try{process.kill(-t.pid,"SIGKILL");return}catch{}t.kill("SIGKILL")}async function G(t,e){if(t.stdin){if(void 0===e)return void t.stdin?.end();await s(d.from([e]),t.stdin)}}export{F as isExecutablePath,S as resolveExecutableOverridePath,b as resolveFileOverridePath,w as runCmd,M as runCmdBackground,g as runCmdDetached,y as runCmdDetachedMonitored,h as runCmdStreaming,E as runCmdSync,A as whichCmd,m as withCommandExecutorOverride,p as withoutCommandExecutorOverride};