@swmansion/argent 0.33.1-next.9 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/assets/Argent.tracetemplate +0 -0
  2. package/bin/argent-android-devtools-0.4.0.apk +0 -0
  3. package/bin/darwin/argent-macos-helper +0 -0
  4. package/bin/darwin/ax-service +0 -0
  5. package/bin/darwin/tvos-ax-service +0 -0
  6. package/bin/darwin/tvos-hid-daemon +0 -0
  7. package/bin/network-inspector/network-inspector.jar +0 -0
  8. package/bin/tcp/ax-service +0 -0
  9. package/dist/cli-cmds.mjs +338 -95
  10. package/dist/client.js +256 -56
  11. package/dist/flow-script-runner.mjs +148 -5
  12. package/dist/installer.mjs +40 -24
  13. package/dist/ios-device-runner/ArgentRunner/ArgentRunnerUITests/ArgentRunnerSession+Snapshot.swift +110 -4
  14. package/dist/mcp-server.mjs +330 -68
  15. package/dist/tool-args.generated.d.ts +22 -20
  16. package/dist/tool-server.cjs +3763 -2146
  17. package/dylibs/libArgentInjectionBootstrap.dylib +0 -0
  18. package/dylibs/libKeyboardPatch.dylib +0 -0
  19. package/dylibs/libNativeDevtoolsIos.dylib +0 -0
  20. package/dylibs/macos/libArgentInjectionBootstrap.dylib +0 -0
  21. package/dylibs/macos/libNativeDevtoolsMacos.dylib +0 -0
  22. package/dylibs/tcp/libArgentInjectionBootstrap.dylib +0 -0
  23. package/dylibs/tcp/libKeyboardPatch.dylib +0 -0
  24. package/dylibs/tcp/libNativeDevtoolsIos.dylib +0 -0
  25. package/dylibs/tvos/libArgentInjectionBootstrap.dylib +0 -0
  26. package/dylibs/tvos/libKeyboardPatch.dylib +0 -0
  27. package/dylibs/tvos/libNativeDevtoolsIos.dylib +0 -0
  28. package/package.json +2 -3
  29. package/rules/argent.md +1 -1
  30. package/skills/argent-create-e2e/references/e2e-yaml.md +11 -1
  31. package/skills/argent-create-e2e/references/reliability-and-recovery.md +1 -1
  32. package/skills/argent-device-interact/SKILL.md +2 -2
  33. package/skills/argent-device-interact/references/harmonyos.md +1 -1
  34. package/skills/argent-macos-app-interact/SKILL.md +5 -1
  35. package/skills/argent-native-profiler/SKILL.md +14 -5
  36. package/skills/argent-react-native-profiler/SKILL.md +7 -0
  37. package/skills/argent-test-ui-flow/SKILL.md +1 -1
  38. package/assets/trace-processor/SHA256SUMS +0 -4
  39. package/assets/trace-processor/engine.mjs +0 -42423
package/dist/client.js CHANGED
@@ -8432,7 +8432,7 @@ function spawnToolsServer(paths, port, options = {}) {
8432
8432
  "error",
8433
8433
  (err) => reject(
8434
8434
  new Error(
8435
- err.code === "ENOENT" && nodeBin === "node" ? "Could not start the argent tool-server: `node` was not found on PATH. Install Node.js 20+ or add it to PATH." : `Could not start the argent tool-server: ${err.message}`
8435
+ err.code === "ENOENT" && nodeBin === "node" ? "Could not start the argent tool-server: `node` was not found on PATH. Install Node.js 22.18+ or add it to PATH." : `Could not start the argent tool-server: ${err.message}`
8436
8436
  )
8437
8437
  )
8438
8438
  );
@@ -8780,7 +8780,10 @@ import { basename, extname } from "node:path";
8780
8780
  var FLOW_NAME_CHARSET = "[A-Za-z0-9_-]+";
8781
8781
  var FLOW_NAME_PATTERN = new RegExp(`^${FLOW_NAME_CHARSET}$`);
8782
8782
  var FLOW_FILE_NAME_PATTERN = new RegExp(`^${FLOW_NAME_CHARSET}\\.yaml$`);
