agent-device 0.17.10 → 0.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.10.apk → agent-device-android-multitouch-helper-0.18.1.apk} +0 -0
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.18.1.apk.sha256 +1 -0
- package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.10.manifest.json → agent-device-android-multitouch-helper-0.18.1.manifest.json} +4 -4
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.10.apk → agent-device-android-snapshot-helper-0.18.1.apk} +0 -0
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.18.1.apk.sha256 +1 -0
- package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.10.manifest.json → agent-device-android-snapshot-helper-0.18.1.manifest.json} +6 -6
- package/apple-runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +156 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj +10 -16
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +2 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +3 -1
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +2 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +2 -4
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +9 -36
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +2 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +2 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +2 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +2 -0
- package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +0 -1
- package/dist/src/1986.js +1 -0
- package/dist/src/2748.js +1 -1
- package/dist/src/2948.js +21 -21
- package/dist/src/314.js +1 -1
- package/dist/src/3340.js +8 -7
- package/dist/src/432.js +4 -4
- package/dist/src/4418.js +1 -1
- package/dist/src/4428.js +3 -3
- package/dist/src/485.js +1 -0
- package/dist/src/495.js +5 -0
- package/dist/src/5484.js +1 -1
- package/dist/src/5643.js +1 -0
- package/dist/src/587.js +1 -1
- package/dist/src/5913.js +4 -0
- package/dist/src/6849.js +1 -0
- package/dist/src/6918.js +1 -1
- package/dist/src/6967.js +1 -0
- package/dist/src/760.js +1 -0
- package/dist/src/7871.js +1 -0
- package/dist/src/8225.js +1 -1
- package/dist/src/8391.js +1 -0
- package/dist/src/8404.js +2 -0
- package/dist/src/8414.js +2 -0
- package/dist/src/8875.js +1 -1
- package/dist/src/8936.js +1 -0
- package/dist/src/9414.js +1 -0
- package/dist/src/9581.js +5 -5
- package/dist/src/9624.js +1 -1
- package/dist/src/9722.js +37 -37
- package/dist/src/android-adb.d.ts +19 -54
- package/dist/src/android-adb.js +1 -1
- package/dist/src/android.js +5 -5
- package/dist/src/apps.js +9 -11
- package/dist/src/audio-probe.js +1 -0
- package/dist/src/batch.d.ts +50 -25
- package/dist/src/batch.js +1 -1
- package/dist/src/cli-help.js +104 -37
- package/dist/src/cli.js +36 -27
- package/dist/src/contracts.d.ts +46 -122
- package/dist/src/contracts.js +1 -1
- package/dist/src/debug-symbols.js +3 -0
- package/dist/src/devices.js +1 -1
- package/dist/src/devices~1.js +1 -1
- package/dist/src/devices~2.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.d.ts +2 -6
- package/dist/src/finders.js +1 -1
- package/dist/src/generic.js +1 -9
- package/dist/src/handler-utils.js +1 -0
- package/dist/src/index.d.ts +500 -182
- package/dist/src/index.js +1 -1
- package/dist/src/input-actions.js +1 -1
- package/dist/src/input-actions~1.js +1 -1
- package/dist/src/install-source.d.ts +0 -26
- package/dist/src/install-source.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interactor.js +1 -0
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/companion-tunnel.js +1 -1
- package/dist/src/internal/png-worker.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/linux.js +1 -1
- package/dist/src/metro.d.ts +10 -134
- package/dist/src/metro.js +1 -1
- package/dist/src/notifications.js +1 -1
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-trace-recording.js +3 -3
- package/dist/src/record-trace.js +1 -1
- package/dist/src/remote-config.d.ts +28 -24
- package/dist/src/remote-config.js +1 -1
- package/dist/src/runner-sequence.js +1 -0
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.d.ts +7 -3
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +2 -2
- package/dist/src/session.js +11 -8
- package/dist/src/simulator.js +2 -0
- package/dist/src/snapshot.js +2 -2
- package/dist/src/web.js +1 -1
- package/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift +297 -0
- package/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift +30 -0
- package/package.json +15 -11
- package/server.json +2 -2
- package/android-multitouch-helper/README.md +0 -41
- package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.10.apk.sha256 +0 -1
- package/android-snapshot-helper/README.md +0 -88
- package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.10.apk.sha256 +0 -1
- package/dist/src/2133.js +0 -1
- package/dist/src/2577.js +0 -1
- package/dist/src/2954.js +0 -2
- package/dist/src/4291.js +0 -1
- package/dist/src/4723.js +0 -1
- package/dist/src/5628.js +0 -1
- package/dist/src/5910.js +0 -2
- package/dist/src/6024.js +0 -1
- package/dist/src/733.js +0 -1
- package/dist/src/7394.js +0 -6
- package/dist/src/8275.js +0 -2
- package/dist/src/8358.js +0 -4
- package/dist/src/9919.js +0 -6
- package/dist/src/android-snapshot-helper.d.ts +0 -359
- package/dist/src/android-snapshot-helper.js +0 -1
- package/dist/src/apple.js +0 -1
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.swift +0 -17
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AccentColor.colorset/Contents.json +0 -11
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AppIcon.appiconset/Contents.json +0 -36
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/AppIcon.appiconset/logo.jpg +0 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Contents.json +0 -6
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Logo.imageset/Contents.json +0 -21
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/Logo.imageset/logo.jpg +0 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/PoweredBy.imageset/Contents.json +0 -21
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/Assets.xcassets/PoweredBy.imageset/powered-by.png +0 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunner/ContentView.swift +0 -34
- package/ios-runner/README.md +0 -53
- package/ios-runner/RUNNER_PROTOCOL.md +0 -76
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/xcshareddata/xcschemes/AgentDeviceRunner.xcscheme +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests.entitlements +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.h +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.m +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Exceptions.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests.xctestplan +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/RecordingScripts/recording-resize.swift +0 -0
- /package/{ios-runner → apple-runner}/AgentDeviceRunner/RecordingScripts/recording-trim.swift +0 -0
- /package/dist/src/{4069.js → 4917.js} +0 -0
- /package/dist/src/{9836.js → 893.js} +0 -0
package/dist/src/314.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{promises as t}from"node:fs";import e from"node:os";import i from"node:path";import{AppError as a}from"./
|
|
1
|
+
import{promises as t}from"node:fs";import e from"node:os";import i from"node:path";import{AppError as a}from"./485.js";function r(n={}){let l=n.cwd??process.cwd(),c=n.tempDir??e.tmpdir(),p=n.rootDir?o(n.rootDir,l):void 0;return{resolveInput:async t=>{if("uploadedArtifact"===t.kind)throw new a("UNSUPPORTED_OPERATION","Uploaded artifact inputs require a custom artifact adapter");return{path:o(t.path,l,p)}},reserveOutput:async(e,a)=>{let r,n=a.visibility??"client-visible",d=e?.kind==="path"?o(e.path,l,p):i.join(r=await t.mkdtemp(i.join(c,`agent-device-${a.field}-`)),`${a.field}${a.ext}`);return await t.mkdir(i.dirname(d),{recursive:!0}),{path:d,visibility:n,...r?{cleanup:async()=>{await t.rm(r,{recursive:!0,force:!0})}}:{},publish:async()=>e?.kind==="downloadableArtifact"?{kind:"localPath",field:a.field,path:d,fileName:e.fileName??i.basename(e.clientPath??d)}:void 0}},createTempFile:async e=>{let a=await t.mkdtemp(i.join(c,`${e.prefix}-`));return{path:i.join(a,`file${e.ext}`),visibility:"internal",cleanup:async()=>{await t.rm(a,{recursive:!0,force:!0})}}}}}function o(t,e,r){var o,n;let l,c=i.isAbsolute(t)?t:i.resolve(e,t);if(r&&(o=c,n=r,""!==(l=i.relative(n,o))&&(l.startsWith("..")||i.isAbsolute(l))))throw new a("INVALID_ARGS","Local path is outside the artifact adapter root",{path:c,rootDir:r});return c}export{r as createLocalArtifactAdapter};
|
package/dist/src/3340.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import{promises as t}from"node:fs";import
|
|
2
|
-
${
|
|
3
|
-
${e}
|
|
4
|
-
${a.
|
|
5
|
-
${
|
|
6
|
-
${
|
|
7
|
-
${
|
|
1
|
+
import{AsyncLocalStorage as e}from"node:async_hooks";import{promises as t}from"node:fs";import a from"node:os";import n from"node:path";import{runCmdBackground as i,withoutCommandExecutorOverride as r,runCmd as o,withCommandExecutorOverride as l,resolveFileOverridePath as s,whichCmd as d,runCmdDetached as u}from"./8875.js";import{asAppError as c,AppError as p}from"./485.js";import{emitDiagnostic as f}from"./432.js";import{ensureAndroidSdkPathConfigured as m,resolveAndroidArchivePackageName as w}from"./3006.js";import{sleep as h}from"./5560.js";import{materializeInstallablePath as A,isTrustedInstallSourceUrl as v}from"./5484.js";let y=new e;function g(e){return async(t,a)=>await r(async()=>await o("adb",["-s",e,...t],{...a,detached:"win32"!==process.platform}))}function M(e,t){let a=y.getStore();return t?t:a?.serial===e.id?a.provider.exec:g(e.id)}function _(e,t){var a,n;let r;if(t)return D(t);let o=y.getStore();return o?.serial===e.id?D(o.provider):{exec:r=g((a=e).id),spawn:(n=a.id,(e,t)=>{let a=i("adb",["-s",n,...e],{...t,allowFailure:!0,captureOutput:!1});return a.wait.catch(()=>{}),a.child}),reverse:L(r),pull:async(e,t,a)=>await r(["pull",e,t],a),install:async(e,t)=>{let{installArgs:a,execOptions:n}=k(t);return await r(["install",...a,e],n)}}}function b(e){let t=y.getStore();return t?.serial===e.id?t.provider.text:void 0}function I(e){let t=y.getStore();return t?.serial===e.id?t.provider.touch:void 0}function O(e){let t=D(e),a=t.reverse??L(t.exec),n=new Map;return{async ensure(e,t){let i=n.get(e.local);if(i&&i.ownerId!==e.ownerId)throw new p("COMMAND_FAILED",`Android port reverse ${e.local} is already owned by ${i.ownerId??"another session"}`,{current:i,requested:e});i?.remote!==e.remote&&(await a.ensure(e,t),n.set(e.local,{...e}))},async remove(e,t){n.has(e)?(await a.remove(e,t),n.delete(e)):await a.remove(e,t)},async removeAllOwned(e,t){let i=[...n.values()].filter(t=>t.ownerId===e).map(e=>e.local);if(0===i.length)return void await a.removeAllOwned(e,t);for(let e of i)await a.remove(e,t),n.delete(e)},list:async e=>a.list?await a.list(e):[...n.values()]}}function D(e){return"function"==typeof e?{exec:e}:e}async function N(e,t,a){let{device:n,provider:i,...o}=a??{},l=C(n,i),s=l?.pull;if(s)return await r(async()=>await s(e,t,o));let d=l?.exec;if(!d)throw new p("COMMAND_FAILED","Android adb pull requires an adb provider");return await r(async()=>await d(["pull",e,t],o))}async function E(e,t){let{device:a,provider:n,...i}=t??{},o=C(a,n),l=o?.install;if(l)return await r(async()=>await l(e,i));let s=o?.exec;if(!s)throw new p("COMMAND_FAILED","Android adb install requires an adb provider");let{installArgs:d,execOptions:u}=k(i);return await r(async()=>await s(["install",...d,e],u))}function C(e,t){if(t)return D(t);if(e)return _(e);let a=y.getStore();if(a)return D(a.provider)}async function T(e,t,a){var n;if(!e)return await a();let i={provider:"function"==typeof e?{exec:e}:e,serial:t.serial},o=(n=i,(e,t,a)=>{if("adb"!==e)return;let i=function(e,t){if("-s"===e[0]&&e[1]&&e[1]===t)return e.slice(2)}(t,n.serial);if(i)return r(async()=>await n.provider.exec(i,a))});return await y.run(i,async()=>await l(o,a))}function L(e){let t=new Map;return{async ensure(a,n){if(await e(["reverse",a.local,a.remote],{allowFailure:!1,signal:n?.signal,timeoutMs:n?.timeoutMs}),a.ownerId){let e=t.get(a.ownerId)??new Set;e.add(a.local),t.set(a.ownerId,e)}},async remove(a,n){var i,r;let o,l=await e(["reverse","--remove",a],{allowFailure:!0,signal:n?.signal,timeoutMs:n?.timeoutMs});if(0!==l.exitCode&&(i=l.stdout,r=l.stderr,!((o=`${i}
|
|
2
|
+
${r}`.toLowerCase()).includes("listener")&&o.includes("not found"))))throw Error(`Failed to remove Android port reverse ${a}: ${l.stderr}`);for(let e of t.values())e.delete(a)},async removeAllOwned(e,a){for(let n of[...t.get(e)??[]])await this.remove(n,a);t.delete(e)},async list(a){let n=await e(["reverse","--list"],{allowFailure:!0,signal:a?.signal,timeoutMs:a?.timeoutMs});return 0!==n.exitCode?[]:function(e,t){let a=new Map;for(let[e,n]of t)for(let t of n)a.set(t,e);return e.split("\n").map(e=>e.trim().split(/\s+/)).filter(e=>e.length>=3).map(([,e,t])=>({local:e,remote:t,ownerId:a.get(e)}))}(n.stdout,t)}}}function k(e){let{replace:t,allowTestPackages:a,allowDowngrade:n,grantPermissions:i,...r}=e??{},o=[];return t&&o.push("-r"),a&&o.push("-t"),n&&o.push("-d"),i&&o.push("-g"),{installArgs:o,execOptions:r}}let x=["mCurrentFocus=Window{","mFocusedApp=AppWindowToken{","mResumedActivity:","ResumedActivity:"],S=/\bApplication Not Responding:\s*([A-Za-z0-9_.]+)/i,R=/([^{}]*\bis(?:n't| not)\s+responding[^{}]*)/i,F=/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\b/;function P(e){let t=new Set;for(let a of e.split("\n")){let e=a.trim();if(!e)continue;let n=e.split(/\s+/)[0]??"";if(!n.includes("/"))continue;let i=n.split("/")[0]??"";i.includes(".")&&i&&t.add(i)}return Array.from(t)}function U(e){return e.split("\n").map(e=>{let t=e.trim();return t.startsWith("package:")?t.slice(8):t}).filter(Boolean)}function B(e){return $(e,e=>(function(e){for(let t of e.trim().split(/\s+/)){let e=t.indexOf("/");if(e<=0)continue;let a=V(t.slice(0,e),!1),n=V(t.slice(e+1),!0);if(a&&n&&a.length===e)return{package:a,activity:n}}return null})(e))}function $(e,t){let a=e.split("\n");for(let e of x)for(let n of a){let a=n.indexOf(e);if(-1===a)continue;let i=n.trim(),r=t(n.slice(a+e.length),i);if(r)return r}return null}function V(e,t){let a=0;for(;a<e.length&&function(e,t){if(!e)return!1;let a=e.charCodeAt(0);return a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||"_"===e||"."===e||t&&"$"===e}(e[a],t);)a+=1;return e.slice(0,a)}function W(e){let t=e.trim();if(!t||/\s/.test(t))return!1;let a=/^([A-Za-z][A-Za-z0-9+.-]*):(.+)$/.exec(t);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 G(e){let t=e.trim().split(":")[0]?.toLowerCase();return"http"===t||"https"===t}function j(e,t){let a=e?.trim();return a||(G(t)?"com.apple.mobilesafari":void 0)}function H(e={}){let t=e.ttlMs??3e4,a=e.nowMs??Date.now,n=new Map,i=e=>{var t;let a=[(t=e).platform,t.deviceId,""].join("\0");for(let e of n.keys())e.startsWith(a)&&n.delete(e)};return{get(e,t){let i=q(e,t),r=n.get(i);if(r)return r.expiresAtMs<=a()?void n.delete(i):r.value},set:(e,i,r)=>(n.set(q(e,i),{value:r,expiresAtMs:a()+t}),r),clear(e){i(e)},async invalidateWhile(e,t){i(e);try{return await t()}finally{i(e)}}}}function q(e,t){return[e.platform,e.deviceId,e.variant??"",t.trim().toLowerCase()].join("\0")}function K(e){return["1","true","yes","on"].includes((e??"").trim().toLowerCase())}class z{startedAtMs;expiresAtMs;constructor(e,t){this.startedAtMs=e,this.expiresAtMs=e+Math.max(0,t)}static fromTimeoutMs(e,t=Date.now()){return new z(t,e)}remainingMs(e=Date.now()){return Math.max(0,this.expiresAtMs-e)}elapsedMs(e=Date.now()){return Math.max(0,e-this.startedAtMs)}isExpired(e=Date.now()){return 0>=this.remainingMs(e)}}async function Z(e,t={},a={}){let n,i={maxAttempts:t.maxAttempts??3,baseDelayMs:t.baseDelayMs??200,maxDelayMs:t.maxDelayMs??2e3,jitter:t.jitter??.2,shouldRetry:t.shouldRetry};for(let t=1;t<=i.maxAttempts;t+=1){if(a.signal?.aborted)throw new p("COMMAND_FAILED","request canceled",{reason:"request_canceled"});if(a.deadline?.isExpired()&&t>1)break;try{let n=await e({attempt:t,maxAttempts:i.maxAttempts,deadline:a.deadline});return a.onEvent?.({phase:a.phase,event:"succeeded",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),X({phase:a.phase,event:"succeeded",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),n}catch(d){n=d;let e=a.classifyReason?.(d),r={phase:a.phase,event:"attempt_failed",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:e};if(a.onEvent?.(r),X(r),t>=i.maxAttempts||i.shouldRetry&&!i.shouldRetry(d,t))break;let o=function(e,t,a,n){let i=Math.min(t,e*2**(n-1));return Math.max(0,i+i*a*(2*Math.random()-1))}(i.baseDelayMs,i.maxDelayMs,i.jitter,t),l=a.deadline?Math.min(o,a.deadline.remainingMs()):o;if(l<=0)break;let s={phase:a.phase,event:"retry_scheduled",attempt:t,maxAttempts:i.maxAttempts,delayMs:l,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:e};a.onEvent?.(s),X(s),await function(e,t){return new Promise(a=>{if(t?.aborted)return void a();let n=!1,i=()=>{n||(n=!0,t&&t.removeEventListener("abort",o),a())},r=setTimeout(i,e);function o(){clearTimeout(r),i()}t&&t.addEventListener("abort",o,{once:!0})})}(l,a.signal)}}let r={phase:a.phase,event:"exhausted",attempt:i.maxAttempts,maxAttempts:i.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:a.classifyReason?.(n)};if(a.onEvent?.(r),X(r),n)throw n;throw new p("COMMAND_FAILED","retry failed")}async function J(e,t={}){return Z(()=>e(),{maxAttempts:t.attempts,baseDelayMs:t.baseDelayMs,maxDelayMs:t.maxDelayMs,jitter:t.jitter,shouldRetry:t.shouldRetry})}function X(e){f({level:"attempt_failed"===e.event||"exhausted"===e.event?"warn":"debug",phase:"retry",data:{...e}})}function Q(e){return e?.trim()||void 0}function Y(e){return Q(e)}function ee(e){return new Set(e.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean))}function et(e,t=process.env){let a=Q(e)??Q(t.AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST);if(a)return ee(a)}let ea=new Set(["IOS_BOOT_TIMEOUT","IOS_RUNNER_CONNECT_TIMEOUT","IOS_TOOL_MISSING","ANDROID_BOOT_TIMEOUT","ADB_TRANSPORT_UNAVAILABLE","CI_RESOURCE_STARVATION_SUSPECTED"]);function en(e){return ea.has(e.toUpperCase())}function ei(e){let t=e.error?c(e.error):null,a=e.context?.platform,n=e.context?.phase;if(t?.code==="TOOL_MISSING")return"android"===a?"ADB_TRANSPORT_UNAVAILABLE":"IOS_TOOL_MISSING";let i=t?.details??{},r="string"==typeof i.message?i.message:void 0,o="string"==typeof i.stdout?i.stdout:void 0,l="string"==typeof i.stderr?i.stderr:void 0,s=i.boot&&"object"==typeof i.boot?i.boot:null,d=i.bootstatus&&"object"==typeof i.bootstatus?i.bootstatus:null,u=[e.message,t?.message,e.stdout,e.stderr,r,o,l,"string"==typeof s?.stdout?s.stdout:void 0,"string"==typeof s?.stderr?s.stderr:void 0,"string"==typeof d?.stdout?d.stdout:void 0,"string"==typeof d?.stderr?d.stderr:void 0].filter(Boolean).join("\n").toLowerCase();return"ios"===a&&(u.includes("runner did not accept connection")||"connect"===n&&(u.includes("timed out")||u.includes("timeout")||u.includes("econnrefused")||u.includes("connection refused")||u.includes("fetch failed")||u.includes("socket hang up")))?"IOS_RUNNER_CONNECT_TIMEOUT":"ios"===a&&"boot"===n&&(u.includes("timed out")||u.includes("timeout"))?"IOS_BOOT_TIMEOUT":"android"===a&&"boot"===n&&(u.includes("timed out")||u.includes("timeout"))?"ANDROID_BOOT_TIMEOUT":u.includes("resource temporarily unavailable")||u.includes("killed: 9")||u.includes("cannot allocate memory")||u.includes("system is low on memory")?"CI_RESOURCE_STARVATION_SUSPECTED":"android"===a&&(u.includes("device not found")||u.includes("no devices")||u.includes("device offline")||u.includes("offline")||u.includes("unauthorized")||u.includes("not authorized")||u.includes("unable to locate device")||u.includes("invalid device"))?"ADB_TRANSPORT_UNAVAILABLE":t?.code==="COMMAND_FAILED"||u.length>0?"BOOT_COMMAND_FAILED":"UNKNOWN"}function er(e){switch(e){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 eo=["android.software.leanback","android.software.leanback_only","android.hardware.type.television"];async function el(e,t,a){let n=Array(e.length),i=0,r=Math.min(t,e.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<e.length;){let t=i;i+=1,n[t]=await a(e[t])}})),n}function es(e){return`${e.stdout}
|
|
3
|
+
${e.stderr}`}function ed(e,t){return["-s",e,...t]}function eu(e){return e.startsWith("emulator-")}function ec(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}async function ep(e,t=1e4){return o("adb",ed(e,["shell","getprop","sys.boot_completed"]),{allowFailure:!0,timeoutMs:t})}async function ef(e,t){let a=t.replace(/_/g," ").trim();if(!eu(e))return a||e;let n=await ew(e);return n?n.replace(/_/g," "):a||e}async function em(e,t,a){try{return await a("adb",ed(e,t),{allowFailure:!0,timeoutMs:1e4})}catch(e){var n;if("COMMAND_FAILED"===(n=c(e)).code&&"number"==typeof n.details?.timeoutMs)return;throw e}}async function ew(e,t=o){for(let a of["ro.boot.qemu.avd_name","persist.sys.avd_name"]){let n=await em(e,["shell","getprop",a],t);if(!n)continue;let i=n.stdout.trim();if(0===n.exitCode&&i.length>0)return i}let a=await em(e,["emu","avd","name"],t);if(!a)return;let n=function(e){let t=e.split("\n").map(e=>e.trim()).filter(e=>e.length>0);if(0!==t.length)return"OK"===t.at(-1)&&t.pop(),t.join("\n").trim()||void 0}(a.stdout);if(0===a.exitCode&&n)return n}async function eh(e,t){let a=es(await o("adb",ed(e,["shell","cmd","package","has-feature",t]),{allowFailure:!0,timeoutMs:1e4})).toLowerCase();return!!a.includes("true")||!a.includes("false")&&null}async function eA(e){return(await el(eo,2,async t=>await eh(e,t))).some(e=>!0===e)}async function ev(e){var t;let a;return"tv"===((a=es(await o("adb",ed(e,["shell","getprop","ro.build.characteristics"]),{allowFailure:!0,timeoutMs:1e4})).toLowerCase()).includes("tv")||a.includes("leanback")?"tv":null)||await eA(e)?"tv":(t=es(await o("adb",ed(e,["shell","pm","list","features"]),{allowFailure:!0,timeoutMs:1e4})),/feature:android\.(software\.leanback(_only)?|hardware\.type\.television)\b/i.test(t))?"tv":"mobile"}async function ey(e={}){if(await m(),!await d("adb"))throw new p("TOOL_MISSING","adb not found in PATH");let t=e.serialAllowlist??et(void 0),a=(await eg()).filter(e=>!t||t.has(e.serial)),n=await el(a,3,async({serial:e,rawModel:t})=>{let[a,n,i]=await Promise.all([ef(e,t),eO(e),ev(e)]);return{platform:"android",id:e,name:a,kind:eu(e)?"emulator":"device",target:i,booted:n}});return[...n,...await e_(n)]}async function eg(){return(await o("adb",["devices","-l"],{timeoutMs:1e4})).stdout.split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith("List of devices")).map(e=>e.split(/\s+/)).flatMap(e=>{let t=e[0];return void 0===t||"device"!==e[1]?[]:[{serial:t,rawModel:(e.find(e=>e.startsWith("model:"))??"").replace("model:","")}]})}async function eM(){let e=await o("emulator",["-list-avds"],{allowFailure:!0,timeoutMs:1e4});if(0!==e.exitCode)throw new p("COMMAND_FAILED","Failed to list Android emulator AVDs",{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,hint:"Verify Android emulator tooling is installed and available in PATH."});return e.stdout.split("\n").map(e=>e.trim()).filter(e=>e.length>0)}async function e_(e){let t=await eM().catch(()=>[]),a=new Set(e.filter(e=>"emulator"===e.kind).map(e=>ec(e.name)));return t.filter(e=>!a.has(ec(e))).map(e=>{var t;return{platform:"android",id:e,name:e,kind:"emulator",target:(t=e,/\b(tv|television)\b/i.test(ec(t))?"tv":"mobile"),booted:!1}})}async function eb(e){let t=Date.now();for(;Date.now()-t<e.timeoutMs;){try{let t=await eI(e.avdName,e.serial);if(t)return{platform:"android",id:t,name:e.avdName,kind:"emulator",target:"mobile",booted:!1}}catch{}await h(1e3)}throw new p("COMMAND_FAILED","Android emulator did not appear in time",{avdName:e.avdName,serial:e.serial,timeoutMs:e.timeoutMs,hint:"Check emulator logs and verify the AVD can start from command line."})}async function eI(e,t){let a=ec(e);for(let e of(await eg()).filter(e=>(!t||e.serial===t)&&eu(e.serial)))if(ec(e.rawModel)===a||ec(await ef(e.serial,e.rawModel))===a)return e.serial}async function eO(e){try{let t=await ep(e);return"1"===t.stdout.trim()}catch{return!1}}async function eD(e){var t,a;let n;await m();let i=e.avdName.trim();if(!i)throw new p("INVALID_ARGS","Android emulator boot requires a non-empty AVD name.");let r=e.timeoutMs??12e4;if(!await d("adb"))throw new p("TOOL_MISSING","adb not found in PATH");if(!await d("emulator"))throw new p("TOOL_MISSING","emulator not found in PATH");let o=await eM(),l=function(e,t){let a=e.find(e=>e===t);if(a)return a;let n=ec(t);return e.find(e=>ec(e)===n)}(o,i);if(!l)throw new p("DEVICE_NOT_FOUND",`No Android emulator AVD named ${e.avdName}`,{requestedAvdName:i,availableAvds:o,hint:"Run `emulator -list-avds` and pass an existing AVD name to --device."});let s=Date.now(),c=(t=await ey(),a=e.serial,n=ec(l),t.find(e=>"android"===e.platform&&"emulator"===e.kind&&(!a||e.id===a)&&ec(e.name)===n)),f=c&&eu(c.id)?c:void 0;if(!f){let t=["-avd",l];e.headless&&t.push("-no-window","-no-audio"),u("emulator",t)}let w=f??await eb({avdName:l,serial:e.serial,timeoutMs:r}),h=Math.max(1e3,r-(Date.now()-s));await eN(w.id,h);let A=(await ey()).find(e=>e.id===w.id);return A?{...A,name:l,booted:!0}:{...w,name:l,booted:!0}}async function eN(e,t=6e4){let a,n=z.fromTimeoutMs(t),i=Math.max(1,Math.ceil(t/1e3)),r=!1;try{await Z(async({deadline:i})=>{if(i?.isExpired())throw r=!0,new p("COMMAND_FAILED","Android boot deadline exceeded",{serial:e,timeoutMs:t,elapsedMs:n.elapsedMs(),message:"timeout"});let o=Math.max(1e3,i?.remainingMs()??t),l=await ep(e,Math.min(o,1e4));if(a=l,"1"!==l.stdout.trim())throw new p("COMMAND_FAILED","Android device is still booting",{serial:e,stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode})},{maxAttempts:i,baseDelayMs:1e3,maxDelayMs:1e3,jitter:0,shouldRetry:e=>{let t=ei({error:e,stdout:a?.stdout,stderr:a?.stderr,context:{platform:"android",phase:"boot"}});return"ADB_TRANSPORT_UNAVAILABLE"!==t&&"ANDROID_BOOT_TIMEOUT"!==t}},{deadline:n,phase:"boot",classifyReason:e=>ei({error:e,stdout:a?.stdout,stderr:a?.stderr,context:{platform:"android",phase:"boot"}})})}catch(f){let i=c(f),o=a?.stdout,l=a?.stderr,s=a?.exitCode,d=ei({error:f,stdout:o,stderr:l,context:{platform:"android",phase:"boot"}});"BOOT_COMMAND_FAILED"===d&&"Android device is still booting"===i.message&&(d="ANDROID_BOOT_TIMEOUT");let u={serial:e,timeoutMs:t,elapsedMs:n.elapsedMs(),reason:d,hint:er(d),stdout:o,stderr:l,exitCode:s};if(r||"ANDROID_BOOT_TIMEOUT"===d)throw new p("COMMAND_FAILED","Android device did not finish booting in time",u);if("TOOL_MISSING"===i.code)throw new p("TOOL_MISSING",i.message,{...u,...i.details??{}});if("ADB_TRANSPORT_UNAVAILABLE"===d)throw new p("COMMAND_FAILED",i.message,{...u,...i.details??{}});throw new p(i.code,i.message,{...u,...i.details??{}},i.cause)}}async function eE(e,t,a){return await M(e)(t,a)}function eC(e){return{platform:"android",id:e,name:e,kind:e.startsWith("emulator-")?"emulator":"device",booted:!0}}function eT(e,t){let a=`${e}
|
|
4
|
+
${t}`.toLowerCase();return a.includes("no shell command implementation")||a.includes("unknown command")}let eL=/\.(?:apk|aab)$/i,ek=/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)+$/;function ex(e){var t,a;let n=e.trim();return 0===n.length?"other":eL.test(n)?n.includes("/")||n.includes("\\")||n.startsWith(".")||n.startsWith("~")||(t=n,!ek.test(t))?"binary":"package":(a=n,ek.test(a))?"package":"other"}function eS(e){return`Android runtime hints require an installed package name, not "${e}". Install or reinstall the app first, then relaunch by package.`}async function eR(e,t){let a="url"===e.kind&&v(e.url),i=await A({source:e,isInstallablePath:(e,t)=>{var a;let i;return t.isFile()&&(a=e,".apk"===(i=n.extname(a).toLowerCase())||".aab"===i)},installableLabel:"Android installable (.apk or .aab)",allowArchiveExtraction:"url"!==e.kind||a,signal:t?.signal});try{let e=t?.resolveIdentity===!1?{}:await eF(i.installablePath);return{archivePath:i.archivePath,installablePath:i.installablePath,packageName:e.packageName,cleanup:i.cleanup}}catch(e){throw await i.cleanup(),e}}async function eF(e){let t=n.extname(e).toLowerCase();return".apk"!==t&&".aab"!==t?{}:{packageName:await w(e)}}let eP={settings:{type:"intent",value:"android.settings.SETTINGS"}},eU="android.intent.category.LAUNCHER",eB="android.intent.category.LEANBACK_LAUNCHER",e$="android.intent.category.DEFAULT",eV="Run agent-device apps --platform android to discover the installed package name, then retry open with that exact package.",eW=new Set(["localhost","127.0.0.1","::1","[::1]"]),eG=H();function ej(e){return{platform:"android",deviceId:e.id,variant:e.target??""}}async function eH(e,t){let a=t.trim();if("package"===ex(a))return{type:"package",value:a};let n=eP[a.toLowerCase()];if(n)return n;let i=ej(e),r=eG.get(i,a);if(r)return r;let o=(await eE(e,["shell","pm","list","packages"])).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean).filter(e=>e.toLowerCase().includes(a.toLowerCase())),l=o[0];if(void 0!==l&&1===o.length)return eG.set(i,a,{type:"package",value:l});if(o.length>1)throw new p("INVALID_ARGS",`Multiple packages matched "${t}"`,{matches:o,hint:"Run agent-device apps --platform android to see the exact installed package names before retrying open."});throw new p("APP_NOT_INSTALLED",`No package found matching "${t}"`,{hint:eV})}async function eq(e,t){let a=await eK(e);return("user-installed"===t?(await eZ(e)).filter(e=>a.has(e)):Array.from(a)).sort((e,t)=>e.localeCompare(t)).map(e=>({package:e,name:eJ(e)}))}async function eK(e){let t=new Set;for(let a of ez(e,{includeFallbackWhenUnknown:!0})){let n=await eE(e,["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 e of P(n.stdout))t.add(e)}return t}function ez(e,t={}){return"tv"===e.target?[eB]:"mobile"===e.target?[eU]:t.includeFallbackWhenUnknown?[eU,eB]:[eU]}async function eZ(e){return U((await eE(e,["shell","pm","list","packages","-3"])).stdout)}function eJ(e){let t=new Set(["com","android","google","app","apps","service","services","mobile","client"]),a=e.split(".").flatMap(e=>e.split(/[_-]+/)).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0),n=a[a.length-1]??e;for(let e=a.length-1;e>=0;e-=1){let i=a[e];if(i&&!t.has(i)){n=i;break}}return n.split(/[^a-z0-9]+/i).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}async function eX(e){let t=await eY(e,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]]);if(t)return t;let a=await eY(e,[["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]);return a||{}}async function eQ(e){return await e0(e,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]])}async function eY(e,t){for(let a of t){let t=B((await eE(e,a,{allowFailure:!0})).stdout??"");if(t)return t}return null}async function e0(e,t){for(let a of t){let t=$((await eE(e,a,{allowFailure:!0})).stdout??"",(e,t)=>(function(e,t){let a=e.split("}")[0]?.trim()??e.trim(),n=S.exec(a);if(n){let e=n[1];return{package:e,focusedWindow:`Application Not Responding: ${e}`,raw:t}}let i=R.exec(a);if(!i)return null;let r=i[1];if(void 0===r)return null;let o=r.trim().replace(/\s+/g," "),l=F.exec(o)?.[1];return{...l?{package:l}:{},focusedWindow:o,raw:t}})(e,t));if(t)return t}return null}async function e1(e,t){let a=function(e){let t;try{t=new URL(e)}catch{return null}let a=t.hostname.toLowerCase();if(!eW.has(a)||!t.port)return null;let n=Number(t.port);return Number.isInteger(n)?`tcp:${n}`:null}(t);if(!a)return;let n=O(_(e));try{await n.ensure({local:a,remote:a})}catch(t){let e={localPort:a.replace("tcp:",""),operation:`adb reverse ${a} ${a}`};throw t instanceof p&&Object.assign(e,{hint:t.details?.hint,diagnosticId:t.details?.diagnosticId,logPath:t.details?.logPath}),new p("COMMAND_FAILED",`Failed to ensure Android port reverse ${a} before opening localhost URL`,e,t)}}function e3(e){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function e2(e){return(e.launchArgs??[]).map(e3)}async function e4(e,t,a){var n;e.booted||await eN(e.id);let i="string"==typeof(n=a)?{activity:n}:n??{},r=i.activity,o=t.trim();if(W(o))return void await e5(e,o,i);if(void 0!==i.url)return void await e9(e,t,i);let l=await eH(e,t),s=ez(e)[0]??eU;"intent"===l.type?await e8(e,l.value,i):r?await e6(e,l.value,r,s,i):await e7(e,l.value,s,i)}async function e5(e,t,a){var n;let i;if(a.activity)throw new p("INVALID_ARGS","Activity override is not supported when opening a deep link URL");await e1(e,t),await eE(e,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",t,...(n=a.appBundleId,(i=n?.trim())?["-p",i]:[]),...e2(a)])}async function e9(e,t,a){if(a.activity)throw new p("INVALID_ARGS","Activity override is not supported when opening an app-bound deep link URL");let n=a.url?.trim()??"";if(!W(n))throw new p("INVALID_ARGS","Android app-bound open requires a valid URL target");let i=await tt(e,t,"app-bound open");await eE(e,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",n,"-p",i,...e2(a)])}async function e8(e,t,a){if(a.activity)throw new p("INVALID_ARGS","Activity override requires a package name, not an intent");await eE(e,["shell","am","start","-W","-a",t,...e2(a)])}async function e6(e,t,a,n,i){let r=a.includes("/")?a:`${t}/${a.startsWith(".")?a:`.${a}`}`;try{await eE(e,te(r,n,i))}catch(a){throw await ti(e,t,a),a}}async function e7(e,t,a,n){let i=await eE(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",e$,"-c",a,"-p",t,...e2(n)],{allowFailure:!0});if(0===i.exitCode&&!tl(i.stdout,i.stderr))return;let r=await to(e,t);if(!r){if(!await tn(e,t))throw ta(t);throw new p("COMMAND_FAILED",`Failed to launch ${t}`,{stdout:i.stdout,stderr:i.stderr})}await eE(e,te(r,a,n))}function te(e,t,a){return["shell","am","start","-W","-a","android.intent.action.MAIN","-c",e$,"-c",t,"-n",e,...e2(a)]}async function tt(e,t,a){let n=await eH(e,t);if("intent"===n.type)throw new p("INVALID_ARGS",`Android ${a} requires a package name, not an intent`);return n.value}function ta(e){return new p("APP_NOT_INSTALLED",`No package found matching "${e}"`,{package:e,hint:eV})}async function tn(e,t){let a=await eE(e,["shell","pm","path",t],{allowFailure:!0}),n=`${a.stdout}
|
|
5
|
+
${a.stderr}`;return!!(0===a.exitCode&&/\bpackage:/i.test(n))||(tr(n),!1)}async function ti(e,t,a){if(tr(a instanceof p?`${String(a.details?.stdout??"")}
|
|
6
|
+
${String(a.details?.stderr??"")}`:"")||!await tn(e,t))throw ta(t)}function tr(e){return/\bunknown package\b/i.test(e)||/\bpackage .* (?:was|is) not found\b/i.test(e)||/\bpackage .* does not exist\b/i.test(e)||/\bcould not find package\b/i.test(e)}async function to(e,t){for(let a of Array.from(new Set(ez(e,{includeFallbackWhenUnknown:!0})))){let n=await eE(e,["shell","cmd","package","resolve-activity","--brief","-a","android.intent.action.MAIN","-c",a,t],{allowFailure:!0});if(0!==n.exitCode)continue;let i=ts(n.stdout);if(i)return i}return null}function tl(e,t){let a=`${e}
|
|
7
|
+
${t}`;return/Error:.*(?:Activity not started|unable to resolve Intent)/i.test(a)}function ts(e){let t=e.split("\n").map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e-=1){let a=t[e];if(void 0===a||!a.includes("/"))continue;let n=a.split(/\s+/)[0];if(void 0!==n)return n}return null}async function td(e){e.booted||await eN(e.id)}async function tu(e,t){if("settings"===t.trim().toLowerCase()){await eE(e,["shell","am","force-stop","com.android.settings"]),await tc(e,"com.android.settings");return}let a=await eH(e,t);if("intent"===a.type)throw new p("INVALID_ARGS","Close requires a package name, not an intent");await eE(e,["shell","am","force-stop",a.value]),await tc(e,a.value)}async function tc(e,t){await tp(e,t),await tm(e,t)}async function tp(e,t){let a=Date.now()+2e3;for(;Date.now()<a;){let a=await tf(e);if(a?.package!==t)return;await h(50)}}async function tf(e){for(let t of[["shell","dumpsys","window","windows"],["shell","dumpsys","window"],["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]){let a=B((await eE(e,t,{allowFailure:!0})).stdout??"");if(a)return a}return null}async function tm(e,t){let a=Date.now()+2e3;for(;Date.now()<a;){if(!await tw(e,t)&&(await h(150),!await tw(e,t)))return;await h(50)}}async function tw(e,t){return((await eE(e,["shell","pidof",t],{allowFailure:!0})).stdout??"").trim().length>0}async function th(e,t){let a=await eH(e,t);if("intent"===a.type)throw new p("INVALID_ARGS","App uninstall requires a package name, not an intent");let n=await eE(e,["uninstall",a.value],{allowFailure:!0});if(0!==n.exitCode){let e=`${n.stdout}
|
|
8
|
+
${n.stderr}`.toLowerCase();if(!e.includes("unknown package")&&!e.includes("not installed"))throw new p("COMMAND_FAILED",`adb uninstall failed for ${a.value}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}return{package:a.value}}let tA=null;async function tv(){let e=`${process.env.PATH??""}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR??""}`;if(tA?.key===e)return tA.invocation;if(await d("bundletool")){let t={cmd:"bundletool",prefixArgs:[]};return tA={key:e,invocation:t},t}let t=await s(process.env.AGENT_DEVICE_BUNDLETOOL_JAR,"AGENT_DEVICE_BUNDLETOOL_JAR");if(!t)throw new p("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",t]};return tA={key:e,invocation:a},a}async function ty(e){let t=await tv();await o(t.cmd,[...t.prefixArgs,...e])}async function tg(e,i){let r=_(e),o="universal";if(r.installBundle)return void await r.installBundle(i,{mode:o});let l=await t.mkdtemp(n.join(a.tmpdir(),"agent-device-aab-")),s=n.join(l,"bundle.apks");try{await ty(["build-apks","--bundle",i,"--output",s,"--mode",o]),await ty(["install-apks","--apks",s,"--device-id",e.id])}finally{await t.rm(l,{recursive:!0,force:!0})}}async function tM(e,t){".aab"===n.extname(t).toLowerCase()?await tg(e,t):await E(t,{device:e,replace:!0})}async function t_(e){return new Set((await eE(e,["shell","pm","list","packages"])).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean))}async function tb(e,t){let a=Array.from(await t_(e)).filter(e=>!t.has(e));if(1===a.length)return a[0]}async function tI(e,t){await eG.invalidateWhile(ej(e),async()=>{e.booted||await eN(e.id),await tM(e,t)})}async function tO(e,t,a){let n=a?void 0:await t_(e);return await tI(e,t),a??(n?await tb(e,n):void 0)}async function tD(e,t){e.booted||await eN(e.id);let a=await eR({kind:"path",path:t});try{let t=await tO(e,a.installablePath,a.packageName),n=t?eJ(t):void 0;return{archivePath:a.archivePath,installablePath:a.installablePath,packageName:t,appName:n,launchTarget:t}}finally{await a.cleanup()}}async function tN(e,t,a){return await eG.invalidateWhile(ej(e),async()=>{e.booted||await eN(e.id);let{package:n}=await th(e,t),i=await eR({kind:"path",path:a},{resolveIdentity:!1});try{await tI(e,i.installablePath)}finally{await i.cleanup()}return{package:n}})}async function tE(e,t={}){let a=["logcat","-d","-v","time"];void 0!==t.lines&&a.push("-t",String(Math.max(1,Math.floor(t.lines))));let n=await e(a,{allowFailure:!0,timeoutMs:t.timeoutMs,signal:t.signal});if(0!==n.exitCode)throw new p("COMMAND_FAILED","Failed to capture Android logcat",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});return n.stdout}function tC(e,t={}){if(!e.spawn)throw new p("UNSUPPORTED_OPERATION","Android ADB provider does not support streams",{capability:"adb.spawn"});let a=["logcat","-v","time"];t.pid&&a.push("--pid",t.pid);let n=e.spawn(a,{stdio:["ignore","pipe","pipe"],signal:t.signal});return t.output&&n.stdout&&n.stdout.pipe(t.output,{end:!1}),n}export{z as Deadline,eC as androidDeviceForSerial,er as bootFailureHint,tE as captureAndroidLogcatWithAdb,ex as classifyAndroidAppTarget,ei as classifyBootFailure,tu as closeAndroidApp,O as createAndroidPortReverseManager,H as createAppResolutionCache,eD as ensureAndroidEmulatorBooted,eS as formatAndroidInstalledPackageRequiredMessage,eX as getAndroidAppState,eQ as getAndroidBlockingDialogFocus,eJ as inferAndroidAppName,E as installAndroidAdbPackage,tD as installAndroidApp,tO as installAndroidInstallablePathAndResolvePackageName,tl as isAmStartError,eT as isClipboardShellUnsupported,W as isDeepLinkTarget,K as isEnvTruthy,en as isInfrastructureBootFailureReason,G as isWebUrl,eq as listAndroidApps,ey as listAndroidDevices,e4 as openAndroidApp,td as openAndroidDevice,B as parseAndroidForegroundApp,ts as parseAndroidLaunchComponent,P as parseAndroidLaunchablePackages,U as parseAndroidUserInstalledPackages,ee as parseSerialAllowlist,eR as prepareAndroidInstallArtifact,N as pullAndroidAdbFile,tN as reinstallAndroidApp,M as resolveAndroidAdbExecutor,_ as resolveAndroidAdbProvider,eH as resolveAndroidApp,et as resolveAndroidSerialAllowlist,b as resolveAndroidTextInjector,I as resolveAndroidTouchInjector,j as resolveIosDeviceDeepLinkBundleId,Y as resolveIosSimulatorDeviceSetPath,Z as retryWithPolicy,eE as runAndroidAdb,tC as streamAndroidLogcatWithAdb,eN as waitForAndroidBoot,T as withAndroidAdbProvider,J as withRetry};
|
package/dist/src/432.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{AsyncLocalStorage as
|
|
2
|
-
`;try{
|
|
3
|
-
`)}let n=
|
|
4
|
-
`),
|
|
1
|
+
import{AsyncLocalStorage as e}from"node:async_hooks";import t from"node:crypto";import n from"node:fs";import o from"node:os";import r from"node:path";import{redactDiagnosticData as i}from"./485.js";let s=new e;function a(){return t.randomBytes(8).toString("hex")}async function c(e,n){let o={...e,diagnosticId:`${Date.now().toString(36)}-${t.randomBytes(4).toString("hex")}`,events:[],liveWrittenEventCount:0,phaseCounts:new Map};return await s.run(o,n)}function g(e){let t=s.getStore();t&&Object.assign(t,e)}function l(){let e=s.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug}:{}}function u(e){let t=s.getStore();if(!t)return 0;let n=0;for(let o of e)n+=t.phaseCounts.get(o)??0;return n}function d(e){let t=s.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??"info",phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?i(e.data):void 0};if(t.events.push(n),t.phaseCounts.set(e.phase,(t.phaseCounts.get(e.phase)??0)+1),!t.debug)return;let o=`${JSON.stringify(n)}
|
|
2
|
+
`;try{t.logPath&&(m(t.logPath,o),t.liveWrittenEventCount=t.events.length),t.traceLogPath&&m(t.traceLogPath,o),t.logPath||t.traceLogPath||process.stderr.write(`[agent-device][diag] ${o}`)}catch{}}async function f(e,t,n){let o=Date.now();try{let r=await t();return d({level:"info",phase:e,durationMs:Date.now()-o,data:n}),r}catch(t){throw d({level:"error",phase:e,durationMs:Date.now()-o,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function h(e={}){let t=s.getStore();if(!t||!e.force&&!t.debug||0===t.events.length)return null;try{if(t.logPath){let e=t.events.slice(t.liveWrittenEventCount);if(e.length>0){let n=e.map(e=>JSON.stringify(i(e)));m(t.logPath,`${n.join("\n")}
|
|
3
|
+
`)}let n=t.logPath;return t.events=[],t.liveWrittenEventCount=0,n}let e=(t.session??"default").replace(/[^a-zA-Z0-9._-]/g,"_"),s=new Date().toISOString().slice(0,10),a=r.join(o.homedir(),".agent-device","logs",e,s);n.mkdirSync(a,{recursive:!0});let c=new Date().toISOString().replace(/[:.]/g,"-"),g=r.join(a,`${c}-${t.diagnosticId}.ndjson`),l=t.events.map(e=>JSON.stringify(i(e)));return n.writeFileSync(g,`${l.join("\n")}
|
|
4
|
+
`),t.events=[],g}catch{return null}}function m(e,t){n.mkdirSync(r.dirname(e),{recursive:!0}),n.appendFileSync(e,t,"utf8")}export{u as countDiagnosticEventsByPhase,a as createRequestId,d as emitDiagnostic,h as flushDiagnosticsToSessionFile,l as getDiagnosticsMeta,g as updateDiagnosticsScope,f as withDiagnosticTimer,c as withDiagnosticsScope};
|
package/dist/src/4418.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{deflateSync as t,inflateSync as e}from"node:zlib";import{AppError as r}from"./
|
|
1
|
+
import{deflateSync as t,inflateSync as e}from"node:zlib";import{AppError as r}from"./485.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/4428.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import e from"node:fs";import{parseAllDocuments as t,stringify as n}from"yaml";import{AppError as r}from"./
|
|
2
|
-
`,s=`${t}.tmp-${process.pid}-${Date.now()}`;e.writeFileSync(s,o),e.renameSync(s,t)}function
|
|
3
|
-
`}function
|
|
1
|
+
import e from"node:fs";import{parseAllDocuments as t,stringify as n}from"yaml";import{AppError as r}from"./485.js";import{recordingQualityInputToExportQuality as i,readScreenshotScriptFlag as o,MAESTRO_COMPAT_TRACKER_URL as s,MAESTRO_NEW_ISSUE_URL as l}from"./2948.js";import{device_PLATFORM_SELECTORS as a}from"./6849.js";import{formatScriptStringLiteral as f,parseReplayOpenFlags as u,formatPortableActionLine as p,parseReplaySeriesFlags as c,parseReplayRuntimeFlags as h,isClickLikeCommand as d}from"./7871.js";let m=/^[A-Z_][A-Z0-9_]*$/,g=/(\\\$\{)|\$\{([A-Za-z_][A-Za-z0-9_.]*)(?::-((?:[^}\\]|\\.)*))?\}/g,A="AD_VAR_";function v(e){return e.startsWith("AD_")}function y(e){return new r("INVALID_ARGS",`The AD_* namespace is reserved for built-in variables. Rename ${e} to avoid the AD_ prefix.`)}function w(e){let t={};if(e.builtins)for(let[n,r]of Object.entries(e.builtins))t[n]=r;for(let n of[e.fileEnv,e.shellEnv,e.cliEnv])if(n)for(let[e,r]of Object.entries(n)){if(v(e))throw y(e);t[e]=r}return{values:t}}function b(e,t){Object.assign(e.values,t)}function I(e){let t={};for(let[n,r]of Object.entries(e)){if("string"!=typeof r||!n.startsWith(A))continue;let e=n.slice(A.length);0!==e.length&&m.test(e)&&(v(e)||(t[e]=r))}return t}function $(e){let t={};for(let n of e){let e=n.indexOf("=");if(e<=0)throw new r("INVALID_ARGS",`Invalid -e entry "${n}": expected KEY=VALUE.`);let i=n.slice(0,e);if(!m.test(i))throw new r("INVALID_ARGS",`Invalid -e key "${i}": keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(v(i))throw y(i);t[i]=n.slice(e+1)}return t}function _(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function S(e){if(e&&"object"==typeof e&&!Array.isArray(e)){let t={};for(let[n,r]of Object.entries(e))"string"==typeof r&&(t[n]=r);return t}return process.env}function N(e,t,n){return e.replace(g,(e,i,o,s)=>{if(i)return"${";if(!o)return e;if(Object.prototype.hasOwnProperty.call(t.values,o))return String(t.values[o]);if(void 0!==s)return s.replace(/\\(.)/g,"$1");throw new r("INVALID_ARGS",`Unresolved variable \${${o}} at ${n.file}:${n.line}.`)})}function R(e,t,n){return{...e,positionals:(e.positionals??[]).map(e=>N(e,t,n)),flags:D(e.flags,t,n)??{},runtime:D(e.runtime,t,n),replayControl:function(e,t,n){if(!e)return e;if(e.kind==="maestroRunFlowWhen"){return{...e,selector:N(e.selector,t,n)}}return e}(e.replayControl,t,n)}}function D(e,t,n){return e?function e(t,n,r){return"string"==typeof t?N(t,n,r):Array.isArray(t)?t.map(t=>e(t,n,r)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,i])=>[t,e(i,n,r)])):t}(e,t,n):e}let M=new Set(a.filter(e=>"apple"!==e&&"web"!==e)),x=new Set(["mobile","tv","desktop"]);function O(e){let t=[],n=[],s=e.split(/\r?\n/),l=!1;for(let[e,a]of s.entries()){let s=a.trim();if(0===s.length||s.startsWith("#"))continue;if(j(s)){if(l)throw new r("INVALID_ARGS",`env directives must precede all actions (line ${e+1}).`);continue}let f=function(e){let t=e.trim();if(0===t.length||t.startsWith("#"))return null;let[n,...s]=function(e){let t=[],n=0;for(;n<e.length&&!((n=function(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}(e,n))>=e.length);){let i='"'===e[n]?function(e,t){let n=!1,i=t+1;for(;i<e.length;i+=1){let t=e.charAt(i);if('"'===t&&!n)break;if(n){n=!1;continue}n="\\"===t}if(i>=e.length)throw new r("INVALID_ARGS",`Invalid replay script line: ${e}`);return{value:JSON.parse(e.slice(t,i+1)),nextCursor:i+1}}(e,n):function(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}(e,n);t.push(i.value),n=i.nextCursor}return t}(t);if(void 0===n||"context"===n)return null;let l={ts:Date.now(),command:n,positionals:[],flags:{}};if("snapshot"===n){l.positionals=[];for(let e=0;e<s.length;e+=1){let t=s[e];if("-i"===t){l.flags.snapshotInteractiveOnly=!0;continue}if("-c"!==t){if("--raw"===t){l.flags.snapshotRaw=!0;continue}if("--force-full"===t){l.flags.snapshotForceFull=!0;continue}if(("-d"===t||"--depth"===t)&&e+1<s.length){let t=Number(s[e+1]);Number.isFinite(t)&&t>=0&&(l.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if(("-s"===t||"--scope"===t)&&e+1<s.length){l.flags.snapshotScope=s[e+1],e+=1;continue}if("--backend"===t&&e+1<s.length){e+=1;continue}}}return l}if("open"===n){let e=u(s);return l.positionals=e.positionals,Object.assign(l.flags,e.flags),l.runtime=e.runtime,l}if("runtime"===n){let e=h(s);return l.positionals=e.positionals,Object.assign(l.flags,e.flags),l}if(d(n)){let e=c(n,s);Object.assign(l.flags,e.flags);let t=e.positionals[0];if(void 0===t)return l;if(t.startsWith("@"))return l.positionals=[t],e.positionals[1]&&(l.result={refLabel:e.positionals[1]}),l;let r=e.positionals[0],i=e.positionals[1];return E(r)&&E(i)&&e.positionals.length>=2?l.positionals=[r,i]:l.positionals=[e.positionals.join(" ")],l}if("fill"===n){let e=c(n,s);if(Object.assign(l.flags,e.flags),!(e.positionals.length>=2))return l.positionals=e.positionals,l;let[t,r,...i]=e.positionals;return t.startsWith("@")?(i.length>0?(l.positionals=[t,i.join(" ")],l.result={refLabel:r}):l.positionals=[t,r],l):(l.positionals=[t,[r,...i].join(" ")],l)}if("get"===n){let e=s[0],t=s[1];return void 0===e||void 0===t?l.positionals=s:t.startsWith("@")?(l.positionals=[e,t],s[2]&&(l.result={refLabel:s[2]})):l.positionals=[e,s.slice(1).join(" ")],l}if("swipe"===n||"type"===n){let e=c(n,s);return Object.assign(l.flags,e.flags),l.positionals=e.positionals,l}if("record"===n){let e=[];for(let t=0;t<s.length;t+=1){let n=s[t];if("--hide-touches"===n){l.flags.hideTouches=!0;continue}if("--fps"===n&&t+1<s.length){let e=Number(s[t+1]);Number.isFinite(e)&&(l.flags.fps=Math.floor(e)),t+=1;continue}if("--quality"===n&&t+1<s.length){let e=i(s[t+1]);void 0!==e&&(l.flags.quality=e),t+=1;continue}if("--max-size"===n&&t+1<s.length){let e=Number(s[t+1]);Number.isFinite(e)&&(l.flags.screenshotMaxSize=Math.floor(e)),t+=1;continue}e.push(n)}return l.positionals=e,l}if("screenshot"===n){let e=[];for(let t=0;t<s.length;t+=1){let n=s[t],r=o({args:s,index:t,flags:l.flags});if(r.handled){t=r.nextIndex;continue}e.push(n)}return l.positionals=e,l}return l.positionals=s,l}(a);f&&(t.push(f),n.push(e+1),l=!0)}return{actions:t,actionLines:n}}function L(e){let t=e.split(/\r?\n/),n={};for(let[e,i]of t.entries()){let t=i.trim();if(0===t.length||t.startsWith("#"))continue;if(j(t)){!function(e,t,n){let{key:i,value:o}=function(e,t){let n=e.slice(3).replace(/^[\s]+/,""),i=n.indexOf("=");if(i<=0)throw new r("INVALID_ARGS",`Invalid env directive on line ${t}: expected "env KEY=VALUE".`);let o=n.slice(0,i);if(!m.test(o))throw new r("INVALID_ARGS",`Invalid env key "${o}" on line ${t}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(o.startsWith("AD_"))throw new r("INVALID_ARGS",`Invalid env key "${o}" on line ${t}: the AD_* namespace is reserved for built-in variables. Rename ${o} to avoid the AD_ prefix.`);return{key:o,value:function(e,t){if(0===e.length)return"";if(e.startsWith('"'))try{let t=JSON.parse(e);if("string"!=typeof t)throw Error("not a string literal");return t}catch{throw new r("INVALID_ARGS",`Invalid quoted env value on line ${t}.`)}return e}(n.slice(i+1),t)}}(t,n),s=e.env??{};if(Object.prototype.hasOwnProperty.call(s,i))throw new r("INVALID_ARGS",`Duplicate env directive "${i}" on line ${n}.`);s[i]=o,e.env=s}(n,t,e+1);continue}if(!t.startsWith("context "))break;let o=t.match(/(?:^|\s)platform=([^\s]+)/);if(o){let e=o[1];e&&M.has(e)&&V(n,"platform",e)}let s=t.match(/(?:^|\s)target=([^\s]+)/);if(s){let e=s[1];e&&x.has(e)&&V(n,"target",e)}let l=t.match(/(?:^|\s)timeout=(\d+)/);if(l){let e=Number(l[1]);Number.isFinite(e)&&e>=1&&V(n,"timeoutMs",Math.floor(e))}let a=t.match(/(?:^|\s)retries=(\d+)/);if(a){let e=Number(a[1]);Number.isFinite(e)&&e>=0&&V(n,"retries",Math.floor(e))}}return n}function j(e){return"env"===e||e.startsWith("env ")||e.startsWith("env ")}function V(e,t,n){let i=e[t];if(void 0!==i)throw new r("INVALID_ARGS",i===n?`Duplicate replay test metadata "${t}" in context header.`:`Conflicting replay test metadata "${t}" in context header: ${String(i)} vs ${String(n)}.`);e[t]=n}function E(e){return!!e&&!Number.isNaN(Number(e))}function k(t,n,r){let i=[];if(r){let e=r.device.kind?` kind=${r.device.kind}`:"",t=r.device.target?` target=${r.device.target}`:"";i.push(`context platform=${r.device.platform}${t} device=${f(r.device.name)}${e} theme=unknown`)}for(let e of n)i.push(p(e,{runtimeIncludeAllPositionals:!0}));let o=`${i.join("\n")}
|
|
2
|
+
`,s=`${t}.tmp-${process.pid}-${Date.now()}`;e.writeFileSync(s,o),e.renameSync(s,t)}function C(e){let n=t(e);for(let e of n)if(e.errors.length>0){let t=e.errors[0]?.message??"Invalid Maestro YAML flow.";throw new r("INVALID_ARGS",`Invalid Maestro YAML flow: ${t}`)}return n.map(e=>e.toJSON()).filter(e=>null!==e)}function G(e){return`${e.map(e=>n(e).trimEnd()).join("\n---\n")}
|
|
3
|
+
`}function P(e,t=[],n){return{ts:Date.now(),command:e,positionals:t,flags:n??{}}}function W(e,t,n){let r=new Set(n),i=Object.keys(e).filter(e=>!r.has(e));if(i.length>0)throw T(`Maestro ${t} field "${i[0]}" is not supported yet.`)}function K(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function F(e){return e.map((e,t)=>{if("string"==typeof e||K(e))return e;throw new r("INVALID_ARGS",`Unsupported Maestro command at index ${t+1}: expected a scalar or one-key map.`)})}function z(e){if(e){let t;return"android"===(t=e.trim().toLowerCase())?"android":"ios"===t?"ios":void 0}}function U(e,t){if(null==e)return{};if(!K(e))throw new r("INVALID_ARGS",`${t} expects a map.`);let n={};for(let[t,r]of Object.entries(e))("string"==typeof r||"number"==typeof r||"boolean"==typeof r)&&(n[t]=String(r));return n}function q(e,t){return K(e)&&"number"==typeof e.timeout&&Number.isFinite(e.timeout)?Math.max(0,Math.floor(e.timeout)):t}function Y(e,t){if(e.appId)return e.appId;throw new r("INVALID_ARGS",`${t} requires appId in the Maestro flow config.`)}function Z(e,t){if("string"==typeof t)return t;throw new r("INVALID_ARGS",`${e} expects a string value.`)}function H(e,t){return e.replace(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(e,n)=>Object.prototype.hasOwnProperty.call(t.env,n)?String(t.env[n]):e)}function J(e){throw T(`Maestro command "${e}" is not supported yet.`)}function T(e){throw new r("INVALID_ARGS",`${e} See supported/unsupported Maestro compatibility at ${s}. If this syntax matters for your flows, comment there or open a focused issue at ${l}.`)}function B(e,t){return`${e},${t}`}function Q(e){let t=e.match(/^(\d+),(\d+)$/);if(!t)throw T('Only absolute Maestro point selectors like "100,200" are supported.');return{x:Number(t[1]),y:Number(t[2])}}function X(e){let t=e.match(/^\s*(\d+)\s*,\s*(\d+)\s*$/);if(t)return{kind:"absolute",x:Number(t[1]),y:Number(t[2])};let n=e.match(/^\s*(\d+(?:\.\d+)?)%\s*,\s*(\d+(?:\.\d+)?)%\s*$/);if(n)return{kind:"percent",x:Number(n[1]),y:Number(n[2])};throw T('Only Maestro swipe coordinates like "100,200" or "50%,75%" are supported.')}export{W as assertOnlyKeys,w as buildReplayVarScope,I as collectReplayShellEnv,B as formatMaestroPoint,K as isPlainRecord,b as mergeReplayVarScopeValues,F as normalizeCommandList,z as normalizePlatform,Q as parseAbsolutePoint,X as parseMaestroPoint,C as parseMaestroYamlDocuments,$ as parseReplayCliEnvEntries,O as parseReplayScriptDetailed,U as readEnvMap,_ as readReplayCliEnvEntries,L as readReplayScriptMetadata,S as readReplayShellEnvSource,q as readTimeoutMs,Y as requireAppId,Z as requireStringValue,H as resolveMaestroString,R as resolveReplayAction,G as stringifyMaestroYamlDocuments,P as support_action,J as unsupportedCommand,T as unsupportedMaestroSyntax,k as writeReplayScript};
|
package/dist/src/485.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let e=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key|user[_-]?code|device[_-]?code|refresh[_-]?credential)/i,r=/\b(?:bearer\s+[a-z0-9._-]+|adc_(?:agent|live|refresh|cli)_[a-z0-9._-]+)\b/gi,t=/\b([a-z0-9_-]*(?:api[_-]?key|token|secret|password|user[_-]?code|device[_-]?code|refresh[_-]?credential)[a-z0-9_-]*)(\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/gi,n=/https?:\/\/[^\s"'<>]+/gi;function i(i){return function i(o,a,s){if(null==o)return o;if("string"==typeof o){var c=o,d=s;let i=c.trim();if(!i)return c;if(d&&e.test(d))return"[REDACTED]";let a=i.replace(n,e=>(function(e){try{let r=new URL(e);return r.search&&(r.search="?REDACTED"),(r.username||r.password)&&(r.username="REDACTED",r.password="REDACTED"),r.toString()}catch{return null}})(e)??e);return(a=(a=a.replace(r,"[REDACTED]")).replace(t,(e,r,t,n,i,o)=>{var a;return function(e){if("token"!==e.key.toLowerCase()||!e.separator.includes(":"))return!1;try{let r=new URL(e.rawValue);if("/api-keys"!==r.pathname.replace(/\/+$/,""))return!1;return/(?:^|\b)(?:service\/)?api\s+$/i.test(e.input.slice(0,e.offset))}catch{return!1}}({key:r,separator:t,rawValue:n,offset:i,input:o})||(a=n,/^adc_(?:agent|live|refresh|cli)_\.\.\.$/i.test(a))?e:`${r}${t}[REDACTED]`}))!==i?a:i.length>400?`${i.slice(0,200)}...<truncated>`:i}if("object"!=typeof o)return o;if(a.has(o))return"[Circular]";if(a.add(o),Array.isArray(o))return o.map(e=>i(e,a));let l={};for(let[r,t]of Object.entries(o)){if(e.test(r)){l[r]="[REDACTED]";continue}l[r]=i(t,a,r)}return l}(i,new WeakSet)}function o(e,r="COMMAND_FAILED"){return"string"==typeof e&&e.length>0?e:r}class a extends Error{code;details;cause;constructor(e,r,t,n){super(r),this.code=e,this.details=t,this.cause=n}}function s(e){return e instanceof a?e:e instanceof Error?new a("UNKNOWN",e.message,void 0,e):new a("UNKNOWN","Unknown error",{err:e})}function c(e){return e instanceof a}function d(e,r={}){return l(e,r)}function l(e,r={}){let t=s(e),n=t.details?i(t.details):void 0,o=n&&"string"==typeof n.hint?n.hint:void 0,a=(n&&"string"==typeof n.diagnosticId?n.diagnosticId:void 0)??r.diagnosticId,c=(n&&"string"==typeof n.logPath?n.logPath:void 0)??r.logPath,d=o??f(t.code),u=function(e){if(!e)return;let r={...e};return delete r.hint,delete r.diagnosticId,delete r.logPath,Object.keys(r).length>0?r:void 0}(n),p=function(e,r,t){if("COMMAND_FAILED"!==e||t?.processExitError!==!0)return r;let n=function(e){let r=[/^an error was encountered processing the command/i,/^underlying error\b/i,/^simulator device failed to complete the requested operation/i];for(let t of e.split("\n")){let e=t.trim();if(e&&!r.some(r=>r.test(e)))return e.length>200?`${e.slice(0,200)}...`:e}return null}("string"==typeof t?.stderr?t.stderr:"");return n||r}(t.code,t.message,n);return{code:t.code,message:p,hint:d,diagnosticId:a,logPath:c,details:u}}function u(e){return"DEVICE_IN_USE"===e||void 0}function f(e){switch(e){case"INVALID_ARGS":return"Check command arguments and run --help for usage examples.";case"SESSION_NOT_FOUND":return"Run open first or pass an explicit device selector.";case"TOOL_MISSING":return"Install required platform tooling and ensure it is available in PATH.";case"DEVICE_NOT_FOUND":return"Verify the target device is booted/connected and selectors match.";case"APP_NOT_INSTALLED":return"Run apps to discover the exact installed package or bundle id, or install the app before open.";case"UNSUPPORTED_OPERATION":return"This command is not available for the selected platform/device.";case"NOT_IMPLEMENTED":return"This command is part of the planned API but is not implemented yet.";case"COMMAND_FAILED":default:return"Retry with --debug and inspect diagnostics log for details.";case"UNAUTHORIZED":return"Refresh daemon metadata and retry the command."}}export{a as AppError,s as asAppError,f as defaultHintForCode,c as isAgentDeviceError,d as normalizeAgentDeviceError,l as normalizeError,i as redactDiagnosticData,u as retriableForErrorCode,o as toAppErrorCode};
|