@swmansion/argent 0.35.1-next.84 → 0.35.1-next.86

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/dist/cli-cmds.mjs CHANGED
@@ -12768,6 +12768,10 @@ import * as path14 from "node:path";
12768
12768
  var LINKED_CALL_HEADER = "x-argent-linked";
12769
12769
  var E2E_DIR_CLIENT_HEADER = "x-argent-e2e-dir";
12770
12770
  var CLIENT_SECRETS_HEADER = "x-argent-client-secrets";
12771
+ var SESSION_HEADER = "x-argent-session";
12772
+ function isValidSession(session) {
12773
+ return /^[\x21-\x7e]{1,128}$/.test(session);
12774
+ }
12771
12775
  var CLIENT_SECRET_SOURCES_HEADER = "x-argent-client-secret-sources";
12772
12776
 
12773
12777
  // ../registry/src/artifacts.ts
@@ -13052,6 +13056,8 @@ var FAILURE_CODES = {
13052
13056
  HTTP_CAPABILITY_UNSUPPORTED_OPERATION: "HTTP_CAPABILITY_UNSUPPORTED_OPERATION",
13053
13057
  HTTP_DEVICE_RESOLUTION_FAILED: "HTTP_DEVICE_RESOLUTION_FAILED",
13054
13058
  HTTP_DEPENDENCY_PREFLIGHT_MISSING: "HTTP_DEPENDENCY_PREFLIGHT_MISSING",
13059
+ // Another session holds a claim on the device the call names.
13060
+ DEVICE_IN_USE: "DEVICE_IN_USE",
13055
13061
  // The client's POST /upload of a file input was refused, so the call was not sent.
13056
13062
  FILE_INPUT_UPLOAD_FAILED: "FILE_INPUT_UPLOAD_FAILED",
13057
13063
  CLI_RUN_TOOL_NOT_FOUND: "CLI_RUN_TOOL_NOT_FOUND",
@@ -33835,6 +33841,9 @@ function removePendingArchives() {
33835
33841
  function removeArchivesOnSignal(signal) {
33836
33842
  removePendingArchives();
33837
33843
  if (process.listenerCount(signal) > 0) return;
33844
+ raiseSignal(signal);
33845
+ }
33846
+ function raiseSignal(signal) {
33838
33847
  try {
33839
33848
  process.kill(process.pid, signal);
33840
33849
  } catch {
@@ -34860,9 +34869,23 @@ function failedRun(result) {
34860
34869
  }
34861
34870
  return result;
34862
34871
  }
34872
+ function sessionFromEnv() {
34873
+ const session = process.env.ARGENT_SESSION?.trim();
34874
+ if (!session) return void 0;
34875
+ if (!isValidSession(session)) {
34876
+ throw new ToolInvocationError(
34877
+ "ARGENT_SESSION must be 1 to 128 printable ASCII characters without spaces."
34878
+ );
34879
+ }
34880
+ return session;
34881
+ }
34882
+ function hasSessionHeader(headers) {
34883
+ return Object.keys(headers).some((name) => name.toLowerCase() === SESSION_HEADER);
34884
+ }
34863
34885
  function createToolsClient(options = {}) {
34864
34886
  let cached3 = null;
34865
34887
  let linkedNoticeShown = false;
34888
+ let cachedToolList;
34866
34889
  const doFetch = options.fetchImpl ?? ((url2, init3) => fetch(url2, init3));
34867
34890
  const diagnose = options.onDiagnostic ?? ((message) => void process.stderr.write(`${message}
34868
34891
  `));
@@ -34895,13 +34918,16 @@ function createToolsClient(options = {}) {
34895
34918
  async function fetchToolList(opts) {
34896
34919
  opts?.signal?.throwIfAborted();
34897
34920
  const { url: url2, token } = await baseUrl();
34921
+ if (cachedToolList?.url === url2) return cachedToolList.list;
34898
34922
  const res = await doFetch(
34899
34923
  `${url2}/tools`,
34900
34924
  { headers: { ...options.headers?.(), ...authHeaders2(token) }, signal: opts?.signal },
34901
34925
  { longRunning: false, carriesUpload: false }
34902
34926
  );
34903
34927
  if (!res.ok) throw new Error(`GET /tools failed: ${res.status} ${res.statusText}`);
34904
- return await res.json();
34928
+ const list = await res.json();
34929
+ if (options.cacheToolList) cachedToolList = { url: url2, list };
34930
+ return list;
34905
34931
  }
34906
34932
  async function fetchTools(opts) {
34907
34933
  return (await fetchToolList(opts)).tools;
@@ -34912,6 +34938,7 @@ function createToolsClient(options = {}) {
34912
34938
  async function callTool(name, args, opts) {
34913
34939
  opts?.signal?.throwIfAborted();
34914
34940
  assertFiniteNumbers(args);
34941
+ const envSession = options.ignoreEnvSession || hasSessionHeader(options.headers?.() ?? {}) ? void 0 : sessionFromEnv();
34915
34942
  const { url: url2, token, remote } = await route();
34916
34943
  let finalArgs = canonicalToolArgs(name, args);
34917
34944
  const { tools: tools2, uploadFormats } = await fetchToolList({ signal: opts?.signal });
@@ -34988,6 +35015,7 @@ function createToolsClient(options = {}) {
34988
35015
  }
34989
35016
  const toolUrl = `${url2}/tools/${encodeURIComponent(meta3?.name ?? name)}`;
34990
35017
  const headers = {
35018
+ ...envSession ? { [SESSION_HEADER]: envSession } : {},
34991
35019
  ...options.headers?.(),
34992
35020
  "Content-Type": "application/json",
34993
35021
  // Tells the tool-server the call came over a link, a link to
@@ -35390,6 +35418,191 @@ function getDeviceIdFromArgs(args) {
35390
35418
  return void 0;
35391
35419
  }
35392
35420
 
35421
+ // ../argent-tools-client/src/auto-capture.ts
35422
+ import { setTimeout as sleep } from "node:timers/promises";
35423
+ var AUTO_SCREENSHOT_TOOLS = /* @__PURE__ */ new Set([
35424
+ "gesture-tap",
35425
+ "gesture-swipe",
35426
+ "gesture-scroll",
35427
+ "gesture-drag",
35428
+ "gesture-hover",
35429
+ "gesture-custom",
35430
+ "gesture-pinch",
35431
+ "gesture-rotate",
35432
+ "button",
35433
+ "keyboard",
35434
+ "paste",
35435
+ "rotate",
35436
+ "fold",
35437
+ "tv-remote",
35438
+ "launch-app",
35439
+ "restart-app",
35440
+ "open-url",
35441
+ "describe",
35442
+ "run-sequence",
35443
+ // A wait is almost always followed by a look at the screen it waited for.
35444
+ "await-ui-element",
35445
+ "file-panel",
35446
+ "menu-bar"
35447
+ ]);
35448
+ var AUTO_SCREENSHOT_DELAY_MS_BY_TOOL = {
35449
+ "launch-app": 3e3,
35450
+ "restart-app": 3e3,
35451
+ "open-url": 2e3,
35452
+ "gesture-swipe": 1500,
35453
+ "gesture-scroll": 1500,
35454
+ "gesture-drag": 1500,
35455
+ "gesture-hover": 1500,
35456
+ "gesture-custom": 1500,
35457
+ "gesture-tap": 1500,
35458
+ "gesture-pinch": 1500,
35459
+ "gesture-rotate": 1500,
35460
+ // Only the settle after the last step; each step is an in-app action.
35461
+ "run-sequence": 3e3,
35462
+ "button": 1500,
35463
+ "tv-remote": 1500,
35464
+ "rotate": 1e3,
35465
+ // The fold tool already waits for the panel hand-over; the cap covers the
35466
+ // repaint after it.
35467
+ "fold": 1500,
35468
+ "keyboard": 300,
35469
+ "paste": 300,
35470
+ "describe": 100,
35471
+ // The wait returns on the first match, often mid-transition; the cap must
35472
+ // leave `await-screen-idle` room to see two identical reads.
35473
+ "await-ui-element": 1500
35474
+ };
35475
+ var DEFAULT_DELAY_MS = 1400;
35476
+ var LAUNCH_SETTLE_MS = 3e3;
35477
+ var CAPTURE_TIMEOUT_MS = 15e3;
35478
+ function autoScreenshotEnabled(options) {
35479
+ return !isFlagEnabled("disable-auto-screenshot", options);
35480
+ }
35481
+ var AUTO_DESCRIBE_TOOLS = /* @__PURE__ */ new Set([
35482
+ "gesture-tap",
35483
+ "gesture-swipe",
35484
+ "gesture-scroll",
35485
+ "gesture-drag",
35486
+ "gesture-hover",
35487
+ "gesture-custom",
35488
+ "gesture-pinch",
35489
+ "gesture-rotate",
35490
+ "button",
35491
+ "keyboard",
35492
+ "paste",
35493
+ "rotate",
35494
+ "fold",
35495
+ "tv-remote",
35496
+ "launch-app",
35497
+ "restart-app",
35498
+ "open-url",
35499
+ "run-sequence",
35500
+ "await-ui-element",
35501
+ "file-panel",
35502
+ "menu-bar"
35503
+ ]);
35504
+ function autoDescribeEnabled(options) {
35505
+ return !isFlagEnabled("disable-auto-describe", options);
35506
+ }
35507
+ var PROFILING_CAPTURE_SKIPPED_NOTE = "Auto-screenshot and element tree skipped while a profiler is recording on this device. Call screenshot or describe if you need to see the screen.";
35508
+ var SECRET_CAPTURE_SKIPPED_NOTE = "Auto-screenshot and element tree skipped: the input contains a {{secret:\u2026}} placeholder, and a capture of this screen could reveal the typed secret. The secret is already typed \u2014 do not send the typing step again, or the field will hold two copies of it. Submit or navigate away, then verify the resulting screen as usual. Only this call is covered: the next call is captured normally, and shows the secret if the field is still on screen. To cover the submit as well, put the typing and the submit in ONE `run-sequence` the next time you type a secret.";
35509
+ var AUTO_DESCRIBE_HEADER = "--- Elements after action (describe) ---";
35510
+ function shouldAutoDescribe(toolName, args) {
35511
+ const canonical = normalizeToolName(toolName);
35512
+ return AUTO_DESCRIBE_TOOLS.has(canonical) && !isListCall(canonical, args);
35513
+ }
35514
+ var SECRET_PLACEHOLDER_MARKER = "{{secret:";
35515
+ function containsSecretPlaceholder(args) {
35516
+ try {
35517
+ return JSON.stringify(args)?.includes(SECRET_PLACEHOLDER_MARKER) ?? false;
35518
+ } catch {
35519
+ return true;
35520
+ }
35521
+ }
35522
+ function getUdidFromArgs(args) {
35523
+ if (args && typeof args === "object" && "udid" in args && typeof args.udid === "string") {
35524
+ return args.udid;
35525
+ }
35526
+ return void 0;
35527
+ }
35528
+ function normalizeToolName(name) {
35529
+ const idx = name.lastIndexOf("__");
35530
+ return idx === -1 ? name : name.slice(idx + 2);
35531
+ }
35532
+ function shouldAutoScreenshot(toolName, args) {
35533
+ const canonical = normalizeToolName(toolName);
35534
+ return canonical !== "screenshot" && AUTO_SCREENSHOT_TOOLS.has(canonical) && !isListCall(canonical, args);
35535
+ }
35536
+ function isListCall(canonical, args) {
35537
+ return (canonical === "menu-bar" || canonical === "file-panel") && args?.action === "list";
35538
+ }
35539
+ function getAutoScreenshotDelayMs(toolName) {
35540
+ const canonical = normalizeToolName(toolName);
35541
+ const base = AUTO_SCREENSHOT_DELAY_MS_BY_TOOL[canonical] ?? DEFAULT_DELAY_MS;
35542
+ const envOverride = process.env.ARGENT_AUTO_SCREENSHOT_DELAY_MS;
35543
+ if (envOverride) {
35544
+ const envMs = parseInt(envOverride, 10);
35545
+ if (!Number.isNaN(envMs)) return Math.max(base, envMs);
35546
+ }
35547
+ return base;
35548
+ }
35549
+ function describedTree(result) {
35550
+ const { description, hint } = result ?? {};
35551
+ if (typeof description !== "string" || description.length === 0) return void 0;
35552
+ const hintLine = typeof hint === "string" && hint && !description.includes(hint) ? `Hint: ${hint}
35553
+ ` : "";
35554
+ return `${hintLine}${description}`;
35555
+ }
35556
+ async function withDeadline(signal, ms, work) {
35557
+ const deadline = new AbortController();
35558
+ const timer = setTimeout(
35559
+ () => deadline.abort(new DOMException("The operation was aborted due to timeout", "TimeoutError")),
35560
+ ms
35561
+ );
35562
+ try {
35563
+ return await work(AbortSignal.any([signal, deadline.signal]));
35564
+ } finally {
35565
+ clearTimeout(timer);
35566
+ }
35567
+ }
35568
+ async function awaitScreenSettled(call, udid, toolName, signal, captureTimeoutMs) {
35569
+ const maxWaitMs = getAutoScreenshotDelayMs(toolName);
35570
+ if (maxWaitMs === 0) return { settled: true };
35571
+ const started = Date.now();
35572
+ const awaitIdle = async (timeoutMs) => await withDeadline(
35573
+ signal,
35574
+ timeoutMs + captureTimeoutMs,
35575
+ (s) => call("await-screen-idle", { udid, timeoutMs }, s)
35576
+ );
35577
+ try {
35578
+ let idle = await awaitIdle(maxWaitMs);
35579
+ if (idle?.launching === true && normalizeToolName(toolName) !== "describe") {
35580
+ idle = await awaitIdle(LAUNCH_SETTLE_MS);
35581
+ }
35582
+ return {
35583
+ settled: idle?.settled === true,
35584
+ readiness: { maxWaitMs, ...idle }
35585
+ };
35586
+ } catch {
35587
+ await sleep(Math.max(0, maxWaitMs - (Date.now() - started)), void 0, { signal }).catch(
35588
+ () => {
35589
+ }
35590
+ );
35591
+ return { settled: false };
35592
+ }
35593
+ }
35594
+ async function captureSettledScreen(options) {
35595
+ const { call, udid, toolName, signal, captureTimeoutMs } = options;
35596
+ const settledResult = await awaitScreenSettled(call, udid, toolName, signal, captureTimeoutMs);
35597
+ await options.onSettled?.(settledResult);
35598
+ return withDeadline(signal, captureTimeoutMs, async (captureSignal) => {
35599
+ const screenshot = options.screenshot?.(captureSignal) ?? Promise.resolve([]);
35600
+ if (!settledResult.settled) await screenshot;
35601
+ const tree = options.tree?.(captureSignal) ?? Promise.resolve([]);
35602
+ return [...await screenshot, ...await tree];
35603
+ });
35604
+ }
35605
+
35393
35606
  // ../../node_modules/@opentelemetry/api-logs/build/esm/types/LogRecord.js
35394
35607
  var SeverityNumber;
35395
35608
  (function(SeverityNumber2) {
@@ -38933,7 +39146,7 @@ function isCi(env = process.env) {
38933
39146
  var SESSION_ID2 = randomUUID5();
38934
39147
  function readCliVersion() {
38935
39148
  if (true) {
38936
- return "0.35.1-next.84";
39149
+ return "0.35.1-next.86";
38937
39150
  }
38938
39151
  return "0.0.0";
38939
39152
  }
@@ -41617,6 +41830,84 @@ ${renderSummary(report, { withDevice: true })}`);
41617
41830
  return exitAfterFlush(report.ok ? 0 : 1);
41618
41831
  }
41619
41832
 
41833
+ // ../argent-cli/src/run-capture.ts
41834
+ import { mkdir as mkdir5, writeFile as writeFile4 } from "node:fs/promises";
41835
+ import { join as join22 } from "node:path";
41836
+ var NO_CAPTURE = { lines: [] };
41837
+ var NEVER_ABORTED = new AbortController().signal;
41838
+ var PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
41839
+ async function captureAfterAction(options) {
41840
+ const { client: client2, toolName, payload, profiling } = options;
41841
+ const udid = getUdidFromArgs(payload);
41842
+ const wantScreenshot = shouldAutoScreenshot(toolName, payload) && autoScreenshotEnabled(options.flagsPath);
41843
+ const wantTree = shouldAutoDescribe(toolName, payload) && autoDescribeEnabled(options.flagsPath);
41844
+ if (!udid || !(wantScreenshot || wantTree)) return NO_CAPTURE;
41845
+ if (containsSecretPlaceholder(payload)) return { lines: [], note: SECRET_CAPTURE_SKIPPED_NOTE };
41846
+ const call = async (name, args, s) => (await client2.callTool(name, args, { signal: s })).data;
41847
+ if (profiling) {
41848
+ if (toolName === "describe") return NO_CAPTURE;
41849
+ await awaitScreenSettled(call, udid, toolName, NEVER_ABORTED, CAPTURE_TIMEOUT_MS);
41850
+ return { lines: [], note: PROFILING_CAPTURE_SKIPPED_NOTE };
41851
+ }
41852
+ const captureScreenshot = async (s) => {
41853
+ const image = await takeScreenshot(client2, call, udid, s);
41854
+ return image ? [{ text: `Screen after action: ${image.localPath}`, image }] : [];
41855
+ };
41856
+ const captureTree = async (s) => {
41857
+ const tree = await readTree(call, udid, s);
41858
+ return tree === void 0 ? [] : [{ text: AUTO_DESCRIBE_HEADER }, { text: tree }];
41859
+ };
41860
+ const parts = await captureSettledScreen({
41861
+ call,
41862
+ udid,
41863
+ toolName,
41864
+ signal: NEVER_ABORTED,
41865
+ captureTimeoutMs: CAPTURE_TIMEOUT_MS,
41866
+ screenshot: wantScreenshot ? captureScreenshot : void 0,
41867
+ tree: wantTree ? captureTree : void 0
41868
+ });
41869
+ return {
41870
+ lines: parts.map((part) => part.text),
41871
+ screenshot: parts.find((part) => part.image)?.image
41872
+ };
41873
+ }
41874
+ async function takeScreenshot(client2, call, udid, signal) {
41875
+ try {
41876
+ const data = await call("screenshot", { udid }, signal);
41877
+ const { url: url2, token } = await client2.baseUrl();
41878
+ const { images } = await materializeArtifacts(data, {
41879
+ toolsUrl: url2,
41880
+ authToken: token,
41881
+ deviceId: udid,
41882
+ signal
41883
+ });
41884
+ return images[0] ?? await fetchLegacyScreenshot(data, udid, signal);
41885
+ } catch {
41886
+ return void 0;
41887
+ }
41888
+ }
41889
+ async function fetchLegacyScreenshot(data, udid, signal) {
41890
+ if (!data || typeof data !== "object") return void 0;
41891
+ const { url: url2 } = data;
41892
+ if (typeof url2 !== "string") return void 0;
41893
+ const res = await fetch(url2, { signal });
41894
+ if (!res.ok) return void 0;
41895
+ const png = Buffer.from(await res.arrayBuffer());
41896
+ if (!png.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) return void 0;
41897
+ const dir = artifactDir(udid);
41898
+ await mkdir5(dir, { recursive: true });
41899
+ const localPath = join22(dir, `screenshot-${Date.now()}.png`);
41900
+ await writeFile4(localPath, png);
41901
+ return { localPath, data: png, mimeType: "image/png" };
41902
+ }
41903
+ async function readTree(call, udid, signal) {
41904
+ try {
41905
+ return describedTree(await call("describe", { udid }, signal));
41906
+ } catch {
41907
+ return void 0;
41908
+ }
41909
+ }
41910
+
41620
41911
  // ../argent-cli/src/run-device-env.ts
41621
41912
  var DEVICE_ENV_VAR = "ARGENT_UDID";
41622
41913
  var DEVICE_FIELDS = ["udid", "device_id"];
@@ -41706,8 +41997,10 @@ ${description}
41706
41997
  console.log(" --args - Read the entire payload as JSON from stdin");
41707
41998
  }
41708
41999
  console.log(" --<field>-json <json> Pass a single field as JSON (objects/nested arrays)");
41709
- console.log(" --json Print the raw JSON result");
41710
- console.log(" --out <path> For image results, save to <path> instead of fetching URL");
42000
+ console.log(" --json Print only the raw JSON result");
42001
+ console.log(
42002
+ " --out <path> Save the image result, or the screen after an action, to <path>"
42003
+ );
41711
42004
  console.log(" --help, -h Show this help");
41712
42005
  const deviceField = requiredDeviceField(schema);
41713
42006
  if (deviceField) console.log(`
@@ -41720,9 +42013,24 @@ async function fetchImageToFile(result, outPath) {
41720
42013
  }
41721
42014
  const res = await fetch(url2);
41722
42015
  if (!res.ok) throw new Error(`Failed to download image: ${res.status} ${res.statusText}`);
41723
- const buf = Buffer.from(await res.arrayBuffer());
42016
+ writeImageFile(outPath, Buffer.from(await res.arrayBuffer()));
42017
+ }
42018
+ function drainStdout() {
42019
+ return new Promise((resolve26) => process.stdout.write("", () => resolve26()));
42020
+ }
42021
+ function onReaderClosed(exit) {
42022
+ for (const stream of [process.stdout, process.stderr]) {
42023
+ const otherHandlers = stream.listeners("error");
42024
+ stream.removeAllListeners("error");
42025
+ stream.on("error", (err) => {
42026
+ if (err.code === "EPIPE") void exit();
42027
+ else for (const handler of otherHandlers) handler.call(stream, err);
42028
+ });
42029
+ }
42030
+ }
42031
+ function writeImageFile(outPath, data) {
41724
42032
  fs16.mkdirSync(path22.dirname(path22.resolve(outPath)), { recursive: true });
41725
- fs16.writeFileSync(outPath, buf);
42033
+ fs16.writeFileSync(outPath, data);
41726
42034
  }
41727
42035
  function renderResult(result, outputHint, images, json2) {
41728
42036
  if (json2) return JSON.stringify(result, null, 2);
@@ -41739,6 +42047,12 @@ var SAFE_TOOL_RE = /^[a-z][a-z0-9_-]{0,63}$/;
41739
42047
  function safeToolName(toolName) {
41740
42048
  return toolName && SAFE_TOOL_RE.test(toolName) ? toolName : "unknown";
41741
42049
  }
42050
+ function callFailureSignal(err) {
42051
+ if (err instanceof ToolInvocationError && err.errorCode === FAILURE_CODES.DEVICE_IN_USE) {
42052
+ return { error_code: FAILURE_CODES.DEVICE_IN_USE, error_kind: "validation" };
42053
+ }
42054
+ return { error_code: FAILURE_CODES.CLI_RUN_TOOL_CALL_FAILED, error_kind: "unknown" };
42055
+ }
41742
42056
  async function trackRunFailure(toolName, startedAt, signal) {
41743
42057
  const tool = toolName ? canonicalToolId(toolName) : toolName;
41744
42058
  track("cli:run_fail", {
@@ -41752,7 +42066,8 @@ async function trackRunFailure(toolName, startedAt, signal) {
41752
42066
  async function run(argv, options) {
41753
42067
  init("cli");
41754
42068
  const startedAt = performance.now();
41755
- const { fetchTool, callTool, baseUrl } = createToolsClient({ paths: options.paths });
42069
+ const client2 = createToolsClient({ paths: options.paths, cacheToolList: true });
42070
+ const { fetchTool, callTool, baseUrl } = client2;
41756
42071
  const [toolName, ...rest] = argv;
41757
42072
  if (!toolName || toolName === "--help" || toolName === "-h") {
41758
42073
  console.log(`Usage: argent run <tool> [flags]
@@ -41767,12 +42082,21 @@ Examples:
41767
42082
  argent run run-sequence --udid <UDID> --steps-json '[{"tool":"button","args":{"button":"home"}}]'
41768
42083
  argent run gesture-tap --args '{"udid":"<UDID>","x":0.5,"y":0.5}'
41769
42084
 
42085
+ After an interaction tool (gestures, key presses, app launches), argent run
42086
+ waits for the screen to settle, then prints a screenshot path and the element
42087
+ tree on stderr, so stdout holds only the result; after describe it adds only
42088
+ the screenshot. --out also saves that screenshot.
42089
+ \`argent enable disable-auto-screenshot\` and
42090
+ \`argent enable disable-auto-describe\` turn these off. --json prints only the
42091
+ result, without waiting.
42092
+
41770
42093
  Set ARGENT_UDID to use that device when a tool needs --udid or --device_id
41771
42094
  and the call does not pass one.
41772
42095
 
41773
- Exits 1 when the tool fails. Also exits 1 when the result reports that the
41774
- call did not do its job: an e2e test that does not pass, an await-ui-element
41775
- or await-network-request wait with success=false, a run-sequence that a step
42096
+ Exits 1 when the tool fails, or when --out without --json gets no screen
42097
+ after an action. Also exits 1 when the result reports that the call did not
42098
+ do its job: an e2e test that does not pass, an await-ui-element or
42099
+ await-network-request wait with success=false, a run-sequence that a step
41776
42100
  stopped, a debugger tool with no connection or an error, a native-devtools
41777
42101
  precheck that stopped the tool, a native-profiler-analyze with status
41778
42102
  analysis_failed, an e2e recording call that recorded nothing, or a baseline
@@ -41920,6 +42244,7 @@ settled=false or debugger-status's not_connected.
41920
42244
  let result;
41921
42245
  let note2;
41922
42246
  let failure2;
42247
+ let profiling = false;
41923
42248
  let images = [];
41924
42249
  try {
41925
42250
  const resp = await callTool(toolName, payload);
@@ -41933,6 +42258,7 @@ settled=false or debugger-status's not_connected.
41933
42258
  images = materialized.images;
41934
42259
  note2 = resp.note;
41935
42260
  failure2 = resp.failure;
42261
+ profiling = resp.profiling === true;
41936
42262
  } catch (err) {
41937
42263
  const report = describeServerValidationFailure(err, payload, schema);
41938
42264
  if (report) {
@@ -41940,46 +42266,96 @@ settled=false or debugger-status's not_connected.
41940
42266
  }
41941
42267
  console.error(err instanceof Error ? err.message : String(err));
41942
42268
  await trackRunFailure(toolName, startedAt, {
41943
- error_code: FAILURE_CODES.CLI_RUN_TOOL_CALL_FAILED,
42269
+ ...callFailureSignal(err),
41944
42270
  failure_stage: "cli_run_call_tool",
41945
- failure_area: "cli",
41946
- error_kind: "unknown"
42271
+ failure_area: "cli"
41947
42272
  });
41948
42273
  process.exit(1);
41949
42274
  }
41950
- if (outPath && meta3.outputHint === "image") {
42275
+ const screenOut = json2 || meta3.outputHint === "image" ? void 0 : outPath;
42276
+ const wantsScreenOut = !!screenOut && shouldAutoScreenshot(toolName, payload);
42277
+ let screenOutWritten = false;
42278
+ let failureTracked;
42279
+ const trackFailureOnce = (signal) => failureTracked ??= trackRunFailure(toolName, startedAt, signal);
42280
+ const resultFailed = () => trackFailureOnce({
42281
+ error_code: FAILURE_CODES.CLI_RUN_TOOL_RESULT_FAILED,
42282
+ failure_stage: "cli_run_tool_result",
42283
+ failure_area: "cli",
42284
+ error_kind: "unknown"
42285
+ });
42286
+ const screenOutFailed = () => trackFailureOnce({
42287
+ error_code: FAILURE_CODES.CLI_RUN_SAVE_IMAGE_FAILED,
42288
+ failure_stage: "cli_run_save_image",
42289
+ failure_area: "cli",
42290
+ error_kind: "unknown"
42291
+ });
42292
+ let readerClosed = false;
42293
+ onReaderClosed(async () => {
42294
+ if (readerClosed) return;
42295
+ readerClosed = true;
42296
+ const outMissing = wantsScreenOut && !screenOutWritten;
42297
+ if (failure2) console.error(failure2);
42298
+ if (outMissing) console.error(`The output closed before ${screenOut} was written.`);
42299
+ process.exitCode = failure2 || outMissing ? 1 : 0;
42300
+ if (failure2) await resultFailed();
42301
+ else if (outMissing) await screenOutFailed();
42302
+ process.exit();
42303
+ });
42304
+ const saveImage = async (write) => {
41951
42305
  try {
41952
- if (images.length > 0) {
41953
- fs16.mkdirSync(path22.dirname(path22.resolve(outPath)), { recursive: true });
41954
- fs16.writeFileSync(outPath, images[0].data);
41955
- } else if (result && typeof result === "object") {
41956
- await fetchImageToFile(result, outPath);
41957
- }
42306
+ await write();
41958
42307
  } catch (err) {
41959
42308
  console.error(`Failed to save image: ${err instanceof Error ? err.message : err}`);
41960
- await trackRunFailure(toolName, startedAt, {
41961
- error_code: FAILURE_CODES.CLI_RUN_SAVE_IMAGE_FAILED,
41962
- failure_stage: "cli_run_save_image",
41963
- failure_area: "cli",
41964
- error_kind: "unknown"
41965
- });
42309
+ await screenOutFailed();
41966
42310
  process.exit(1);
41967
42311
  }
42312
+ };
42313
+ if (outPath && meta3.outputHint === "image") {
42314
+ await saveImage(async () => {
42315
+ if (images.length > 0) {
42316
+ writeImageFile(outPath, images[0].data);
42317
+ } else if (result && typeof result === "object") {
42318
+ await fetchImageToFile(result, outPath);
42319
+ }
42320
+ });
41968
42321
  }
41969
42322
  if (note2) console.error(note2);
41970
42323
  console.log(renderResult(result, meta3.outputHint, images, json2));
41971
42324
  if (outPath && meta3.outputHint === "image" && !json2) {
41972
42325
  console.log(`Wrote: ${outPath}`);
41973
42326
  }
42327
+ if (!json2) {
42328
+ const capture = await captureAfterAction({ client: client2, toolName, payload, profiling });
42329
+ if (readerClosed) return;
42330
+ const { screenshot } = capture;
42331
+ if (screenOut && screenshot) {
42332
+ await saveImage(async () => writeImageFile(screenOut, screenshot.data));
42333
+ screenOutWritten = true;
42334
+ }
42335
+ if (capture.note || capture.lines.length > 0 || wantsScreenOut) {
42336
+ await drainStdout();
42337
+ if (readerClosed) return;
42338
+ }
42339
+ if (capture.note) console.error(capture.note);
42340
+ for (const line of capture.lines) console.error(line);
42341
+ if (screenOutWritten) {
42342
+ console.error(`Wrote: ${screenOut}`);
42343
+ } else if (wantsScreenOut) {
42344
+ const reason = !autoScreenshotEnabled() ? "The disable-auto-screenshot flag is on" : profiling ? "A profiler is recording on this device" : "No screen was captured";
42345
+ console.error(`${reason}, so ${screenOut} was not written.`);
42346
+ }
42347
+ }
41974
42348
  if (failure2) {
41975
- await new Promise((resolve26) => process.stdout.write("", () => resolve26()));
42349
+ await drainStdout();
42350
+ if (readerClosed) return;
41976
42351
  console.error(failure2);
41977
- await trackRunFailure(toolName, startedAt, {
41978
- error_code: FAILURE_CODES.CLI_RUN_TOOL_RESULT_FAILED,
41979
- failure_stage: "cli_run_tool_result",
41980
- failure_area: "cli",
41981
- error_kind: "unknown"
41982
- });
42352
+ await resultFailed();
42353
+ await exitAfterFlush(1, [process.stderr]);
42354
+ }
42355
+ if (wantsScreenOut && !screenOutWritten) {
42356
+ await drainStdout();
42357
+ if (readerClosed) return;
42358
+ await screenOutFailed();
41983
42359
  await exitAfterFlush(1, [process.stderr]);
41984
42360
  }
41985
42361
  }
@@ -42861,15 +43237,15 @@ function isSessionAlive(session) {
42861
43237
  // ../argent-cli/src/lens-pty.ts
42862
43238
  import { chmodSync, readdirSync as readdirSync3 } from "node:fs";
42863
43239
  import { createRequire } from "node:module";
42864
- import { dirname as dirname14, join as join22 } from "node:path";
43240
+ import { dirname as dirname14, join as join23 } from "node:path";
42865
43241
  var nodeRequire = createRequire(import.meta.url);
42866
43242
  function ensureSpawnHelperExecutable(req = nodeRequire) {
42867
43243
  if (process.platform !== "darwin") return;
42868
43244
  try {
42869
- const prebuilds = join22(dirname14(req.resolve("node-pty/package.json")), "prebuilds");
43245
+ const prebuilds = join23(dirname14(req.resolve("node-pty/package.json")), "prebuilds");
42870
43246
  for (const entry of readdirSync3(prebuilds)) {
42871
43247
  try {
42872
- chmodSync(join22(prebuilds, entry, "spawn-helper"), 493);
43248
+ chmodSync(join23(prebuilds, entry, "spawn-helper"), 493);
42873
43249
  } catch {
42874
43250
  }
42875
43251
  }
@@ -42900,7 +43276,7 @@ function ptyInjectBeats(text2) {
42900
43276
  { delayBeforeMs: BEAT_AFTER_TEXT_MS, data: ENTER }
42901
43277
  ];
42902
43278
  }
42903
- function sleep(ms) {
43279
+ function sleep2(ms) {
42904
43280
  return new Promise((resolve26) => setTimeout(resolve26, ms));
42905
43281
  }
42906
43282
  var DEFAULT_COLS = 80;
@@ -42957,7 +43333,7 @@ function startPtyProxy(opts) {
42957
43333
  const waitForTypingPause = async () => {
42958
43334
  const started = Date.now();
42959
43335
  while (!disposed && lastUserInputAt > 0 && Date.now() - lastUserInputAt < QUIET_BEFORE_INJECT_MS && Date.now() - started < MAX_QUIET_WAIT_MS) {
42960
- await sleep(QUIET_POLL_MS);
43336
+ await sleep2(QUIET_POLL_MS);
42961
43337
  }
42962
43338
  };
42963
43339
  let queue = Promise.resolve();
@@ -42969,7 +43345,7 @@ function startPtyProxy(opts) {
42969
43345
  queue = queue.then(async () => {
42970
43346
  await waitForTypingPause();
42971
43347
  for (const beat of beats) {
42972
- if (beat.delayBeforeMs) await sleep(beat.delayBeforeMs);
43348
+ if (beat.delayBeforeMs) await sleep2(beat.delayBeforeMs);
42973
43349
  if (disposed) return;
42974
43350
  term.write(beat.data);
42975
43351
  }
@@ -43122,14 +43498,14 @@ var SPAWN_GRACE_MS = 8e3;
43122
43498
  var DEATH_CONFIRMATIONS = 3;
43123
43499
  var SSE_RECONNECT_MS = 1e3;
43124
43500
  var authHeaders3 = {};
43125
- function sleep2(ms) {
43501
+ function sleep3(ms) {
43126
43502
  return new Promise((resolve26) => setTimeout(resolve26, ms));
43127
43503
  }
43128
43504
  var TRUST_PROMPT_RE = /trust this folder|do you trust|yes,? i trust|trust the files in this/i;
43129
43505
  async function dismissTrustPrompt(session) {
43130
43506
  const deadline = Date.now() + 12e3;
43131
43507
  while (Date.now() < deadline) {
43132
- await sleep2(700);
43508
+ await sleep3(700);
43133
43509
  const text2 = readSessionText(session);
43134
43510
  if (text2 == null) {
43135
43511
  pressEnter(session);
@@ -43159,7 +43535,7 @@ function dismissTrustPromptViaPty(proxy) {
43159
43535
  });
43160
43536
  }
43161
43537
  async function injectSeedViaPty(proxy) {
43162
- await sleep2(5e3);
43538
+ await sleep3(5e3);
43163
43539
  proxy.inject(buildSeedPrompt());
43164
43540
  }
43165
43541
  function isInteractiveTty() {
@@ -43203,7 +43579,7 @@ function planAgent(agentId) {
43203
43579
  return { choose: installed };
43204
43580
  }
43205
43581
  async function injectSeedAfterBoot(session) {
43206
- await sleep2(5e3);
43582
+ await sleep3(5e3);
43207
43583
  writeToSession(session, buildSeedPrompt());
43208
43584
  }
43209
43585
  function buildSeedPrompt() {
@@ -43501,7 +43877,7 @@ async function awaitAgentChoiceViaStream(baseUrl) {
43501
43877
  }
43502
43878
  reconnects++;
43503
43879
  if (ac.signal.aborted || reconnects > AGENT_CHOICE_MAX_RECONNECTS) break;
43504
- await sleep2(SSE_RECONNECT_MS);
43880
+ await sleep3(SSE_RECONNECT_MS);
43505
43881
  }
43506
43882
  } finally {
43507
43883
  ac.abort();
@@ -43571,7 +43947,7 @@ async function runRelaySession(baseUrl, inject, registerDeath, quiet) {
43571
43947
  }
43572
43948
  } catch {
43573
43949
  }
43574
- if (alive && !ac.signal.aborted) await sleep2(SSE_RECONNECT_MS);
43950
+ if (alive && !ac.signal.aborted) await sleep3(SSE_RECONNECT_MS);
43575
43951
  }
43576
43952
  }
43577
43953
  async function httpErrorMessage(res) {
@@ -44973,7 +45349,7 @@ import { styleText as styleText2, stripVTControlCharacters } from "node:util";
44973
45349
  import process$1 from "node:process";
44974
45350
  var import_sisteransi2 = __toESM(require_src(), 1);
44975
45351
  import { existsSync as existsSync8, lstatSync as lstatSync4, readdirSync as readdirSync4 } from "node:fs";
44976
- import { dirname as dirname18, join as join26 } from "node:path";
45352
+ import { dirname as dirname18, join as join27 } from "node:path";
44977
45353
  function isUnicodeSupported() {
44978
45354
  if (process$1.platform !== "win32") {
44979
45355
  return process$1.env.TERM !== "linux";