8783
- var SCRIPT_FILE_NAME_PATTERN = new RegExp(`^${FLOW_NAME_CHARSET}\\.mjs$`);
8783
+ var SCRIPT_FILE_EXTENSIONS = [".mjs", ".mts", ".js", ".ts"];
8784
+ var SCRIPT_FILE_NAME_PATTERN = new RegExp(
8785
+ `^${FLOW_NAME_CHARSET}(?:${SCRIPT_FILE_EXTENSIONS.map((ext) => `\\${ext}`).join("|")})$`
8786
+ );
8784
8787
  function interpolateFileInputPath(template, args) {
8785
8788
  let missing = false;
8786
8789
  const out = template.replace(/\$\{([A-Za-z0-9_]+)\}/g, (_m, name) => {
@@ -9271,6 +9274,9 @@ var FAILURE_CODES = {
9271
9274
  NATIVE_PROFILER_SESSION_TORN_DOWN: "NATIVE_PROFILER_SESSION_TORN_DOWN",
9272
9275
  NATIVE_PROFILER_APP_PROCESS_NOT_FOUND: "NATIVE_PROFILER_APP_PROCESS_NOT_FOUND",
9273
9276
  NATIVE_PROFILER_NO_EXPORTED_TRACE: "NATIVE_PROFILER_NO_EXPORTED_TRACE",
9277
+ NATIVE_PROFILER_APP_NOT_DEBUGGABLE: "NATIVE_PROFILER_APP_NOT_DEBUGGABLE",
9278
+ NATIVE_PROFILER_APP_HAS_WEBKIT_HEAP: "NATIVE_PROFILER_APP_HAS_WEBKIT_HEAP",
9279
+ NATIVE_PROFILER_APP_HEAP_CHECK_FAILED: "NATIVE_PROFILER_APP_HEAP_CHECK_FAILED",
9274
9280
  // Android perfetto start failures, mirroring the iOS xctrace set above.
9275
9281
  NATIVE_PROFILER_PERFETTO_PROCESS_ERROR: "NATIVE_PROFILER_PERFETTO_PROCESS_ERROR",
9276
9282
  NATIVE_PROFILER_PERFETTO_READY_TIMEOUT: "NATIVE_PROFILER_PERFETTO_READY_TIMEOUT",
@@ -9300,6 +9306,8 @@ var FAILURE_CODES = {
9300
9306
  FLOW_DEVICE_RESOLUTION: "FLOW_DEVICE_RESOLUTION",
9301
9307
  // The target does not satisfy the test's `requires:` block; a directory run skips it.
9302
9308
  FLOW_REQUIREMENTS_UNMET: "FLOW_REQUIREMENTS_UNMET",
9309
+ // The tool-server's Node.js cannot run a TypeScript `script:` step the test holds.
9310
+ FLOW_SCRIPT_TYPESCRIPT_UNSUPPORTED: "FLOW_SCRIPT_TYPESCRIPT_UNSUPPORTED",
9303
9311
  PROFILER_QUERY_MODE_INVALID: "PROFILER_QUERY_MODE_INVALID",
9304
9312
  PROFILER_QUERY_REQUIRED_PARAM_MISSING: "PROFILER_QUERY_REQUIRED_PARAM_MISSING",
9305
9313
  PROFILER_DATA_NOT_LOADED: "PROFILER_DATA_NOT_LOADED",
@@ -9516,7 +9524,7 @@ async function getResolvedToolsUrl() {
9516
9524
 
9517
9525
  // ../argent-tools-client/src/file-inputs.ts
9518
9526
  import { createHash as createHash2, randomUUID as randomUUID4 } from "node:crypto";
9519
- import { createReadStream, rmSync as rmSync2 } from "node:fs";
9527
+ import { createReadStream as createReadStream2, rmSync as rmSync2 } from "node:fs";
9520
9528
  import {
9521
9529
  chmod as chmod3,
9522
9530
  lstat,
@@ -9532,50 +9540,234 @@ import { constants, tmpdir } from "node:os";
9532
9540
  import * as path10 from "node:path";
9533
9541
 
9534
9542
  // ../archive/src/index.ts
9535
- import { execFile } from "node:child_process";
9536
- import { rm, readdir as readdir3 } from "node:fs/promises";
9537
- import { basename as basename4, dirname as dirname5, join as join9, posix as posix2, resolve as resolve6, sep as sep2 } from "node:path";
9538
- import { promisify } from "node:util";
9539
- var execFileAsync = promisify(execFile);
9543
+ import { spawn as spawn2 } from "node:child_process";
9544
+ import { once } from "node:events";
9545
+ import { createReadStream, createWriteStream } from "node:fs";
9546
+ import { open, rm, readdir as readdir3 } from "node:fs/promises";
9547
+ import { basename as basename4, dirname as dirname5, join as join9, resolve as resolve6, sep as sep2 } from "node:path";
9548
+ import { Writable } from "node:stream";
9549
+ import { pipeline } from "node:stream/promises";
9550
+ import zlib from "node:zlib";
9540
9551
  var ArchiveError = class extends Error {
9541
9552
  };
9542
- function createTarGzArgs(sourcePath, target) {
9543
- return ["-czf", target, "-C", dirname5(sourcePath), basename4(sourcePath)];
9553
+ var ARCHIVE_FORMATS = typeof zlib.createZstdCompress === "function" ? ["zstd", "gzip"] : ["gzip"];
9554
+ var ARCHIVE_CONTENT_TYPES = {
9555
+ zstd: "application/zstd",
9556
+ gzip: "application/gzip"
9557
+ };
9558
+ function pickArchiveFormat(peerFormats) {
9559
+ return ARCHIVE_FORMATS.find((f) => peerFormats?.includes(f)) ?? "gzip";
9560
+ }
9561
+ var CHUNK_BYTES = 1 << 20;
9562
+ function createCompressor(format) {
9563
+ return format === "zstd" ? zlib.createZstdCompress({
9564
+ chunkSize: CHUNK_BYTES,
9565
+ // Lets the decoder detect corruption.
9566
+ params: { [zlib.constants.ZSTD_c_checksumFlag]: 1 }
9567
+ }) : zlib.createGzip({ chunkSize: CHUNK_BYTES });
9568
+ }
9569
+ function createTarArgs(sourcePath) {
9570
+ const name = basename4(sourcePath);
9571
+ return ["-cf", "-", "-C", dirname5(sourcePath), /^[-@]/.test(name) ? `./${name}` : name];
9572
+ }
9573
+ var MAX_LISTING_BYTES = 32 << 20;
9574
+ var MAX_LISTING_LINES = 1 << 18;
9575
+ var MAX_STDERR_BYTES = 16 << 10;
9576
+ var MAX_UNREAD_BYTES = 16 << 20;
9577
+ function collect(stream, maxBytes, { maxLines = Infinity, onOverflow } = {}) {
9578
+ const chunks = [];
9579
+ let bytes = 0;
9580
+ let lines = 0;
9581
+ let overflowed = false;
9582
+ stream?.on("data", (chunk) => {
9583
+ if (overflowed) return;
9584
+ chunks.push(chunk.subarray(0, maxBytes - bytes));
9585
+ bytes += chunk.length;
9586
+ for (let i = chunk.indexOf(10); i !== -1 && lines <= maxLines; i = chunk.indexOf(10, i + 1)) {
9587
+ lines++;
9588
+ }
9589
+ if (bytes > maxBytes || lines > maxLines) {
9590
+ overflowed = true;
9591
+ onOverflow?.();
9592
+ }
9593
+ });
9594
+ return {
9595
+ overflowed: () => overflowed,
9596
+ text: () => Buffer.concat(chunks).toString("utf8") + (overflowed ? "\u2026" : "")
9597
+ };
9544
9598
  }
9545
- async function createTarGzFile(sourcePath, tarPath) {
9599
+ async function createArchiveFile(sourcePath, archivePath, format, signal) {
9600
+ const out = createWriteStream(archivePath);
9601
+ await once(out, "ready");
9546
9602
  try {
9547
- await execFileAsync("tar", createTarGzArgs(sourcePath, tarPath));
9603
+ await archiveInto(out, sourcePath, format, signal);
9548
9604
  } catch (err) {
9549
- await rm(tarPath, { force: true }).catch(() => {
9605
+ out.destroy();
9606
+ await rm(archivePath, { force: true }).catch(() => {
9550
9607
  });
9608
+ signal?.throwIfAborted();
9551
9609
  throw err;
9552
9610
  }
9553
9611
  }
9612
+ async function archiveInto(out, sourcePath, format, signal) {
9613
+ const child = spawn2("tar", createTarArgs(sourcePath), {
9614
+ stdio: ["ignore", "pipe", "pipe"],
9615
+ signal
9616
+ });
9617
+ const exited = new Promise((res, rej) => {
9618
+ child.on("error", rej);
9619
+ child.on("close", res);
9620
+ });
9621
+ const stderr = collect(child.stderr, MAX_STDERR_BYTES);
9622
+ const [written, closed] = await Promise.allSettled([
9623
+ pipeline(child.stdout, createCompressor(format), out),
9624
+ exited
9625
+ ]);
9626
+ if (closed.status === "rejected") throw closed.reason;
9627
+ if (written.status === "rejected") throw written.reason;
9628
+ if (closed.value !== 0) {
9629
+ throw new Error(`tar exited with code ${closed.value}: ${stderr.text().trim()}`);
9630
+ }
9631
+ }
9632
+ async function sniffFormat(archivePath) {
9633
+ const fh = await open(archivePath, "r");
9634
+ try {
9635
+ const { buffer, bytesRead } = await fh.read(Buffer.alloc(4), 0, 4, 0);
9636
+ const magic = buffer.subarray(0, bytesRead).toString("hex");
9637
+ if (magic.startsWith("1f8b")) return "gzip";
9638
+ if (magic === "28b52ffd" && ARCHIVE_FORMATS.includes("zstd")) return "zstd";
9639
+ throw new ArchiveError("unrecognized compression");
9640
+ } finally {
9641
+ await fh.close();
9642
+ }
9643
+ }
9644
+ var ZSTD_FRAME_MAGIC = 4247762216;
9645
+ async function assertSingleCompleteZstdFrame(archivePath) {
9646
+ const fh = await open(archivePath, "r");
9647
+ try {
9648
+ const { size } = await fh.stat();
9649
+ const window = Buffer.alloc(4096);
9650
+ let windowStart = 0;
9651
+ let windowEnd = 0;
9652
+ let pos = 0;
9653
+ const read = async (n) => {
9654
+ if (pos < windowStart || pos + n > windowEnd) {
9655
+ const { bytesRead } = await fh.read(window, 0, window.length, pos);
9656
+ windowStart = pos;
9657
+ windowEnd = pos + bytesRead;
9658
+ if (bytesRead < n) throw new ArchiveError("truncated zstd frame");
9659
+ }
9660
+ return window.subarray(pos - windowStart, pos - windowStart + n);
9661
+ };
9662
+ for (let frame = 0; pos < size; frame++) {
9663
+ const header = await read(5);
9664
+ if (header.readUInt32LE(0) !== ZSTD_FRAME_MAGIC) throw new ArchiveError("bad zstd frame");
9665
+ const descriptor = header[4];
9666
+ const singleSegment = descriptor >> 5 & 1;
9667
+ pos += 5 + (singleSegment ? 0 : 1) + // window descriptor
9668
+ [0, 1, 2, 4][descriptor & 3] + // dictionary id
9669
+ [singleSegment, 2, 4, 8][descriptor >> 6];
9670
+ let hasData = false;
9671
+ for (let last = 0; !last; ) {
9672
+ const block = (await read(3)).readUIntLE(0, 3);
9673
+ last = block & 1;
9674
+ const type = block >> 1 & 3;
9675
+ const blockSize = block >> 3;
9676
+ if (blockSize > 0) hasData = true;
9677
+ pos += 3 + (type === 1 ? 1 : blockSize);
9678
+ }
9679
+ if (descriptor >> 2 & 1) pos += 4;
9680
+ if (hasData && frame > 0) throw new ArchiveError("multi-frame zstd");
9681
+ }
9682
+ if (pos !== size) throw new ArchiveError("truncated zstd frame");
9683
+ } finally {
9684
+ await fh.close();
9685
+ }
9686
+ }
9687
+ var TAR_LOCALE = process.platform === "darwin" ? "en_US.UTF-8" : "C.UTF-8";
9688
+ function tarEnv(env) {
9689
+ const characterType = env.LC_ALL || env.LC_CTYPE || env.LANG || "";
9690
+ return /utf-?8/i.test(characterType) ? env : { ...env, LC_ALL: TAR_LOCALE };
9691
+ }
9692
+ async function runTar(archive, args) {
9693
+ const child = spawn2("tar", [...args, "-f", "-"], {
9694
+ env: tarEnv(process.env)
9695
+ });
9696
+ const exited = new Promise((res, rej) => {
9697
+ child.on("error", rej);
9698
+ child.on("close", res);
9699
+ });
9700
+ const stdout = collect(child.stdout, MAX_LISTING_BYTES, {
9701
+ maxLines: MAX_LISTING_LINES,
9702
+ onOverflow: () => child.kill()
9703
+ });
9704
+ const stderr = collect(child.stderr, MAX_STDERR_BYTES);
9705
+ child.stdin?.on("error", () => {
9706
+ });
9707
+ const unreadLimit = new Error("unread limit");
9708
+ let unread = 0;
9709
+ const fed = pipeline(
9710
+ createReadStream(archive.path, { highWaterMark: CHUNK_BYTES }),
9711
+ archive.format === "zstd" ? zlib.createZstdDecompress({ chunkSize: CHUNK_BYTES }) : zlib.createGunzip({ chunkSize: CHUNK_BYTES }),
9712
+ new Writable({
9713
+ write(chunk, _encoding, done) {
9714
+ if (child.stdin?.writable) return void child.stdin.write(chunk, () => done());
9715
+ unread += chunk.length;
9716
+ done(unread > MAX_UNREAD_BYTES ? unreadLimit : null);
9717
+ },
9718
+ final(done) {
9719
+ child.stdin?.end();
9720
+ done();
9721
+ },
9722
+ destroy(err, done) {
9723
+ if (err) child.stdin?.destroy();
9724
+ done(err);
9725
+ }
9726
+ })
9727
+ ).then(
9728
+ () => null,
9729
+ (err) => err
9730
+ );
9731
+ const [code, feedError] = await Promise.all([exited, fed]);
9732
+ if (stdout.overflowed()) {
9733
+ throw new Error(
9734
+ `tar ${args.join(" ")} listed more than ${MAX_LISTING_LINES} members or ${MAX_LISTING_BYTES >> 20} MiB`
9735
+ );
9736
+ }
9737
+ if (feedError && feedError !== unreadLimit) throw feedError;
9738
+ if (code !== 0)
9739
+ throw new Error(`tar ${args.join(" ")} exited with code ${code}: ${stderr.text().trim()}`);
9740
+ return stdout.text();
9741
+ }
9554
9742
  function normalizeTarMemberPath(memberPath) {
9555
9743
  return memberPath.replace(/^\.\//, "").replace(/\\/g, "/");
9556
9744
  }
9745
+ function isContainedPath(path14, windows = process.platform === "win32") {
9746
+ const slashed = path14.replace(/\\/g, "/");
9747
+ const drive = windows ? /^[A-Za-z]:/ : /^[A-Za-z]:\//;
9748
+ return !slashed.startsWith("/") && !drive.test(slashed) && !slashed.split("/").includes("..");
9749
+ }
9557
9750
  function isSafeTarMember(memberPath, destDir) {
9558
9751
  const normalized = normalizeTarMemberPath(memberPath);
9559
- if (!normalized || normalized === "." || normalized === "./") return false;
9560
- if (normalized.startsWith("/") || /^[A-Za-z]:[\\/]/.test(normalized)) return false;
9561
- const relative2 = posix2.normalize(normalized);
9562
- if (relative2 === ".." || relative2.startsWith("../") || relative2.split("/").includes("..")) {
9563
- return false;
9564
- }
9752
+ if (!isContainedPath(normalized)) return false;
9565
9753
  const root = resolve6(destDir);
9566
- const resolved = resolve6(destDir, relative2);
9567
- return resolved === root || resolved.startsWith(root + sep2);
9754
+ return resolve6(destDir, normalized).startsWith(root + sep2);
9568
9755
  }
9569
- async function listTarMembers(tarPath) {
9570
- const { stdout } = await execFileAsync("tar", ["-tzf", tarPath]);
9571
- return stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
9756
+ async function readListing(archive, args) {
9757
+ try {
9758
+ return await runTar(archive, args);
9759
+ } catch (err) {
9760
+ throw new ArchiveError(
9761
+ `Could not read archive: ${err instanceof Error ? err.message : String(err)}`
9762
+ );
9763
+ }
9572
9764
  }
9573
- function isEscapingLinkTarget(target) {
9574
- if (target.startsWith("/") || /^[A-Za-z]:[\\/]/.test(target)) return true;
9575
- return posix2.normalize(target.replace(/\\/g, "/")).split("/").includes("..");
9765
+ async function listTarMembers(archive) {
9766
+ const stdout = await readListing(archive, ["-t"]);
9767
+ return stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
9576
9768
  }
9577
- async function assertSafeMemberTypes(tarPath) {
9578
- const { stdout } = await execFileAsync("tar", ["-tzvf", tarPath]);
9769
+ async function assertSafeMemberTypes(archive) {
9770
+ const stdout = await readListing(archive, ["-tv"]);
9579
9771
  for (const line of stdout.split("\n")) {
9580
9772
  if (!line.trim()) continue;
9581
9773
  const type = line[0];
@@ -9583,7 +9775,7 @@ async function assertSafeMemberTypes(tarPath) {
9583
9775
  if (type === "l") {
9584
9776
  const parts = line.split(" -> ");
9585
9777
  const target = parts.length === 2 ? parts[1].trim() : "";
9586
- if (parts.length !== 2 || !target || isEscapingLinkTarget(target)) {
9778
+ if (parts.length !== 2 || !target || !isContainedPath(target)) {
9587
9779
  throw new ArchiveError(
9588
9780
  `Archive contains a symlink whose target could not be confirmed safe: "${line.trim()}".`
9589
9781
  );
@@ -9595,15 +9787,8 @@ async function assertSafeMemberTypes(tarPath) {
9595
9787
  );
9596
9788
  }
9597
9789
  }
9598
- async function assertSafeArchive(tarPath, destDir) {
9599
- let members;
9600
- try {
9601
- members = await listTarMembers(tarPath);
9602
- } catch (err) {
9603
- throw new ArchiveError(
9604
- `Could not read archive: ${err instanceof Error ? err.message : String(err)}`
9605
- );
9606
- }
9790
+ async function assertSafeArchive(archive, destDir) {
9791
+ const members = await listTarMembers(archive);
9607
9792
  if (members.length === 0) {
9608
9793
  throw new ArchiveError("Archive is empty.");
9609
9794
  }
@@ -9612,7 +9797,7 @@ async function assertSafeArchive(tarPath, destDir) {
9612
9797
  throw new ArchiveError(`Archive contains an unsafe path "${member}" \u2014 refusing extraction.`);
9613
9798
  }
9614
9799
  }
9615
- await assertSafeMemberTypes(tarPath);
9800
+ await assertSafeMemberTypes(archive);
9616
9801
  }
9617
9802
  async function resolveMember(destDir, expectedName) {
9618
9803
  const entries = await readdir3(destDir);
@@ -9627,9 +9812,18 @@ async function resolveMember(destDir, expectedName) {
9627
9812
  }
9628
9813
  return join9(destDir, real[0]);
9629
9814
  }
9630
- async function safeExtractTarGz(tarPath, destDir, expectedName) {
9631
- await assertSafeArchive(tarPath, destDir);
9632
- await execFileAsync("tar", ["-xzf", tarPath, "-C", destDir]);
9815
+ async function safeExtractArchive(archivePath, destDir, expectedName) {
9816
+ let archive;
9817
+ try {
9818
+ archive = { path: archivePath, format: await sniffFormat(archivePath) };
9819
+ if (archive.format === "zstd") await assertSingleCompleteZstdFrame(archivePath);
9820
+ } catch (err) {
9821
+ throw new ArchiveError(
9822
+ `Could not read archive: ${err instanceof Error ? err.message : String(err)}`
9823
+ );
9824
+ }
9825
+ await assertSafeArchive(archive, destDir);
9826
+ await runTar(archive, ["-x", "-C", destDir]);
9633
9827
  return resolveMember(destDir, expectedName);
9634
9828
  }
9635
9829
 
@@ -9710,7 +9904,7 @@ function untrackArchive(archive) {
9710
9904
  function sha256File(filePath) {
9711
9905
  return new Promise((resolve9, reject) => {
9712
9906
  const hash = createHash2("sha256");
9713
- createReadStream(filePath).on("data", (chunk) => hash.update(chunk)).on("end", () => resolve9(hash.digest("hex"))).on("error", reject);
9907
+ createReadStream2(filePath).on("data", (chunk) => hash.update(chunk)).on("end", () => resolve9(hash.digest("hex"))).on("error", reject);
9714
9908
  });
9715
9909
  }
9716
9910
  function toolServerError(text) {
@@ -9736,15 +9930,15 @@ function uploadFailure(url, res, text, bytes) {
9736
9930
  errorKind: "validation"
9737
9931
  });
9738
9932
  }
9739
- async function uploadTar(tarPath, endpoint, signal) {
9933
+ async function uploadTar(tarPath, format, endpoint, signal) {
9740
9934
  const { size } = await stat3(tarPath);
9741
9935
  const init = {
9742
9936
  method: "POST",
9743
9937
  headers: {
9744
- "content-type": "application/gzip",
9938
+ "content-type": ARCHIVE_CONTENT_TYPES[format],
9745
9939
  ...endpoint.token ? { Authorization: `Bearer ${endpoint.token}` } : {}
9746
9940
  },
9747
- body: createReadStream(tarPath),
9941
+ body: createReadStream2(tarPath),
9748
9942
  duplex: "half",
9749
9943
  signal
9750
9944
  };
@@ -9761,12 +9955,13 @@ async function uploadTar(tarPath, endpoint, signal) {
9761
9955
  return json.uploadId;
9762
9956
  }
9763
9957
  async function uploadFile(sourcePath, endpoint, signal) {
9958
+ const format = pickArchiveFormat(endpoint.formats);
9764
9959
  const tarPath = path10.join(tmpdir(), `argent-upload-${randomUUID4()}.tar.gz`);
9765
9960
  trackArchive(tarPath);
9766
9961
  try {
9767
- await createTarGzFile(await realpath2(sourcePath), tarPath);
9962
+ await createArchiveFile(await realpath2(sourcePath), tarPath, format, signal);
9768
9963
  const contentHash = await sha256File(tarPath);
9769
- return { uploadId: await uploadTar(tarPath, endpoint, signal), contentHash };
9964
+ return { uploadId: await uploadTar(tarPath, format, endpoint, signal), contentHash };
9770
9965
  } finally {
9771
9966
  untrackArchive(tarPath);
9772
9967
  await rm2(tarPath, { force: true }).catch(() => {
@@ -10621,7 +10816,7 @@ function createToolsClient(options = {}) {
10621
10816
  const { url, token } = await route();
10622
10817
  return { url, token };
10623
10818
  }
10624
- async function fetchTools(opts) {
10819
+ async function fetchToolList(opts) {
10625
10820
  opts?.signal?.throwIfAborted();
10626
10821
  const { url, token } = await baseUrl();
10627
10822
  const res = await doFetch(
@@ -10630,8 +10825,10 @@ function createToolsClient(options = {}) {
10630
10825
  { longRunning: false, carriesUpload: false }
10631
10826
  );
10632
10827
  if (!res.ok) throw new Error(`GET /tools failed: ${res.status} ${res.statusText}`);
10633
- const json = await res.json();
10634
- return json.tools;
10828
+ return await res.json();
10829
+ }
10830
+ async function fetchTools(opts) {
10831
+ return (await fetchToolList(opts)).tools;
10635
10832
  }
10636
10833
  async function fetchTool(name, opts) {
10637
10834
  return findTool(await fetchTools(opts), name);
@@ -10640,7 +10837,7 @@ function createToolsClient(options = {}) {
10640
10837
  opts?.signal?.throwIfAborted();
10641
10838
  const { url, token, remote } = await route();
10642
10839
  let finalArgs = canonicalToolArgs(name, args);
10643
- const tools = await fetchTools({ signal: opts?.signal });
10840
+ const { tools, uploadFormats } = await fetchToolList({ signal: opts?.signal });
10644
10841
  const meta = findTool(tools, name);
10645
10842
  const olderServer = meta !== null && !tools.some((t) => t.name === canonicalToolId(meta.name));
10646
10843
  if (meta) {
@@ -10657,7 +10854,7 @@ function createToolsClient(options = {}) {
10657
10854
  if (remote) assertRequiredPresent(meta, finalArgs);
10658
10855
  finalArgs = await prepareFileInputs(meta.fileInputs, finalArgs ?? {}, {
10659
10856
  includeContent: remote,
10660
- uploadEndpoint: remote ? { url, token } : void 0,
10857
+ uploadEndpoint: remote ? { url, token, formats: uploadFormats } : void 0,
10661
10858
  log: diagnose,
10662
10859
  baselineDirs,
10663
10860
  collectMembers: collectFlowMembers,
@@ -10954,7 +11151,7 @@ async function downloadAndExtractArchive(handle, data, dir) {
10954
11151
  const tarball = join13(dir, `${sanitizeSegment(handle.filename)}.tar.gz`);
10955
11152
  try {
10956
11153
  await writeFile4(tarball, data);
10957
- return await safeExtractTarGz(tarball, dir, handle.filename);
11154
+ return await safeExtractArchive(tarball, dir, handle.filename);
10958
11155
  } catch {
10959
11156
  return null;
10960
11157
  } finally {
@@ -11033,7 +11230,10 @@ async function materializeArtifacts(result, ctx) {
11033
11230
  }
11034
11231
  try {
11035
11232
  const res = await fetchFn(`${ctx.toolsUrl}/artifacts/${value.id}`, {
11036
- headers: authHeaders3,
11233
+ headers: value.archive ? {
11234
+ ...authHeaders3,
11235
+ Accept: ARCHIVE_FORMATS.map((f) => ARCHIVE_CONTENT_TYPES[f]).join(", ")
11236
+ } : authHeaders3,
11037
11237
  signal: ctx.signal
11038
11238
  });
11039
11239
  if (!res.ok) return null;
@@ -2,6 +2,9 @@
2
2
  // next to the compiled executor and resolves its watchdogs against its own URL.
3
3
 
4
4
  import fs from "node:fs";
5
+ import { Module } from "node:module";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
5
8
  import { isMainThread, Worker } from "node:worker_threads";
6
9
 
7
10
  const LIFELINE_WATCHDOG = "flow-script-watchdog-lifeline.mjs";
@@ -20,6 +23,7 @@ let finished = false;
20
23
  let maxOutputBytes = 0;
21
24
 
22
25
  let probing = false;
26
+ let entryThrew = false;
23
27
 
24
28
  let idleResources = [];
25
29
 
@@ -65,10 +69,12 @@ const decodeJson = JSON.parse;
65
69
 
66
70
  const runnerListeners = [];
67
71
 
68
- if (isMainThread && process.env[ACTIVATION_ENV] === "1") {
69
- delete process.env[ACTIVATION_ENV];
70
- await prepare();
71
- }
72
+ /**
73
+ * The CommonJS loader's entry point, which is how plain `node` starts a main
74
+ * module. Node's types do not carry it, and a Node without it leaves the entry
75
+ * to Node. See `loadEntryAsPlainNodeDoes`.
76
+ */
77
+ const commonJsLoad = /** @type {{ _load?: unknown }} */ (/** @type {unknown} */ (Module))._load;
72
78
 
73
79
  async function prepare() {
74
80
  const raw = await nextRequest();
@@ -129,6 +135,8 @@ async function prepare() {
129
135
  });
130
136
 
131
137
  closeChannelToScript();
138
+ const commonJsLoaderEntry = entryForCommonJsLoader(request.scriptUrl);
139
+ if (commonJsLoaderEntry === undefined) claimMainModuleIdentity(request.scriptUrl);
132
140
 
133
141
  // Registered here rather than at module scope: Node references the IPC
134
142
  // channel while a `message` or `disconnect` listener exists, and in the
@@ -151,6 +159,8 @@ async function prepare() {
151
159
  // Read last, so it is the loop as the script inherits it. Node awaits this
152
160
  // module before it loads the entry, so there is no later point that holds.
153
161
  idleResources = process.getActiveResourcesInfo();
162
+
163
+ if (commonJsLoaderEntry !== undefined) return loadEntryAsPlainNodeDoes(commonJsLoaderEntry);
154
164
  }
155
165
 
156
166
  /**
@@ -209,7 +219,133 @@ function reportWhenEntrySettled(scriptUrl) {
209
219
  : { type: "result", outputJson: encoded.json }
210
220
  );
211
221
  };
212
- import(scriptUrl).then(report, report);
222
+ // An entry that threw in `loadEntryAsPlainNodeDoes` left no module behind, so
223
+ // an import here would run the script a second time.
224
+ (entryThrew ? Promise.resolve() : import(scriptUrl)).then(report, report);
225
+ }
226
+
227
+ /**
228
+ * The path of a `.ts` entry that Node may run as CommonJS, which this preload
229
+ * then loads itself (see {@link loadEntryAsPlainNodeDoes}); undefined for every
230
+ * other entry.
231
+ *
232
+ * `.mts` cannot be CommonJS, and neither can a `.ts` file under
233
+ * `"type": "module"`. A `.js` entry stays with Node: its `require` is whole
234
+ * either way, and `claimMainModuleIdentity` covers what differs.
235
+ */
236
+ function entryForCommonJsLoader(scriptUrl) {
237
+ if (typeof commonJsLoad !== "function") return undefined;
238
+ let entryPath;
239
+ try {
240
+ entryPath = fileURLToPath(scriptUrl);
241
+ } catch {
242
+ return undefined;
243
+ }
244
+ if (!entryPath.endsWith(".ts")) return undefined;
245
+ return nearestPackageType(entryPath) === "module" ? undefined : entryPath;
246
+ }
247
+
248
+ /**
249
+ * The `type` of the `package.json` nearest to `file`, as Node looks it up: the
250
+ * first one found going up, and never past a `node_modules` directory. A file
251
+ * that will not read or parse counts as no answer: Node then decides, and
252
+ * reports that file itself.
253
+ */
254
+ function nearestPackageType(file) {
255
+ let dir = path.dirname(file);
256
+ for (;;) {
257
+ if (path.basename(dir) === "node_modules") return undefined;
258
+ try {
259
+ return decodeJson(fs.readFileSync(path.join(dir, "package.json"), "utf8"))?.type;
260
+ } catch (err) {
261
+ if (err?.code !== "ENOENT") return undefined;
262
+ }
263
+ const parent = path.dirname(dir);
264
+ if (parent === dir) return undefined;
265
+ dir = parent;
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Loads the entry through the CommonJS loader, which is where plain `node`
271
+ * starts a `.ts` file outside `"type": "module"`. Node decides the module type
272
+ * there as it does with no preload: a file with ES module syntax goes on to
273
+ * the ESM loader, and anything else runs as CommonJS, as the main module.
274
+ *
275
+ * Left to Node, the `--import` that carries this preload sends the entry
276
+ * through the ESM loader instead, and on Node 22, 24.0 to 24.17 and 25 that
277
+ * loader gives a CommonJS TypeScript file a reduced `require`: no
278
+ * `require.cache`, no `require.extensions`, and an undefined `module.parent`
279
+ * in every module the script loads. Node still imports the entry after this
280
+ * preload, and finds the module this call left in its cache, so the script
281
+ * runs once.
282
+ *
283
+ * A script that throws leaves no module in that cache, and Node would run it
284
+ * again. So the preload never settles, which keeps Node from the entry, and
285
+ * the error goes where plain `node` sends it: to `uncaughtException`.
286
+ */
287
+ function loadEntryAsPlainNodeDoes(entryPath) {
288
+ try {
289
+ /** @type {Function} */ (commonJsLoad).call(Module, entryPath, null, true);
290
+ } catch (err) {
291
+ entryThrew = true;
292
+ queueMicrotask(() => {
293
+ throw err;
294
+ });
295
+ return never();
296
+ }
297
+ return undefined;
298
+ }
299
+
300
+ /**
301
+ * Under plain `node` a CommonJS entry is the main module three ways:
302
+ * `require.main === module`, `module.id === "."` and `module.parent === null`.
303
+ * This preload rides in on `--import`, which sends the entry through the ESM
304
+ * loader, and there Node sets only the first: `id` is the file's path and
305
+ * `parent` is `undefined`. A script that guards its body with either of the
306
+ * other two would skip it, and the step would pass having done nothing.
307
+ *
308
+ * Node builds the entry's module object and runs the script with no hook in
309
+ * between, so the values go in from inside the constructor: its first statement
310
+ * is `this.id = id`, which a setter on the prototype receives. `parent` is an
311
+ * accessor on that same prototype, so an own property answers for it.
312
+ *
313
+ * The setter is spent on the first module built, whichever it is. For a
314
+ * CommonJS entry that is the entry. An ES module entry never builds one for
315
+ * itself, so the first is some dependency's and comes out as Node made it —
316
+ * unless the script calls `createRequire` on its own path first, whose hidden
317
+ * parent module then carries the entry's identity, which is what it stands for.
318
+ *
319
+ * `.mjs` and `.mts` are skipped: neither can be CommonJS. A `.ts` entry that
320
+ * may be CommonJS does not come here at all: `loadEntryAsPlainNodeDoes` makes
321
+ * it the main module the way Node does.
322
+ */
323
+ function claimMainModuleIdentity(scriptUrl) {
324
+ let entryPath;
325
+ try {
326
+ entryPath = fileURLToPath(scriptUrl);
327
+ } catch {
328
+ return;
329
+ }
330
+ if (/\.m[jt]s$/.test(entryPath)) return;
331
+ const own = (target, key, value, enumerable) =>
332
+ Object.defineProperty(target, key, { value, writable: true, enumerable, configurable: true });
333
+ Object.defineProperty(Module.prototype, "id", {
334
+ configurable: true,
335
+ enumerable: false,
336
+ get() {
337
+ return undefined;
338
+ },
339
+ set(value) {
340
+ delete Module.prototype.id;
341
+ if (value !== entryPath) {
342
+ this.id = value;
343
+ return;
344
+ }
345
+ own(this, "id", ".", true);
346
+ own(this, "parent", null, false);
347
+ },
348
+ });
213
349
  }
214
350
 
215
351
  function keepListener(event, handler) {
@@ -794,3 +930,10 @@ function sendToParent(message, callback) {
794
930
  runnerIsSending = false;
795
931
  }
796
932
  }
933
+
934
+ // Last in the file: `prepare` may never settle, and a handler that runs while
935
+ // this module is parked there reads the constants declared above.
936
+ if (isMainThread && process.env[ACTIVATION_ENV] === "1") {
937
+ delete process.env[ACTIVATION_ENV];
938
+ await prepare();
939
+ }