@swmansion/argent 0.34.1-next.47 → 0.34.1-next.49

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.
@@ -1746,7 +1746,7 @@ var init_failure_codes = __esm({
1746
1746
  ANDROID_NETWORK_INSPECTOR_RUN_AS_FAILED: "ANDROID_NETWORK_INSPECTOR_RUN_AS_FAILED",
1747
1747
  ANDROID_NETWORK_INSPECTOR_DEVICE_IN_USE: "ANDROID_NETWORK_INSPECTOR_DEVICE_IN_USE",
1748
1748
  ANDROID_NETWORK_INSPECTOR_NO_DEVICE_PORT: "ANDROID_NETWORK_INSPECTOR_NO_DEVICE_PORT",
1749
- NATIVE_NETWORK_LOGS_STOP_UNSUPPORTED: "NATIVE_NETWORK_LOGS_STOP_UNSUPPORTED",
1749
+ NETWORK_CAPTURE_UNAVAILABLE: "NETWORK_CAPTURE_UNAVAILABLE",
1750
1750
  NDJSON_CDP_REQUEST_TIMEOUT: "NDJSON_CDP_REQUEST_TIMEOUT",
1751
1751
  NDJSON_CDP_REQUEST_FAILED: "NDJSON_CDP_REQUEST_FAILED",
1752
1752
  NDJSON_CDP_CONNECTION_CLOSED: "NDJSON_CDP_CONNECTION_CLOSED",
@@ -4281,9 +4281,9 @@ function parseURLObject(trimmed, def) {
4281
4281
  function stripTabAndNewline(value) {
4282
4282
  return value.replace(asciiTabOrNewline, "");
4283
4283
  }
4284
- function urlHostnameOk(url2, hostname4) {
4285
- hostname4.lastIndex = 0;
4286
- return hostname4.test(url2.hostname);
4284
+ function urlHostnameOk(url2, hostname5) {
4285
+ hostname5.lastIndex = 0;
4286
+ return hostname5.test(url2.hostname);
4287
4287
  }
4288
4288
  function urlProtocolOk(url2, protocol) {
4289
4289
  protocol.lastIndex = 0;
@@ -65626,10 +65626,10 @@ var require_request = __commonJS({
65626
65626
  return addrs;
65627
65627
  });
65628
65628
  defineGetter(req, "subdomains", function subdomains() {
65629
- var hostname4 = this.hostname;
65630
- if (!hostname4) return [];
65629
+ var hostname5 = this.hostname;
65630
+ if (!hostname5) return [];
65631
65631
  var offset = this.app.get("subdomain offset");
65632
- var subdomains2 = !isIP(hostname4) ? hostname4.split(".").reverse() : [hostname4];
65632
+ var subdomains2 = !isIP(hostname5) ? hostname5.split(".").reverse() : [hostname5];
65633
65633
  return subdomains2.slice(offset);
65634
65634
  });
65635
65635
  defineGetter(req, "path", function path72() {
@@ -65645,7 +65645,7 @@ var require_request = __commonJS({
65645
65645
  }
65646
65646
  return val || void 0;
65647
65647
  });
65648
- defineGetter(req, "hostname", function hostname4() {
65648
+ defineGetter(req, "hostname", function hostname5() {
65649
65649
  var host = this.host;
65650
65650
  if (!host) return;
65651
65651
  var offset = host[0] === "[" ? host.indexOf("]") + 1 : 0;
@@ -79663,7 +79663,7 @@ function assertSupported(toolId, capability42, device) {
79663
79663
  if (macosRefusal) throw new UnsupportedOperationError(toolId, device, macosRefusal);
79664
79664
  const matrix = platformMatrix(device.platform, capability42);
79665
79665
  if (!matrix) {
79666
- const reason2 = (device.platform === "macos" ? MACOS_REFUSAL_REASONS[toolId] : void 0) ?? `no ${device.platform} support declared`;
79666
+ const reason2 = (device.platform === "macos" ? MACOS_REFUSAL_REASONS[toolId] : void 0) ?? (toolId === "network-capture-start" || toolId === "network-capture-stop" ? NO_CAPTURE_START_STOP_REASONS[device.platform] : void 0) ?? `no ${device.platform} support declared`;
79667
79667
  throw new UnsupportedOperationError(toolId, device, reason2);
79668
79668
  }
79669
79669
  const supported2 = matrix[device.kind] === true;
@@ -79676,7 +79676,7 @@ function assertSupported(toolId, capability42, device) {
79676
79676
  throw new UnsupportedOperationError(toolId, device, "supports() refiner rejected device");
79677
79677
  }
79678
79678
  }
79679
- var UnsupportedOperationError, NotImplementedOnPlatformError, InvalidToolInputError, MACOS_APPS_FLAG, MACOS_APPS_FLAG_OFF_REASON, MACOS_POINTER_ONLY, MACOS_NO_TRACKPAD_GESTURES, MACOS_REFUSAL_REASONS, CATALYST_NO_APPKIT_VIEWS, MACOS_CATALYST_REFUSAL_REASONS;
79679
+ var UnsupportedOperationError, NotImplementedOnPlatformError, InvalidToolInputError, MACOS_APPS_FLAG, MACOS_APPS_FLAG_OFF_REASON, MACOS_POINTER_ONLY, MACOS_NO_TRACKPAD_GESTURES, MACOS_REFUSAL_REASONS, NO_CAPTURE_START_STOP_REASONS, CATALYST_NO_APPKIT_VIEWS, MACOS_CATALYST_REFUSAL_REASONS;
79680
79680
  var init_capability = __esm({
79681
79681
  "../tool-server/src/utils/capability.ts"() {
79682
79682
  "use strict";
@@ -79752,6 +79752,10 @@ var init_capability = __esm({
79752
79752
  "button": "a Mac app has no hardware buttons: use keyboard for key presses",
79753
79753
  "reinstall-app": "argent does not install Mac apps, it starts the .app where it was built. Rebuild the app, then run restart-app (or boot-device with macosAppPath for a .app at another path)"
79754
79754
  };
79755
+ NO_CAPTURE_START_STOP_REASONS = {
79756
+ vega: "a Vega app's network capture has no start or stop: view-network-logs turns it on at its first call",
79757
+ chromium: "a Chromium app's network capture has no start or stop: argent turns it on at the first tool call on the app; read the requests with view-network-logs"
79758
+ };
79755
79759
  CATALYST_NO_APPKIT_VIEWS = "a Mac Catalyst app's UIKit views are not in its AppKit view tree: use describe, which lists them with their identifiers and frames";
79756
79760
  MACOS_CATALYST_REFUSAL_REASONS = {
79757
79761
  "native-find-views": CATALYST_NO_APPKIT_VIEWS,
@@ -97887,7 +97891,7 @@ __export(index_exports, {
97887
97891
  });
97888
97892
  module.exports = __toCommonJS(index_exports);
97889
97893
  var path71 = __toESM(require("node:path"));
97890
- var import_node_os19 = require("node:os");
97894
+ var import_node_os20 = require("node:os");
97891
97895
  init_src();
97892
97896
  init_src2();
97893
97897
 
@@ -101443,7 +101447,7 @@ function isCi(env = process.env) {
101443
101447
  var SESSION_ID = (0, import_node_crypto3.randomUUID)();
101444
101448
  function readCliVersion() {
101445
101449
  if (true) {
101446
- return "0.34.1-next.47";
101450
+ return "0.34.1-next.49";
101447
101451
  }
101448
101452
  return "0.0.0";
101449
101453
  }
@@ -123839,6 +123843,140 @@ function createNdjsonCdpRequester(socket, options) {
123839
123843
  init_src2();
123840
123844
  init_external_devices();
123841
123845
 
123846
+ // ../tool-server/src/utils/debugger/device-alias.ts
123847
+ var logicalIdToConnectId = /* @__PURE__ */ new Map();
123848
+ function rememberDeviceAlias(logicalDeviceId, connectDeviceId) {
123849
+ if (!logicalDeviceId || logicalDeviceId === connectDeviceId) return;
123850
+ logicalIdToConnectId.set(logicalDeviceId, connectDeviceId);
123851
+ }
123852
+ function canonicalDeviceId(deviceId) {
123853
+ if (!deviceId) return deviceId;
123854
+ return logicalIdToConnectId.get(deviceId) ?? deviceId;
123855
+ }
123856
+ function deviceIdsOf(deviceId) {
123857
+ const connectId = canonicalDeviceId(deviceId) ?? deviceId;
123858
+ const logicalIds = [...logicalIdToConnectId].filter(([, aliased]) => aliased === connectId).map(([logicalId]) => logicalId);
123859
+ return [.../* @__PURE__ */ new Set([deviceId, connectId, ...logicalIds])];
123860
+ }
123861
+ function forgetDeviceAlias(logicalDeviceId) {
123862
+ if (logicalDeviceId) logicalIdToConnectId.delete(logicalDeviceId);
123863
+ }
123864
+ var logicalKeyedConnectIds = /* @__PURE__ */ new Set();
123865
+ function rememberLogicalKeyedDevice(logicalDeviceId, connectDeviceId) {
123866
+ if (logicalDeviceId && logicalDeviceId === connectDeviceId) {
123867
+ logicalKeyedConnectIds.add(connectDeviceId.toLowerCase());
123868
+ }
123869
+ }
123870
+ function isLogicalKeyedDevice(deviceId) {
123871
+ return deviceId !== void 0 && logicalKeyedConnectIds.has(deviceId.toLowerCase());
123872
+ }
123873
+ function forgetLogicalKeyedDevice(connectDeviceId) {
123874
+ logicalKeyedConnectIds.delete(connectDeviceId.toLowerCase());
123875
+ }
123876
+
123877
+ // ../tool-server/src/utils/native-network-record.ts
123878
+ init_external_devices();
123879
+ function deviceKeyOf(deviceId) {
123880
+ return externalNativeId(canonicalDeviceId(deviceId) ?? deviceId);
123881
+ }
123882
+ var MAX_RECORDS = 2e3;
123883
+ var RECORD_CHARS_BUDGET = 32 * 1024 * 1024;
123884
+ var MAX_VALUE_CHARS = 64 * 1024;
123885
+ var MAX_HEADERS = 256;
123886
+ var MAX_HEADER_MAP_CHARS = 256 * 1024;
123887
+ var MAX_LAYER_ID_CHARS = 200;
123888
+ var MAX_CACHED_BODIES = 64;
123889
+ var NOT_RECONNECTED = "the agent did not reconnect after its connection dropped, so this request's final events never arrived";
123890
+ var PROCESS_ENDED = "the app process ended before the request finished";
123891
+ var PROCESS_GONE = "the app process that made the request is gone";
123892
+ function isOpen(record2) {
123893
+ return record2.state === "pending" || record2.state === "headers";
123894
+ }
123895
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
123896
+ var ANDROID_EMULATOR_HOST = "10.0.2.2";
123897
+ var DEFAULT_PORTS = {
123898
+ "http:": 80,
123899
+ "ws:": 80,
123900
+ "https:": 443,
123901
+ "wss:": 443
123902
+ };
123903
+ function isMetroTraffic(url2, metroPort2, { androidEmulatorHost = false } = {}) {
123904
+ let parsed2;
123905
+ try {
123906
+ parsed2 = new URL(url2);
123907
+ } catch {
123908
+ return false;
123909
+ }
123910
+ const port = parsed2.port === "" ? DEFAULT_PORTS[parsed2.protocol] : Number(parsed2.port);
123911
+ const host = parsed2.hostname;
123912
+ const isHost = LOOPBACK_HOSTS.has(host) || androidEmulatorHost && host === ANDROID_EMULATOR_HOST;
123913
+ return isHost && port === metroPort2;
123914
+ }
123915
+ function capString(value, max = MAX_VALUE_CHARS) {
123916
+ return value.length > max ? `${value.slice(0, max)}\u2026[${value.length - max} more chars]` : value;
123917
+ }
123918
+ function headerMap(value) {
123919
+ const headers = {};
123920
+ let kept = 0;
123921
+ let chars = 0;
123922
+ let left = 0;
123923
+ for (const [name, v] of Object.entries(asObject(value))) {
123924
+ if (typeof v !== "string" && typeof v !== "number" && typeof v !== "boolean") continue;
123925
+ const key2 = capString(name, 1024);
123926
+ const text = capString(String(v));
123927
+ if (kept >= MAX_HEADERS || chars + key2.length + text.length > MAX_HEADER_MAP_CHARS) {
123928
+ left++;
123929
+ continue;
123930
+ }
123931
+ headers[key2] = text;
123932
+ kept++;
123933
+ chars += key2.length + text.length;
123934
+ }
123935
+ if (left > 0) headers["(not kept)"] = `${left} more headers`;
123936
+ return headers;
123937
+ }
123938
+ function mapChars(map2) {
123939
+ let chars = 0;
123940
+ for (const [name, value] of Object.entries(map2 ?? {})) chars += name.length + value.length;
123941
+ return chars;
123942
+ }
123943
+ function recordSize(record2) {
123944
+ let chars = record2.request.url.length + record2.request.method.length + mapChars(record2.request.headers) + mapChars(record2.request.wireHeaders) + (record2.errorText?.length ?? 0) + 256;
123945
+ if (record2.response) {
123946
+ chars += record2.response.url.length + record2.response.statusText.length + record2.response.mimeType.length + mapChars(record2.response.headers);
123947
+ }
123948
+ for (const hop of record2.redirects ?? []) {
123949
+ chars += hop.url.length + hop.statusText.length + mapChars(hop.headers) + mapChars(hop.requestHeaders);
123950
+ }
123951
+ return chars;
123952
+ }
123953
+ function toBody(result, kind) {
123954
+ const r = asObject(result);
123955
+ const text = kind === "response" ? r.body : r.postData;
123956
+ if (r.bodyAvailable === false || typeof text !== "string") {
123957
+ return unavailable(
123958
+ kind === "response" ? "the agent holds no body for this response" : "the agent holds no body for this request"
123959
+ );
123960
+ }
123961
+ const incomplete = kind === "post" && r.incomplete === true;
123962
+ return {
123963
+ available: true,
123964
+ body: text,
123965
+ base64Encoded: r.base64Encoded === true,
123966
+ truncated: r.wasTruncated === true || incomplete,
123967
+ ...incomplete ? { incomplete } : {}
123968
+ };
123969
+ }
123970
+ function unavailable(reason2) {
123971
+ return { available: false, body: "", base64Encoded: false, truncated: false, reason: reason2 };
123972
+ }
123973
+ function asObject(value) {
123974
+ return typeof value === "object" && value !== null ? value : {};
123975
+ }
123976
+ function asString2(value) {
123977
+ return typeof value === "string" ? value : "";
123978
+ }
123979
+
123842
123980
  // ../tool-server/src/utils/ios-host.ts
123843
123981
  var import_node_child_process15 = require("node:child_process");
123844
123982
  var import_node_events = require("node:events");
@@ -124536,144 +124674,14 @@ async function withKeyedLock(locks, key2, fn) {
124536
124674
  return run2;
124537
124675
  }
124538
124676
 
124539
- // ../tool-server/src/utils/debugger/device-alias.ts
124540
- var logicalIdToConnectId = /* @__PURE__ */ new Map();
124541
- function rememberDeviceAlias(logicalDeviceId, connectDeviceId) {
124542
- if (!logicalDeviceId || logicalDeviceId === connectDeviceId) return;
124543
- logicalIdToConnectId.set(logicalDeviceId, connectDeviceId);
124544
- }
124545
- function canonicalDeviceId(deviceId) {
124546
- if (!deviceId) return deviceId;
124547
- return logicalIdToConnectId.get(deviceId) ?? deviceId;
124548
- }
124549
- function deviceIdsOf(deviceId) {
124550
- const connectId = canonicalDeviceId(deviceId) ?? deviceId;
124551
- const logicalIds = [...logicalIdToConnectId].filter(([, aliased]) => aliased === connectId).map(([logicalId]) => logicalId);
124552
- return [.../* @__PURE__ */ new Set([deviceId, connectId, ...logicalIds])];
124553
- }
124554
- function forgetDeviceAlias(logicalDeviceId) {
124555
- if (logicalDeviceId) logicalIdToConnectId.delete(logicalDeviceId);
124556
- }
124557
- var logicalKeyedConnectIds = /* @__PURE__ */ new Set();
124558
- function rememberLogicalKeyedDevice(logicalDeviceId, connectDeviceId) {
124559
- if (logicalDeviceId && logicalDeviceId === connectDeviceId) {
124560
- logicalKeyedConnectIds.add(connectDeviceId.toLowerCase());
124561
- }
124562
- }
124563
- function isLogicalKeyedDevice(deviceId) {
124564
- return deviceId !== void 0 && logicalKeyedConnectIds.has(deviceId.toLowerCase());
124565
- }
124566
- function forgetLogicalKeyedDevice(connectDeviceId) {
124567
- logicalKeyedConnectIds.delete(connectDeviceId.toLowerCase());
124568
- }
124569
-
124570
- // ../tool-server/src/utils/native-network-record.ts
124571
- init_external_devices();
124572
- function deviceKeyOf(deviceId) {
124573
- return externalNativeId(canonicalDeviceId(deviceId) ?? deviceId);
124574
- }
124575
- var MAX_RECORDS = 2e3;
124576
- var RECORD_CHARS_BUDGET = 32 * 1024 * 1024;
124577
- var MAX_VALUE_CHARS = 64 * 1024;
124578
- var MAX_HEADERS = 256;
124579
- var MAX_HEADER_MAP_CHARS = 256 * 1024;
124580
- var MAX_LAYER_ID_CHARS = 200;
124581
- var MAX_CACHED_BODIES = 64;
124582
- var NOT_RECONNECTED = "the agent did not reconnect after its connection dropped, so this request's final events never arrived";
124583
- var PROCESS_ENDED = "the app process ended before the request finished";
124584
- var PROCESS_GONE = "the app process that made the request is gone";
124585
- function isOpen(record2) {
124586
- return record2.state === "pending" || record2.state === "headers";
124587
- }
124588
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
124589
- var ANDROID_EMULATOR_HOST = "10.0.2.2";
124590
- var DEFAULT_PORTS = {
124591
- "http:": 80,
124592
- "ws:": 80,
124593
- "https:": 443,
124594
- "wss:": 443
124595
- };
124596
- function isMetroTraffic(url2, metroPort2, { androidEmulatorHost = false } = {}) {
124597
- let parsed2;
124598
- try {
124599
- parsed2 = new URL(url2);
124600
- } catch {
124601
- return false;
124602
- }
124603
- const port = parsed2.port === "" ? DEFAULT_PORTS[parsed2.protocol] : Number(parsed2.port);
124604
- const host = parsed2.hostname;
124605
- const isHost = LOOPBACK_HOSTS.has(host) || androidEmulatorHost && host === ANDROID_EMULATOR_HOST;
124606
- return isHost && port === metroPort2;
124607
- }
124608
- function capString(value, max = MAX_VALUE_CHARS) {
124609
- return value.length > max ? `${value.slice(0, max)}\u2026[${value.length - max} more chars]` : value;
124610
- }
124611
- function headerMap(value) {
124612
- const headers = {};
124613
- let kept = 0;
124614
- let chars = 0;
124615
- let left = 0;
124616
- for (const [name, v] of Object.entries(asObject(value))) {
124617
- if (typeof v !== "string" && typeof v !== "number" && typeof v !== "boolean") continue;
124618
- const key2 = capString(name, 1024);
124619
- const text = capString(String(v));
124620
- if (kept >= MAX_HEADERS || chars + key2.length + text.length > MAX_HEADER_MAP_CHARS) {
124621
- left++;
124622
- continue;
124623
- }
124624
- headers[key2] = text;
124625
- kept++;
124626
- chars += key2.length + text.length;
124627
- }
124628
- if (left > 0) headers["(not kept)"] = `${left} more headers`;
124629
- return headers;
124630
- }
124631
- function mapChars(map2) {
124632
- let chars = 0;
124633
- for (const [name, value] of Object.entries(map2 ?? {})) chars += name.length + value.length;
124634
- return chars;
124635
- }
124636
- function recordSize(record2) {
124637
- let chars = record2.request.url.length + record2.request.method.length + mapChars(record2.request.headers) + mapChars(record2.request.wireHeaders) + (record2.errorText?.length ?? 0) + 256;
124638
- if (record2.response) {
124639
- chars += record2.response.url.length + record2.response.statusText.length + record2.response.mimeType.length + mapChars(record2.response.headers);
124640
- }
124641
- for (const hop of record2.redirects ?? []) {
124642
- chars += hop.url.length + hop.statusText.length + mapChars(hop.headers) + mapChars(hop.requestHeaders);
124643
- }
124644
- return chars;
124645
- }
124646
- function toBody(result, kind) {
124647
- const r = asObject(result);
124648
- const text = kind === "response" ? r.body : r.postData;
124649
- if (r.bodyAvailable === false || typeof text !== "string") {
124650
- return unavailable(
124651
- kind === "response" ? "the agent holds no body for this response" : "the agent holds no body for this request"
124652
- );
124653
- }
124654
- const incomplete = kind === "post" && r.incomplete === true;
124655
- return {
124656
- available: true,
124657
- body: text,
124658
- base64Encoded: r.base64Encoded === true,
124659
- truncated: r.wasTruncated === true || incomplete,
124660
- ...incomplete ? { incomplete } : {}
124661
- };
124662
- }
124663
- function unavailable(reason2) {
124664
- return { available: false, body: "", base64Encoded: false, truncated: false, reason: reason2 };
124665
- }
124666
- function asObject(value) {
124667
- return typeof value === "object" && value !== null ? value : {};
124668
- }
124669
- function asString2(value) {
124670
- return typeof value === "string" ? value : "";
124671
- }
124672
-
124673
124677
  // ../tool-server/src/blueprints/ios-network-records.ts
124674
124678
  var RUN_TAG = (0, import_node_crypto7.randomBytes)(2).toString("hex");
124675
124679
  var IOS_NATIVE_REQUEST_ID = /^ios-[0-9a-f]{4}-\d+$/;
124680
+ var MACOS_NATIVE_REQUEST_ID = /^macos-[0-9a-f]{4}-\d+$/;
124676
124681
  var nextRecordNumber = 1;
124682
+ function lastIosRecordNumber() {
124683
+ return nextRecordNumber - 1;
124684
+ }
124677
124685
  var POST_DATA_WAIT_MS = 5e3;
124678
124686
  var POST_DATA_TIMEOUT_MS = 2 ** 31 - 1;
124679
124687
  var RESPONSE_BODY_TIMEOUT_MS = 1e4;
@@ -124684,8 +124692,11 @@ var NO_EARLIER_ANSWER = `the app did not answer an earlier body read within ${RE
124684
124692
  var CONNECTION_CLOSED = "the agent's connection closed before this body was read";
124685
124693
  var REQUEST_BODY_GONE = "the agent holds no body for this request";
124686
124694
  var BODY_NO_LONGER_HELD = "the agent no longer holds this body";
124695
+ var MACOS_NO_BODIES = "argent does not keep the bodies of a Mac app's requests";
124696
+ var MACOS_CONNECTION_DROPPED = "argent's connection to the app dropped while this request ran, so argent can have missed its end; the request completes if its end comes later";
124687
124697
  var NO_RESPONSE_BODY = "the response has no body";
124688
- function createIosNetworkRecords(state3, link) {
124698
+ function createIosNetworkRecords(state3, link, recording = () => true, layer = "ios-native") {
124699
+ const idPrefix = layer === "macos-native" ? "macos" : "ios";
124689
124700
  const records = [];
124690
124701
  let recordChars = 0;
124691
124702
  const recordSizes = /* @__PURE__ */ new WeakMap();
@@ -124709,8 +124720,8 @@ function createIosNetworkRecords(state3, link) {
124709
124720
  const startedAt = typeof p.wallTime === "number" ? p.wallTime * 1e3 : typeof p.timestamp === "number" ? p.timestamp * 1e3 : Date.now();
124710
124721
  const postData = typeof req.postData === "string" ? req.postData : "";
124711
124722
  const record2 = {
124712
- id: `ios-${RUN_TAG}-${nextRecordNumber++}`,
124713
- layer: "ios-native",
124723
+ id: `${idPrefix}-${RUN_TAG}-${nextRecordNumber++}`,
124724
+ layer,
124714
124725
  layerId,
124715
124726
  connection,
124716
124727
  state: "pending",
@@ -124762,6 +124773,7 @@ function createIosNetworkRecords(state3, link) {
124762
124773
  bodies.delete(`post:${record2.id}`);
124763
124774
  }
124764
124775
  function closedReason(connection) {
124776
+ if (layer === "macos-native") return MACOS_NO_BODIES;
124765
124777
  const live = link.liveConnection();
124766
124778
  if (live !== void 0) sawConnection(live);
124767
124779
  return endedConnections.has(connection) || newestConnection > connection ? PROCESS_GONE : CONNECTION_CLOSED;
@@ -124898,6 +124910,7 @@ function createIosNetworkRecords(state3, link) {
124898
124910
  const at = message.indexOf(marker);
124899
124911
  const detail = at === -1 ? message : message.slice(at + marker.length);
124900
124912
  if (/^no /i.test(detail)) {
124913
+ if (layer === "macos-native") return MACOS_NO_BODIES;
124901
124914
  if (kind === "response") return BODY_NO_LONGER_HELD;
124902
124915
  if (/^no request stored\b/i.test(detail)) {
124903
124916
  return record2.state === "pending" ? STILL_SENDING : BODY_NO_LONGER_HELD;
@@ -124919,7 +124932,7 @@ function createIosNetworkRecords(state3, link) {
124919
124932
  if (!layerId || layerId.length > MAX_LAYER_ID_CHARS) return;
124920
124933
  if (method === "Network.requestWillBeSent") {
124921
124934
  if (p.redirectResponse !== void 0 && p.redirectResponse !== null) return;
124922
- startRecord(connection, layerId, p);
124935
+ if (recording()) startRecord(connection, layerId, p);
124923
124936
  return;
124924
124937
  }
124925
124938
  const record2 = byLayerId.get(keyOf(connection, layerId));
@@ -124929,6 +124942,7 @@ function createIosNetworkRecords(state3, link) {
124929
124942
  case "Network.responseReceived": {
124930
124943
  const r = asObject(p.response);
124931
124944
  const status = typeof r.status === "number" ? r.status : 0;
124945
+ delete record2.errorText;
124932
124946
  record2.state = "headers";
124933
124947
  record2.response = {
124934
124948
  // The URL of the final response, after any redirects.
@@ -124943,6 +124957,7 @@ function createIosNetworkRecords(state3, link) {
124943
124957
  }
124944
124958
  case "Network.loadingFinished":
124945
124959
  cleared.delete(record2);
124960
+ delete record2.errorText;
124946
124961
  record2.state = "complete";
124947
124962
  if (typeof p.encodedDataLength === "number")
124948
124963
  record2.encodedDataLength = p.encodedDataLength;
@@ -124965,10 +124980,12 @@ function createIosNetworkRecords(state3, link) {
124965
124980
  sawConnection(connection);
124966
124981
  const ended = check3.superseded || check3.running === false || check3.runningPid !== void 0 && check3.connectionPid !== void 0 && check3.runningPid !== check3.connectionPid;
124967
124982
  if (ended) endedConnections.add(connection);
124968
- const open5 = records.filter((r) => r.connection === connection && isOpen(r));
124983
+ const open5 = records.filter(
124984
+ (r) => r.connection === connection && (isOpen(r) || ended && r.errorText === MACOS_CONNECTION_DROPPED)
124985
+ );
124969
124986
  for (const record2 of open5) {
124970
124987
  record2.state = "failed";
124971
- record2.errorText = ended ? PROCESS_ENDED : NOT_RECONNECTED;
124988
+ record2.errorText = ended ? PROCESS_ENDED : layer === "macos-native" ? MACOS_CONNECTION_DROPPED : NOT_RECONNECTED;
124972
124989
  cleared.delete(record2);
124973
124990
  }
124974
124991
  for (const record2 of open5) resize(record2);
@@ -125026,15 +125043,20 @@ function findIosNativeRecord(id) {
125026
125043
  }
125027
125044
  return void 0;
125028
125045
  }
125046
+ function hasIosNetworkCapture() {
125047
+ return [...liveCaptures].some(
125048
+ (captures) => (captures.startedBundleIds ?? captures.bundleIds).size > 0 || captures.stoppedBundleIds.size > 0
125049
+ );
125050
+ }
125029
125051
  function capturing(captures, bundleId) {
125030
- return captures.bundleIds.has(bundleId) && captures.stores.has(bundleId);
125052
+ return (captures.bundleIds.has(bundleId) || captures.unconfirmedStopBundleIds?.has(bundleId) === true) && captures.stores.has(bundleId);
125031
125053
  }
125032
125054
  function liveIosNetworkCaptures(deviceId) {
125033
125055
  const key2 = deviceKeyOf(deviceId);
125034
125056
  const bundleIds = /* @__PURE__ */ new Set();
125035
125057
  for (const captures of liveCaptures) {
125036
125058
  if (deviceKeyOf(captures.udid) !== key2) continue;
125037
- for (const bundleId of captures.bundleIds) {
125059
+ for (const bundleId of [...captures.bundleIds, ...captures.unconfirmedStopBundleIds ?? []]) {
125038
125060
  if (capturing(captures, bundleId)) bundleIds.add(bundleId);
125039
125061
  }
125040
125062
  }
@@ -125103,17 +125125,20 @@ function isNativeDevtoolsBlockResult(toolId, result) {
125103
125125
  const status = result.status;
125104
125126
  return typeof status === "string" && NATIVE_DEVTOOLS_BLOCK_STATUSES.has(status);
125105
125127
  }
125128
+ function nonInjectableError(bundleId) {
125129
+ return new FailureError(
125130
+ `${bundleId} is an Apple system app: it is never the app under test, so Argent native devtools refuse to read one \u2014 treat it as unavailable rather than retrying. ` + NON_INJECTABLE_RECOVERY,
125131
+ {
125132
+ error_code: FAILURE_CODES.NATIVE_DEVTOOLS_NOT_INJECTABLE,
125133
+ failure_stage: "native_devtools_precheck",
125134
+ failure_area: "tool_server",
125135
+ error_kind: "validation"
125136
+ }
125137
+ );
125138
+ }
125106
125139
  async function precheckNativeDevtools(api, udid, bundleId) {
125107
125140
  if (bundleId !== void 0 && !isInjectableBundleId(bundleId)) {
125108
- throw new FailureError(
125109
- `${bundleId} is an Apple system app: it is never the app under test, so Argent native devtools refuse to read one \u2014 treat it as unavailable rather than retrying. ` + NON_INJECTABLE_RECOVERY,
125110
- {
125111
- error_code: FAILURE_CODES.NATIVE_DEVTOOLS_NOT_INJECTABLE,
125112
- failure_stage: "native_devtools_precheck",
125113
- failure_area: "tool_server",
125114
- error_kind: "validation"
125115
- }
125116
- );
125141
+ throw nonInjectableError(bundleId);
125117
125142
  }
125118
125143
  const existing = api.getInitFailure();
125119
125144
  if (existing?.givenUp) return buildInitFailedResult(udid, existing);
@@ -125153,11 +125178,15 @@ async function precheckNativeDevtools(api, udid, bundleId) {
125153
125178
  function nativeDevtoolsRef(device, { transport = "unix" } = {}) {
125154
125179
  const transportSuffix = transport === "tcp" ? ":tcp" : "";
125155
125180
  return {
125156
- urn: `${NATIVE_DEVTOOLS_NAMESPACE}:${device.id}${transportSuffix}`,
125181
+ // A provider's `ext:` id and its raw udid name one app connection and one
125182
+ // capture, so both key the service by the udid, as the simulator watcher does.
125183
+ urn: `${NATIVE_DEVTOOLS_NAMESPACE}:${deviceKeyOf(device.id)}${transportSuffix}`,
125157
125184
  options: { device, transport }
125158
125185
  };
125159
125186
  }
125160
125187
  var NETWORK_ENABLE_TIMEOUT_MS = 5e3;
125188
+ var NETWORK_DISABLE_TIMEOUT_MS = 5e3;
125189
+ var DISPOSE_DISABLE_TIMEOUT_MS = 1e3;
125161
125190
  var LAUNCH_ARM_WAIT_MS = 5e3;
125162
125191
  var LENT_HANDSHAKE_PROMPT_MS = 1e3;
125163
125192
  var WAITING_FOR_ENABLE = "waiting for the agent to acknowledge Network.enable";
@@ -125217,7 +125246,7 @@ function bindNativeDevtoolsUnixSocket(server, socketPath) {
125217
125246
  var nativeDevtoolsBlueprint = {
125218
125247
  namespace: NATIVE_DEVTOOLS_NAMESPACE,
125219
125248
  getURN(device) {
125220
- return `${NATIVE_DEVTOOLS_NAMESPACE}:${device.id}`;
125249
+ return nativeDevtoolsRef(device).urn;
125221
125250
  },
125222
125251
  async factory(_deps, _payload, options) {
125223
125252
  const opts = options;
@@ -125273,6 +125302,9 @@ var nativeDevtoolsBlueprint = {
125273
125302
  let inFlight4 = null;
125274
125303
  let envRetired = false;
125275
125304
  const activatedBundleIds = /* @__PURE__ */ new Set();
125305
+ const stoppedBundleIds = /* @__PURE__ */ new Set();
125306
+ const unconfirmedStopBundleIds = /* @__PURE__ */ new Set();
125307
+ const captureMarks = /* @__PURE__ */ new Map();
125276
125308
  const captureGaps = /* @__PURE__ */ new Set();
125277
125309
  const networkConditions = /* @__PURE__ */ new Map();
125278
125310
  const providerCapture = /* @__PURE__ */ new Map();
@@ -125370,7 +125402,7 @@ var nativeDevtoolsBlueprint = {
125370
125402
  connectionWaiters.add(check3);
125371
125403
  });
125372
125404
  };
125373
- const enableOn = (conn) => {
125405
+ const enableOn = (bundleId, conn) => {
125374
125406
  if (conn.armed && !lentSocketPath) return Promise.resolve(true);
125375
125407
  if (conn.enabling) return conn.enabling;
125376
125408
  delete conn.enableFailure;
@@ -125380,6 +125412,7 @@ var nativeDevtoolsBlueprint = {
125380
125412
  {
125381
125413
  timeoutMs: NETWORK_ENABLE_TIMEOUT_MS,
125382
125414
  onResult: (result) => {
125415
+ if (stoppedBundleIds.has(bundleId)) return;
125383
125416
  conn.armed = !lentSocketPath || result?.enabled === true;
125384
125417
  if (!conn.armed) conn.enableFailure = PROVIDER_CAPTURE_OFF;
125385
125418
  wakeConnectionWaiters();
@@ -125391,7 +125424,7 @@ var nativeDevtoolsBlueprint = {
125391
125424
  if (conn.socket.destroyed || disposed) return false;
125392
125425
  const timedOut3 = getFailureSignal(err)?.error_kind === "timeout";
125393
125426
  const detail = err instanceof Error ? err.message : String(err);
125394
- conn.enableFailure = lentSocketPath ? timedOut3 ? `the agent did not say within ${NETWORK_ENABLE_TIMEOUT_MS / 1e3} s whether capture is on; the next call asks again` : `the agent did not say whether capture is on (${detail}); the next call asks again` : timedOut3 ? `the agent did not acknowledge Network.enable within ${NETWORK_ENABLE_TIMEOUT_MS / 1e3} s; the next call asks again` : `the agent did not enable capture (${detail}); the next call asks again`;
125427
+ conn.enableFailure = lentSocketPath ? timedOut3 ? `the agent did not say within ${NETWORK_ENABLE_TIMEOUT_MS / 1e3} s whether capture is on; the next call asks again` : `the agent did not say whether capture is on (${detail}); the next call asks again` : timedOut3 ? `the agent did not acknowledge Network.enable within ${NETWORK_ENABLE_TIMEOUT_MS / 1e3} s; network-capture-start asks again` : `the agent did not enable capture (${detail}); network-capture-start asks again`;
125395
125428
  process.stderr.write(`[native-devtools ${udid.slice(0, 8)}] ${conn.enableFailure}
125396
125429
  `);
125397
125430
  wakeConnectionWaiters();
@@ -125414,7 +125447,8 @@ var nativeDevtoolsBlueprint = {
125414
125447
  return {
125415
125448
  armed: conn.armed,
125416
125449
  ...conn.pid !== void 0 ? { pid: conn.pid } : {},
125417
- ...conn.armed ? {} : conn.enabling ? { note: lentSocketPath ? WAITING_FOR_CAPTURE_STATE : WAITING_FOR_ENABLE } : conn.enableFailure ? { note: conn.enableFailure } : {}
125450
+ // A failure is the answer to the request still on its way, which settles just after.
125451
+ ...conn.armed ? {} : conn.enableFailure ? { note: conn.enableFailure } : conn.enabling ? { note: lentSocketPath ? WAITING_FOR_CAPTURE_STATE : WAITING_FOR_ENABLE } : {}
125418
125452
  };
125419
125453
  };
125420
125454
  const readConnectionPid = async (bundleId, conn) => {
@@ -125446,7 +125480,10 @@ var nativeDevtoolsBlueprint = {
125446
125480
  const closeConnection = (bundleId, conn) => {
125447
125481
  conn.cdp.close();
125448
125482
  conn.armed = false;
125449
- if (connections2.get(bundleId) === conn) connections2.delete(bundleId);
125483
+ if (connections2.get(bundleId) === conn) {
125484
+ connections2.delete(bundleId);
125485
+ unconfirmedStopBundleIds.delete(bundleId);
125486
+ }
125450
125487
  connectionCloses += 1;
125451
125488
  wakeConnectionWaiters();
125452
125489
  void settleClosedConnection(bundleId, conn);
@@ -125514,7 +125551,7 @@ var nativeDevtoolsBlueprint = {
125514
125551
  };
125515
125552
  const armOn = (bundleId, conn) => {
125516
125553
  const sendsEnable = !lentSocketPath && !conn.armed && !conn.enabling;
125517
- const arming = enableOn(conn);
125554
+ const arming = enableOn(bundleId, conn);
125518
125555
  if (sendsEnable) reapplyStoredThrottle(bundleId);
125519
125556
  return arming;
125520
125557
  };
@@ -125578,20 +125615,27 @@ var nativeDevtoolsBlueprint = {
125578
125615
  const app = bundleId;
125579
125616
  networkStores.set(
125580
125617
  app,
125581
- createIosNetworkRecords(() => captureState(app), {
125582
- liveConnection: () => connections2.get(app)?.index,
125583
- request: (index, method, params, timeoutMs) => {
125584
- const live = connections2.get(app);
125585
- return live?.index === index ? live.cdp.request(method, params, { timeoutMs }) : Promise.reject(closedBeforeRequest(app, method));
125586
- }
125587
- })
125618
+ createIosNetworkRecords(
125619
+ () => captureState(app),
125620
+ {
125621
+ liveConnection: () => connections2.get(app)?.index,
125622
+ request: (index, method, params, timeoutMs) => {
125623
+ const live = connections2.get(app);
125624
+ return live?.index === index ? live.cdp.request(method, params, { timeoutMs }) : Promise.reject(closedBeforeRequest(app, method));
125625
+ }
125626
+ },
125627
+ () => !stoppedBundleIds.has(app)
125628
+ )
125588
125629
  );
125589
125630
  }
125590
125631
  if (lentSocketPath && performance.now() - lentConnectedAt < LENT_HANDSHAKE_PROMPT_MS) {
125591
125632
  captureGaps.add(bundleId);
125592
125633
  }
125593
125634
  if (activatedBundleIds.has(bundleId)) {
125594
- if (!lentSocketPath) captureGaps.delete(bundleId);
125635
+ if (!lentSocketPath) {
125636
+ captureGaps.delete(bundleId);
125637
+ conn.launchRecorded = true;
125638
+ }
125595
125639
  void armOn(bundleId, conn);
125596
125640
  } else {
125597
125641
  reapplyStoredThrottle(bundleId);
@@ -125735,14 +125779,67 @@ var nativeDevtoolsBlueprint = {
125735
125779
  if (processAgeMs < NATIVE_DEVTOOLS_CONNECT_BUDGET_MS) return "connecting";
125736
125780
  return "unregistered";
125737
125781
  },
125738
- activateNetworkInspection(bundleId) {
125782
+ startNetworkCapture(bundleId, metroPort2, waitForConnectionMs = 0) {
125783
+ stoppedBundleIds.delete(bundleId);
125784
+ unconfirmedStopBundleIds.delete(bundleId);
125785
+ captureMarks.set(bundleId, { lastRecord: lastIosRecordNumber(), metroPort: metroPort2 });
125739
125786
  const startedNow = !activatedBundleIds.has(bundleId);
125740
125787
  activatedBundleIds.add(bundleId);
125741
125788
  const conn = connections2.get(bundleId);
125742
- if (!conn) return Promise.resolve(false);
125743
- if (startedNow && !lentSocketPath) captureGaps.add(bundleId);
125789
+ if (!conn) {
125790
+ return waitForConnection(() => {
125791
+ const next = connections2.get(bundleId);
125792
+ return next?.armed === true || next?.enableFailure !== void 0;
125793
+ }, waitForConnectionMs).then(() => connections2.get(bundleId)?.armed === true);
125794
+ }
125795
+ if (startedNow && !lentSocketPath && !conn.launchRecorded) captureGaps.add(bundleId);
125744
125796
  return armOn(bundleId, conn);
125745
125797
  },
125798
+ async stopNetworkCapture(bundleId) {
125799
+ stoppedBundleIds.add(bundleId);
125800
+ activatedBundleIds.delete(bundleId);
125801
+ captureGaps.delete(bundleId);
125802
+ const conn = connections2.get(bundleId);
125803
+ if (!conn) return { confirmed: true };
125804
+ conn.armed = false;
125805
+ conn.enabling = void 0;
125806
+ delete conn.enableFailure;
125807
+ wakeConnectionWaiters();
125808
+ if (lentSocketPath) {
125809
+ return {
125810
+ confirmed: true,
125811
+ reason: "the device provider keeps its own capture setting for the app; argent records none of its new requests"
125812
+ };
125813
+ }
125814
+ const disabling = conn.cdp.request(
125815
+ "Network.disable",
125816
+ {},
125817
+ { timeoutMs: NETWORK_DISABLE_TIMEOUT_MS }
125818
+ );
125819
+ reapplyStoredThrottle(bundleId);
125820
+ try {
125821
+ await disabling;
125822
+ unconfirmedStopBundleIds.delete(bundleId);
125823
+ return { confirmed: true };
125824
+ } catch (err) {
125825
+ if (conn.socket.destroyed || disposed) return { confirmed: true };
125826
+ if (stoppedBundleIds.has(bundleId)) unconfirmedStopBundleIds.add(bundleId);
125827
+ const timedOut3 = getFailureSignal(err)?.error_kind === "timeout";
125828
+ const detail = err instanceof Error ? err.message : String(err);
125829
+ return {
125830
+ confirmed: false,
125831
+ reason: `${timedOut3 ? `the app did not acknowledge Network.disable within ${NETWORK_DISABLE_TIMEOUT_MS / 1e3} s` : `the app did not disable capture (${detail})`}; argent records none of its new requests, and its next process starts without capture`
125832
+ };
125833
+ }
125834
+ },
125835
+ isNetworkCaptureStarted: (bundleId) => activatedBundleIds.has(bundleId),
125836
+ isNetworkCaptureStopped: (bundleId) => stoppedBundleIds.has(bundleId),
125837
+ networkCaptureMark: (bundleId) => captureMarks.get(bundleId),
125838
+ async refreshLentNetworkCapture(bundleId) {
125839
+ if (!lentSocketPath || !activatedBundleIds.has(bundleId)) return;
125840
+ const conn = connections2.get(bundleId);
125841
+ if (conn) await enableOn(bundleId, conn);
125842
+ },
125746
125843
  async setNetworkConditions(bundleId, throttle) {
125747
125844
  const previous = networkConditions.get(bundleId) ?? null;
125748
125845
  storeThrottle(bundleId, throttle);
@@ -125763,28 +125860,42 @@ var nativeDevtoolsBlueprint = {
125763
125860
  takeCaptureGap: (bundleId) => captureGaps.delete(bundleId),
125764
125861
  networkRecords: (bundleId) => networkStores.get(bundleId),
125765
125862
  async networkCaptureAfterLaunch(bundleId) {
125766
- if (!activatedBundleIds.has(bundleId) || lentSocketPath) return void 0;
125863
+ if (lentSocketPath) return void 0;
125864
+ const stoppedNote = `native network capture is stopped for ${bundleId} (network-capture-stop); this process runs without it until network-capture-start`;
125865
+ if (stoppedBundleIds.has(bundleId) && !unconfirmedStopBundleIds.has(bundleId)) {
125866
+ return stoppedNote;
125867
+ }
125868
+ if (!activatedBundleIds.has(bundleId) && !unconfirmedStopBundleIds.has(bundleId)) {
125869
+ return void 0;
125870
+ }
125767
125871
  let closes = connectionCloses;
125768
125872
  const inspection = await host.inspectRunningApp(udid, bundleId).catch(() => null);
125769
125873
  if (disposed) return void 0;
125770
- const gone = `native network capture is on for ${bundleId}, but no process of it is running after the launch; its next process is armed when it connects`;
125771
- if (inspection?.running === false) return gone;
125772
125874
  const pid = inspection?.process?.pid;
125773
125875
  const ofLaunch = () => {
125774
125876
  const conn = connections2.get(bundleId);
125775
125877
  return conn && (pid === void 0 || conn.pid === pid) ? conn : void 0;
125776
125878
  };
125879
+ const noteWhenStopped = () => {
125880
+ const conn = unconfirmedStopBundleIds.has(bundleId) ? ofLaunch() : void 0;
125881
+ if (!conn) return stoppedNote;
125882
+ const pidText2 = conn.pid !== void 0 ? ` (pid ${conn.pid})` : "";
125883
+ return `native network capture is stopped for ${bundleId} (network-capture-stop), but its running process${pidText2} has not acknowledged Network.disable, so it may still intercept its requests; argent records none of them, and restart-app starts a process without capture`;
125884
+ };
125885
+ if (stoppedBundleIds.has(bundleId)) return noteWhenStopped();
125886
+ const gone = `native network capture is on for ${bundleId}, but no process of it is running after the launch; its next process is armed when it connects`;
125887
+ if (inspection?.running === false) return gone;
125777
125888
  const running = inspection?.process;
125778
125889
  if (running && !ofLaunch()) {
125779
125890
  if (!processCarriesInjection(running.env, endpoint)) {
125780
- return `native network capture is on for ${bundleId}, but its running process (pid ${running.pid}) was launched without argent's injection for this simulator, so capture cannot be armed in it; call restart-app to start a process that is armed`;
125891
+ return `native network capture is on for ${bundleId}, but its running process (pid ${running.pid}) was launched without argent's injection for this simulator, so capture cannot be armed in it; call restart-app to start a process that is armed, then network-capture-start again, since a relaunch ends the JS layer's capture`;
125781
125892
  }
125782
125893
  if (running.ageMs > Date.now() - listeningSince + NATIVE_DEVTOOLS_AGE_SLOP_MS) {
125783
- return `native network capture is on for ${bundleId}, but its running process (pid ${running.pid}) started before this tool-server's native-devtools listener, so it never connects and capture cannot be armed in it; call restart-app to start a process that is armed`;
125894
+ return `native network capture is on for ${bundleId}, but its running process (pid ${running.pid}) started before this tool-server's native-devtools listener, so it never connects and capture cannot be armed in it; call restart-app to start a process that is armed, then network-capture-start again, since a relaunch ends the JS layer's capture`;
125784
125895
  }
125785
125896
  }
125786
125897
  const asked = ofLaunch();
125787
- if (asked && !asked.armed && !asked.enabling) void enableOn(asked);
125898
+ if (asked && !asked.armed && !asked.enabling) void enableOn(bundleId, asked);
125788
125899
  let exited = false;
125789
125900
  const watchExit = () => {
125790
125901
  if (closes === connectionCloses) return;
@@ -125807,18 +125918,20 @@ var nativeDevtoolsBlueprint = {
125807
125918
  connectionWaiters.delete(watchExit);
125808
125919
  }
125809
125920
  if (disposed) return void 0;
125921
+ if (stoppedBundleIds.has(bundleId)) return noteWhenStopped();
125810
125922
  if (exited) return gone;
125811
125923
  let launched = ofLaunch();
125812
125924
  if (!launched) {
125813
125925
  const now = await host.inspectRunningApp(udid, bundleId).catch(() => null);
125814
125926
  if (disposed) return void 0;
125927
+ if (stoppedBundleIds.has(bundleId)) return noteWhenStopped();
125815
125928
  if (now?.running === false) return gone;
125816
125929
  launched = ofLaunch();
125817
125930
  }
125818
125931
  const shownPid = pid ?? launched?.pid;
125819
125932
  const pidText = shownPid !== void 0 ? ` (pid ${shownPid})` : "";
125820
125933
  if (launched?.armed) {
125821
- return `native network capture is armed for ${bundleId}${pidText}; stop-all-simulator-servers for this device, then restart-app, ends it`;
125934
+ return `native network capture is armed for ${bundleId}${pidText}; network-capture-stop ends it`;
125822
125935
  }
125823
125936
  if (launched?.enableFailure !== void 0) {
125824
125937
  return `native network capture is on for ${bundleId}, but its process${pidText} is not armed: ${launched.enableFailure}`;
@@ -125872,6 +125985,9 @@ var nativeDevtoolsBlueprint = {
125872
125985
  udid,
125873
125986
  // A lent agent's capture is its provider's, so argent has none on there.
125874
125987
  bundleIds: lentSocketPath ? /* @__PURE__ */ new Set() : activatedBundleIds,
125988
+ startedBundleIds: activatedBundleIds,
125989
+ stoppedBundleIds,
125990
+ unconfirmedStopBundleIds,
125875
125991
  stores: networkStores
125876
125992
  });
125877
125993
  return {
@@ -125879,6 +125995,14 @@ var nativeDevtoolsBlueprint = {
125879
125995
  dispose: async () => {
125880
125996
  disposed = true;
125881
125997
  unregisterCaptures();
125998
+ wakeConnectionWaiters();
125999
+ if (!lentSocketPath) {
126000
+ await Promise.all(
126001
+ [...connections2].filter(([app]) => activatedBundleIds.has(app) || stoppedBundleIds.has(app)).map(
126002
+ ([, { cdp }]) => cdp.request("Network.disable", {}, { timeoutMs: DISPOSE_DISABLE_TIMEOUT_MS }).catch(() => void 0)
126003
+ )
126004
+ );
126005
+ }
125882
126006
  if (lentSocketPath) await releaseLentThrottles();
125883
126007
  for (const { socket, cdp } of connections2.values()) {
125884
126008
  cdp.close();
@@ -125886,6 +126010,9 @@ var nativeDevtoolsBlueprint = {
125886
126010
  }
125887
126011
  connections2.clear();
125888
126012
  activatedBundleIds.clear();
126013
+ stoppedBundleIds.clear();
126014
+ unconfirmedStopBundleIds.clear();
126015
+ captureMarks.clear();
125889
126016
  captureGaps.clear();
125890
126017
  networkStores.clear();
125891
126018
  wakeConnectionWaiters();
@@ -128037,7 +128164,7 @@ var os9 = __toESM(require("node:os"));
128037
128164
  function metroOriginCandidates(wsUrl) {
128038
128165
  const { protocol, host, port } = new URL(wsUrl);
128039
128166
  const scheme = protocol === "wss:" ? "https://" : "http://";
128040
- const at = (hostname4) => `${scheme}${bracketed(hostname4)}${port ? `:${port}` : ""}`;
128167
+ const at = (hostname5) => `${scheme}${bracketed(hostname5)}${port ? `:${port}` : ""}`;
128041
128168
  const candidates = [
128042
128169
  scheme + host.replace("localhost", "127.0.0.1"),
128043
128170
  at("localhost"),
@@ -128066,8 +128193,8 @@ async function expoManifestOrigin(wsUrl) {
128066
128193
  function lanAddresses() {
128067
128194
  return Object.values(os9.networkInterfaces()).flat().filter((address) => address && !address.internal && address.family === "IPv4").map((address) => address.address);
128068
128195
  }
128069
- function bracketed(hostname4) {
128070
- return hostname4.includes(":") && !hostname4.startsWith("[") ? `[${hostname4}]` : hostname4;
128196
+ function bracketed(hostname5) {
128197
+ return hostname5.includes(":") && !hostname5.startsWith("[") ? `[${hostname5}]` : hostname5;
128071
128198
  }
128072
128199
 
128073
128200
  // ../tool-server/src/utils/debugger/scripts/await-promise.ts
@@ -145610,7 +145737,8 @@ async function startSuspensionWatch(helperPath, pid) {
145610
145737
  }
145611
145738
 
145612
145739
  // ../tool-server/src/blueprints/macos-app.ts
145613
- var NATIVE_NETWORK_LOG_LIMIT = 1e3;
145740
+ var NETWORK_CAPTURE_ACK_TIMEOUT_MS = 5e3;
145741
+ var PROCESS_EXIT_WAIT_MS = 2e3;
145614
145742
  var MACOS_APP_NAMESPACE = "MacosApp";
145615
145743
  function macosAppRef(device) {
145616
145744
  return { urn: `${MACOS_APP_NAMESPACE}:${device.id}`, options: { device } };
@@ -145654,6 +145782,58 @@ function notRunningError(bundleId) {
145654
145782
  "not_found"
145655
145783
  );
145656
145784
  }
145785
+ var BUILD_UNKNOWN_STAGE = "macos_app_locate";
145786
+ function buildUnknownError(bundleId) {
145787
+ return macosFailure(
145788
+ `No copy of ${bundleId} that argent started is running. argent cannot find the app's build, so it cannot tell whether a copy that it did not start runs. Start the app with boot-device with macosAppPath (the .app path) on the device ${macosAppIdFromBundleId(bundleId)}: boot-device reports a copy that already runs.`,
145789
+ FAILURE_CODES.MACOS_APP_NOT_RUNNING,
145790
+ BUILD_UNKNOWN_STAGE,
145791
+ "not_found"
145792
+ );
145793
+ }
145794
+ async function noLaunchedCopyError(bundleId) {
145795
+ const appPath = getTrackedMacosApp(bundleId)?.appPath ?? await findMacosAppByBundleId(bundleId);
145796
+ let info;
145797
+ try {
145798
+ info = appPath ? await inspectMacosApp(appPath) : void 0;
145799
+ } catch {
145800
+ info = void 0;
145801
+ }
145802
+ if (!info || info.bundleId !== bundleId) return buildUnknownError(bundleId);
145803
+ const copies = await findRunningCopies(bundleId, info.executable);
145804
+ const refuse = (message) => macosFailure(
145805
+ message,
145806
+ FAILURE_CODES.MACOS_APP_ALREADY_RUNNING,
145807
+ "macos_app_reconnect",
145808
+ "validation"
145809
+ );
145810
+ if (copies.same.length > 0) {
145811
+ return refuse(
145812
+ `${bundleId} is running (pid ${copies.same.join(", ")}) without the argent library: argent did not start that copy, and argent drives only a copy that it starts. launch-app refuses to start a second copy beside it. That copy may be the user's: ask the user to quit it, or to agree to boot-device with force: true, which quits it and starts the app with the library. Unsaved changes in that copy are lost.`
145813
+ );
145814
+ }
145815
+ if (copies.otherBuilds.length > 0) {
145816
+ const where = copies.otherBuilds.map((b) => `${b.appPath} (pid ${b.pid})`).join(", ");
145817
+ return refuse(
145818
+ `${bundleId} is running from ${where} without the argent library: argent did not start that copy, and argent drives only a copy that it starts. argent runs one copy of a bundle id at a time, so launch-app refuses to start ${info.appPath} beside it. Quit that copy if it is yours.`
145819
+ );
145820
+ }
145821
+ return notRunningError(bundleId);
145822
+ }
145823
+ async function macosLaunchRefusal(bundleId) {
145824
+ if (await runningTrackedApp(bundleId)) return void 0;
145825
+ const tracked = getTrackedMacosApp(bundleId)?.appPath;
145826
+ const appPath = tracked ?? await findMacosAppByBundleId(bundleId);
145827
+ if (!appPath) return void 0;
145828
+ let info;
145829
+ try {
145830
+ info = await inspectMacosApp(appPath);
145831
+ } catch {
145832
+ return void 0;
145833
+ }
145834
+ if (info.bundleId !== bundleId) return void 0;
145835
+ return chromiumRefusal(info) ?? (tracked ? hardenedRuntimeRefusal(info) : void 0) ?? void 0;
145836
+ }
145657
145837
  function errorMessage2(err) {
145658
145838
  return err instanceof Error ? err.message : String(err);
145659
145839
  }
@@ -145739,13 +145919,28 @@ function closedByArgentError(bundleId, method) {
145739
145919
  var LibraryChannel = class {
145740
145920
  /**
145741
145921
  * @param expectedPid the app's pid when known; a launch learns it from the helper after the spawn.
145742
- * @param onNetworkEvent receives each network event, with the pid of the process that sent it.
145922
+ * @param network receives the network events and the close.
145743
145923
  */
145744
- constructor(socket, bundleId, expectedPid, onNetworkEvent) {
145924
+ constructor(socket, bundleId, expectedPid, network) {
145745
145925
  this.socket = socket;
145746
145926
  this.bundleId = bundleId;
145747
145927
  this.expectedPid = expectedPid;
145748
- this.onNetworkEvent = onNetworkEvent;
145928
+ this.network = network;
145929
+ this.cdp = createNdjsonCdpRequester(socket, {
145930
+ label: `macos-app ${bundleId}`,
145931
+ send: (frame2) => {
145932
+ const p = frame2.payload;
145933
+ if (p.method === "Network.enable") {
145934
+ this.disableIds.clear();
145935
+ this.enableIds.add(p.id);
145936
+ }
145937
+ if (p.method === "Network.disable") {
145938
+ this.enableIds.clear();
145939
+ this.disableIds.add(p.id);
145940
+ }
145941
+ return writeNdjsonFrame(socket, frame2);
145942
+ }
145943
+ });
145749
145944
  this.ready.catch(() => void 0);
145750
145945
  attachNdjsonReader(socket, {
145751
145946
  onDropped: reportDroppedFrameToStderr(`macos-app ${bundleId}`),
@@ -145759,7 +145954,31 @@ var LibraryChannel = class {
145759
145954
  socket;
145760
145955
  bundleId;
145761
145956
  expectedPid;
145762
- onNetworkEvent;
145957
+ network;
145958
+ /** The CDP requests of the network capture, such as Network.enable. */
145959
+ cdp;
145960
+ /** The library acknowledged Network.enable on this channel. */
145961
+ armed = false;
145962
+ /** The Network.enable on its way, resolved by the acknowledgement. */
145963
+ enabling;
145964
+ /** Resolves `enabling` as armed when the acknowledgement of an earlier Network.enable arms the channel first. */
145965
+ armEnabling;
145966
+ /** Why the last Network.enable did not arm this channel. */
145967
+ enableFailure;
145968
+ /** A stop's Network.disable timed out, and no acknowledgement of a Network.disable came since. */
145969
+ stopUnconfirmed = false;
145970
+ /** Confirms the waiting stop when the acknowledgement of an earlier Network.disable comes first. */
145971
+ confirmDisabling;
145972
+ /**
145973
+ * The CDP ids of the Network.enable requests sent on this channel since its
145974
+ * last Network.disable: an acknowledgement of any of them arms it.
145975
+ */
145976
+ enableIds = /* @__PURE__ */ new Set();
145977
+ /**
145978
+ * The CDP ids of the Network.disable requests sent on this channel since its
145979
+ * last Network.enable: an acknowledgement of any of them confirms a stop.
145980
+ */
145981
+ disableIds = /* @__PURE__ */ new Set();
145763
145982
  pending = /* @__PURE__ */ new Map();
145764
145983
  nextId = 1;
145765
145984
  hello = null;
@@ -145818,11 +146037,6 @@ var LibraryChannel = class {
145818
146037
  );
145819
146038
  });
145820
146039
  }
145821
- /** A `Control` command, which the library does not answer. */
145822
- sendControl(command) {
145823
- if (this.closeError) return;
145824
- this.socket.write(JSON.stringify({ type: "Control", payload: { command } }) + "\n");
145825
- }
145826
146040
  close() {
145827
146041
  this.closedByArgent = true;
145828
146042
  this.socket.destroy();
@@ -145843,11 +146057,16 @@ var LibraryChannel = class {
145843
146057
  }
145844
146058
  if (msg.type === "CDP") {
145845
146059
  const p = msg.payload;
146060
+ if (p && typeof p.id === "number" && this.enableIds.has(p.id) && "result" in p) {
146061
+ this.network.enabled(this);
146062
+ }
146063
+ if (p && typeof p.id === "number" && this.disableIds.has(p.id) && "result" in p) {
146064
+ this.stopUnconfirmed = false;
146065
+ this.confirmDisabling?.();
146066
+ }
146067
+ if (this.cdp.handleResponse(p)) return;
145846
146068
  if (p && typeof p.method === "string" && p.id === void 0) {
145847
- this.onNetworkEvent(
145848
- { method: p.method, params: p.params, timestamp: Date.now() },
145849
- this.hello.pid
145850
- );
146069
+ this.network.event(p.method, p.params, this.hello.pid);
145851
146070
  }
145852
146071
  return;
145853
146072
  }
@@ -145882,10 +146101,13 @@ var LibraryChannel = class {
145882
146101
  "unknown"
145883
146102
  )
145884
146103
  );
146104
+ this.network.closed(this);
145885
146105
  }
145886
146106
  fail(err) {
145887
146107
  if (this.closeError) return;
145888
146108
  this.closeError = err;
146109
+ this.armed = false;
146110
+ this.cdp.close();
145889
146111
  this.settleHello.reject(err);
145890
146112
  for (const call of this.pending.values()) {
145891
146113
  clearTimeout(call.timer);
@@ -145967,6 +146189,28 @@ async function helperPid(child, executable) {
145967
146189
  }
145968
146190
  var lifecycles = /* @__PURE__ */ new Map();
145969
146191
  var heldQuits = /* @__PURE__ */ new Map();
146192
+ function connectionClosedBefore(bundleId, method) {
146193
+ return new FailureError(
146194
+ `macos-app ${bundleId}: the connection closed before ${method} was answered`,
146195
+ {
146196
+ error_code: FAILURE_CODES.NDJSON_CDP_CONNECTION_CLOSED,
146197
+ failure_stage: "ndjson_cdp_request",
146198
+ failure_area: "tool_server",
146199
+ error_kind: "network"
146200
+ }
146201
+ );
146202
+ }
146203
+ var macosCaptures = /* @__PURE__ */ new Set();
146204
+ function findMacosNativeRecord(id) {
146205
+ for (const { records } of macosCaptures) {
146206
+ const record2 = records.record(id);
146207
+ if (record2) return { records, record: record2 };
146208
+ }
146209
+ return void 0;
146210
+ }
146211
+ function hasMacosNetworkCapture() {
146212
+ return [...macosCaptures].some(({ captured }) => captured());
146213
+ }
145970
146214
  async function waitWhileSuspended(watch, method) {
145971
146215
  const since = watch.suspendedSince();
145972
146216
  if (since === null) return;
@@ -145983,26 +146227,109 @@ function createMacosAppApi(bundleId) {
145983
146227
  let connecting = null;
145984
146228
  let launching = false;
145985
146229
  let disposed = false;
145986
- let networkInspection = false;
145987
- let networkLog = [];
145988
- let networkLogPid = null;
145989
- const networkLogOf = (pid) => {
145990
- if (pid !== networkLogPid) {
145991
- networkLog = [];
145992
- networkLogPid = pid;
145993
- }
145994
- return networkLog;
145995
- };
145996
- const recordNetworkEvent = (event2, pid) => {
145997
- const log = networkLogOf(pid);
145998
- if (log.length >= NATIVE_NETWORK_LOG_LIMIT) log.shift();
145999
- log.push(event2);
146000
- };
146001
- const adopt = (ch) => {
146230
+ let captureStarted = false;
146231
+ let captureStopped = false;
146232
+ let captureGap = false;
146233
+ let armedSinceLaunch = false;
146234
+ let recordedProcess = null;
146235
+ let nextProcessIndex = 1;
146236
+ const liveChannel = () => channel?.isOpen && channel.handshake ? channel : null;
146237
+ const captureState = () => {
146238
+ const ch = liveChannel();
146239
+ if (!ch) {
146240
+ return {
146241
+ armed: false,
146242
+ note: captureStarted ? "the app is not connected; capture arms when argent starts the app or connects to it, as network-capture-start does" : "the app is not connected"
146243
+ };
146244
+ }
146245
+ return {
146246
+ armed: ch.armed,
146247
+ pid: ch.handshake.pid,
146248
+ ...ch.armed ? {} : ch.enabling ? { note: "waiting for the app to acknowledge Network.enable" } : ch.enableFailure ? { note: ch.enableFailure } : {}
146249
+ };
146250
+ };
146251
+ const records = createIosNetworkRecords(
146252
+ captureState,
146253
+ {
146254
+ liveConnection: () => {
146255
+ const ch = liveChannel();
146256
+ return ch && recordedProcess?.pid === ch.handshake.pid ? recordedProcess.index : void 0;
146257
+ },
146258
+ request: (index, method, params, timeoutMs) => {
146259
+ const ch = liveChannel();
146260
+ return ch && recordedProcess?.index === index && recordedProcess.pid === ch.handshake.pid ? ch.cdp.request(method, params, { timeoutMs }) : Promise.reject(connectionClosedBefore(bundleId, method));
146261
+ }
146262
+ },
146263
+ () => captureStarted,
146264
+ "macos-native"
146265
+ );
146266
+ const capture = { records, captured: () => captureStarted || captureStopped };
146267
+ macosCaptures.add(capture);
146268
+ const network = {
146269
+ event(method, params, pid) {
146270
+ if (recordedProcess?.pid === pid) records.fold(recordedProcess.index, method, params);
146271
+ },
146272
+ closed(ch) {
146273
+ const process2 = recordedProcess;
146274
+ if (!ch.handshake || process2?.pid !== ch.handshake.pid) return;
146275
+ void pollPidsUntilGone([process2.pid], {
146276
+ timeoutMs: PROCESS_EXIT_WAIT_MS,
146277
+ pollIntervalMs: POLL_MS
146278
+ }).then((left) => {
146279
+ if (disposed) return;
146280
+ if (left.length === 0) {
146281
+ records.connectionClosed(process2.index, { superseded: false, running: false });
146282
+ } else if (recordedProcess?.channel === ch) {
146283
+ records.connectionClosed(process2.index, { superseded: false, running: true });
146284
+ }
146285
+ });
146286
+ },
146287
+ enabled(ch) {
146288
+ if (!captureStarted) return;
146289
+ ch.armed = true;
146290
+ delete ch.enableFailure;
146291
+ ch.armEnabling?.();
146292
+ }
146293
+ };
146294
+ const enableOn = (ch) => {
146295
+ if (ch.armed) return Promise.resolve(true);
146296
+ if (ch.enabling) return ch.enabling;
146297
+ delete ch.enableFailure;
146298
+ const enabling = new Promise((resolve21) => {
146299
+ ch.armEnabling = () => resolve21(true);
146300
+ ch.cdp.request("Network.enable", {}, { timeoutMs: NETWORK_CAPTURE_ACK_TIMEOUT_MS }).then(
146301
+ () => resolve21(ch.armed),
146302
+ (err) => {
146303
+ if (ch.isOpen && !disposed && !ch.armed) {
146304
+ ch.enableFailure = getFailureSignal(err)?.error_kind === "timeout" ? `the app did not acknowledge Network.enable within ${NETWORK_CAPTURE_ACK_TIMEOUT_MS / 1e3} s; network-capture-start asks again` : `the app did not enable capture (${errorMessage2(err)}); network-capture-start asks again`;
146305
+ }
146306
+ resolve21(false);
146307
+ }
146308
+ );
146309
+ }).finally(() => {
146310
+ if (ch.enabling !== enabling) return;
146311
+ ch.enabling = void 0;
146312
+ ch.armEnabling = void 0;
146313
+ });
146314
+ ch.enabling = enabling;
146315
+ return enabling;
146316
+ };
146317
+ const adopt = (ch, launched = false) => {
146002
146318
  if (channel !== ch) channel?.close();
146003
146319
  channel = ch;
146004
- networkLogOf(ch.handshake.pid);
146005
- if (networkInspection) ch.sendControl("activateNetworkInspection");
146320
+ const pid = ch.handshake.pid;
146321
+ if (recordedProcess?.pid !== pid) {
146322
+ if (recordedProcess) {
146323
+ records.connectionClosed(recordedProcess.index, { superseded: true });
146324
+ }
146325
+ recordedProcess = { pid, index: nextProcessIndex++, channel: ch };
146326
+ captureGap = captureStarted && !launched;
146327
+ armedSinceLaunch = launched && captureStarted;
146328
+ } else if (recordedProcess.channel !== ch) {
146329
+ records.connectionClosed(recordedProcess.index, { superseded: false, running: true });
146330
+ recordedProcess.channel = ch;
146331
+ }
146332
+ if (captureStarted) void enableOn(ch);
146006
146333
  };
146007
146334
  const closeChannel = () => {
146008
146335
  channel?.close();
@@ -146010,7 +146337,7 @@ function createMacosAppApi(bundleId) {
146010
146337
  };
146011
146338
  const reconnect = async () => {
146012
146339
  const app = await runningTrackedApp(bundleId);
146013
- if (!app) throw notRunningError(bundleId);
146340
+ if (!app) throw await noLaunchedCopyError(bundleId);
146014
146341
  const notConnected3 = (detail, cause) => macosFailure(
146015
146342
  `${bundleId} is running (pid ${app.pid}) but argent cannot reach its library: ${detail} If it is paused in a debugger, continue it and try again. Otherwise run restart-app to start it again with the library.`,
146016
146343
  FAILURE_CODES.MACOS_APP_NOT_CONNECTED,
@@ -146030,7 +146357,7 @@ function createMacosAppApi(bundleId) {
146030
146357
  net8.createConnection(app.listenSocket),
146031
146358
  bundleId,
146032
146359
  app.pid,
146033
- recordNetworkEvent
146360
+ network
146034
146361
  );
146035
146362
  try {
146036
146363
  await ch.waitForHandshake(RECONNECT_TIMEOUT_MS);
@@ -146319,12 +146646,7 @@ function createMacosAppApi(bundleId) {
146319
146646
  } catch (err) {
146320
146647
  throw helperLaunchFailure(info.executable, errorMessage2(err), err);
146321
146648
  }
146322
- const ch = new LibraryChannel(
146323
- helper.stdio[3],
146324
- bundleId,
146325
- null,
146326
- recordNetworkEvent
146327
- );
146649
+ const ch = new LibraryChannel(helper.stdio[3], bundleId, null, network);
146328
146650
  let pid;
146329
146651
  try {
146330
146652
  pid = await helperPid(helper, info.executable);
@@ -146393,7 +146715,7 @@ function createMacosAppApi(bundleId) {
146393
146715
  sandboxed: info.sandboxed,
146394
146716
  logPath
146395
146717
  };
146396
- adopt(ch);
146718
+ adopt(ch, true);
146397
146719
  const { note: noWindow, refusal: noDrivableWindow } = await waitForFirstWindow(
146398
146720
  ch,
146399
146721
  pid,
@@ -146469,20 +146791,91 @@ function createMacosAppApi(bundleId) {
146469
146791
  },
146470
146792
  isConnected: () => Boolean(channel?.isOpen && channel.handshake),
146471
146793
  handshake: () => channel?.isOpen ? channel.handshake : null,
146472
- async activateNetworkInspection() {
146473
- networkInspection = true;
146794
+ async startNetworkCapture() {
146795
+ captureStopped = false;
146796
+ const startedNow = !captureStarted;
146797
+ captureStarted = true;
146798
+ if (channel) channel.stopUnconfirmed = false;
146799
+ const servicesStopped = {
146800
+ armed: false,
146801
+ reason: "the app's services stopped during this start, which ended the capture; call network-capture-start again"
146802
+ };
146474
146803
  await lifecycles.get(bundleId)?.settled;
146475
- (await ensureChannel()).sendControl("activateNetworkInspection");
146804
+ if (disposed) return servicesStopped;
146805
+ let ch;
146806
+ try {
146807
+ ch = await ensureChannel();
146808
+ } catch (err) {
146809
+ if (disposed) return servicesStopped;
146810
+ const code = errorCode(err);
146811
+ const notRunning = code === FAILURE_CODES.MACOS_APP_NOT_RUNNING;
146812
+ const buildUnknown = notRunning && getFailureSignal(err)?.failure_stage === BUILD_UNKNOWN_STAGE;
146813
+ const notOurs = code === FAILURE_CODES.MACOS_APP_ALREADY_RUNNING;
146814
+ if (!notRunning && !notOurs && startedNow && !armedSinceLaunch) captureGap = true;
146815
+ return {
146816
+ armed: false,
146817
+ reason: buildUnknown ? `no copy of ${bundleId} that argent started is running, and argent cannot find the app's build to look for another copy; capture arms when boot-device with macosAppPath starts it` : notRunning ? `${bundleId} is not running; capture arms when boot-device, launch-app or restart-app starts it` : notOurs ? `capture arms when argent starts ${bundleId}, which needs the copy that runs now to quit first: ${errorMessage2(err)}` : `argent cannot reach ${bundleId}, so capture arms when argent connects to it: ${errorMessage2(err)}`
146818
+ };
146819
+ }
146820
+ if (startedNow && !armedSinceLaunch) captureGap = true;
146821
+ const armed = await enableOn(ch);
146822
+ if (disposed) return servicesStopped;
146823
+ if (armed) return { armed };
146824
+ return { armed, reason: captureState().note ?? "the app did not acknowledge Network.enable" };
146476
146825
  },
146477
- networkLog: () => [...networkLog],
146478
- clearNetworkLog: () => {
146479
- networkLog.length = 0;
146480
- }
146826
+ async stopNetworkCapture() {
146827
+ captureStopped = true;
146828
+ captureStarted = false;
146829
+ captureGap = false;
146830
+ armedSinceLaunch = false;
146831
+ const ch = liveChannel();
146832
+ if (!ch) return { confirmed: true };
146833
+ ch.armed = false;
146834
+ ch.enabling = void 0;
146835
+ ch.armEnabling = void 0;
146836
+ delete ch.enableFailure;
146837
+ let confirm;
146838
+ const disabling = new Promise((resolve21, reject) => {
146839
+ confirm = resolve21;
146840
+ ch.cdp.request("Network.disable", {}, { timeoutMs: NETWORK_CAPTURE_ACK_TIMEOUT_MS }).then(() => resolve21(), reject);
146841
+ });
146842
+ ch.confirmDisabling = confirm;
146843
+ try {
146844
+ await disabling;
146845
+ return { confirmed: true };
146846
+ } catch (err) {
146847
+ if (disposed) {
146848
+ return {
146849
+ confirmed: true,
146850
+ reason: "the app's services stopped during this stop, which dropped the requests it recorded"
146851
+ };
146852
+ }
146853
+ if (!ch.isOpen) return { confirmed: true };
146854
+ if (captureStopped) ch.stopUnconfirmed = true;
146855
+ return {
146856
+ confirmed: false,
146857
+ reason: `${getFailureSignal(err)?.error_kind === "timeout" ? `the app did not acknowledge Network.disable within ${NETWORK_CAPTURE_ACK_TIMEOUT_MS / 1e3} s` : `the app did not disable capture (${errorMessage2(err)})`}; argent records none of its new requests, and its next process starts without capture`
146858
+ };
146859
+ } finally {
146860
+ if (ch.confirmDisabling === confirm) ch.confirmDisabling = void 0;
146861
+ }
146862
+ },
146863
+ isNetworkCaptureStarted: () => captureStarted,
146864
+ isNetworkCaptureStopped: () => captureStopped,
146865
+ isNetworkCaptureStopUnconfirmed: () => liveChannel()?.stopUnconfirmed === true,
146866
+ takeCaptureGap: () => {
146867
+ const gap = captureGap;
146868
+ captureGap = false;
146869
+ return gap;
146870
+ },
146871
+ networkRecords: () => records
146481
146872
  };
146482
146873
  return {
146483
146874
  api,
146484
146875
  dispose: () => {
146485
146876
  disposed = true;
146877
+ macosCaptures.delete(capture);
146878
+ records.clear();
146486
146879
  if (!launching) closeChannel();
146487
146880
  }
146488
146881
  };
@@ -148086,8 +148479,8 @@ function isAllowedSourceMapURL(raw) {
148086
148479
  }
148087
148480
  if (parsed2.protocol !== "http:" && parsed2.protocol !== "https:") return false;
148088
148481
  if (!parsed2.pathname.endsWith(".map")) return false;
148089
- const hostname4 = parsed2.hostname.startsWith("[") && parsed2.hostname.endsWith("]") ? parsed2.hostname.slice(1, -1) : parsed2.hostname;
148090
- return ALLOWED_SOURCE_MAP_HOSTS.has(hostname4);
148482
+ const hostname5 = parsed2.hostname.startsWith("[") && parsed2.hostname.endsWith("]") ? parsed2.hostname.slice(1, -1) : parsed2.hostname;
148483
+ return ALLOWED_SOURCE_MAP_HOSTS.has(hostname5);
148091
148484
  }
148092
148485
  var MAX_SOURCE_MAP_BYTES = 64 * 1024 * 1024;
148093
148486
  async function drainCappedBody(res, maxBytes = MAX_SOURCE_MAP_BYTES) {
@@ -148690,9 +149083,9 @@ function trackDebuggerOutcome(tool, outcome, params, ctx) {
148690
149083
  ...ctx?.toolInvocationId ? { tool_invocation_id: ctx.toolInvocationId } : {}
148691
149084
  });
148692
149085
  }
148693
- async function resolveDebuggerService(registry2, params) {
149086
+ async function resolveDebuggerService(registry2, params, options) {
148694
149087
  const ref = debuggerServiceRef(params);
148695
- return typeof ref === "string" ? registry2.resolveService(ref) : registry2.resolveService(ref.urn, ref.options);
149088
+ return typeof ref === "string" ? registry2.resolveService(ref, options) : registry2.resolveService(ref.urn, ref.options);
148696
149089
  }
148697
149090
  function isDebuggerNotConnectedResult(toolId, result) {
148698
149091
  return (toolId === "debugger-status" || toolId === "debugger-log-registry") && typeof result === "object" && result !== null && result.status === "not_connected";
@@ -149041,8 +149434,8 @@ function createHttpApp(registry2, options) {
149041
149434
  res.status(400).json({ error: "Missing Host header" });
149042
149435
  return;
149043
149436
  }
149044
- const hostname4 = extractHostname(host);
149045
- if (!allowedHostnames.has(hostname4)) {
149437
+ const hostname5 = extractHostname(host);
149438
+ if (!allowedHostnames.has(hostname5)) {
149046
149439
  res.status(403).json({
149047
149440
  error: `Refusing request with Host "${host}". The tool-server accepts loopback hostnames (127.0.0.1, localhost, ::1)` + (isLoopbackHost(bindHost) ? "" : ` and its bind host (${bindHost})`) + ` to defend against DNS-rebinding. If you are reaching this from your own client, use one of those instead of a public hostname.`
149048
149441
  });
@@ -149951,11 +150344,16 @@ var ARM_PROCESS_CHECK_MS = 500;
149951
150344
  var RECHECK_DELAYS_MS = [500, 1e3, 2e3, 4e3, 8e3];
149952
150345
  var ENABLE_TIMEOUT_MS = 6e4;
149953
150346
  var DISABLE_TIMEOUT_MS = 1e3;
150347
+ var STOP_DISABLE_TIMEOUT_MS = 5e3;
149954
150348
  var SESSION_REMOVE_TIMEOUT_MS = 5e3;
149955
150349
  var AGENT_BINARIES_MISSING_REASON = "agent binaries not present in this build";
149956
150350
  var AGENT_GONE_REASON = "the agent that recorded the request is no longer in the app, as after an emulator snapshot load";
149957
150351
  var LOST_WHILE_DISCONNECTED = "the agent lost this request's final events while it was disconnected";
149958
- var JS_LAYER_FALLBACK = "Use view-network-logs: the JS layer still records the app's JavaScript requests while Metro serves the app.";
150352
+ var STOPPED_BEFORE_FINISH = "capture stopped before the request finished";
150353
+ var DROPPED_NOTE = "the agent's connection dropped; it reconnects by itself while the app runs";
150354
+ var NOT_RECONNECTED_NOTE = "the agent's connection dropped, and it did not reconnect; network-capture-start connects it again";
150355
+ var STOPPED_NOTE = "capture stopped by network-capture-stop; network-capture-start turns it on again";
150356
+ var AWAY_AT_STOP = "the agent's connection was down at the stop, so it did not get Network.disable; it gets it when it connects again, and argent records none of the app's new requests meanwhile";
149959
150357
  var LOGGED_DETAIL_EVENTS = /* @__PURE__ */ new Set(["interceptor_installed", "interceptor_failed"]);
149960
150358
  var RUN_TAG2 = (0, import_node_crypto13.randomBytes)(2).toString("hex");
149961
150359
  var ANDROID_NATIVE_REQUEST_ID = /^android-[0-9a-f]{4}-\d+$/;
@@ -149971,8 +150369,14 @@ function findAndroidNativeRecord(id) {
149971
150369
  }
149972
150370
  return void 0;
149973
150371
  }
150372
+ function hasAndroidNetworkCapture() {
150373
+ return allHandles().some((handle) => handle.isLive() || handle.isStopped());
150374
+ }
150375
+ function stoppedLaunchNote(packageName) {
150376
+ return `native network capture is stopped for ${packageName} (network-capture-stop); this process runs without it until network-capture-start`;
150377
+ }
149974
150378
  function liveAndroidNetworkCaptures(deviceId) {
149975
- return [...liveInspectors.get(deviceKeyOf(deviceId)) ?? []].filter((handle) => handle.isLive()).map((handle) => handle.packageName).sort();
150379
+ return [...liveInspectors.get(deviceKeyOf(deviceId)) ?? []].filter((handle) => handle.mayIntercept()).map((handle) => handle.packageName).sort();
149976
150380
  }
149977
150381
  function liveAndroidNetworkCaptureSerials() {
149978
150382
  return liveCaptureSerials(() => true);
@@ -149981,13 +150385,15 @@ function liveAndroidNetworkCaptureDevices(packageName) {
149981
150385
  return liveCaptureSerials((handle) => handle.packageName === packageName);
149982
150386
  }
149983
150387
  function liveCaptureSerials(matches2) {
149984
- const serials = allHandles().filter((handle) => matches2(handle) && handle.isLive()).map((handle) => handle.serial);
150388
+ const serials = allHandles().filter((handle) => matches2(handle) && handle.mayIntercept()).map((handle) => handle.serial);
149985
150389
  return [...new Set(serials)].sort();
149986
150390
  }
149987
150391
  async function attachAndroidNetworkInspectorToLaunch(deviceId, packageName) {
149988
150392
  try {
149989
150393
  for (const handle of liveInspectors.get(deviceKeyOf(deviceId)) ?? []) {
149990
- if (handle.packageName !== packageName || !handle.isLive()) continue;
150394
+ if (handle.packageName !== packageName) continue;
150395
+ if (handle.isStopped()) return await handle.stoppedLaunch();
150396
+ if (!handle.isLive()) continue;
149991
150397
  return await handle.attachLaunch();
149992
150398
  }
149993
150399
  } catch (err) {
@@ -150060,6 +150466,11 @@ function createInspector(serial, packageName, initialMetroPort) {
150060
150466
  let metroPort2 = initialMetroPort;
150061
150467
  let disposed = false;
150062
150468
  let live = false;
150469
+ let stopped = false;
150470
+ let stops = 0;
150471
+ let notAttached = false;
150472
+ let mark;
150473
+ let unavailableReason;
150063
150474
  let ready2 = false;
150064
150475
  let gates = null;
150065
150476
  let appUser = 0;
@@ -150072,6 +150483,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150072
150483
  let sessionPort = 0;
150073
150484
  const attachedProcesses = /* @__PURE__ */ new Set();
150074
150485
  let note;
150486
+ let startNote;
150075
150487
  let awaiting = null;
150076
150488
  const pendingSockets = /* @__PURE__ */ new Set();
150077
150489
  const connections2 = [];
@@ -150082,20 +150494,21 @@ function createInspector(serial, packageName, initialMetroPort) {
150082
150494
  const bodies = /* @__PURE__ */ new Map();
150083
150495
  const cleared = /* @__PURE__ */ new WeakSet();
150084
150496
  const lostOnly = /* @__PURE__ */ new WeakSet();
150497
+ const failedAtStopTimeout = /* @__PURE__ */ new WeakSet();
150085
150498
  const hops = /* @__PURE__ */ new WeakMap();
150086
150499
  const startArrivals = /* @__PURE__ */ new WeakMap();
150087
150500
  const armWaiters = /* @__PURE__ */ new Set();
150088
150501
  const attachLock = /* @__PURE__ */ new Map();
150089
150502
  const tunnelLock = /* @__PURE__ */ new Map();
150090
150503
  const rechecks = /* @__PURE__ */ new Map();
150504
+ const missedStop = /* @__PURE__ */ new Set();
150091
150505
  const user = () => appUser;
150092
150506
  const checkpoint = () => {
150093
- if (disposed) throw new InspectorStopped();
150507
+ if (disposed || stopped) throw new InspectorStopped();
150094
150508
  };
150095
150509
  const notAttachable = (reason2) => ({
150096
150510
  status: "not_attachable",
150097
- reason: reason2,
150098
- fallback: JS_LAYER_FALLBACK
150511
+ reason: reason2
150099
150512
  });
150100
150513
  function sessionLine(port) {
150101
150514
  return `${JSON.stringify({ v: PROTOCOL_VERSION, port, secret })}
@@ -150188,7 +150601,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150188
150601
  );
150189
150602
  if (other) {
150190
150603
  throw new FailureError(
150191
- `${packageName} on this device is already inspected through adb serial ${other.serial}, and ${serial} is another connection to the same device. Use ${other.serial}, or end that capture first with native-network-logs and stop: true on ${other.serial}.`,
150604
+ `${packageName} on this device is already inspected through adb serial ${other.serial}, and ${serial} is another connection to the same device. Use ${other.serial}, or end that capture first with stop-all-simulator-servers for ${other.serial}.`,
150192
150605
  {
150193
150606
  error_code: FAILURE_CODES.ANDROID_NETWORK_INSPECTOR_DEVICE_IN_USE,
150194
150607
  failure_stage: "android_network_inspector_device_identity",
@@ -150255,7 +150668,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150255
150668
  }
150256
150669
  async function assertReverse() {
150257
150670
  await withKeyedLock(tunnelLock, "tunnel", async () => {
150258
- checkpoint();
150671
+ if (disposed) throw new InspectorStopped();
150259
150672
  if (devicePort !== 0) {
150260
150673
  try {
150261
150674
  await adbReverse(serial, devicePort, hostPort, { timeoutMs: 1e4 });
@@ -150283,7 +150696,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150283
150696
  } catch (err) {
150284
150697
  if (!isPortTaken(err)) throw err;
150285
150698
  log(`device port ${port} is taken; trying another`);
150286
- checkpoint();
150699
+ if (disposed) throw new InspectorStopped();
150287
150700
  continue;
150288
150701
  }
150289
150702
  devicePort = port;
@@ -150345,8 +150758,9 @@ function createInspector(serial, packageName, initialMetroPort) {
150345
150758
  }
150346
150759
  if (copy === "loaded") {
150347
150760
  if (known) return "known";
150348
- note = `pid ${proc.pid} already has the agent loaded, and it should connect within a few seconds. If it does not, another Argent tool-server is capturing this app or the agent is from an earlier Argent; restart-app gives the app a new process with this tool-server's agent, but it ends the other tool-server's capture of the app`;
150761
+ note = `pid ${proc.pid} already has the agent loaded, and it should connect within a few seconds. If it does not, another Argent tool-server holds the agent's connection, also after a network-capture-stop there, or the agent is from an earlier Argent; restart-app gives the app a new process with this tool-server's agent, but it ends the other tool-server's connection to the app; after restart-app, call network-capture-start again, since a relaunch ends the JS layer's capture`;
150349
150762
  awaiting = { key: key2, note, since };
150763
+ notAttached = false;
150350
150764
  log(`pid ${proc.pid} already has the agent loaded`);
150351
150765
  return "loaded";
150352
150766
  }
@@ -150356,7 +150770,12 @@ function createInspector(serial, packageName, initialMetroPort) {
150356
150770
  }
150357
150771
  log(`pid ${proc.pid} lost the agent, as after an emulator snapshot load; attaching again`);
150358
150772
  }
150359
- checkpoint();
150773
+ try {
150774
+ checkpoint();
150775
+ } catch (err) {
150776
+ attachedProcesses.delete(key2);
150777
+ throw err;
150778
+ }
150360
150779
  const dir = agentDirFor(packageName, user());
150361
150780
  const agentOptions = `jar=${dir}/${JAR_NAME},pkg=${packageName}`;
150362
150781
  try {
@@ -150369,13 +150788,14 @@ function createInspector(serial, packageName, initialMetroPort) {
150369
150788
  } catch (err) {
150370
150789
  attachedProcesses.delete(key2);
150371
150790
  checkpoint();
150372
- note = `attach-agent failed for pid ${proc.pid} (${firstLine3(adbFailureDetail(err))}); the next native-network-logs call or launch tries again`;
150791
+ note = `attach-agent failed for pid ${proc.pid} (${firstLine3(adbFailureDetail(err))}); the next launch or network-capture-start tries again`;
150373
150792
  log(note);
150374
150793
  return "attach_failed";
150375
150794
  }
150376
150795
  checkpoint();
150377
150796
  note = `attached to pid ${proc.pid}; waiting for the agent to connect`;
150378
150797
  awaiting = { key: key2, note, since };
150798
+ notAttached = false;
150379
150799
  log(`attached the agent to pid ${proc.pid}`);
150380
150800
  return "attached";
150381
150801
  }
@@ -150570,6 +150990,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150570
150990
  phase = "ready";
150571
150991
  conn = openConnection(socket, cdp, send, handshake);
150572
150992
  sendMetroPort(conn);
150993
+ if (missedStop.delete(handshake.instance)) conn.afterMissedStop = true;
150573
150994
  enableNetwork(conn);
150574
150995
  return;
150575
150996
  }
@@ -150600,6 +151021,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150600
151021
  function openConnection(socket, cdp, send, handshake) {
150601
151022
  const key2 = `${handshake.pid}:${handshake.startTime}`;
150602
151023
  if (awaiting?.key === key2) awaiting = null;
151024
+ notAttached = false;
150603
151025
  for (const c of connections2) {
150604
151026
  if (c.closed || c.instance !== handshake.instance) continue;
150605
151027
  c.closed = true;
@@ -150620,6 +151042,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150620
151042
  armed: false,
150621
151043
  closed: false,
150622
151044
  droppedEvents: 0,
151045
+ enabling: false,
150623
151046
  byLayerId: /* @__PURE__ */ new Map()
150624
151047
  };
150625
151048
  const dropped = [...connections2].reverse().find((c) => c.closed && c.instance === handshake.instance && !c.resumedBy && !c.agentGone);
@@ -150653,15 +151076,27 @@ function createInspector(serial, packageName, initialMetroPort) {
150653
151076
  return max;
150654
151077
  }
150655
151078
  function enableNetwork(conn) {
151079
+ conn.enabling = true;
151080
+ conn.disabled = false;
151081
+ const stopsBefore = stops;
151082
+ const stale = () => stops !== stopsBefore;
150656
151083
  conn.cdp.request(
150657
151084
  "Network.enable",
150658
151085
  {},
150659
- { timeoutMs: ENABLE_TIMEOUT_MS, onResult: (result) => onEnabled(conn, result) }
151086
+ {
151087
+ timeoutMs: ENABLE_TIMEOUT_MS,
151088
+ onResult: (result) => {
151089
+ if (stale() && !stopped) return;
151090
+ conn.enabling = false;
151091
+ onEnabled(conn, result);
151092
+ }
151093
+ }
150660
151094
  ).catch((err) => {
150661
- if (conn.closed || disposed) {
151095
+ if (conn.closed || disposed || stale()) {
150662
151096
  log(`Network.enable on connection ${conn.index} failed: ${errorMessage3(err)}`);
150663
151097
  return;
150664
151098
  }
151099
+ conn.enabling = false;
150665
151100
  if (getFailureSignal(err)?.error_kind === "timeout") {
150666
151101
  connectionClosed(
150667
151102
  conn,
@@ -150676,6 +151111,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150676
151111
  }
150677
151112
  function onEnabled(conn, result) {
150678
151113
  if (conn.closed || disposed) return;
151114
+ conn.afterMissedStop = false;
150679
151115
  const r = asObject(result);
150680
151116
  const capture = parseCapture(r.capture);
150681
151117
  if (capture) conn.capture = capture;
@@ -150692,10 +151128,55 @@ function createInspector(serial, packageName, initialMetroPort) {
150692
151128
  }
150693
151129
  }
150694
151130
  }
151131
+ if (stopped) {
151132
+ void disableOn(conn, STOP_DISABLE_TIMEOUT_MS);
151133
+ return;
151134
+ }
150695
151135
  conn.armed = true;
150696
151136
  note = void 0;
150697
151137
  for (const wake of armWaiters) wake();
150698
151138
  }
151139
+ function disableOn(conn, timeoutMs) {
151140
+ return conn.cdp.request(
151141
+ "Network.disable",
151142
+ {},
151143
+ {
151144
+ timeoutMs,
151145
+ onResult: () => {
151146
+ if (stopped) conn.disabled = true;
151147
+ failStopped(conn);
151148
+ }
151149
+ }
151150
+ ).then(
151151
+ () => {
151152
+ conn.stopUnconfirmed = false;
151153
+ return true;
151154
+ },
151155
+ (err) => {
151156
+ if (conn.closed || disposed) return true;
151157
+ log(`Network.disable on connection ${conn.index} failed: ${errorMessage3(err)}`);
151158
+ if (stopped) conn.stopUnconfirmed = true;
151159
+ if (stopped && getFailureSignal(err)?.error_kind === "timeout") failStopped(conn, true);
151160
+ return false;
151161
+ }
151162
+ );
151163
+ }
151164
+ function failStopped(conn, settleLater = false) {
151165
+ const open5 = [];
151166
+ for (let c = conn; c; c = c.resumes) {
151167
+ for (const record2 of c.byLayerId.values()) {
151168
+ if (isOpen(record2) || lostOnly.has(record2)) open5.push(record2);
151169
+ }
151170
+ }
151171
+ for (const record2 of open5) {
151172
+ lostOnly.delete(record2);
151173
+ if (settleLater) failedAtStopTimeout.add(record2);
151174
+ record2.state = "failed";
151175
+ record2.errorText = STOPPED_BEFORE_FINISH;
151176
+ cleared.delete(record2);
151177
+ }
151178
+ for (const record2 of open5) resize(record2);
151179
+ }
150699
151180
  function onStatus(conn, payload) {
150700
151181
  const event2 = asString2(payload.event);
150701
151182
  if (event2 === "capture") {
@@ -150717,7 +151198,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150717
151198
  if (disposed) return;
150718
151199
  log(`agent connection ${conn.index} closed${why ? `: ${why}` : ""}`);
150719
151200
  if (!connections2.some((c) => !c.closed)) {
150720
- note = "the agent's connection dropped; it reconnects by itself while the app runs";
151201
+ note = DROPPED_NOTE;
150721
151202
  }
150722
151203
  const running = rechecks.get(conn.processKey);
150723
151204
  if (running) {
@@ -150752,7 +151233,13 @@ function createInspector(serial, packageName, initialMetroPort) {
150752
151233
  const running = runningKeys(read);
150753
151234
  if (!running.has(key2)) {
150754
151235
  failOrphans(running);
150755
- if (!connections2.some((c) => !c.closed)) note = afterExitNote(read);
151236
+ if (!connections2.some((c) => !c.closed)) {
151237
+ const next = processOfUser(read, read.user ?? appUser);
151238
+ if (!next || !attachedProcesses.has(processKey(next))) {
151239
+ note = afterExitNote(read);
151240
+ notAttached = true;
151241
+ }
151242
+ }
150756
151243
  return;
150757
151244
  }
150758
151245
  await assertReverse().catch(() => {
@@ -150765,18 +151252,21 @@ function createInspector(serial, packageName, initialMetroPort) {
150765
151252
  if (isOpen(record2)) markLost(record2, NOT_RECONNECTED);
150766
151253
  }
150767
151254
  }
151255
+ if (note === DROPPED_NOTE && !connections2.some((c) => !c.closed)) {
151256
+ note = NOT_RECONNECTED_NOTE;
151257
+ }
150768
151258
  } finally {
150769
151259
  if (rechecks.get(key2) === recheck) rechecks.delete(key2);
150770
151260
  if (recheck.restart && !disposed && !reconnected()) void recheckAfterDrop(key2);
150771
151261
  }
150772
151262
  }
150773
151263
  function afterExitNote(read) {
150774
- const trigger = "launch-app, restart-app or the next native-network-logs call attaches the agent";
150775
151264
  const foreground = read.user ?? appUser;
150776
- if (!processOfUser(read, foreground)) {
150777
- return `${packageName} exited; ${trigger} to its new process`;
151265
+ const next = processOfUser(read, foreground);
151266
+ if (!next) {
151267
+ return `the process of ${packageName} that capture was attached to exited, and no later process has capture; launch-app or restart-app attaches capture to the next process, or call network-capture-start once the app runs`;
150778
151268
  }
150779
- return foreground === appUser ? `the app restarted; ${trigger} to its new process` : `Android user ${foreground} is in the foreground now; ${trigger} to that user's process of ${packageName}`;
151269
+ return foreground === appUser ? `the app restarted as pid ${next.pid}, and this tool-server did not attach capture to that process; call network-capture-start to attach it` : `Android user ${foreground} is in the foreground now, and its process of ${packageName} runs without capture; restart-app attaches capture to it, or call network-capture-start`;
150780
151270
  }
150781
151271
  function fold2(conn, method, params) {
150782
151272
  if (typeof params !== "object" || params === null) return;
@@ -150806,7 +151296,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150806
151296
  case "Network.responseReceived": {
150807
151297
  revive(record2);
150808
151298
  const r = asObject(p.response);
150809
- record2.state = "headers";
151299
+ if (!failedAtStopTimeout.has(record2)) record2.state = "headers";
150810
151300
  record2.response = {
150811
151301
  url: capString(asString2(r.url)) || hops.get(record2)?.url || record2.request.url,
150812
151302
  status: typeof r.status === "number" ? r.status : 0,
@@ -150820,6 +151310,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150820
151310
  }
150821
151311
  case "Network.loadingFinished":
150822
151312
  revive(record2);
151313
+ if (failedAtStopTimeout.delete(record2)) delete record2.errorText;
150823
151314
  cleared.delete(record2);
150824
151315
  record2.state = "complete";
150825
151316
  if (typeof p.encodedDataLength === "number") record2.encodedDataLength = p.encodedDataLength;
@@ -150827,6 +151318,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150827
151318
  break;
150828
151319
  case "Network.loadingFailed":
150829
151320
  revive(record2);
151321
+ failedAtStopTimeout.delete(record2);
150830
151322
  cleared.delete(record2);
150831
151323
  record2.state = "failed";
150832
151324
  record2.errorText = capString(asString2(p.errorText)) || "Unknown error";
@@ -150887,6 +151379,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150887
151379
  );
150888
151380
  break;
150889
151381
  }
151382
+ if (stopped || conn.afterMissedStop) return;
150890
151383
  const req = asObject(p.request);
150891
151384
  const startedAt = typeof p.wallTime === "number" ? p.wallTime * 1e3 : typeof p.timestamp === "number" ? p.timestamp * 1e3 : Date.now();
150892
151385
  const record2 = {
@@ -150916,7 +151409,9 @@ function createInspector(serial, packageName, initialMetroPort) {
150916
151409
  if (own2) return own2;
150917
151410
  for (let dropped = conn.resumes; dropped; dropped = dropped.resumes) {
150918
151411
  const record2 = dropped.byLayerId.get(layerId);
150919
- if (record2 && (isOpen(record2) || lostOnly.has(record2))) return record2;
151412
+ if (record2 && (isOpen(record2) || lostOnly.has(record2) || failedAtStopTimeout.has(record2))) {
151413
+ return record2;
151414
+ }
150920
151415
  }
150921
151416
  return void 0;
150922
151417
  }
@@ -151014,6 +151509,7 @@ function createInspector(serial, packageName, initialMetroPort) {
151014
151509
  return fetched;
151015
151510
  }
151016
151511
  function failOrphans(running) {
151512
+ for (const c of connections2) if (!running.has(c.processKey)) c.ended = true;
151017
151513
  for (const record2 of records) {
151018
151514
  if (!isOpen(record2) && !lostOnly.has(record2)) continue;
151019
151515
  const conn = byId.get(record2.id)?.conn;
@@ -151034,42 +151530,148 @@ function createInspector(serial, packageName, initialMetroPort) {
151034
151530
  function armedFor(key2) {
151035
151531
  return connections2.some((c) => c.armed && !c.closed && c.processKey === key2);
151036
151532
  }
151037
- async function ensureAttached(port) {
151533
+ async function attachCurrent() {
151534
+ const blocked = await prepare();
151535
+ if (blocked) return { blocked };
151536
+ const read = await readAppProcesses(serial, packageName);
151537
+ checkpoint();
151538
+ const switched = await followUser(read.user);
151539
+ if (switched) return { blocked: switched };
151540
+ const current = processOfUser(read, user());
151541
+ failOrphans(runningKeys(read));
151542
+ if (!current) {
151543
+ if (!armedConnection()) {
151544
+ note = `${packageName} was not running at network-capture-start; launch-app or restart-app attaches the agent to its next process, or call network-capture-start once it runs`;
151545
+ }
151546
+ return { current: null };
151547
+ }
151548
+ if (await attach(current) !== "attached") await refreshAgentReason(current);
151549
+ if (!ready2) {
151550
+ const again = await prepare();
151551
+ if (again) return { blocked: again };
151552
+ }
151553
+ return { current };
151554
+ }
151555
+ async function startCapture2(port) {
151038
151556
  setMetroPort(port);
151039
- return withKeyedLock(attachLock, "attach", async () => {
151040
- if (disposed) return null;
151041
- const hadCapture = live;
151042
- try {
151043
- const blocked = await prepare();
151044
- if (blocked) return blocked;
151045
- const read = await readAppProcesses(serial, packageName);
151046
- checkpoint();
151047
- const switched = await followUser(read.user);
151048
- if (switched) return switched;
151049
- const current = processOfUser(read, user());
151050
- failOrphans(runningKeys(read));
151051
- if (!current) {
151052
- if (!armedConnection()) {
151053
- note = `${packageName} is not running; launch-app or restart-app attaches the agent to its next process`;
151054
- }
151055
- } else {
151056
- if (await attach(current) !== "attached") await refreshAgentReason(current);
151057
- if (!ready2) {
151058
- const again = await prepare();
151059
- if (again) return again;
151557
+ let found = { stopped, mark, live };
151558
+ const unavailableStart = (reason2) => {
151559
+ if (found.stopped) stopped = true;
151560
+ if (!found.live) live = false;
151561
+ mark = found.mark;
151562
+ unavailableReason = reason2;
151563
+ note = reason2;
151564
+ startNote = reason2;
151565
+ return { result: { armed: false, unavailable: true, reason: reason2 } };
151566
+ };
151567
+ const attached = await withKeyedLock(
151568
+ attachLock,
151569
+ "attach",
151570
+ async () => {
151571
+ if (disposed) return { result: { armed: false, reason: "capture was disposed" } };
151572
+ found = { stopped, mark, live };
151573
+ mark = { lastRecord: nextRecordNumber2 - 1, metroPort: port };
151574
+ stopped = false;
151575
+ notAttached = false;
151576
+ if (note === startNote || note === NOT_RECONNECTED_NOTE) note = awaiting?.note;
151577
+ try {
151578
+ const outcome = await attachCurrent();
151579
+ if ("blocked" in outcome) return unavailableStart(outcome.blocked.reason);
151580
+ live = true;
151581
+ unavailableReason = void 0;
151582
+ for (const conn2 of connections2) {
151583
+ if (!conn2.closed && !conn2.armed && !conn2.enabling) enableNetwork(conn2);
151584
+ }
151585
+ return outcome;
151586
+ } catch (err) {
151587
+ if (err instanceof InspectorStopped) {
151588
+ return {
151589
+ result: { armed: false, reason: disposed ? "capture was disposed" : STOPPED_NOTE }
151590
+ };
151060
151591
  }
151592
+ if (isUnavailableFailure(err)) return unavailableStart(errorMessage3(err));
151593
+ live = true;
151594
+ unavailableReason = void 0;
151595
+ const reason2 = isOwnFailure(err) ? errorMessage3(err) : `adb did not answer (${firstLine3(adbFailureDetail(err))}); the next launch or network-capture-start tries again`;
151596
+ log(reason2);
151597
+ note = reason2;
151598
+ startNote = reason2;
151599
+ return { result: { armed: false, reason: reason2 } };
151061
151600
  }
151062
- live = true;
151063
- return null;
151064
- } catch (err) {
151065
- if (err instanceof InspectorStopped) return null;
151066
- if (!hadCapture) throw err;
151067
- const callNote = isOwnFailure(err) ? `${errorMessage3(err)} Listing the requests captured so far.` : `adb did not answer (${firstLine3(adbFailureDetail(err))}); listing the requests captured so far`;
151068
- log(callNote);
151069
- return { status: "ok", note: callNote };
151070
151601
  }
151602
+ );
151603
+ if ("result" in attached) return attached.result;
151604
+ if (!attached.current) {
151605
+ return {
151606
+ armed: false,
151607
+ reason: shownNote() ?? `${packageName} is not running; launch-app or restart-app attaches the agent to its next process`
151608
+ };
151609
+ }
151610
+ const key2 = processKey(attached.current);
151611
+ await waitForArmed(key2, ARM_WAIT_MS);
151612
+ if (disposed) return { armed: false, reason: "capture was disposed" };
151613
+ if (stopped) return { armed: false, reason: STOPPED_NOTE };
151614
+ const conn = connections2.find((c) => c.armed && !c.closed && c.processKey === key2);
151615
+ if (!conn) {
151616
+ const reason2 = await refreshAgentReason(attached.current);
151617
+ note ??= `waiting for the agent in pid ${attached.current.pid}${reason2 ? `: ${reason2}` : ""}`;
151618
+ return { armed: false, reason: shownNote() ?? note };
151619
+ }
151620
+ if (conn.capture?.state === "unavailable") {
151621
+ const { result } = unavailableStart(
151622
+ `capture unavailable${conn.capture.detail ? `: ${conn.capture.detail}` : ""}`
151623
+ );
151624
+ if (stopped) {
151625
+ void stopCapture2();
151626
+ unavailableReason = result.reason;
151627
+ }
151628
+ return result;
151629
+ }
151630
+ return { armed: true };
151631
+ }
151632
+ async function stopCapture2() {
151633
+ if (disposed) return { confirmed: true };
151634
+ stopped = true;
151635
+ live = false;
151636
+ notAttached = false;
151637
+ unavailableReason = void 0;
151638
+ stops++;
151639
+ for (const conn of connections2) {
151640
+ conn.armed = false;
151641
+ conn.enabling = false;
151642
+ conn.stopUnconfirmed = false;
151643
+ }
151644
+ for (const wake of armWaiters) wake();
151645
+ return withKeyedLock(attachLock, "attach", async () => {
151646
+ if (disposed) return { confirmed: true };
151647
+ const answers = await Promise.all(
151648
+ connections2.filter((c) => !c.closed).map((c) => disableOn(c, STOP_DISABLE_TIMEOUT_MS))
151649
+ );
151650
+ const reasons = [];
151651
+ if (answers.some((answered) => !answered)) {
151652
+ reasons.push(
151653
+ `the agent did not acknowledge Network.disable within ${STOP_DISABLE_TIMEOUT_MS / 1e3} s; argent records none of the app's new requests, and launches do not attach it`
151654
+ );
151655
+ }
151656
+ if (await awayAtStop()) reasons.push(AWAY_AT_STOP);
151657
+ return reasons.length === 0 ? { confirmed: true } : { confirmed: false, reason: reasons.join("; ") };
151071
151658
  });
151072
151659
  }
151660
+ function isAway(c) {
151661
+ return c.closed && !c.resumedBy && !c.agentGone && !c.ended && !c.disabled;
151662
+ }
151663
+ async function awayAtStop() {
151664
+ const away = () => connections2.filter(isAway);
151665
+ if (away().length === 0) return false;
151666
+ try {
151667
+ const read = await readAppProcesses(serial, packageName, STOP_DISABLE_TIMEOUT_MS);
151668
+ failOrphans(runningKeys(read));
151669
+ if (away().length > 0) await assertReverse();
151670
+ } catch {
151671
+ }
151672
+ for (const c of away()) missedStop.add(c.instance);
151673
+ return away().length > 0;
151674
+ }
151073
151675
  async function attachLaunch() {
151074
151676
  if (!live || disposed) return void 0;
151075
151677
  let outcome;
@@ -151093,36 +151695,54 @@ function createInspector(serial, packageName, initialMetroPort) {
151093
151695
  }
151094
151696
  });
151095
151697
  } catch (err) {
151096
- if (err instanceof InspectorStopped || disposed) return void 0;
151698
+ if (disposed) return void 0;
151699
+ if (err instanceof InspectorStopped) return stoppedLaunchNote(packageName);
151097
151700
  return `native network capture could not follow this launch of ${packageName}: ${firstLine3(isOwnFailure(err) ? errorMessage3(err) : adbFailureDetail(err))}`;
151098
151701
  }
151099
151702
  if (outcome.kind === "attached") await waitForArmed(processKey(outcome.proc), ARM_WAIT_MS);
151100
151703
  const reason2 = "proc" in outcome && !armedFor(processKey(outcome.proc)) ? await refreshAgentReason(outcome.proc) : void 0;
151101
151704
  if (disposed) return void 0;
151705
+ if (stopped) return stoppedLaunchNote(packageName);
151102
151706
  return launchNote(outcome, reason2);
151103
151707
  }
151708
+ function unconfirmedStop() {
151709
+ if (!stopped) return void 0;
151710
+ return connections2.find((c) => !c.closed && c.stopUnconfirmed) ?? connections2.find((c) => missedStop.has(c.instance) && isAway(c));
151711
+ }
151712
+ async function stoppedLaunch() {
151713
+ const conn = unconfirmedStop();
151714
+ if (!conn) return stoppedLaunchNote(packageName);
151715
+ const read = await readAppProcesses(serial, packageName).catch(() => null);
151716
+ if (read) failOrphans(runningKeys(read));
151717
+ const current = read ? processOfUser(read, user()) : null;
151718
+ if (unconfirmedStop() !== conn) return stoppedLaunchNote(packageName);
151719
+ if (read && (!current || processKey(current) !== conn.processKey)) {
151720
+ return stoppedLaunchNote(packageName);
151721
+ }
151722
+ return `native network capture is stopped for ${packageName} (network-capture-stop), but its running process (pid ${conn.pid}) has not acknowledged Network.disable, so it may still intercept its requests; argent records none of them, and restart-app starts a process without capture`;
151723
+ }
151104
151724
  function launchNote(outcome, reason2) {
151105
151725
  switch (outcome.kind) {
151106
151726
  case "blocked":
151107
151727
  return `native network capture cannot follow ${packageName}: ${outcome.reason}`;
151108
151728
  case "no_process":
151109
- return `native network capture is on for ${packageName}, but no process of it appeared within ${NEW_PROCESS_WAIT_MS / 1e3} s; the next native-network-logs call attaches the agent`;
151729
+ return `native network capture is on for ${packageName}, but no process of it appeared within ${NEW_PROCESS_WAIT_MS / 1e3} s; restart-app attaches the agent to its next process, or call network-capture-start once it runs`;
151110
151730
  case "copy_failed":
151111
151731
  case "attach_failed":
151112
151732
  return `native network capture could not follow this launch: ${note ?? "the attach failed"}`;
151113
151733
  default: {
151114
151734
  const { pid } = outcome.proc;
151115
- return armedFor(processKey(outcome.proc)) ? `native network capture is attached to ${packageName} (pid ${pid}); native-network-logs with stop: true ends it` : `native network capture is attaching to ${packageName} (pid ${pid}), and the agent has not connected yet; native-network-logs shows when it is armed${reason2 ? `; the agent says: ${reason2}` : ""}`;
151735
+ return armedFor(processKey(outcome.proc)) ? `native network capture is attached to ${packageName} (pid ${pid}); network-capture-stop ends it` : `native network capture is attaching to ${packageName} (pid ${pid}), and the agent has not connected yet; native-network-logs shows when it is armed${reason2 ? `; the agent says: ${reason2}` : ""}`;
151116
151736
  }
151117
151737
  }
151118
151738
  }
151119
151739
  async function waitForArmed(key2, timeoutMs) {
151120
151740
  const deadline = Date.now() + timeoutMs;
151121
- while (!disposed && !armedFor(key2)) {
151741
+ while (!disposed && !stopped && !armedFor(key2)) {
151122
151742
  const left = deadline - Date.now();
151123
151743
  if (left <= 0) return;
151124
151744
  const woken = await nextArmEvent(Math.min(ARM_PROCESS_CHECK_MS, left));
151125
- if (woken || disposed || armedFor(key2)) continue;
151745
+ if (woken || disposed || stopped || armedFor(key2)) continue;
151126
151746
  const readTimeoutMs = deadline - Date.now();
151127
151747
  if (readTimeoutMs <= 0) return;
151128
151748
  try {
@@ -151147,15 +151767,22 @@ function createInspector(serial, packageName, initialMetroPort) {
151147
151767
  }
151148
151768
  const api = {
151149
151769
  packageName,
151150
- ensureAttached,
151770
+ startCapture: startCapture2,
151771
+ stopCapture: stopCapture2,
151772
+ isStarted: () => live && !disposed,
151773
+ isStopped: () => stopped && !disposed,
151774
+ unavailableReason: () => unavailableReason,
151775
+ captureMark: () => mark,
151151
151776
  state() {
151152
151777
  const conn = armedConnection();
151153
151778
  return {
151154
151779
  armed: Boolean(conn),
151780
+ ...stopped ? { stopped: true } : {},
151781
+ ...!conn && notAttached && !stopped ? { notAttached: true } : {},
151155
151782
  ...conn ? { process: { pid: conn.pid, startTime: conn.startTime } } : {},
151156
151783
  ...conn?.capture ? { capture: { ...conn.capture } } : {},
151157
151784
  ...conn && conn.droppedEvents > 0 ? { droppedEvents: conn.droppedEvents } : {},
151158
- ...!conn && note ? { note: shownNote() } : {}
151785
+ ...!conn && note && !stopped ? { note: shownNote() } : {}
151159
151786
  };
151160
151787
  },
151161
151788
  records: (port) => records.filter(
@@ -151174,7 +151801,10 @@ function createInspector(serial, packageName, initialMetroPort) {
151174
151801
  packageName,
151175
151802
  hardwareKey: null,
151176
151803
  isLive: () => live && !disposed,
151177
- attachLaunch
151804
+ isStopped: () => stopped && !disposed,
151805
+ mayIntercept: () => !disposed && (live || unconfirmedStop() !== void 0),
151806
+ attachLaunch,
151807
+ stoppedLaunch
151178
151808
  };
151179
151809
  return {
151180
151810
  handle,
@@ -151300,6 +151930,10 @@ function agentFiles() {
151300
151930
  function isAgentAbi(abi) {
151301
151931
  return AGENT_ABIS.includes(abi);
151302
151932
  }
151933
+ function isUnavailableFailure(err) {
151934
+ const code = getFailureSignal(err)?.error_code;
151935
+ return code === FAILURE_CODES.ANDROID_NETWORK_INSPECTOR_UNKNOWN_PACKAGE || code === FAILURE_CODES.ANDROID_NETWORK_INSPECTOR_DEVICE_IN_USE || code === FAILURE_CODES.EXTERNAL_DEVICE_CAPABILITY_DENIED;
151936
+ }
151303
151937
  function isOwnFailure(err) {
151304
151938
  const code = getFailureSignal(err)?.error_code;
151305
151939
  return code === FAILURE_CODES.ANDROID_NETWORK_INSPECTOR_UNKNOWN_PACKAGE || code === FAILURE_CODES.ANDROID_NETWORK_INSPECTOR_RUN_AS_FAILED || code === FAILURE_CODES.ANDROID_NETWORK_INSPECTOR_DEVICE_IN_USE || code === FAILURE_CODES.ANDROID_NETWORK_INSPECTOR_NO_DEVICE_PORT;
@@ -151460,7 +152094,124 @@ Fails if the simulator server is not running for the given UDID.`,
151460
152094
  init_zod();
151461
152095
  init_src2();
151462
152096
  init_device_info();
151463
- init_external_devices();
152097
+
152098
+ // ../tool-server/src/tools/network/network-capture.ts
152099
+ init_zod();
152100
+ init_src2();
152101
+
152102
+ // ../tool-server/src/utils/bundle-id.ts
152103
+ var BUNDLE_ID_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
152104
+ var BUNDLE_ID_MESSAGE = "bundleId may only contain letters, digits, '.', '_' and '-', and may not start with '-' or '.'";
152105
+
152106
+ // ../tool-server/src/tools/network/network-capture.ts
152107
+ init_device_info();
152108
+ var captureSchema = external_exports.object({
152109
+ udid: external_exports.string().describe(
152110
+ "Device ID from list-devices: an iOS simulator UDID or Android serial<flag:macos-apps>, or a Mac app id (macos-app-<bundle id>)</flag:macos-apps>"
152111
+ ),
152112
+ bundleId: external_exports.string().regex(BUNDLE_ID_PATTERN, BUNDLE_ID_MESSAGE).describe(
152113
+ "App bundle ID on iOS or package name on Android<flag:macos-apps> (on a Mac app, the bundle id in the device id)</flag:macos-apps>"
152114
+ ),
152115
+ port: metroPortField.describe(
152116
+ "The app's Metro port: the JS layer is reached through it, and the native layers leave its requests out. Omit it to use this device's port, 8081 by default."
152117
+ ),
152118
+ logicalDeviceId: external_exports.string().min(1).optional().describe(
152119
+ "Only when several devices share the Metro port: this device's logicalDeviceId, which the JS layer's reason lists. The JS layer connects to that runtime, and view-network-logs then takes it as device_id. The native layer always uses udid."
152120
+ )
152121
+ });
152122
+ var CAPTURE_CAPABILITY = {
152123
+ apple: { simulator: true },
152124
+ appleRemote: { simulator: true },
152125
+ android: { emulator: true, device: true },
152126
+ macos: { app: true, catalyst: true }
152127
+ };
152128
+ var captureLocks = /* @__PURE__ */ new Map();
152129
+ var captureSweeps = /* @__PURE__ */ new Set();
152130
+ function lockDevice(udid) {
152131
+ return deviceKeyOf(udid).toLowerCase();
152132
+ }
152133
+ var nativeUnavailable = /* @__PURE__ */ new Map();
152134
+ function nativeUnavailableKey(udid, bundleId) {
152135
+ return `${lockDevice(udid)}:${bundleId}`;
152136
+ }
152137
+ function setNativeUnavailable(udid, bundleId, reason2) {
152138
+ if (reason2 === void 0) nativeUnavailable.delete(nativeUnavailableKey(udid, bundleId));
152139
+ else nativeUnavailable.set(nativeUnavailableKey(udid, bundleId), reason2);
152140
+ }
152141
+ function nativeUnavailableReason(udid, bundleId) {
152142
+ return nativeUnavailable.get(nativeUnavailableKey(udid, bundleId));
152143
+ }
152144
+ function forgetNativeUnavailableOf(devices2) {
152145
+ const covered = devices2 && new Set(devices2.map(lockDevice));
152146
+ for (const key2 of nativeUnavailable.keys()) {
152147
+ if (!covered || covered.has(key2.slice(0, key2.lastIndexOf(":")))) nativeUnavailable.delete(key2);
152148
+ }
152149
+ }
152150
+ function withCaptureLock(udid, bundleId, fn) {
152151
+ const device = lockDevice(udid);
152152
+ const sweeps = [...captureSweeps].filter((sweep) => !sweep.devices || sweep.devices.has(device)).map((sweep) => sweep.done);
152153
+ return withKeyedLock(captureLocks, `${device}:${bundleId}`, async () => {
152154
+ await Promise.all(sweeps);
152155
+ return fn();
152156
+ });
152157
+ }
152158
+ async function withCaptureSweep(devices2, wait, fn) {
152159
+ const covered = devices2 && new Set(devices2.map(lockDevice));
152160
+ const underWay = [...captureLocks].filter(([key2]) => !covered || covered.has(key2.slice(0, key2.lastIndexOf(":")))).map(([, held]) => held);
152161
+ let end;
152162
+ const sweep = { devices: covered, done: new Promise((resolve21) => end = resolve21) };
152163
+ captureSweeps.add(sweep);
152164
+ try {
152165
+ await settleWithin(Promise.all(underWay), wait.maxMs, wait.signal);
152166
+ return await fn();
152167
+ } finally {
152168
+ captureSweeps.delete(sweep);
152169
+ end();
152170
+ }
152171
+ }
152172
+ async function runLayers(layers) {
152173
+ const settled = await Promise.allSettled(layers);
152174
+ const failed3 = settled.find((s) => s.status === "rejected");
152175
+ if (failed3) throw failed3.reason;
152176
+ return settled.map((s) => s.value);
152177
+ }
152178
+ function isLiveService(registry2, urn) {
152179
+ const state3 = registry2.getSnapshot().services.get(urn)?.state;
152180
+ return state3 !== void 0 && isLiveServiceState(state3);
152181
+ }
152182
+ async function resolveJsRuntime(registry2, udid, logicalDeviceId, port) {
152183
+ if (logicalDeviceId !== void 0 && classifyDevice(udid) === "ios-remote") {
152184
+ await proxyStart(udid, port);
152185
+ }
152186
+ return resolveDebuggerService(
152187
+ registry2,
152188
+ { port, device_id: logicalDeviceId ?? udid },
152189
+ { physicalDeviceId: udid }
152190
+ );
152191
+ }
152192
+ function jsNotReached(reason2, port, err) {
152193
+ const detail = errorMessage4(err);
152194
+ switch (reason2) {
152195
+ case "metro_not_running":
152196
+ return `Metro is not running on port ${port}; start it, or pass the port of the app's Metro`;
152197
+ case "device_mismatch": {
152198
+ const listed = /connected to Metro on port \d+: (.+?)\. Re-target/.exec(detail)?.[1];
152199
+ return `several devices are connected to Metro on port ${port}, so the JS layer cannot tell which runtime is this device's; pass this device's logicalDeviceId (${listed ? `in parentheses: ${listed}` : detail}), or give each device its own Metro port`;
152200
+ }
152201
+ case "no_app_connected":
152202
+ return `no app is connected to Metro on port ${port} yet`;
152203
+ case void 0:
152204
+ return `the JS debugger could not connect: ${detail}`;
152205
+ default:
152206
+ return `the app's JS runtime did not answer (${reason2}: ${detail})`;
152207
+ }
152208
+ }
152209
+ function otherPortHint(bundleId, port) {
152210
+ return `this device has network capture for ${bundleId} on Metro port ${port}: pass port ${port}`;
152211
+ }
152212
+ function errorMessage4(err) {
152213
+ return err instanceof Error ? err.message : String(err);
152214
+ }
151464
152215
 
151465
152216
  // ../tool-server/src/tools/native-devtools/macos-view-hierarchy.ts
151466
152217
  init_zod();
@@ -151626,25 +152377,29 @@ var zodSchema4 = external_exports.object({
151626
152377
  "App bundle ID on iOS or package name on Android<flag:macos-apps> (on a Mac app, the bundle id in the device id)</flag:macos-apps>"
151627
152378
  ),
151628
152379
  port: metroPortField.describe(
151629
- "The app's Metro port, whose requests are left out of the listing. Omit it to use this device's port, 8081 by default.<flag:macos-apps> A Mac app ignores it.</flag:macos-apps>"
152380
+ "The app's Metro port, whose requests are left out of the listing. Omit it to use this device's port, 8081 by default."
151630
152381
  ),
151631
152382
  limit: external_exports.number().int().nonnegative().optional().default(50).describe(
151632
- "Maximum number of requests to return: the most recent ones, oldest first. 0 returns only the header and the total.<flag:macos-apps> On a Mac app it counts events, not requests: one request gives several events. 0 returns no events.</flag:macos-apps>"
152383
+ "Maximum number of requests to return: the most recent ones, oldest first. 0 returns only the header and the total."
151633
152384
  ),
151634
152385
  clear: external_exports.boolean().optional().default(false).describe(
151635
- "Clear the log after reading. On iOS and Android, the IDs of cleared requests still work in view-network-request-details"
152386
+ "Clear the log after reading. The IDs of cleared requests still work in view-network-request-details"
151636
152387
  ),
151637
- stop: external_exports.boolean().optional().describe(
151638
- "Android only: turn native capture off for this app instead of listing. Other apps keep theirs."
152388
+ // Declared so this non-strict object refuses the old stop instead of stripping it: the read
152389
+ // would succeed while capture records on.
152390
+ stop: external_exports.never({
152391
+ error: "native-network-logs no longer stops capture: call network-capture-stop with this udid and bundleId, which keeps what was captured (stop-all-simulator-servers for the device also ends it). Drop `stop` from this call; `stop: false` was a plain read"
152392
+ }).optional().describe(
152393
+ "Retired: native-network-logs only reads. Call network-capture-stop with the same udid and bundleId to stop capture; drop `stop: false`, which was a plain read."
151639
152394
  )
151640
152395
  });
151641
152396
  function createNativeNetworkLogsTool(registry2) {
151642
152397
  return {
151643
152398
  id: "native-network-logs",
151644
152399
  interaction: {
151645
- startedMsg: ({ params }) => params.stop ? `Stopping native network capture for ${params.bundleId}` : `Reading native network activity for ${params.bundleId}`,
151646
- completedMsg: ({ params }) => params.stop ? `Stopped native network capture for ${params.bundleId}` : `Read native network activity for ${params.bundleId}`,
151647
- failedMsg: ({ params, failureSignal: failureSignal2 }) => params.stop ? `Failed to stop native network capture for ${params.bundleId}: ${failureSignal2.error_code}` : `Failed to read native network activity for ${params.bundleId}: ${failureSignal2.error_code}`
152400
+ startedMsg: ({ params }) => `Reading native network activity for ${params.bundleId}`,
152401
+ completedMsg: ({ params }) => `Read native network activity for ${params.bundleId}`,
152402
+ failedMsg: ({ params, failureSignal: failureSignal2 }) => `Failed to read native network activity for ${params.bundleId}: ${failureSignal2.error_code}`
151648
152403
  },
151649
152404
  capability: {
151650
152405
  apple: { simulator: true },
@@ -151652,38 +152407,34 @@ function createNativeNetworkLogsTool(registry2) {
151652
152407
  android: { emulator: true, device: true },
151653
152408
  macos: { app: true, catalyst: true }
151654
152409
  },
151655
- description: `Retrieve network requests captured at the native level: NSURLProtocol on iOS, OkHttp on Android.
152410
+ description: `Retrieve network requests captured at the native level: NSURLProtocol on iOS<flag:macos-apps> and Mac apps</flag:macos-apps>, OkHttp on Android.
151656
152411
  Use when inspecting native-level HTTP traffic that view-network-logs cannot see: requests that never pass through JS XMLHttpRequest or fetch.
151657
- On iOS it sees URLSession requests (default and ephemeral session configurations, and URLSession.shared) from native modules and Swift/Objective-C code. It does not see background URLSession transfers, WKWebView, Network.framework, or HTTP stacks that bypass URLSession (e.g. Flutter), so an empty result does not mean the app sent nothing.
151658
- Returns { status, header, armed, count, total, requests }: one line per request, oldest first, with its id (ios-3f9a-12, android-3f9a-12), method, URL, state (pending, headers, complete or failed), status, mimeType, durationMs and errorText. The header says whether capture is armed, how many requests there are and the app's pid once read, and why capture is not armed when it is not. Requests to Metro on \`port\` are left out. Pass a request's id to view-network-request-details for its headers and bodies, and on Android its redirects. The history is kept across relaunches of the app.
151659
- The first call for an app starts capture, so earlier requests are not captured: repeat the action whose requests you need, then call again.
151660
- On iOS: the first call waits until the app acknowledges capture. When capture started while the app was already running, the header of the first answer says that the app's launch was not recorded; to capture the launch, restart-app and call again, unless the header says the launch cannot be recorded on that device. Capture stays on for later processes of the app.
151661
- <flag:macos-apps>On a Mac app: { status, count, events } of NSURLSession requests, react-native-macos fetch included; capture stays on across restart-app, a new log per process.
152412
+ On iOS<flag:macos-apps> and Mac apps</flag:macos-apps> it sees URLSession requests (default and ephemeral session configurations, and URLSession.shared) from native modules and Swift/Objective-C code<flag:macos-apps>, and react-native-macos fetch</flag:macos-apps>. It does not see background URLSession transfers, WKWebView, Network.framework, or HTTP stacks that bypass URLSession (e.g. Flutter), so an empty result does not mean the app sent nothing.
152413
+ Returns { status, header, armed, count, total, requests }: one line per request, oldest first, with its id (ios-3f9a-12, android-3f9a-12<flag:macos-apps>, macos-3f9a-12</flag:macos-apps>), method, URL, state (pending, headers, complete or failed), status, mimeType, durationMs and errorText. The header says whether capture is armed, how many requests there are and the app's pid once read, and why capture is not armed when it is not. Requests to Metro on \`port\` are left out. Pass a request's id to view-network-request-details for its headers and bodies, and on Android its redirects. The history is kept across relaunches of the app, except on a device whose devtools agent argent attached to.
152414
+ This tool only reads and never starts capture: call network-capture-start for the app first, then repeat the action whose requests you need. Before a start it returns started: false and a header that says capture is not started; on iOS and Android, after a start that found the native layer unavailable, started: false and a header that gives the reason of that start; after network-capture-stop it returns stopped: true and still lists what was captured.
152415
+ On iOS: when capture started while the app was already running, the header of the first answer says that the app's launch was not recorded; to capture the launch, call restart-app, then network-capture-start (a relaunch ends JS capture), then this tool, unless the header says the launch cannot be recorded on that device. On a local simulator, launch-app and restart-app return networkCapture saying whether capture is armed in the new process.
152416
+ <flag:macos-apps>On a Mac app: when capture started while the app was already running, the header of the first answer says that its requests before the start were not recorded. Capture stays on across restart-app, and requests sent while the app starts can be missing.
151662
152417
  </flag:macos-apps>On iOS: If status is restart_required: follow the message (usually restart-app), then retry. If status is service_stale: the app is already injected, so restarting it cannot help. Restart the tool-server (\`argent server stop && argent server start --detach\`) and retry. If the same status comes back after that restart, stop restarting: follow the message, which names the terminal fallback. If status is connect_pending: the app is injected and still connecting. Do not restart it, wait a few seconds and retry. If status is init_failed: follow the message (re-boot the simulator) rather than retrying.
151663
- On a device whose devtools agent argent attached to rather than armed itself, only the agent's owner turns capture off; the list starts at argent's connection, not at the first call; a relaunch ends capture and clears the list; a not-connected app fails with \`NATIVE_DEVTOOLS_NOT_CONNECTED\` instead of a status, and no restart on argent's side fixes it. An Apple system app is rejected outright (terminal: never retry it).
151664
- On Android: needs a debuggable build. The first call usually returns armed: false. Call it again every few seconds until armed is true, then repeat the action whose requests you need.
152418
+ On a device whose devtools agent argent attached to rather than armed itself, a not-connected app fails with \`NATIVE_DEVTOOLS_NOT_CONNECTED\` instead of a status, and no restart on argent's side fixes it. An Apple system app is rejected outright (terminal: never retry it).
152419
+ On Android: needs a debuggable build. A header that says not attached means this tool-server did not attach capture to the app's current process: network-capture-start attaches it.
151665
152420
  Capture also misses a request already in flight at the attach and requests from clients other than OkHttp (e.g. HttpURLConnection, Cronet); an app whose OkHttp is fully minified reports capture unavailable.
151666
- Android results also carry capture and captureDetail. When capture is active, captureDetail and the header can say that only some requests are captured: then an empty or short list does not mean the app sent nothing.
151667
- Capture can slow the app. It stays on, and launch-app and restart-app attach it to each new process, until a call with stop: true turns it off for this app (stop-all-simulator-servers for the device also does); restart-app then starts the app without the agent. stop: true returns { status, stopped, message }, where stopped is false when capture was not on for the app. On iOS stop: true fails: capture ends only with stop-all-simulator-servers for this device or a local simulator shutdown, and in the running process only when the app restarts.
151668
- When status is not_attachable, use view-network-logs and do not retry.`,
152421
+ Android results also carry capture and captureDetail. When capture is active, captureDetail and the header can say that only some requests are captured: then an empty or short list does not mean the app sent nothing.`,
151669
152422
  zodSchema: zodSchema4,
151670
152423
  services: (params) => {
151671
152424
  const device = resolveDevice(params.udid);
151672
- if (params.stop) return {};
151673
152425
  if (device.platform === "macos") return macosAppServices(device);
152426
+ const live = (urn) => isLiveService(registry2, urn);
151674
152427
  if (device.platform === "android") {
151675
152428
  const port = metroPort({ device_id: params.udid, port: params.port });
151676
- return { androidNetwork: androidNetworkInspectorRef(device, params.bundleId, port) };
152429
+ const ref2 = androidNetworkInspectorRef(device, params.bundleId, port);
152430
+ return live(ref2.urn) ? { androidNetwork: ref2 } : {};
151677
152431
  }
151678
- return { nativeDevtools: nativeDevtoolsRef(device) };
152432
+ const ref = nativeDevtoolsRef(device);
152433
+ return live(ref.urn) ? { nativeDevtools: ref } : {};
151679
152434
  },
151680
152435
  async execute(services, params) {
151681
- if (params.stop) return stopAndroidNative(registry2, params);
151682
- if (services.androidNetwork) {
151683
- await ensureDeps(["adb"]);
151684
- return listAndroidNative(services.androidNetwork, params);
151685
- }
151686
152436
  const device = resolveDevice(params.udid);
152437
+ const port = metroPort({ device_id: params.udid, port: params.port });
151687
152438
  if (device.platform === "macos") {
151688
152439
  const app = requireMacosAppOfBundle(
151689
152440
  services,
@@ -151691,32 +152442,138 @@ When status is not_attachable, use view-network-logs and do not retry.`,
151691
152442
  "native-network-logs",
151692
152443
  params.bundleId
151693
152444
  );
151694
- await app.activateNetworkInspection();
151695
- const events = params.limit === 0 ? [] : app.networkLog().slice(-params.limit);
151696
- if (params.clear) app.clearNetworkLog();
151697
- return { status: "ok", count: events.length, events };
152445
+ if (!isInjectableBundleId(params.bundleId)) throw macosNotInjectable(params.bundleId);
152446
+ return listMacosNative(app, params, port);
151698
152447
  }
151699
- await ensureDeps(device.platform === "ios-remote" ? ["sim-remote"] : ["xcrun"]);
152448
+ if (device.platform === "android") {
152449
+ const api2 = services.androidNetwork;
152450
+ if (!api2 || !api2.isStarted() && !api2.isStopped()) {
152451
+ const reason2 = api2?.unavailableReason() ?? nativeUnavailableReason(device.id, params.bundleId);
152452
+ return reason2 ? {
152453
+ ...unavailableListing("android-native", reason2),
152454
+ capture: "unavailable",
152455
+ captureDetail: reason2
152456
+ } : notStarted("android-native", params.bundleId);
152457
+ }
152458
+ return listAndroidNative(api2, params, port);
152459
+ }
152460
+ if (!isInjectableBundleId(params.bundleId)) throw nonInjectableError(params.bundleId);
151700
152461
  const api = services.nativeDevtools;
152462
+ const unavailable3 = nativeUnavailableReason(device.id, params.bundleId);
152463
+ if (api?.isNetworkCaptureStopped(params.bundleId)) {
152464
+ return listStopped(
152465
+ "ios-native",
152466
+ api.networkRecords(params.bundleId),
152467
+ params,
152468
+ port,
152469
+ stoppedDetail(liveIosNetworkCaptures(params.udid).includes(params.bundleId), unavailable3)
152470
+ );
152471
+ }
152472
+ if (!api?.isNetworkCaptureStarted(params.bundleId)) {
152473
+ return unavailable3 ? unavailableListing("ios-native", unavailable3) : notStarted("ios-native", params.bundleId);
152474
+ }
152475
+ await ensureDeps(device.platform === "ios-remote" ? ["sim-remote"] : ["xcrun"]);
151701
152476
  const blocked = await precheckNativeDevtools(api, params.udid, params.bundleId);
151702
- const arming = api.activateNetworkInspection(params.bundleId);
151703
152477
  if (blocked) return blocked;
151704
152478
  if (!api.isConnected(params.bundleId)) throw notConnected(api, params.bundleId);
151705
- await arming;
152479
+ await api.refreshLentNetworkCapture(params.bundleId);
151706
152480
  const store = api.networkRecords(params.bundleId);
151707
152481
  if (!store) throw notConnected(api, params.bundleId);
151708
- const all = store.records(metroPort({ device_id: params.udid, port: params.port }));
152482
+ const all = store.records(port);
151709
152483
  const state3 = store.state();
151710
152484
  const detail = [];
151711
152485
  if (state3.pid !== void 0) detail.push(`pid ${state3.pid}`);
151712
152486
  if (state3.note) detail.push(state3.note);
151713
152487
  if (api.takeCaptureGap(params.bundleId)) detail.push(captureGapNote(api.armsEnv));
151714
- const listing = listNative("ios-native", all, params.limit, state3.armed, detail);
152488
+ const listing = listNative("ios-native", all, params.limit, {
152489
+ armed: state3.armed,
152490
+ state: state3.armed ? "armed" : "not armed",
152491
+ detail
152492
+ });
151715
152493
  if (params.clear) store.clear();
151716
152494
  return listing;
151717
152495
  }
151718
152496
  };
151719
152497
  }
152498
+ var STOPPED_DETAIL = "capture stopped by network-capture-stop; network-capture-start turns it on again";
152499
+ function listStopped(layer, store, params, port, detail = [STOPPED_DETAIL]) {
152500
+ const listing = listNative(layer, store?.records(port) ?? [], params.limit, {
152501
+ armed: false,
152502
+ state: "stopped",
152503
+ detail
152504
+ });
152505
+ if (params.clear) store?.clear();
152506
+ return { ...listing, stopped: true };
152507
+ }
152508
+ function listMacosNative(app, params, port) {
152509
+ const store = app.networkRecords();
152510
+ if (app.isNetworkCaptureStopped()) {
152511
+ return listStopped(
152512
+ "macos-native",
152513
+ store,
152514
+ params,
152515
+ port,
152516
+ stoppedDetail(app.isNetworkCaptureStopUnconfirmed())
152517
+ );
152518
+ }
152519
+ if (!app.isNetworkCaptureStarted()) return notStarted("macos-native", params.bundleId);
152520
+ const state3 = store.state();
152521
+ const detail = [];
152522
+ if (state3.pid !== void 0) detail.push(`pid ${state3.pid}`);
152523
+ if (state3.note) detail.push(state3.note);
152524
+ if (app.takeCaptureGap()) {
152525
+ detail.push(
152526
+ "capture started while the app was already running, so the requests before that were not recorded"
152527
+ );
152528
+ }
152529
+ const listing = listNative("macos-native", store.records(port), params.limit, {
152530
+ armed: state3.armed,
152531
+ state: state3.armed ? "armed" : "not armed",
152532
+ detail
152533
+ });
152534
+ if (params.clear) store.clear();
152535
+ return listing;
152536
+ }
152537
+ function macosNotInjectable(bundleId) {
152538
+ return new FailureError(
152539
+ `${bundleId} is an Apple app; argent captures only apps it can load its library into, such as your own builds. Treat its native network log as unavailable rather than retrying.`,
152540
+ {
152541
+ error_code: FAILURE_CODES.NATIVE_DEVTOOLS_NOT_INJECTABLE,
152542
+ error_kind: "validation",
152543
+ failure_area: "tool_server",
152544
+ failure_stage: "native_network_logs_macos_bundle_id"
152545
+ }
152546
+ );
152547
+ }
152548
+ function stoppedDetail(mayIntercept, unavailableReason) {
152549
+ const stopped = unavailableReason ? `capture stopped by network-capture-stop; a later network-capture-start found the layer unavailable: ${unavailableReason}` : STOPPED_DETAIL;
152550
+ return mayIntercept ? [
152551
+ stopped,
152552
+ "the app's process did not acknowledge Network.disable, so it may still intercept its requests; argent records none of them, and restart-app starts a process without capture"
152553
+ ] : [stopped];
152554
+ }
152555
+ function notStarted(layer, bundleId) {
152556
+ return {
152557
+ status: "ok",
152558
+ header: `${layer}: not started, 0 requests (network capture is off for ${bundleId}; call network-capture-start for it, then repeat the action)`,
152559
+ armed: false,
152560
+ started: false,
152561
+ count: 0,
152562
+ total: 0,
152563
+ requests: []
152564
+ };
152565
+ }
152566
+ function unavailableListing(layer, reason2) {
152567
+ return {
152568
+ status: "ok",
152569
+ header: `${layer}: unavailable, 0 requests (${reason2})`,
152570
+ armed: false,
152571
+ started: false,
152572
+ count: 0,
152573
+ total: 0,
152574
+ requests: []
152575
+ };
152576
+ }
151720
152577
  function notConnected(api, bundleId) {
151721
152578
  const remedy = api.armsEnv ? `Network capture is on for it and arms once it connects, so call again in a few seconds. Requests made before then are not recorded.` : `Native devtools here are an external provider's agent, which serves only the app that provider chose to lend. ${bundleId} is either not that app or its connection has not landed yet, so no native network log is being captured for it. argent did not launch this process and cannot re-point it, so restarting anything is the provider's call rather than argent's. Retry if the app has just started; otherwise, for a React Native app, read its JavaScript requests with view-network-logs.`;
151722
152579
  return new FailureError(`Native devtools not connected for bundleId: ${bundleId}. ${remedy}`, {
@@ -151727,77 +152584,42 @@ function notConnected(api, bundleId) {
151727
152584
  });
151728
152585
  }
151729
152586
  function captureGapNote(armsEnv) {
151730
- return armsEnv ? "capture started while the app was already running, so the requests before that, its launch among them, were not recorded; to capture the launch, restart-app and call again" : "argent connected to the app's agent while the app was running, so the requests before that, its launch among them, were not recorded; on this device a relaunch ends capture, so the launch cannot be recorded here: do not restart the app for it";
151731
- }
151732
- async function stopAndroidNative(registry2, params) {
151733
- const device = resolveDevice(params.udid);
151734
- if (device.platform !== "android") {
151735
- throw new FailureError(
151736
- device.platform === "macos" ? "stop applies to Android only. On a Mac app, network capture stays on until stop-all-simulator-servers stops this device's services or the tool-server stops." : externalClaimForAnyId(device.id) ? "stop applies to Android only. On this simulator the device provider controls network capture: argent does not turn it on or off, so turn it off in the provider." : "stop applies to Android only. On iOS, network capture stays on for the app until stop-all-simulator-servers stops this device's services and the app restarts.",
151737
- {
151738
- error_code: FAILURE_CODES.NATIVE_NETWORK_LOGS_STOP_UNSUPPORTED,
151739
- failure_stage: "native_network_logs_stop",
151740
- failure_area: "tool_server",
151741
- error_kind: "unsupported"
151742
- }
151743
- );
151744
- }
151745
- const notOn = {
151746
- status: "ok",
151747
- stopped: false,
151748
- message: `native network capture was not on for ${params.bundleId} on ${params.udid}`
151749
- };
151750
- const port = metroPort({ device_id: params.udid, port: params.port });
151751
- const { urn } = androidNetworkInspectorRef(device, params.bundleId, port);
151752
- const state3 = registry2.getSnapshot().services.get(urn)?.state;
151753
- if (state3 === void 0 || state3 === "IDLE" /* IDLE */) return notOn;
151754
- const wasOn = state3 === "RUNNING" /* RUNNING */ && liveAndroidNetworkCaptures(params.udid).includes(params.bundleId);
151755
- let pid;
151756
- if (wasOn) {
151757
- const api = await registry2.resolveService(urn);
151758
- pid = api.state().process?.pid;
151759
- }
151760
- await registry2.disposeService(urn);
151761
- if (!wasOn) return notOn;
151762
- return {
151763
- status: "ok",
151764
- stopped: true,
151765
- message: `native network capture stopped for ${params.bundleId} on ${params.udid}. ` + (pid !== void 0 ? `The in-app agent stays loaded in pid ${pid}, without capturing, until that process ends; ` : "An in-app agent that was attached stays loaded until its process ends; ") + "restart-app starts the app without it."
151766
- };
152587
+ return armsEnv ? "capture started while the app was already running, so the requests before that, its launch among them, were not recorded; to capture the launch, call restart-app, then network-capture-start again, since a relaunch ends the JS layer's capture, then call this again" : "argent connected to the app's agent while the app was running, so the requests before that, its launch among them, were not recorded; on this device a relaunch ends capture, so the launch cannot be recorded here: do not restart the app for it";
151767
152588
  }
151768
- async function listAndroidNative(api, params) {
151769
- const port = metroPort({ device_id: params.udid, port: params.port });
151770
- const attached = await api.ensureAttached(port);
151771
- if (attached?.status === "not_attachable") return attached;
152589
+ function listAndroidNative(api, params, port) {
151772
152590
  const all = api.records(port);
151773
152591
  const state3 = api.state();
151774
- const listing = listNative(
151775
- "android-native",
151776
- all,
151777
- params.limit,
151778
- state3.armed,
151779
- headerDetail(state3, attached?.note)
151780
- );
152592
+ const unavailable3 = state3.stopped ? api.unavailableReason() : void 0;
152593
+ const listing = listNative("android-native", all, params.limit, {
152594
+ armed: state3.armed,
152595
+ state: state3.stopped ? "stopped" : state3.armed ? "armed" : state3.notAttached ? "not attached" : "not armed",
152596
+ detail: state3.stopped ? stoppedDetail(
152597
+ liveAndroidNetworkCaptures(params.udid).includes(params.bundleId),
152598
+ unavailable3
152599
+ ) : headerDetail(state3)
152600
+ });
151781
152601
  if (params.clear) api.clear();
151782
152602
  return {
151783
152603
  ...listing,
152604
+ ...state3.stopped ? { stopped: true } : {},
152605
+ ...unavailable3 ? { started: false, capture: "unavailable", captureDetail: unavailable3 } : {},
151784
152606
  ...state3.capture ? { capture: state3.capture.state } : {},
151785
152607
  ...state3.capture?.detail ? { captureDetail: state3.capture.detail } : {}
151786
152608
  };
151787
152609
  }
151788
- function listNative(layer, all, limit, armed, detail) {
152610
+ function listNative(layer, all, limit, shape) {
151789
152611
  const shown = limit === 0 ? [] : all.slice(-limit);
151790
152612
  const noun = all.length === 1 ? "request" : "requests";
151791
152613
  return {
151792
152614
  status: "ok",
151793
- header: `${layer}: ${armed ? "armed" : "not armed"}, ${all.length} ${noun}` + (detail.length > 0 ? ` (${detail.join("; ")})` : ""),
151794
- armed,
152615
+ header: `${layer}: ${shape.state}, ${all.length} ${noun}` + (shape.detail.length > 0 ? ` (${shape.detail.join("; ")})` : ""),
152616
+ armed: shape.armed,
151795
152617
  count: shown.length,
151796
152618
  total: all.length,
151797
152619
  requests: shown.map(toRequestLine)
151798
152620
  };
151799
152621
  }
151800
- function headerDetail(state3, callNote) {
152622
+ function headerDetail(state3) {
151801
152623
  const parts2 = [];
151802
152624
  if (state3.process) parts2.push(`pid ${state3.process.pid}`);
151803
152625
  const capture = state3.capture;
@@ -151810,15 +152632,12 @@ function headerDetail(state3, callNote) {
151810
152632
  );
151811
152633
  }
151812
152634
  if (capture?.state === "unavailable") {
151813
- parts2.push(
151814
- `capture unavailable${capture.detail ? `: ${capture.detail}` : ""}; use view-network-logs`
151815
- );
152635
+ parts2.push(`capture unavailable${capture.detail ? `: ${capture.detail}` : ""}`);
151816
152636
  }
151817
152637
  if (state3.droppedEvents) {
151818
152638
  parts2.push(`${state3.droppedEvents} events were lost while the agent was disconnected`);
151819
152639
  }
151820
152640
  if (state3.note) parts2.push(state3.note);
151821
- if (callNote) parts2.push(callNote);
151822
152641
  return parts2;
151823
152642
  }
151824
152643
  function toRequestLine(record2) {
@@ -152719,12 +153538,13 @@ var jsRuntimeDebuggerBlueprint = {
152719
153538
  error_kind: "validation"
152720
153539
  });
152721
153540
  }
153541
+ const physicalDeviceId = typeof options?.physicalDeviceId === "string" && options.physicalDeviceId ? options.physicalDeviceId : deviceId;
152722
153542
  if (classifyDevice(deviceId) === "ios-remote") {
152723
153543
  await proxyStart(deviceId, port);
152724
153544
  }
152725
- await assertExternalCapability(JS_RUNTIME_DEBUGGER_NAMESPACE, deviceId, "js-debugger");
153545
+ await assertExternalCapability(JS_RUNTIME_DEBUGGER_NAMESPACE, physicalDeviceId, "js-debugger");
152726
153546
  const metro = await discoverMetro(port).catch((error63) => {
152727
- const published = publishedMetroPort(deviceId, port);
153547
+ const published = publishedMetroPort(physicalDeviceId, port);
152728
153548
  if (published !== void 0 && error63 instanceof FailureError) {
152729
153549
  error63.message += ` The provider offering this device publishes Metro on port ${published} \u2014 omit the 'port' parameter to use it.`;
152730
153550
  }
@@ -152735,8 +153555,8 @@ var jsRuntimeDebuggerBlueprint = {
152735
153555
  deviceId,
152736
153556
  simulatorName: await simulatorNameOnSharedMetro(deviceId, metro.targets)
152737
153557
  });
152738
- const onPublishedBundler = publishedMetroPort(deviceId, port) === void 0;
152739
- const proxied = onPublishedBundler ? externalJsDebuggerUrl(deviceId) : void 0;
153558
+ const onPublishedBundler = publishedMetroPort(physicalDeviceId, port) === void 0;
153559
+ const proxied = onPublishedBundler ? externalJsDebuggerUrl(physicalDeviceId) : void 0;
152740
153560
  const cdp = new CDPClient(proxied ?? selected.webSocketUrl, {
152741
153561
  awaitPromisesInApp: !selected.legacyInspector
152742
153562
  });
@@ -152871,14 +153691,22 @@ var jsRuntimeDebuggerBlueprint = {
152871
153691
  init_src2();
152872
153692
 
152873
153693
  // ../tool-server/src/utils/debugger/scripts/network-interceptor.ts
153694
+ var import_node_crypto15 = require("node:crypto");
153695
+ var import_node_os12 = require("node:os");
153696
+ init_src3();
152874
153697
  var BINARY_BODY_TYPES = /^(image\/(?!svg)|audio\/|video\/|font\/|application\/(octet-stream|pdf|zip|gzip|wasm|x-protobuf)$)/;
152875
153698
  var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
152876
153699
  var g = globalThis;
152877
- if (g.__argent_network_v2) return JSON.stringify({ installed: false, reason: 'already installed' });
153700
+ if (g.__argent_network_v3) return JSON.stringify({ installed: false, reason: 'already installed' });
153701
+ // A runtime can be reached before its bundle runs, and the bundle sets up XMLHttpRequest. An
153702
+ // install then would patch nothing yet keep its guard, so this context would never record.
153703
+ if (typeof g.XMLHttpRequest !== 'function') return JSON.stringify({ installed: false, reason: 'no XMLHttpRequest yet' });
153704
+ g.__argent_network_v3 = true;
153705
+ // An older tool-server installs only where this flag is unset, so it never replaces this script.
152878
153706
  g.__argent_network_v2 = true;
152879
- // The previous fetch-only script, injected by an older tool-server before an upgrade, stays
152880
- // installed until the app reloads. Its fetch wrapper keeps the buffers below in a closure, so
152881
- // empty them and stop them from growing: it then still reads each response, but keeps nothing.
153707
+ // An older script, injected by an older tool-server before an upgrade, stays installed until
153708
+ // the app reloads. Its wrappers keep the buffers below in a closure, so empty them and stop
153709
+ // them from growing: they then still read each response, but keep nothing.
152882
153710
  if (g.__argent_network_installed && Array.isArray(g.__argent_network_log)) {
152883
153711
  var oldLog = g.__argent_network_log;
152884
153712
  oldLog.length = 0;
@@ -152903,6 +153731,15 @@ var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
152903
153731
  g.__argent_network_log = log;
152904
153732
  g.__argent_network_by_id = byId;
152905
153733
  var nextId = 1;
153734
+ // Only an identity: a new JS context gets another one, and its ids start at 1 again.
153735
+ var installToken = Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10);
153736
+ g.__argent_network_install = installToken;
153737
+ g.__argent_network_mark = function() {
153738
+ return JSON.stringify({ install: installToken, lastId: nextId - 1 });
153739
+ };
153740
+ function paused() {
153741
+ return g.__argent_network_paused === true;
153742
+ }
152906
153743
  var bufferedChars = 0;
152907
153744
  // Above zero while an XHR is sent: the request React Native's network module gets then is the
152908
153745
  // XHR's, which has its record.
@@ -152923,6 +153760,13 @@ var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
152923
153760
  }
152924
153761
  }
152925
153762
 
153763
+ // A request in flight keeps its record object, but adds to the buffer only while byId has it.
153764
+ g.__argent_network_clear = function() {
153765
+ log.length = 0;
153766
+ for (var key in byId) delete byId[key];
153767
+ bufferedChars = 0;
153768
+ };
153769
+
152926
153770
  // Runs on the app's JS thread for every text response. The loop costs about 200 ms per MiB in
152927
153771
  // Hermes with a debugger attached, so the native checks go first.
152928
153772
  function utf8Length(text) {
@@ -153416,6 +154260,10 @@ var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
153416
154260
  xhrSending--;
153417
154261
  }
153418
154262
  if (!slot || !slot.headers) return result;
154263
+ if (paused()) {
154264
+ slot.headers = null;
154265
+ return result;
154266
+ }
153419
154267
  var rec = createRecord(isFetchXhr(this, slot) ? 'Fetch' : 'XHR', slot.method, slot.url, slot.headers, body, startedAt);
153420
154268
  slot.headers = null;
153421
154269
  listen(this, rec);
@@ -153640,7 +154488,7 @@ var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
153640
154488
  var startedAt = Date.now();
153641
154489
  var promise = origStart.apply(this, arguments);
153642
154490
  var response = responses.get(this);
153643
- if (!response || !promise || typeof promise.then !== 'function') return promise;
154491
+ if (!response || !promise || typeof promise.then !== 'function' || paused()) return promise;
153644
154492
  try {
153645
154493
  var rec = createRecord('Fetch', String((init && init.method) || 'GET').toUpperCase(), String(url),
153646
154494
  lowerCaseHeaders(init && init.headers), body, startedAt);
@@ -153881,7 +154729,7 @@ var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
153881
154729
  var origSendRequest = networking.sendRequest;
153882
154730
  var origAbortRequest = networking.abortRequest;
153883
154731
  networking.sendRequest = function(method, trackingName, url, headers, data, responseType, incrementalUpdates, timeout, callback) {
153884
- if (xhrSending || typeof callback !== 'function') return origSendRequest.apply(this, arguments);
154732
+ if (xhrSending || typeof callback !== 'function' || paused()) return origSendRequest.apply(this, arguments);
153885
154733
  var watcher = null;
153886
154734
  try { watcher = watchRequest(networking, method, url, headers, data, responseType); } catch (e) {}
153887
154735
  if (!watcher) return origSendRequest.apply(this, arguments);
@@ -153908,6 +154756,62 @@ var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
153908
154756
 
153909
154757
  return JSON.stringify({ installed: true });
153910
154758
  })()`;
154759
+ var NETWORK_CAPTURE_MARK_SCRIPT = `(function() {
154760
+ var g = globalThis;
154761
+ return typeof g.__argent_network_mark === 'function' ? g.__argent_network_mark() : JSON.stringify({ install: null });
154762
+ })()`;
154763
+ var HOLDER = JSON.stringify((0, import_node_crypto15.randomUUID)());
154764
+ function holderRecord(capturing2) {
154765
+ return JSON.stringify({ capturing: capturing2, pid: process.pid, host: (0, import_node_os12.hostname)() });
154766
+ }
154767
+ function makeNetworkCaptureControlScript(paused) {
154768
+ return `(function() {
154769
+ var g = globalThis;
154770
+ g.__argent_network_paused = ${paused ? "true" : "false"};${paused ? `
154771
+ var holders = g.__argent_network_holders;
154772
+ if (holders && Object.prototype.hasOwnProperty.call(holders, ${HOLDER})) holders[${HOLDER}] = ${holderRecord(false)};` : `
154773
+ (g.__argent_network_holders = g.__argent_network_holders || {})[${HOLDER}] = ${holderRecord(true)};`}
154774
+ return JSON.stringify({ installed: typeof g.__argent_network_mark === 'function' });
154775
+ })()`;
154776
+ }
154777
+ var NETWORK_CAPTURE_END_SCRIPT = `(function() {
154778
+ var g = globalThis;
154779
+ g.__argent_network_paused = true;
154780
+ if (g.__argent_network_holders) delete g.__argent_network_holders[${HOLDER}];
154781
+ if (typeof g.__argent_network_clear === 'function') g.__argent_network_clear();
154782
+ })()`;
154783
+ function makeNetworkCaptureReleaseScript(exited) {
154784
+ return `(function() {
154785
+ var g = globalThis;
154786
+ var holders = g.__argent_network_holders;
154787
+ var readers = false;
154788
+ if (holders) {
154789
+ delete holders[${HOLDER}];
154790
+ var exited = ${JSON.stringify(exited)};
154791
+ for (var i = 0; i < exited.length; i++) delete holders[exited[i]];
154792
+ for (var key in holders) {
154793
+ if (!Object.prototype.hasOwnProperty.call(holders, key)) continue;
154794
+ if (holders[key].capturing) return JSON.stringify({ holders: holders });
154795
+ readers = true;
154796
+ }
154797
+ }
154798
+ g.__argent_network_paused = true;
154799
+ if (!readers && typeof g.__argent_network_clear === 'function') g.__argent_network_clear();
154800
+ return JSON.stringify({ holders: holders || {} });
154801
+ })()`;
154802
+ }
154803
+ function exitedHolders(answer) {
154804
+ let holders;
154805
+ try {
154806
+ holders = JSON.parse(String(answer)).holders;
154807
+ } catch {
154808
+ return [];
154809
+ }
154810
+ return Object.keys(holders).filter((key2) => {
154811
+ const { pid, host } = holders[key2];
154812
+ return host === (0, import_node_os12.hostname)() && typeof pid === "number" && !isProcessAlive(pid);
154813
+ });
154814
+ }
153911
154815
  function makeNetworkLogReadScript(start2, limit, metroPort2) {
153912
154816
  return `(function() {
153913
154817
  var log = globalThis.__argent_network_log;
@@ -153950,13 +154854,18 @@ function makeNetworkLogReadScript(start2, limit, metroPort2) {
153950
154854
  });
153951
154855
  }
153952
154856
 
153953
- return JSON.stringify({ entries: entries, total: total, interceptorInstalled: true });
154857
+ return JSON.stringify({
154858
+ entries: entries,
154859
+ total: total,
154860
+ interceptorInstalled: true,
154861
+ paused: globalThis.__argent_network_paused === true
154862
+ });
153954
154863
  })()`;
153955
154864
  }
153956
154865
  function makeNetworkDetailReadScript(requestId) {
153957
154866
  return `(function() {
153958
154867
  var byId = globalThis.__argent_network_by_id;
153959
- if (!byId) return JSON.stringify({ error: 'Network interceptor not installed' });
154868
+ if (!byId) return JSON.stringify({ error: 'Network interceptor not installed', installed: false });
153960
154869
  var entry = byId[${JSON.stringify(requestId)}];
153961
154870
  if (!entry) return JSON.stringify({ error: 'Request not found' });
153962
154871
  if (typeof globalThis.__argent_network_decode === 'function') globalThis.__argent_network_decode(entry);
@@ -153981,7 +154890,187 @@ function makeNetworkDetailReadScript(requestId) {
153981
154890
  }
153982
154891
 
153983
154892
  // ../tool-server/src/blueprints/network-inspector.ts
154893
+ init_device_info();
154894
+ init_external_devices();
153984
154895
  var NETWORK_INSPECTOR_NAMESPACE = "NetworkInspector";
154896
+ var jsCaptures = /* @__PURE__ */ new Map();
154897
+ var jsUnavailable = /* @__PURE__ */ new Map();
154898
+ function splitPayload(payload) {
154899
+ const at = payload.indexOf(":");
154900
+ return { port: Number(payload.slice(0, at)), device: payload.slice(at + 1) };
154901
+ }
154902
+ function sameDevice(a, b) {
154903
+ return externalNativeId(a).toLowerCase() === externalNativeId(b).toLowerCase();
154904
+ }
154905
+ function jsCapturePayload(port, device) {
154906
+ return `${port}:${device}`;
154907
+ }
154908
+ function storedPayload(payload) {
154909
+ const { port, device } = splitPayload(payload);
154910
+ return payloadsOf([device]).find((key2) => splitPayload(key2).port === port);
154911
+ }
154912
+ function jsCapture(payload) {
154913
+ const key2 = storedPayload(payload);
154914
+ return key2 === void 0 ? void 0 : jsCaptures.get(key2);
154915
+ }
154916
+ function forgetJsCapture(device, bundleId) {
154917
+ for (const [payload, capture] of jsCaptures) {
154918
+ if (capture.bundleId === bundleId && sameDevice(splitPayload(payload).device, device)) {
154919
+ jsCaptures.delete(payload);
154920
+ }
154921
+ }
154922
+ for (const [payload, found] of jsUnavailable) {
154923
+ if (found.bundleId === bundleId && sameDevice(splitPayload(payload).device, device)) {
154924
+ jsUnavailable.delete(payload);
154925
+ }
154926
+ }
154927
+ }
154928
+ function setJsCapture(payload, capture) {
154929
+ forgetJsCapture(splitPayload(payload).device, capture.bundleId);
154930
+ const held = storedPayload(payload);
154931
+ if (held !== void 0) jsCaptures.delete(held);
154932
+ const unavailable3 = unavailablePayload(payload);
154933
+ if (unavailable3 !== void 0) jsUnavailable.delete(unavailable3);
154934
+ jsCaptures.set(payload, capture);
154935
+ }
154936
+ function unavailablePayload(payload) {
154937
+ const { port, device } = splitPayload(payload);
154938
+ return [...jsUnavailable.keys()].find((key2) => {
154939
+ const at = splitPayload(key2);
154940
+ return at.port === port && sameDevice(at.device, device);
154941
+ });
154942
+ }
154943
+ function setJsUnavailable(payload, bundleId, reason2) {
154944
+ const held = unavailablePayload(payload);
154945
+ if (held !== void 0) jsUnavailable.delete(held);
154946
+ jsUnavailable.set(payload, { bundleId, reason: reason2 });
154947
+ }
154948
+ function jsUnavailableOn(payload) {
154949
+ const key2 = unavailablePayload(payload);
154950
+ return key2 === void 0 ? void 0 : jsUnavailable.get(key2);
154951
+ }
154952
+ function jsCapturesOn(device) {
154953
+ const found = [];
154954
+ for (const [payload, capture] of jsCaptures) {
154955
+ const { port, device: of } = splitPayload(payload);
154956
+ if (sameDevice(of, device)) found.push({ ...capture, port });
154957
+ }
154958
+ return found;
154959
+ }
154960
+ function findJsCapture(device, bundleId) {
154961
+ return jsCapturesOn(device).find((capture) => capture.bundleId === bundleId);
154962
+ }
154963
+ function payloadsOf(devices2) {
154964
+ return [...jsCaptures.keys()].filter((payload) => {
154965
+ const { device } = splitPayload(payload);
154966
+ return !devices2 || devices2.some((id) => sameDevice(id, device));
154967
+ });
154968
+ }
154969
+ function forgetJsCapturesOf(devices2, paused) {
154970
+ for (const payload of jsUnavailable.keys()) {
154971
+ const { device } = splitPayload(payload);
154972
+ if (!devices2 || devices2.some((id) => sameDevice(id, device))) jsUnavailable.delete(payload);
154973
+ }
154974
+ for (const payload of payloadsOf(devices2)) {
154975
+ const capture = jsCaptures.get(payload);
154976
+ if (paused && !paused.has(payload) && capture.installed && !capture.paused) {
154977
+ jsCaptures.set(payload, {
154978
+ bundleId: capture.bundleId,
154979
+ intent: "stopped",
154980
+ ...capture.mark ? { mark: capture.mark } : {},
154981
+ installed: true,
154982
+ ...capture.physicalDeviceId ? { physicalDeviceId: capture.physicalDeviceId } : {}
154983
+ });
154984
+ } else {
154985
+ jsCaptures.delete(payload);
154986
+ }
154987
+ }
154988
+ }
154989
+ function forgetJsCaptures(payloads) {
154990
+ for (const payload of payloads) jsCaptures.delete(payload);
154991
+ }
154992
+ var PAUSE_BEFORE_FORGET_TIMEOUT_MS = 1e3;
154993
+ async function pauseJsCapturesOf(registry2, devices2, { atExit = false } = {}) {
154994
+ const services = registry2.getSnapshot().services;
154995
+ const paused = /* @__PURE__ */ new Set();
154996
+ await Promise.all(
154997
+ payloadsOf(devices2).map(async (payload) => {
154998
+ const urn = `${JS_RUNTIME_DEBUGGER_NAMESPACE}:${payload}`;
154999
+ const state3 = services.get(urn)?.state;
155000
+ if (state3 === void 0 || !isLiveServiceState(state3)) return;
155001
+ const { bundleId } = jsCaptures.get(payload);
155002
+ const pause = (async () => {
155003
+ const dbg = await registry2.resolveService(urn);
155004
+ const appId = dbg.runtimeApp?.appId;
155005
+ if (appId !== void 0 && appId !== bundleId) return false;
155006
+ const options = { timeout: PAUSE_BEFORE_FORGET_TIMEOUT_MS };
155007
+ if (!atExit) {
155008
+ await dbg.cdp.evaluate(NETWORK_CAPTURE_END_SCRIPT, options);
155009
+ return true;
155010
+ }
155011
+ const left = await dbg.cdp.evaluate(makeNetworkCaptureReleaseScript([]), options);
155012
+ const exited = exitedHolders(left);
155013
+ if (exited.length > 0) {
155014
+ await dbg.cdp.evaluate(makeNetworkCaptureReleaseScript(exited), options);
155015
+ }
155016
+ return true;
155017
+ })();
155018
+ let timer;
155019
+ const late = new Promise((resolve21) => {
155020
+ timer = setTimeout(() => resolve21(false), PAUSE_BEFORE_FORGET_TIMEOUT_MS);
155021
+ });
155022
+ try {
155023
+ if (await Promise.race([pause, late])) paused.add(payload);
155024
+ } catch {
155025
+ } finally {
155026
+ clearTimeout(timer);
155027
+ }
155028
+ })
155029
+ );
155030
+ return paused;
155031
+ }
155032
+ var NO_XHR_YET = "no XMLHttpRequest yet";
155033
+ async function installNetworkInterceptor(cdp, payload, runtimeApp) {
155034
+ const { device } = splitPayload(payload);
155035
+ if (resolveDevice(device).platform === "vega") {
155036
+ return parseInstall(await cdp.evaluate(NETWORK_INTERCEPTOR_SCRIPT));
155037
+ }
155038
+ const capture = jsCapture(payload);
155039
+ if (capture?.intent !== "started") {
155040
+ return { installed: false, reason: `capture is ${capture ? "stopped" : "not started"}` };
155041
+ }
155042
+ if (runtimeApp?.appId !== void 0 && runtimeApp.appId !== capture.bundleId) {
155043
+ return { installed: false, reason: `the JS runtime is ${runtimeApp.appId}'s` };
155044
+ }
155045
+ const before = capture.installed;
155046
+ capture.installed = true;
155047
+ try {
155048
+ await cdp.evaluate(makeNetworkCaptureControlScript(false));
155049
+ } catch (err) {
155050
+ if (neverSent(err)) capture.installed = before;
155051
+ throw err;
155052
+ }
155053
+ const install = parseInstall(await cdp.evaluate(NETWORK_INTERCEPTOR_SCRIPT));
155054
+ if (install.installed || install.reason === "already installed") return { installed: true };
155055
+ if (install.reason === NO_XHR_YET) capture.installed = before;
155056
+ return install;
155057
+ }
155058
+ function neverSent(err) {
155059
+ const code = getFailureSignal(err)?.error_code;
155060
+ return code === FAILURE_CODES.DEBUGGER_CDP_NOT_CONNECTED || code === FAILURE_CODES.JS_RUNTIME_PAUSED;
155061
+ }
155062
+ function parseInstall(raw) {
155063
+ try {
155064
+ const parsed2 = JSON.parse(String(raw));
155065
+ if (parsed2.installed === true) return { installed: true };
155066
+ return {
155067
+ installed: false,
155068
+ reason: typeof parsed2.reason === "string" ? parsed2.reason : "unknown"
155069
+ };
155070
+ } catch {
155071
+ return { installed: false, reason: `unexpected answer: ${String(raw).slice(0, 200)}` };
155072
+ }
155073
+ }
153985
155074
  var networkInspectorBlueprint = {
153986
155075
  namespace: NETWORK_INSPECTOR_NAMESPACE,
153987
155076
  // payload is "port:deviceId"
@@ -153991,10 +155080,10 @@ var networkInspectorBlueprint = {
153991
155080
  getDependencies(payload) {
153992
155081
  return { debugger: `JsRuntimeDebugger:${payload}` };
153993
155082
  },
153994
- async factory(deps, _payload) {
155083
+ async factory(deps, payload) {
153995
155084
  const debuggerApi = deps.debugger;
153996
155085
  const cdp = debuggerApi.cdp;
153997
- await cdp.evaluate(NETWORK_INTERCEPTOR_SCRIPT).catch((err) => {
155086
+ await installNetworkInterceptor(cdp, payload, debuggerApi.runtimeApp).catch((err) => {
153998
155087
  const msg = err instanceof Error ? err.message : String(err);
153999
155088
  process.stderr.write(
154000
155089
  `[NetworkInspector:${debuggerApi.port}] NETWORK_INTERCEPTOR_SCRIPT failed (non-fatal): ${msg}
@@ -154867,7 +155956,7 @@ function clearLostProfilerRun(port, deviceId) {
154867
155956
  var import_node_child_process34 = require("node:child_process");
154868
155957
  var import_node_fs16 = require("node:fs");
154869
155958
  var import_promises14 = require("node:fs/promises");
154870
- var import_node_os14 = require("node:os");
155959
+ var import_node_os15 = require("node:os");
154871
155960
  var import_node_path19 = require("node:path");
154872
155961
  var import_node_util24 = require("node:util");
154873
155962
  init_zod();
@@ -154914,7 +156003,7 @@ async function listEmulatorPidsForAvd(avdName) {
154914
156003
 
154915
156004
  // ../tool-server/src/utils/linux-preflight.ts
154916
156005
  var fs43 = __toESM(require("node:fs"));
154917
- var import_node_os12 = require("node:os");
156006
+ var import_node_os13 = require("node:os");
154918
156007
  var import_node_path17 = require("node:path");
154919
156008
  var import_ini2 = __toESM(require_ini());
154920
156009
  function linuxBootDiagnostics(avdName) {
@@ -154943,7 +156032,7 @@ function checkKvm() {
154943
156032
  var MIN_RAM_MB = 4096;
154944
156033
  var MIN_HEAP_MB = 512;
154945
156034
  function checkAvdSizing(avdName) {
154946
- const configPath = (0, import_node_path17.join)((0, import_node_os12.homedir)(), ".android", "avd", `${avdName}.avd`, "config.ini");
156035
+ const configPath = (0, import_node_path17.join)((0, import_node_os13.homedir)(), ".android", "avd", `${avdName}.avd`, "config.ini");
154947
156036
  let content;
154948
156037
  try {
154949
156038
  content = fs43.readFileSync(configPath, "utf8");
@@ -154979,7 +156068,7 @@ function readMb(config2, key2) {
154979
156068
  // ../tool-server/src/utils/simulator-app-launch.ts
154980
156069
  var import_node_child_process32 = require("node:child_process");
154981
156070
  var import_node_fs15 = __toESM(require("node:fs"));
154982
- var import_node_os13 = __toESM(require("node:os"));
156071
+ var import_node_os14 = __toESM(require("node:os"));
154983
156072
  var import_node_path18 = __toESM(require("node:path"));
154984
156073
  var import_node_util23 = require("node:util");
154985
156074
  var execFileAsync23 = (0, import_node_util23.promisify)(import_node_child_process32.execFile);
@@ -154988,7 +156077,7 @@ var LAUNCH_WATCH_MS = 1e4;
154988
156077
  var LAUNCH_POLL_MS = 250;
154989
156078
  var launchLocks = /* @__PURE__ */ new Map();
154990
156079
  function verdictFilePath() {
154991
- return import_node_path18.default.join(import_node_os13.default.homedir(), ".argent", "simulator-app-launch.json");
156080
+ return import_node_path18.default.join(import_node_os14.default.homedir(), ".argent", "simulator-app-launch.json");
154992
156081
  }
154993
156082
  function loadVerdicts() {
154994
156083
  try {
@@ -155847,7 +156936,7 @@ async function attemptBoot(params) {
155847
156936
  let stdio = "ignore";
155848
156937
  if (process.platform === "win32") {
155849
156938
  const safeName = params.avdName.replace(/[^\w.-]/g, "_");
155850
- const logPath = (0, import_node_path19.join)((0, import_node_os14.tmpdir)(), `argent-emulator-${safeName}.log`);
156939
+ const logPath = (0, import_node_path19.join)((0, import_node_os15.tmpdir)(), `argent-emulator-${safeName}.log`);
155851
156940
  emulatorLogFd = (0, import_node_fs16.openSync)(logPath, "w");
155852
156941
  stdio = ["ignore", emulatorLogFd, emulatorLogFd];
155853
156942
  }
@@ -156376,11 +157465,11 @@ async function startHarmonyEmulator(instanceName) {
156376
157465
  });
156377
157466
  }
156378
157467
  try {
156379
- for (const entry of (0, import_node_fs16.readdirSync)((0, import_node_os14.tmpdir)())) {
157468
+ for (const entry of (0, import_node_fs16.readdirSync)((0, import_node_os15.tmpdir)())) {
156380
157469
  if (!entry.startsWith("argent-harmony-") || !entry.endsWith(".log")) continue;
156381
157470
  try {
156382
- if (Date.now() - (0, import_node_fs16.statSync)((0, import_node_path19.join)((0, import_node_os14.tmpdir)(), entry)).mtimeMs > HARMONY_LOG_TTL_MS) {
156383
- (0, import_node_fs16.rmSync)((0, import_node_path19.join)((0, import_node_os14.tmpdir)(), entry), { force: true });
157471
+ if (Date.now() - (0, import_node_fs16.statSync)((0, import_node_path19.join)((0, import_node_os15.tmpdir)(), entry)).mtimeMs > HARMONY_LOG_TTL_MS) {
157472
+ (0, import_node_fs16.rmSync)((0, import_node_path19.join)((0, import_node_os15.tmpdir)(), entry), { force: true });
156384
157473
  }
156385
157474
  } catch {
156386
157475
  }
@@ -156388,7 +157477,7 @@ async function startHarmonyEmulator(instanceName) {
156388
157477
  } catch {
156389
157478
  }
156390
157479
  const safeName = instanceName.replace(/[^\w.-]/g, (c) => `%${c.codePointAt(0).toString(16)}`);
156391
- const logPath = (0, import_node_path19.join)((0, import_node_os14.tmpdir)(), `argent-harmony-${safeName}-${process.hrtime.bigint()}.log`);
157480
+ const logPath = (0, import_node_path19.join)((0, import_node_os15.tmpdir)(), `argent-harmony-${safeName}-${process.hrtime.bigint()}.log`);
156392
157481
  let logFd;
156393
157482
  try {
156394
157483
  logFd = (0, import_node_fs16.openSync)(logPath, "w");
@@ -156495,7 +157584,7 @@ async function waitForHarmonyTarget(before, deadline, checkAlive, expected) {
156495
157584
  }
156496
157585
  }
156497
157586
  async function waitForHarmonyDrivable(connectKey, deadline, checkAlive) {
156498
- const probePath = (0, import_node_path19.join)((0, import_node_os14.tmpdir)(), `argent-harmony-bootprobe-${process.hrtime.bigint()}.json`);
157587
+ const probePath = (0, import_node_path19.join)((0, import_node_os15.tmpdir)(), `argent-harmony-bootprobe-${process.hrtime.bigint()}.json`);
156499
157588
  let inFlight4 = null;
156500
157589
  try {
156501
157590
  for (; ; ) {
@@ -156964,10 +158053,6 @@ function dispatchByPlatform(opts) {
156964
158053
  };
156965
158054
  }
156966
158055
 
156967
- // ../tool-server/src/utils/bundle-id.ts
156968
- var BUNDLE_ID_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
156969
- var BUNDLE_ID_MESSAGE = "bundleId may only contain letters, digits, '.', '_' and '-', and may not start with '-' or '.'";
156970
-
156971
158056
  // ../tool-server/src/tools/launch-app/platforms/ios.ts
156972
158057
  var import_node_child_process35 = require("node:child_process");
156973
158058
  var import_node_util25 = require("node:util");
@@ -157478,7 +158563,7 @@ function createLaunchAppTool(registry2) {
157478
158563
  longRunning: true,
157479
158564
  description: `Open an installed app, or confirm the running renderer (Chromium).<flag:macos-apps> On a Mac app it starts the app in the background when it does not run, and leaves a running app as it is.</flag:macos-apps>
157480
158565
  Use when starting any app; prefer this over tapping home-screen / launcher icons. Also prepares the native-devtools injection before the app starts (iOS and Apple TV).
157481
- Returns { launched, bundleId, <flag:macos-apps>kind?, appPath?, args?, </flag:macos-apps>note?, networkCapture? }. Fails if the app is not installed on the target device (iOS / Android<flag:harmonyos> / HarmonyOS</flag:harmonyos>). On a physical iPhone this registers the app every other tool acts on; com.apple.springboard and com.apple.Spotlight register without launching. note warns when runner signing is not ready. networkCapture (Android, and local iOS simulators where capture stays on for later processes) says whether native network capture followed the launch.<flag:macos-apps>
158566
+ Returns { launched, bundleId, <flag:macos-apps>kind?, appPath?, args?, </flag:macos-apps>note?, networkCapture? }. Fails if the app is not installed on the target device (iOS / Android<flag:harmonyos> / HarmonyOS</flag:harmonyos>). On a physical iPhone this registers the app every other tool acts on; com.apple.springboard and com.apple.Spotlight register without launching. note warns when runner signing is not ready. networkCapture (Android, and local iOS simulators where capture stays on for later processes), once network-capture-start started native network capture for the app, says whether it followed the launch, or that network-capture-stop stopped it.<flag:macos-apps>
157482
158567
  For Mac apps, kind is 'catalyst' or 'app'. Check appPath and args to confirm the build and arguments in use. The note can report an already running app or a missing window.</flag:macos-apps>
157483
158568
  For Chromium, the app is already running behind a CDP port; this call simply refreshes the cached viewport and acknowledges the bundleId tag. To change the visible route, use \`open-url\`.
157484
158569
 
@@ -157778,7 +158863,7 @@ function createRestartAppTool(registry2) {
157778
158863
  longRunning: true,
157779
158864
  description: `Terminate then relaunch an app on iOS, Android, <flag:harmonyos>HarmonyOS, </flag:harmonyos><flag:macos-apps>macOS, </flag:macos-apps>or Vega.
157780
158865
  Use when you need a clean in-memory state without a full reinstall. The relaunch also refreshes the native-devtools injection (iOS and Apple TV).<flag:macos-apps> On a Mac app it quits the app and starts the same .app again in the background.</flag:macos-apps>
157781
- Returns { restarted, bundleId, <flag:macos-apps>kind?, appPath?, args?, note?, </flag:macos-apps>networkCapture? }. networkCapture (Android, and local iOS simulators where capture stays on for later processes) says whether native network capture followed the launch. Fails if the app is not installed, on a local iOS simulator if terminating it does not finish within 15s, or on a remote simulator if terminating it fails for a reason other than the app not running.<flag:macos-apps>
158866
+ Returns { restarted, bundleId, <flag:macos-apps>kind?, appPath?, args?, note?, </flag:macos-apps>networkCapture? }. networkCapture (Android, and local iOS simulators where capture stays on for later processes), once network-capture-start started native network capture for the app, says whether it followed the launch, or that network-capture-stop stopped it. Fails if the app is not installed, on a local iOS simulator if terminating it does not finish within 15s, or on a remote simulator if terminating it fails for a reason other than the app not running.<flag:macos-apps>
157782
158867
  For Mac apps, kind is 'catalyst' or 'app'. Check appPath and args to confirm the restarted build and arguments. Check note for warnings such as a force-quit or no window.</flag:macos-apps>`,
157783
158868
  zodSchema: zodSchema12,
157784
158869
  alwaysLoad: true,
@@ -159136,14 +160221,14 @@ function androidDevtoolsRotationPeek(registry2, device) {
159136
160221
 
159137
160222
  // ../tool-server/src/utils/vega-screen.ts
159138
160223
  var import_promises17 = require("node:fs/promises");
159139
- var import_node_os16 = require("node:os");
160224
+ var import_node_os17 = require("node:os");
159140
160225
  var import_node_path28 = require("node:path");
159141
160226
  var import_pngjs3 = __toESM(require_png());
159142
160227
  init_src2();
159143
160228
  init_adb();
159144
160229
 
159145
160230
  // ../tool-server/src/utils/emulator-console.ts
159146
- var import_node_os15 = require("node:os");
160231
+ var import_node_os16 = require("node:os");
159147
160232
  var import_node_path27 = require("node:path");
159148
160233
  init_adb();
159149
160234
  async function runEmuConsole(serial, args) {
@@ -159160,7 +160245,7 @@ function describeConsoleReply(stdout) {
159160
160245
  const lines = replyLines(stdout);
159161
160246
  const reply = lines.join("; ") || "empty reply";
159162
160247
  if (!lines.at(-1)?.startsWith("KO: unknown command")) return reply;
159163
- const tokenFile = (0, import_node_path27.join)((0, import_node_os15.homedir)(), ".emulator_console_auth_token");
160248
+ const tokenFile = (0, import_node_path27.join)((0, import_node_os16.homedir)(), ".emulator_console_auth_token");
159164
160249
  const fileKind = process.platform === "win32" ? "a file" : "a regular file, not a symlink,";
159165
160250
  return `${reply} (adb authenticates to the console with ${tokenFile}, which must be ${fileKind} holding the emulator's token)`;
159166
160251
  }
@@ -159175,7 +160260,7 @@ async function captureVegaScreenshotPng(opts = {}) {
159175
160260
  async function captureViaEmulatorConsole(opts) {
159176
160261
  const port = await discoverVegaConsolePort();
159177
160262
  const serial = `emulator-${port}`;
159178
- const outDir = await (0, import_promises17.mkdtemp)((0, import_node_path28.join)((0, import_node_os16.tmpdir)(), "vega-shot-"));
160263
+ const outDir = await (0, import_promises17.mkdtemp)((0, import_node_path28.join)((0, import_node_os17.tmpdir)(), "vega-shot-"));
159179
160264
  try {
159180
160265
  const { stdout } = await runAdb(["-s", serial, "emu", "screenrecord", "screenshot", outDir], {
159181
160266
  timeoutMs: 2e4
@@ -159197,7 +160282,7 @@ async function captureViaEmulatorConsole(opts) {
159197
160282
  decoded2,
159198
160283
  opts.scale ?? getScreenshotScaleOverride() ?? tvDefaultScale(decoded2.width, decoded2.height)
159199
160284
  );
159200
- const outPath = (0, import_node_path28.join)((0, import_node_os16.tmpdir)(), `vega-screenshot-${process.hrtime.bigint()}.png`);
160285
+ const outPath = (0, import_node_path28.join)((0, import_node_os17.tmpdir)(), `vega-screenshot-${process.hrtime.bigint()}.png`);
159201
160286
  await (0, import_promises17.writeFile)(outPath, import_pngjs3.PNG.sync.write(scaled));
159202
160287
  return outPath;
159203
160288
  } finally {
@@ -159208,7 +160293,7 @@ async function captureViaEmulatorConsole(opts) {
159208
160293
 
159209
160294
  // ../tool-server/src/utils/harmony-screen.ts
159210
160295
  var import_promises18 = require("node:fs/promises");
159211
- var import_node_os17 = require("node:os");
160296
+ var import_node_os18 = require("node:os");
159212
160297
  var import_node_path29 = require("node:path");
159213
160298
  var import_pngjs4 = __toESM(require_png());
159214
160299
  init_src2();
@@ -159230,12 +160315,12 @@ function decodeCapture(raw, connectKey) {
159230
160315
  }
159231
160316
  }
159232
160317
  async function captureHarmonyScreenshotPng(opts) {
159233
- const rawPath = (0, import_node_path29.join)((0, import_node_os17.tmpdir)(), `argent-harmony-raw-${process.hrtime.bigint()}.png`);
160318
+ const rawPath = (0, import_node_path29.join)((0, import_node_os18.tmpdir)(), `argent-harmony-raw-${process.hrtime.bigint()}.png`);
159234
160319
  try {
159235
160320
  await harmonyScreenCap(opts.connectKey, rawPath);
159236
160321
  const decoded2 = decodeCapture(await (0, import_promises18.readFile)(rawPath), opts.connectKey);
159237
160322
  const scaled = scaleDecodedPng(decoded2, opts.scale);
159238
- const outPath = (0, import_node_path29.join)((0, import_node_os17.tmpdir)(), `harmony-screenshot-${process.hrtime.bigint()}.png`);
160323
+ const outPath = (0, import_node_path29.join)((0, import_node_os18.tmpdir)(), `harmony-screenshot-${process.hrtime.bigint()}.png`);
159239
160324
  if (scaled === decoded2) {
159240
160325
  await (0, import_promises18.rename)(rawPath, outPath);
159241
160326
  } else {
@@ -163128,7 +164213,7 @@ init_device_info();
163128
164213
  init_capability();
163129
164214
 
163130
164215
  // ../tool-server/src/utils/sub-invoke.ts
163131
- var import_node_crypto15 = require("node:crypto");
164216
+ var import_node_crypto16 = require("node:crypto");
163132
164217
  init_src2();
163133
164218
  async function invokeSubTool(registry2, ctx, toolId, args, extra) {
163134
164219
  const signal = ctx?.signal;
@@ -163144,7 +164229,7 @@ async function invokeSubTool(registry2, ctx, toolId, args, extra) {
163144
164229
  if (!recordChildInvocation) {
163145
164230
  return signal || Object.keys(forwarded).length > 0 ? registry2.invokeTool(toolId, args, { ...signal ? { signal } : {}, ...forwarded }) : registry2.invokeTool(toolId, args);
163146
164231
  }
163147
- const toolInvocationId = (0, import_node_crypto15.randomUUID)();
164232
+ const toolInvocationId = (0, import_node_crypto16.randomUUID)();
163148
164233
  const release2 = recordChildInvocation(toolInvocationId, args);
163149
164234
  try {
163150
164235
  return await registry2.invokeTool(toolId, args, {
@@ -165062,6 +166147,41 @@ var ITEMS_PER_PAGE = 50;
165062
166147
  function notInstalled(installError) {
165063
166148
  return installError ? `Network interceptor could not be installed in the app's JS runtime: ${installError}` : "Network interceptor not installed: the app's JS runtime reloaded, which clears captured requests. Call view-network-logs again to reinstall it, then repeat the action that sends the requests.";
165064
166149
  }
166150
+ var NOT_STARTED = "Network capture is not started for this app, so no requests are recorded. Call network-capture-start with udid and bundleId, repeat the action, then";
166151
+ var PAUSED_BY_STOP = "JS runtime does not record new requests: an earlier stop paused it (network-capture-stop, stop-all-simulator-servers or the exit of a tool-server), and no network-capture-start reached it since";
166152
+ function jsReadPort(params) {
166153
+ if (params.port !== void 0) return params.port;
166154
+ const device = canonicalDeviceId(params.device_id);
166155
+ const provided = device ? jsCapturesOn(device).find(
166156
+ (capture) => capture.physicalDeviceId !== void 0 && metroPort({ device_id: capture.physicalDeviceId }) === capture.port
166157
+ ) : void 0;
166158
+ return provided?.port ?? metroPort(params);
166159
+ }
166160
+ function jsCaptureDebuggerRef(params, capture) {
166161
+ const urn = debuggerServiceRef({ ...params, port: jsReadPort(params) });
166162
+ return capture.physicalDeviceId && typeof urn === "string" ? { urn, options: { physicalDeviceId: capture.physicalDeviceId } } : urn;
166163
+ }
166164
+ function jsCaptureForRead(payload, runtimeApp) {
166165
+ const capture = jsCapture(payload);
166166
+ if (!capture) return void 0;
166167
+ if (runtimeApp?.appId !== void 0 && runtimeApp.appId !== capture.bundleId) return void 0;
166168
+ return capture;
166169
+ }
166170
+ function jsNotStarted(device, port, then = "call view-network-logs again", lead = "") {
166171
+ const elsewhere = jsCapturesOn(device).filter((capture) => capture.port !== port).map(
166172
+ (capture) => ` This device has network capture for ${capture.bundleId} on Metro port ${capture.port}: pass port ${capture.port} to read it.`
166173
+ ).join("");
166174
+ const unavailable3 = jsUnavailableOn(jsCapturePayload(port, device));
166175
+ const head = unavailable3 ? `Network capture is not started on the JS layer: network-capture-start for ${unavailable3.bundleId} found it unavailable (${unavailable3.reason}). native-network-logs lists the requests of the native layer. Once the JS layer can start, call network-capture-start again, repeat the action, then` : NOT_STARTED;
166176
+ return `${lead}${head} ${then}.${elsewhere}`;
166177
+ }
166178
+ function jsNoLog(capture) {
166179
+ if (capture.intent === "stopped") {
166180
+ return capture.installed ? `Network capture is stopped for ${capture.bundleId} (network-capture-stop), and the app's JS runtime reloaded since, which cleared its requests. Call network-capture-start to capture again, then repeat the action.` : `Network capture is stopped for ${capture.bundleId} (network-capture-stop), and nothing was recorded in the app's current JS runtime. Call network-capture-start to capture again, then repeat the action.`;
166181
+ }
166182
+ const native = "native-network-logs lists the requests of the native layer.";
166183
+ return capture.installed ? `The JS layer of network capture for this app stopped recording at a JavaScript reload, so it recorded no requests since the reload. ${native} To record the app's JavaScript requests again, call network-capture-start, repeat the action, then read again.` : `Network capture for this app is started, but the app's JavaScript runtime was not ready at the start, so the JS layer recorded no requests. ${native} To record the app's JavaScript requests, call network-capture-start again, repeat the action, then read again.`;
166184
+ }
165065
166185
  function formatBytes2(bytes) {
165066
166186
  return (0, import_bytes3.default)(bytes, { decimalPlaces: 1, unitSeparator: " " }) ?? `${bytes} B`;
165067
166187
  }
@@ -165178,7 +166298,7 @@ var networkLogsTool = {
165178
166298
  Returns a paginated list of requests with method, URL, status, resource type, size, and duration.
165179
166299
  A size with "~" is estimated from the body's length in characters; on React Native, "\u2192 <url>" is the final URL after a redirect.
165180
166300
  Pass an entry's requestId to view-network-request-details for full details.
165181
- On React Native (iOS / Android / Vega) an interceptor injected into the JS runtime records each request once, from XMLHttpRequest (axios included), React Native's fetch, Expo's fetch, and, in a Metro development build, a fetch library that sends through React Native's network module itself, such as react-native-fetch-api. Capture starts at the first network-tool call; a reload clears it. On Chromium it reads the CDP Network domain of the active tab (all request types).
166301
+ On React Native (iOS / Android / Vega) an interceptor injected into the JS runtime records each request once, from XMLHttpRequest (axios included), React Native's fetch, Expo's fetch, and, in a Metro development build, a fetch library that sends through React Native's network module itself, such as react-native-fetch-api. On iOS and Android this tool only reads: call network-capture-start first, then repeat the action; until then it says capture is not started. A reload clears the requests and stops recording until network-capture-start runs again, which the answer says. On Vega capture starts at the first network-tool call. On Chromium it reads the CDP Network domain of the active tab (all request types).
165182
166302
  Use when inspecting outbound HTTP traffic or debugging API calls in the running app.
165183
166303
  Fails if the app is not connected (RN) or the device is not reachable (Chromium).`,
165184
166304
  zodSchema: zodSchema38,
@@ -165194,49 +166314,74 @@ Fails if the app is not connected (RN) or the device is not reachable (Chromium)
165194
166314
  if (device.platform === "chromium") {
165195
166315
  return { chromium: chromiumCdpRef(device) };
165196
166316
  }
165197
- return {
165198
- inspector: `NetworkInspector:${metroPort(params)}:${canonicalDeviceId(params.device_id)}`
165199
- };
166317
+ const payload = jsCapturePayload(jsReadPort(params), canonicalDeviceId(params.device_id));
166318
+ if (device.platform === "vega") return { inspector: `NetworkInspector:${payload}` };
166319
+ const capture = jsCapture(payload);
166320
+ return capture ? { debugger: jsCaptureDebuggerRef(params, capture) } : {};
165200
166321
  },
165201
166322
  async execute(services, params) {
165202
- if (resolveDevice(params.device_id).platform === "chromium") {
166323
+ const device = resolveDevice(params.device_id);
166324
+ if (device.platform === "chromium") {
165203
166325
  const chromium = services.chromium;
165204
166326
  return renderChromiumPage(chromium.server.network.requests(), params.pageIndex);
165205
166327
  }
165206
- const api = services.inspector;
165207
- const installError = await api.cdp.evaluate(NETWORK_INTERCEPTOR_SCRIPT).then(
165208
- () => void 0,
165209
- (err) => err instanceof Error ? err.message : String(err)
165210
- );
165211
- const countRaw = await api.cdp.evaluate(makeNetworkLogReadScript(0, 0, api.port));
165212
- const { total, interceptorInstalled } = JSON.parse(countRaw);
165213
- if (!interceptorInstalled) return notInstalled(installError);
165214
- if (total === 0) {
165215
- return "No network traffic captured. Make sure the app is running and making HTTP requests. Network interception is active: it records XMLHttpRequest (axios included), React Native's fetch, Expo's fetch, and a fetch library that sends through React Native's network module, but not requests sent before capture started (at the first network-tool call).";
165216
- }
165217
- const pageCount = Math.ceil(total / ITEMS_PER_PAGE);
165218
- const pageIndex = params.pageIndex === "latest" ? pageCount - 1 : params.pageIndex;
165219
- if (pageIndex < 0 || pageIndex >= pageCount) {
165220
- return `Page index out of range. Valid range: 0-${pageCount - 1} (${pageCount} pages, ${total} total requests).`;
166328
+ const port = jsReadPort(params);
166329
+ if (device.platform === "vega") {
166330
+ const api = services.inspector;
166331
+ const installError = await api.cdp.evaluate(NETWORK_INTERCEPTOR_SCRIPT).then(
166332
+ () => void 0,
166333
+ (err) => err instanceof Error ? err.message : String(err)
166334
+ );
166335
+ return renderJsLog(api.cdp, port, params.pageIndex, {
166336
+ noLog: () => notInstalled(installError),
166337
+ empty: "No network traffic captured. Make sure the app is running and making HTTP requests. Network interception is active: it records XMLHttpRequest (axios included), React Native's fetch, Expo's fetch, and a fetch library that sends through React Native's network module, but not requests sent before capture started (at the first network-tool call)."
166338
+ });
165221
166339
  }
165222
- const start2 = pageIndex * ITEMS_PER_PAGE;
165223
- const readScript = makeNetworkLogReadScript(start2, ITEMS_PER_PAGE, api.port);
165224
- const raw = await api.cdp.evaluate(readScript);
165225
- const data = JSON.parse(raw);
165226
- if (!data.interceptorInstalled) return notInstalled(installError);
165227
- const lines = data.entries.map(
165228
- (entry) => formatEntry(
165229
- entry.response ? {
165230
- ...entry,
165231
- response: { ...entry.response, statusText: reasonPhrase(entry.response.status) }
165232
- } : entry
165233
- )
165234
- );
165235
- return `=== NETWORK LOGS (page ${pageIndex + 1}/${pageCount}, ${data.total} total) ===
165236
-
165237
- ${lines.join("\n")}`;
166340
+ const deviceId = canonicalDeviceId(params.device_id);
166341
+ const dbg = services.debugger;
166342
+ const capture = dbg && jsCaptureForRead(jsCapturePayload(port, deviceId), dbg.runtimeApp);
166343
+ if (!dbg || !capture) return jsNotStarted(deviceId, port);
166344
+ const stopped = capture.intent === "stopped";
166345
+ return renderJsLog(dbg.cdp, port, params.pageIndex, {
166346
+ noLog: () => jsNoLog(capture),
166347
+ empty: stopped ? `No network traffic captured: network capture is stopped for ${capture.bundleId} (network-capture-stop). Call network-capture-start to capture again, then repeat the action.` : "No network traffic captured. Make sure the app is running and making HTTP requests. Network interception is active: it records XMLHttpRequest (axios included), React Native's fetch, Expo's fetch, and a fetch library that sends through React Native's network module, but not requests sent before network-capture-start.",
166348
+ headerNote: stopped ? "capture stopped" : void 0,
166349
+ // A start that does not reach the app's JS context keeps the pause of an earlier stop there.
166350
+ paused: stopped ? void 0 : {
166351
+ empty: `No network traffic captured. The app's ${PAUSED_BY_STOP}. Call network-capture-start, then repeat the action.`,
166352
+ headerNote: `the app's ${PAUSED_BY_STOP}, so call network-capture-start, then repeat the action`
166353
+ }
166354
+ });
165238
166355
  }
165239
166356
  };
166357
+ async function renderJsLog(cdp, port, pageIndexParam, texts) {
166358
+ const countRaw = await cdp.evaluate(makeNetworkLogReadScript(0, 0, port));
166359
+ const { total, interceptorInstalled, paused } = JSON.parse(countRaw);
166360
+ if (!interceptorInstalled) return texts.noLog();
166361
+ const shown = paused === true && texts.paused || texts;
166362
+ if (total === 0) return shown.empty;
166363
+ const pageCount = Math.ceil(total / ITEMS_PER_PAGE);
166364
+ const pageIndex = pageIndexParam === "latest" ? pageCount - 1 : pageIndexParam;
166365
+ if (pageIndex < 0 || pageIndex >= pageCount) {
166366
+ return `Page index out of range. Valid range: 0-${pageCount - 1} (${pageCount} pages, ${total} total requests).`;
166367
+ }
166368
+ const start2 = pageIndex * ITEMS_PER_PAGE;
166369
+ const raw = await cdp.evaluate(makeNetworkLogReadScript(start2, ITEMS_PER_PAGE, port));
166370
+ const data = JSON.parse(raw);
166371
+ if (!data.interceptorInstalled) return texts.noLog();
166372
+ const lines = data.entries.map(
166373
+ (entry) => formatEntry(
166374
+ entry.response ? {
166375
+ ...entry,
166376
+ response: { ...entry.response, statusText: reasonPhrase(entry.response.status) }
166377
+ } : entry
166378
+ )
166379
+ );
166380
+ const note = shown.headerNote ? `; ${shown.headerNote}` : "";
166381
+ return `=== NETWORK LOGS (page ${pageIndex + 1}/${pageCount}, ${data.total} total${note}) ===
166382
+
166383
+ ${lines.join("\n")}`;
166384
+ }
165240
166385
 
165241
166386
  // ../tool-server/src/tools/network/network-request.ts
165242
166387
  var zlib3 = __toESM(require("node:zlib"));
@@ -165268,12 +166413,18 @@ function redactHeaders(headers) {
165268
166413
  }
165269
166414
  return result;
165270
166415
  }
165271
- var NATIVE_ID_PREFIXES = { android: "android-", ios: "ios-" };
166416
+ var NATIVE_ID_PREFIXES = { android: "android-", ios: "ios-", macos: "macos-" };
165272
166417
  function nativeIdPlatform2(requestId) {
165273
166418
  if (requestId.startsWith(NATIVE_ID_PREFIXES.android)) return "android";
165274
166419
  if (requestId.startsWith(NATIVE_ID_PREFIXES.ios)) return "ios";
166420
+ if (requestId.startsWith(NATIVE_ID_PREFIXES.macos)) return "macos";
165275
166421
  return void 0;
165276
166422
  }
166423
+ var NATIVE_LAYERS = {
166424
+ android: { source: "an Android device", name: "Android" },
166425
+ ios: { source: "an iOS simulator", name: "iOS" },
166426
+ macos: { source: "a Mac app", name: "Mac app" }
166427
+ };
165277
166428
  var MAX_BODY_SIZE = 1e3;
165278
166429
  var MAX_DECODED_BODY_BYTES = 16 * 1024 * 1024;
165279
166430
  function cutMarker(fullSize, mimeType, shown = MAX_BODY_SIZE) {
@@ -165300,19 +166451,19 @@ ${postData.slice(0, MAX_BODY_SIZE)}...`;
165300
166451
  var zodSchema39 = external_exports.object({
165301
166452
  port: metroPortField,
165302
166453
  device_id: external_exports.string().describe(
165303
- "Device id from list-devices (iOS simulator UDID or Android serial), the same id used with debugger-connect. An ios- or android- ID needs no debugger connection."
166454
+ "Device id from list-devices (iOS simulator UDID or Android serial, the same id used with debugger-connect<flag:macos-apps>, or a Mac app id</flag:macos-apps>). A native ID needs no debugger connection."
165304
166455
  ),
165305
166456
  requestId: external_exports.string().describe(
165306
- "The requestId from view-network-logs, or an ios- or android- ID from native-network-logs."
166457
+ "The requestId from view-network-logs, or a native ID (ios-, android-<flag:macos-apps> or macos-</flag:macos-apps>) from native-network-logs."
165307
166458
  ),
165308
166459
  includeBody: external_exports.boolean().default(true).describe("Whether to include the response body (if captured).")
165309
166460
  });
165310
166461
  var networkRequestTool = {
165311
166462
  id: "view-network-request-details",
165312
- description: `Get full details of a specific network request by its requestId: one from view-network-logs, or an ios- or android- ID from native-network-logs, which needs no debugger connection.
166463
+ description: `Get full details of a specific network request by its requestId: one from view-network-logs, or a native ID (ios-, android-<flag:macos-apps> or macos-</flag:macos-apps>) from native-network-logs, which needs no debugger connection.
165313
166464
  Returns request/response headers (sensitive headers redacted), status, timing, the request body, and optionally the response body.
165314
- Request and response bodies over 1000 chars are cut to 1000 under a "[TRUNCATED: ...]" line that gives the full size; a binary response body is omitted, as is a binary request body of an ios- or android- ID. For an ios- or android- ID, a body that cannot be read shows "[unavailable: <reason>]"; when the reason says the app may still be sending the request body, call again once the request has ended. Use when you need headers, body, or timing for a specific request after listing logs.
165315
- Returns an error message string if the requestId is not found.`,
166465
+ Request and response bodies over 1000 chars are cut to 1000 under a "[TRUNCATED: ...]" line that gives the full size; a binary response body is omitted, as is a binary request body of a native ID. For a native ID, a body that cannot be read shows "[unavailable: <reason>]"; when the reason says the app may still be sending the request body, call again once the request has ended. Use when you need headers, body, or timing for a specific request after listing logs.
166466
+ Returns an error message string if the requestId is not found; on iOS<flag:macos-apps>, a Mac app</flag:macos-apps> and Android it also says when network capture is not started, which network-capture-start does. IDs keep working after network-capture-stop. A view-network-logs ID holds until the app's JS runtime reloads: the new runtime numbers its requests from rn-net-1 again, so an old ID can name a new request. Native IDs are not affected.`,
165316
166467
  zodSchema: zodSchema39,
165317
166468
  readOnly: true,
165318
166469
  interaction: {
@@ -165320,17 +166471,20 @@ Returns an error message string if the requestId is not found.`,
165320
166471
  completedMsg: ({ params }) => `Read network request ${params.requestId}`,
165321
166472
  failedMsg: ({ params, failureSignal: failureSignal2 }) => `Failed to read network request ${params.requestId}: ${failureSignal2.error_code}`
165322
166473
  },
165323
- capability: DEBUGGER_TOOL_CAPABILITY,
166474
+ // A Mac app has only native IDs, which need no debugger.
166475
+ capability: { ...DEBUGGER_TOOL_CAPABILITY, macos: { app: true, catalyst: true } },
165324
166476
  services: (params) => {
165325
166477
  if (isNativeRequestId(params.requestId)) return {};
165326
166478
  const device = resolveDevice(params.device_id);
166479
+ if (device.platform === "macos") return {};
165327
166480
  if (device.platform === "chromium") {
165328
166481
  return { chromium: chromiumCdpRef(device) };
165329
166482
  }
165330
166483
  if (nativeIdPlatform2(params.requestId)) return {};
165331
- return {
165332
- inspector: `NetworkInspector:${metroPort(params)}:${canonicalDeviceId(params.device_id)}`
165333
- };
166484
+ const payload = jsCapturePayload(jsReadPort(params), canonicalDeviceId(params.device_id));
166485
+ if (device.platform === "vega") return { inspector: `NetworkInspector:${payload}` };
166486
+ const capture = jsCapture(payload);
166487
+ return capture ? { debugger: jsCaptureDebuggerRef(params, capture) } : {};
165334
166488
  },
165335
166489
  async execute(services, params) {
165336
166490
  if (ANDROID_NATIVE_REQUEST_ID.test(params.requestId)) {
@@ -165341,7 +166495,18 @@ Returns an error message string if the requestId is not found.`,
165341
166495
  const found = findIosNativeRecord(params.requestId);
165342
166496
  return found ? nativeRequestDetails(found.record, found.records, params.includeBody) : nativeNotFound(params.requestId, params.device_id, "ios");
165343
166497
  }
166498
+ if (MACOS_NATIVE_REQUEST_ID.test(params.requestId)) {
166499
+ const found = findMacosNativeRecord(params.requestId);
166500
+ return found ? nativeRequestDetails(found.record, found.records, params.includeBody) : nativeNotFound(params.requestId, params.device_id, "macos");
166501
+ }
165344
166502
  const device = resolveDevice(params.device_id);
166503
+ if (device.platform === "macos") {
166504
+ return nativeNotFound(
166505
+ params.requestId,
166506
+ params.device_id,
166507
+ nativeIdPlatform2(params.requestId) ?? "macos"
166508
+ );
166509
+ }
165345
166510
  if (device.platform === "chromium") {
165346
166511
  const chromium = services.chromium;
165347
166512
  const rec = chromium.server.network.get(params.requestId);
@@ -165394,13 +166559,34 @@ Returns an error message string if the requestId is not found.`,
165394
166559
  }
165395
166560
  const nativePlatform = nativeIdPlatform2(params.requestId);
165396
166561
  if (nativePlatform) return nativeNotFound(params.requestId, params.device_id, nativePlatform);
165397
- const api = services.inspector;
165398
- await api.cdp.evaluate(NETWORK_INTERCEPTOR_SCRIPT).catch(() => {
165399
- });
166562
+ let cdp;
166563
+ let noLog;
166564
+ if (device.platform === "vega") {
166565
+ const api = services.inspector;
166566
+ await api.cdp.evaluate(NETWORK_INTERCEPTOR_SCRIPT).catch(() => {
166567
+ });
166568
+ cdp = api.cdp;
166569
+ } else {
166570
+ const port = jsReadPort(params);
166571
+ const deviceId = canonicalDeviceId(params.device_id);
166572
+ const dbg = services.debugger;
166573
+ const capture = dbg && jsCaptureForRead(jsCapturePayload(port, deviceId), dbg.runtimeApp);
166574
+ if (!dbg || !capture) {
166575
+ return jsNotStarted(
166576
+ deviceId,
166577
+ port,
166578
+ "list the requests with view-network-logs",
166579
+ `Request ${params.requestId} not found. `
166580
+ );
166581
+ }
166582
+ cdp = dbg.cdp;
166583
+ noLog = `Request ${params.requestId} not found. ${jsNoLog(capture)}`;
166584
+ }
165400
166585
  const script = makeNetworkDetailReadScript(params.requestId);
165401
- const raw = await api.cdp.evaluate(script);
166586
+ const raw = await cdp.evaluate(script);
165402
166587
  const data = JSON.parse(raw);
165403
166588
  if ("error" in data) {
166589
+ if (data.installed === false && noLog) return noLog;
165404
166590
  return `${data.error}. Use view-network-logs to list available requests.`;
165405
166591
  }
165406
166592
  const entry = data;
@@ -165449,12 +166635,17 @@ ${body.slice(0, MAX_BODY_SIZE)}...`;
165449
166635
  }
165450
166636
  };
165451
166637
  function isNativeRequestId(requestId) {
165452
- return ANDROID_NATIVE_REQUEST_ID.test(requestId) || IOS_NATIVE_REQUEST_ID.test(requestId);
166638
+ return ANDROID_NATIVE_REQUEST_ID.test(requestId) || IOS_NATIVE_REQUEST_ID.test(requestId) || MACOS_NATIVE_REQUEST_ID.test(requestId);
165453
166639
  }
165454
166640
  function nativeNotFound(requestId, deviceId, layer) {
165455
166641
  const { platform } = resolveDevice(deviceId);
165456
166642
  const prefix = NATIVE_ID_PREFIXES[layer];
165457
- return platform === "chromium" || platform === "vega" ? `Request ${requestId} not found. An ${prefix} ID comes from ${layer === "android" ? "an Android device" : "an iOS simulator"}. Use view-network-logs to list this device's requests.` : `Request ${requestId} not found. Use native-network-logs to list the requests the ${layer === "android" ? "Android" : "iOS"} native layer recorded.`;
166643
+ const { source, name } = NATIVE_LAYERS[layer];
166644
+ if (platform === "chromium" || platform === "vega") {
166645
+ return `Request ${requestId} not found. ${layer === "macos" ? "A" : "An"} ${prefix} ID comes from ${source}. Use view-network-logs to list this device's requests.`;
166646
+ }
166647
+ const captured = layer === "android" ? hasAndroidNetworkCapture() : layer === "ios" ? hasIosNetworkCapture() : hasMacosNetworkCapture();
166648
+ return captured ? `Request ${requestId} not found. Use native-network-logs to list the requests the ${name} native layer recorded.` : `Request ${requestId} not found. Native network capture is not started, so no requests are recorded. Call network-capture-start with udid and bundleId, repeat the action, then list the requests with native-network-logs.`;
165458
166649
  }
165459
166650
  async function nativeRequestDetails(record2, bodies, includeBody) {
165460
166651
  const { wireHeaders } = record2.request;
@@ -165509,8 +166700,8 @@ async function nativeRequestDetails(record2, bodies, includeBody) {
165509
166700
  resp.body = await readNativeBody(() => bodies.responseBody(record2.id), {
165510
166701
  mimeType: record2.response.mimeType,
165511
166702
  contentType: headerValue(record2.response.headers, "content-type"),
165512
- // An iOS response body is read decoded, so its Content-Encoding is not applied again.
165513
- contentEncoding: record2.layer === "ios-native" ? "" : headerValue(record2.response.headers, "content-encoding"),
166703
+ // An iOS or Mac app response body is read decoded, so its Content-Encoding is not applied again.
166704
+ contentEncoding: record2.layer === "ios-native" || record2.layer === "macos-native" ? "" : headerValue(record2.response.headers, "content-encoding"),
165514
166705
  wholeSize: sizeInBytes(record2.encodedDataLength ?? NaN, "as the app received them")
165515
166706
  });
165516
166707
  }
@@ -165671,6 +166862,589 @@ function headerValue(headers, wanted) {
165671
166862
  return "";
165672
166863
  }
165673
166864
 
166865
+ // ../tool-server/src/tools/network/network-capture-start.ts
166866
+ init_src2();
166867
+ init_device_info();
166868
+ init_capability();
166869
+ var IOS_CONNECT_WAIT_MS = 5e3;
166870
+ var JS_ANSWER_WAIT_MS = 5e3;
166871
+ function createNetworkCaptureStartTool(registry2) {
166872
+ return {
166873
+ id: "network-capture-start",
166874
+ description: `Start network capture for an app on every layer that sees its requests: the app's JS runtime and the native layer (NSURLProtocol on iOS; OkHttp on Android, which needs a debuggable build).<flag:macos-apps> On a Mac app, only its native NSURLProtocol layer.</flag:macos-apps>
166875
+ Use when you are about to trigger requests you need to inspect, also as a step of an e2e test. Unlike the read tools (native-network-logs and view-network-logs on iOS and Android<flag:macos-apps>, native-network-logs on a Mac app</flag:macos-apps>), which only read and say capture is not started until this runs, this turns capture on and waits a few seconds for each layer to arm. A second call keeps the requests captured so far.
166876
+ Returns { status, layers }: per layer, armed, and a reason when it is not armed (unavailable: true when nothing arms it without a change you must make). A native layer that is not armed yet arms by itself, for example at the app's next launch (on Android, only a launch by launch-app or restart-app), and native capture follows the app into later processes that launch-app and restart-app start, until network-capture-stop. On a device whose devtools agent argent attached to, a relaunch ends native capture: call this tool again after it. The JS layer arms only at a call of this tool: call it again once the app's JavaScript has loaded, and after a reload or relaunch. Capture can slow the app.
166877
+ Fails with NETWORK_CAPTURE_UNAVAILABLE when no layer can capture this app.`,
166878
+ zodSchema: captureSchema,
166879
+ capability: CAPTURE_CAPABILITY,
166880
+ interaction: {
166881
+ startedMsg: ({ params }) => `Starting network capture for ${params.bundleId}`,
166882
+ completedMsg: ({ params }) => `Started network capture for ${params.bundleId}`,
166883
+ failedMsg: ({ params, failureSignal: failureSignal2 }) => `Failed to start network capture for ${params.bundleId}: ${failureSignal2.error_code}`
166884
+ },
166885
+ // Each layer resolves its own service, so one that fails leaves the others running.
166886
+ services: () => ({}),
166887
+ async execute(_services, params) {
166888
+ const device = resolveDevice(params.udid);
166889
+ assertSupported("network-capture-start", CAPTURE_CAPABILITY, device);
166890
+ if (device.platform === "macos") {
166891
+ const layer = await withCaptureLock(
166892
+ params.udid,
166893
+ params.bundleId,
166894
+ () => startMacosLayer(registry2, device, params)
166895
+ );
166896
+ return { status: "ok", layers: [layer] };
166897
+ }
166898
+ const port = metroPort({ device_id: params.udid, port: params.port });
166899
+ const layers = await withCaptureLock(params.udid, params.bundleId, async () => {
166900
+ if (device.platform === "ios-remote") await ensureDeps(["sim-remote"]);
166901
+ if (device.platform === "ios" && isInjectableBundleId(params.bundleId)) {
166902
+ await refuseWhileXcodeInstalls(registry2, device, params.bundleId);
166903
+ }
166904
+ return runLayers([
166905
+ device.platform !== "android" && !isInjectableBundleId(params.bundleId) ? Promise.resolve(
166906
+ unavailable2(
166907
+ "js",
166908
+ `${params.bundleId} is an Apple system app, which runs no React Native JS`
166909
+ )
166910
+ ) : startJsLayer(registry2, params.udid, params.logicalDeviceId, params.bundleId, port),
166911
+ device.platform === "android" ? startAndroidLayer(registry2, device, params.bundleId, port) : startIosLayer(registry2, device, params.bundleId, port)
166912
+ ]);
166913
+ });
166914
+ if (layers.every((layer) => layer.unavailable)) {
166915
+ const error63 = unavailableError(params, layers);
166916
+ const missing = await missingNativeDep(device);
166917
+ if (missing && layers.some((layer) => layer.reason === missing.message)) {
166918
+ throw new DependencyMissingError(missing.missing, error63.message);
166919
+ }
166920
+ throw error63;
166921
+ }
166922
+ return { status: "ok", layers };
166923
+ }
166924
+ };
166925
+ }
166926
+ async function startMacosLayer(registry2, device, params) {
166927
+ const ref = macosAppRef(device);
166928
+ const app = requireMacosAppOfBundle(
166929
+ { macosApp: await registry2.resolveService(ref.urn, ref.options) },
166930
+ device,
166931
+ "network-capture-start",
166932
+ params.bundleId
166933
+ );
166934
+ if (!isInjectableBundleId(params.bundleId)) {
166935
+ throw unavailableError(params, [
166936
+ unavailable2(
166937
+ "macos-native",
166938
+ `${params.bundleId} is an Apple app; argent captures only apps it can load its library into, such as your own builds`
166939
+ )
166940
+ ]);
166941
+ }
166942
+ const refusal = app.isConnected() ? void 0 : await macosLaunchRefusal(params.bundleId);
166943
+ if (refusal) throw unavailableError(params, [unavailable2("macos-native", refusal)]);
166944
+ const { armed, reason: reason2 } = await app.startNetworkCapture();
166945
+ return { layer: "macos-native", armed, ...reason2 ? { reason: reason2 } : {} };
166946
+ }
166947
+ function unavailableError(params, layers) {
166948
+ return new FailureError(
166949
+ `Network capture cannot start for ${params.bundleId} on ${params.udid}: ` + layers.map((layer) => `${layer.layer}: ${layer.reason}`).join("; "),
166950
+ {
166951
+ error_code: FAILURE_CODES.NETWORK_CAPTURE_UNAVAILABLE,
166952
+ failure_stage: "network_capture_start",
166953
+ failure_area: "tool_server",
166954
+ error_kind: "unsupported"
166955
+ }
166956
+ );
166957
+ }
166958
+ function unavailable2(layer, reason2) {
166959
+ return { layer, armed: false, reason: reason2, unavailable: true };
166960
+ }
166961
+ async function missingNativeDep(device) {
166962
+ if (device.platform === "ios-remote") return void 0;
166963
+ try {
166964
+ await ensureDeps([device.platform === "android" ? "adb" : "xcrun"]);
166965
+ return void 0;
166966
+ } catch (err) {
166967
+ if (err instanceof DependencyMissingError) return err;
166968
+ throw err;
166969
+ }
166970
+ }
166971
+ async function refuseWhileXcodeInstalls(registry2, device, bundleId) {
166972
+ if (!xcodeFirstLaunchPending("simctl")) return;
166973
+ let api;
166974
+ try {
166975
+ const ref = nativeDevtoolsRef(device);
166976
+ api = await registry2.resolveService(ref.urn, ref.options);
166977
+ } catch {
166978
+ return;
166979
+ }
166980
+ if (api.armsEnv && !api.isConnected(bundleId)) throw new XcodeFirstLaunchPendingError("simctl");
166981
+ }
166982
+ async function startJsLayer(registry2, udid, logicalDeviceId, bundleId, port) {
166983
+ const jsDeviceId = logicalDeviceId ?? udid;
166984
+ const device = canonicalDeviceId(jsDeviceId) ?? jsDeviceId;
166985
+ const payload = jsCapturePayload(port, device);
166986
+ const found = findJsCapture(device, bundleId);
166987
+ const other = found && found.port !== port ? found : void 0;
166988
+ const installedHere = found !== void 0 && !other && found.installed;
166989
+ const recording = installedHere && found.paused !== true;
166990
+ let dbg;
166991
+ try {
166992
+ dbg = await resolveJsRuntime(registry2, udid, logicalDeviceId, port);
166993
+ } catch (err) {
166994
+ const reason2 = classifyNotConnected(err);
166995
+ const code = getFailureSignal(err)?.error_code;
166996
+ const lost = reason2 === "metro_not_running" || reason2 === "device_mismatch" || code === FAILURE_CODES.EXTERNAL_DEVICE_CAPABILITY_DENIED || code === FAILURE_CODES.EXTERNAL_DEVICE_UNAVAILABLE;
166997
+ if (other) {
166998
+ const text = `${jsNotReached(reason2, port, err)}; ${otherPortHint(bundleId, other.port)}`;
166999
+ return lost ? unavailable2("js", text) : { layer: "js", armed: false, reason: text };
167000
+ }
167001
+ if (lost && recording) {
167002
+ return {
167003
+ layer: "js",
167004
+ armed: false,
167005
+ reason: `${jsNotReached(reason2, port, err)}; the interceptor already in the app's JS runtime may still record, so call network-capture-start again once the app answers`
167006
+ };
167007
+ }
167008
+ if (lost) {
167009
+ const text = jsNotReached(reason2, port, err);
167010
+ if (installedHere) return unavailable2("js", text);
167011
+ forgetJsCapture(device, bundleId);
167012
+ setJsUnavailable(payload, bundleId, text);
167013
+ return unavailable2("js", text);
167014
+ }
167015
+ setJsCapture(payload, {
167016
+ bundleId,
167017
+ intent: "started",
167018
+ mark: { install: null },
167019
+ installed: installedHere,
167020
+ physicalDeviceId: udid,
167021
+ ...installedHere && found?.paused ? { paused: true } : {}
167022
+ });
167023
+ return {
167024
+ layer: "js",
167025
+ armed: false,
167026
+ reason: `${jsNotReached(reason2, port, err)}; call network-capture-start again once the app runs`
167027
+ };
167028
+ }
167029
+ const appId = dbg.runtimeApp?.appId;
167030
+ if (appId !== void 0 && appId !== bundleId) {
167031
+ const notOurs = `the JS runtime on Metro port ${port} is ${appId}'s, not ${bundleId}'s`;
167032
+ if (recording) {
167033
+ return {
167034
+ layer: "js",
167035
+ armed: false,
167036
+ reason: `${notOurs}; the interceptor already in ${bundleId}'s JS runtime may still record, so call network-capture-start again once that runtime answers on this port`
167037
+ };
167038
+ }
167039
+ if (other) return unavailable2("js", `${notOurs}; ${otherPortHint(bundleId, other.port)}`);
167040
+ const text = `${notOurs}; if that runtime is the app, pass bundleId ${appId}; otherwise pass the port of ${bundleId}'s Metro`;
167041
+ if (installedHere) return unavailable2("js", text);
167042
+ forgetJsCapture(device, bundleId);
167043
+ setJsUnavailable(payload, bundleId, text);
167044
+ return unavailable2("js", text);
167045
+ }
167046
+ const capture = {
167047
+ bundleId,
167048
+ intent: "started",
167049
+ installed: installedHere,
167050
+ physicalDeviceId: udid
167051
+ };
167052
+ setJsCapture(payload, capture);
167053
+ try {
167054
+ capture.mark = await readMark(dbg);
167055
+ } catch (err) {
167056
+ capture.mark = { install: null };
167057
+ if (installedHere && found?.paused) capture.paused = true;
167058
+ return {
167059
+ layer: "js",
167060
+ armed: false,
167061
+ reason: `the app's JS runtime did not answer (${errorMessage4(err)}); call network-capture-start again once it answers`
167062
+ };
167063
+ }
167064
+ try {
167065
+ const api = await registry2.resolveService(`NetworkInspector:${payload}`);
167066
+ const install = await installNetworkInterceptor(api.cdp, payload, dbg.runtimeApp);
167067
+ if (install.installed) return { layer: "js", armed: true };
167068
+ if (install.reason === NO_XHR_YET) {
167069
+ return {
167070
+ layer: "js",
167071
+ armed: false,
167072
+ reason: "the app's JavaScript has not loaded yet; call network-capture-start again once it has"
167073
+ };
167074
+ }
167075
+ return {
167076
+ layer: "js",
167077
+ armed: false,
167078
+ reason: `the interceptor did not install: ${install.reason}`
167079
+ };
167080
+ } catch (err) {
167081
+ return {
167082
+ layer: "js",
167083
+ armed: false,
167084
+ reason: `the interceptor did not install: ${errorMessage4(err)}`
167085
+ };
167086
+ }
167087
+ }
167088
+ async function readMark(dbg) {
167089
+ const answer = await dbg.cdp.evaluate(NETWORK_CAPTURE_MARK_SCRIPT, {
167090
+ timeout: JS_ANSWER_WAIT_MS
167091
+ });
167092
+ try {
167093
+ const parsed2 = JSON.parse(String(answer));
167094
+ return typeof parsed2.install === "string" && typeof parsed2.lastId === "number" ? { install: parsed2.install, lastId: parsed2.lastId } : { install: null };
167095
+ } catch {
167096
+ return { install: null };
167097
+ }
167098
+ }
167099
+ async function startIosLayer(registry2, device, bundleId, port) {
167100
+ if (!isInjectableBundleId(bundleId)) {
167101
+ return unavailable2(
167102
+ "ios-native",
167103
+ `${bundleId} is an Apple system app, which native network capture never covers`
167104
+ );
167105
+ }
167106
+ const notTurnedOn = (reason2) => {
167107
+ setNativeUnavailable(device.id, bundleId, reason2);
167108
+ return unavailable2("ios-native", reason2);
167109
+ };
167110
+ const missing = await missingNativeDep(device);
167111
+ if (missing) return notTurnedOn(missing.message);
167112
+ let api;
167113
+ try {
167114
+ const ref = nativeDevtoolsRef(device);
167115
+ api = await registry2.resolveService(ref.urn, ref.options);
167116
+ } catch (err) {
167117
+ return notTurnedOn(errorMessage4(err));
167118
+ }
167119
+ let block = null;
167120
+ if (!api.isConnected(bundleId)) {
167121
+ try {
167122
+ block = await precheckNativeDevtools(api, device.id, bundleId);
167123
+ } catch (err) {
167124
+ if (err instanceof XcodeFirstLaunchPendingError) throw err;
167125
+ return notTurnedOn(errorMessage4(err));
167126
+ }
167127
+ if (block?.status === "service_stale" || block?.status === "init_failed") {
167128
+ return notTurnedOn(block.message);
167129
+ }
167130
+ }
167131
+ setNativeUnavailable(device.id, bundleId);
167132
+ const armed = await api.startNetworkCapture(
167133
+ bundleId,
167134
+ port,
167135
+ // A lent agent says whether the provider has capture on only after it connects.
167136
+ block?.status === "connect_pending" || !api.armsEnv ? IOS_CONNECT_WAIT_MS : 0
167137
+ );
167138
+ if (armed) return { layer: "ios-native", armed: true };
167139
+ if (api.isConnected(bundleId)) {
167140
+ const note = api.networkRecords(bundleId)?.state().note;
167141
+ if (note === PROVIDER_CAPTURE_OFF) return unavailable2("ios-native", note);
167142
+ return {
167143
+ layer: "ios-native",
167144
+ armed: false,
167145
+ reason: note ?? "waiting for the agent to acknowledge Network.enable"
167146
+ };
167147
+ }
167148
+ if (!api.armsEnv) {
167149
+ return {
167150
+ layer: "ios-native",
167151
+ armed: false,
167152
+ reason: "the app has not connected through the device's devtools agent; it arms when it does"
167153
+ };
167154
+ }
167155
+ return {
167156
+ layer: "ios-native",
167157
+ armed: false,
167158
+ reason: block?.status === "restart_required" ? "no running process of the app can be armed; capture arms at its next launch, so call restart-app to capture it now, then network-capture-start again, since a relaunch ends the JS layer's capture; if restart-app fails rather than starting the app, the bundle id is not installed on this simulator: check it, or install the app" : "the app has not connected yet; capture arms when it does"
167159
+ };
167160
+ }
167161
+ async function startAndroidLayer(registry2, device, bundleId, port) {
167162
+ const notTurnedOn = (reason2) => {
167163
+ setNativeUnavailable(device.id, bundleId, reason2);
167164
+ return unavailable2("android-native", reason2);
167165
+ };
167166
+ const missing = await missingNativeDep(device);
167167
+ if (missing) return notTurnedOn(missing.message);
167168
+ let api;
167169
+ try {
167170
+ const ref = androidNetworkInspectorRef(device, bundleId, port);
167171
+ api = await registry2.resolveService(ref.urn, ref.options);
167172
+ } catch (err) {
167173
+ return notTurnedOn(errorMessage4(err));
167174
+ }
167175
+ setNativeUnavailable(device.id, bundleId);
167176
+ const started = await api.startCapture(port);
167177
+ if (started.unavailable) return unavailable2("android-native", started.reason ?? "unavailable");
167178
+ return {
167179
+ layer: "android-native",
167180
+ armed: started.armed,
167181
+ ...started.reason ? { reason: started.reason } : {}
167182
+ };
167183
+ }
167184
+
167185
+ // ../tool-server/src/tools/network/network-capture-stop.ts
167186
+ init_device_info();
167187
+ init_capability();
167188
+ var NOT_STARTED2 = "capture was not started for this app";
167189
+ var JS_ANSWER_WAIT_MS2 = 5e3;
167190
+ function createNetworkCaptureStopTool(registry2) {
167191
+ return {
167192
+ id: "network-capture-stop",
167193
+ description: `Stop network capture for an app on every layer and keep what was captured.
167194
+ Use when you have the requests you need, before you profile, or to end capture in an e2e test. Unlike stop-all-simulator-servers, the requests stay listed in native-network-logs and view-network-logs, and their ids keep working in view-network-request-details (a view-network-logs id until the app's JS runtime reloads).
167195
+ Capture stays off: the read tools, launch-app and restart-app do not turn it on again; network-capture-start does. A request in flight at the stop completes in the list on iOS<flag:macos-apps> and Mac apps</flag:macos-apps> and in the JS runtime; on Android the list marks it failed, while the app's own request goes on. On Android, a body that view-network-request-details did not read before the stop is no longer available.
167196
+ Returns { status, layers }: per layer, armed (false once the layer confirmed the stop), total (the requests it keeps for the app, or 0 when the stop could not count them, as on a JS runtime it did not reach) and a reason when the layer was not reached or was not started.`,
167197
+ zodSchema: captureSchema,
167198
+ capability: CAPTURE_CAPABILITY,
167199
+ interaction: {
167200
+ startedMsg: ({ params }) => `Stopping network capture for ${params.bundleId}`,
167201
+ completedMsg: ({ params }) => `Stopped network capture for ${params.bundleId}`,
167202
+ failedMsg: ({ params, failureSignal: failureSignal2 }) => `Failed to stop network capture for ${params.bundleId}: ${failureSignal2.error_code}`
167203
+ },
167204
+ // A stop must not create the services it stops, so each layer looks them up itself.
167205
+ services: () => ({}),
167206
+ async execute(_services, params) {
167207
+ const device = resolveDevice(params.udid);
167208
+ assertSupported("network-capture-stop", CAPTURE_CAPABILITY, device);
167209
+ const port = metroPort({ device_id: params.udid, port: params.port });
167210
+ if (device.platform === "macos") {
167211
+ const layer = await withCaptureLock(
167212
+ params.udid,
167213
+ params.bundleId,
167214
+ () => stopMacosLayer(registry2, device, params.bundleId, port)
167215
+ );
167216
+ return { status: "ok", layers: [layer] };
167217
+ }
167218
+ const layers = await withCaptureLock(
167219
+ params.udid,
167220
+ params.bundleId,
167221
+ () => runLayers([
167222
+ device.platform !== "android" && !isInjectableBundleId(params.bundleId) ? Promise.resolve({
167223
+ layer: "js",
167224
+ armed: false,
167225
+ total: 0,
167226
+ reason: `${params.bundleId} is an Apple system app, which runs no React Native JS`
167227
+ }) : stopJsLayer(registry2, params.udid, params.logicalDeviceId, params.bundleId, port),
167228
+ device.platform === "android" ? stopAndroidLayer(registry2, device, params.bundleId, port) : stopIosLayer(registry2, device, params.bundleId, port)
167229
+ ])
167230
+ );
167231
+ return { status: "ok", layers };
167232
+ }
167233
+ };
167234
+ }
167235
+ async function stopJsLayer(registry2, udid, logicalDeviceId, bundleId, port) {
167236
+ const jsDeviceId = logicalDeviceId ?? udid;
167237
+ const device = canonicalDeviceId(jsDeviceId) ?? jsDeviceId;
167238
+ const payload = jsCapturePayload(port, device);
167239
+ const prior = findJsCapture(device, bundleId);
167240
+ const kept = prior?.port === port ? prior : void 0;
167241
+ const other = prior && !kept ? prior : void 0;
167242
+ const otherArmed = other !== void 0 && (other.intent === "started" || other.installed && other.paused !== true);
167243
+ const here = jsCapture(payload);
167244
+ if (here && here.bundleId !== bundleId) {
167245
+ const stays = `the capture of ${here.bundleId} on Metro port ${port} stays as it is`;
167246
+ if (other) {
167247
+ return {
167248
+ layer: "js",
167249
+ armed: otherArmed,
167250
+ total: 0,
167251
+ reason: `${stays}; ${otherPortHint(bundleId, other.port)}`
167252
+ };
167253
+ }
167254
+ return { layer: "js", armed: false, total: 0, reason: `${NOT_STARTED2}; ${stays}` };
167255
+ }
167256
+ const storeStopped = (paused) => {
167257
+ const capture = {
167258
+ bundleId,
167259
+ intent: "stopped",
167260
+ ...kept?.mark ? { mark: kept.mark } : {},
167261
+ installed: kept?.installed ?? false,
167262
+ ...paused ? { paused: true } : {},
167263
+ physicalDeviceId: udid
167264
+ };
167265
+ setJsCapture(payload, capture);
167266
+ return capture;
167267
+ };
167268
+ const endedWithApp = async (stored2) => {
167269
+ if (await appRuns(udid, bundleId) !== false) return void 0;
167270
+ stored2.installed = false;
167271
+ return `${bundleId} is not running, so nothing records; while capture is stopped, its next JS runtime gets no interceptor`;
167272
+ };
167273
+ let dbg;
167274
+ try {
167275
+ dbg = await resolveJsRuntime(registry2, udid, logicalDeviceId, port);
167276
+ } catch (err) {
167277
+ const notReached = jsNotReached(classifyNotConnected(err), port, err);
167278
+ if (other) {
167279
+ return {
167280
+ layer: "js",
167281
+ armed: otherArmed,
167282
+ total: 0,
167283
+ reason: `${notReached}; ${otherPortHint(bundleId, other.port)}`
167284
+ };
167285
+ }
167286
+ if (!prior) {
167287
+ return { layer: "js", armed: false, total: 0, reason: `${notReached}; ${NOT_STARTED2}` };
167288
+ }
167289
+ const stored2 = storeStopped(kept?.paused === true);
167290
+ const unconfirmed = kept?.installed === true && kept.paused !== true;
167291
+ const ended = unconfirmed ? await endedWithApp(stored2) : void 0;
167292
+ if (ended) return { layer: "js", armed: false, total: 0, reason: `${notReached}; ${ended}` };
167293
+ return {
167294
+ layer: "js",
167295
+ armed: unconfirmed,
167296
+ total: 0,
167297
+ reason: unconfirmed ? `${notReached}; the interceptor already in the app's JS runtime may still record, so call network-capture-stop again once the app answers` : `${notReached}; while capture is stopped, the app's JS runtime gets no interceptor`
167298
+ };
167299
+ }
167300
+ const appId = dbg.runtimeApp?.appId;
167301
+ if (appId !== void 0 && appId !== bundleId) {
167302
+ const notOurs = `the JS runtime on Metro port ${port} is ${appId}'s, not ${bundleId}'s`;
167303
+ if (other) {
167304
+ return {
167305
+ layer: "js",
167306
+ armed: otherArmed,
167307
+ total: 0,
167308
+ reason: `${notOurs}, so nothing changed there; ${otherPortHint(bundleId, other.port)}`
167309
+ };
167310
+ }
167311
+ if (!kept) {
167312
+ return {
167313
+ layer: "js",
167314
+ armed: false,
167315
+ total: 0,
167316
+ reason: `${notOurs}, so nothing changed there; if that runtime is the app, pass bundleId ${appId}; otherwise pass the port of ${bundleId}'s Metro`
167317
+ };
167318
+ }
167319
+ const stored2 = storeStopped(kept.paused === true);
167320
+ const unconfirmed = kept.installed && kept.paused !== true;
167321
+ const ended = unconfirmed ? await endedWithApp(stored2) : void 0;
167322
+ if (ended) return { layer: "js", armed: false, total: 0, reason: `${notOurs}; ${ended}` };
167323
+ return {
167324
+ layer: "js",
167325
+ armed: unconfirmed,
167326
+ total: 0,
167327
+ reason: unconfirmed ? `${notOurs}; the interceptor already in ${bundleId}'s JS runtime may still record, so call network-capture-stop again once that runtime answers on this port` : `${notOurs}; while capture is stopped, ${bundleId}'s JS runtime gets no interceptor`
167328
+ };
167329
+ }
167330
+ const stored = storeStopped(false);
167331
+ try {
167332
+ await dbg.cdp.evaluate(makeNetworkCaptureControlScript(true), { timeout: JS_ANSWER_WAIT_MS2 });
167333
+ } catch (err) {
167334
+ return {
167335
+ layer: "js",
167336
+ armed: true,
167337
+ total: 0,
167338
+ reason: `the app's JS runtime did not pause capture: ${errorMessage4(err)}`
167339
+ };
167340
+ }
167341
+ stored.paused = true;
167342
+ try {
167343
+ const { total, interceptorInstalled } = JSON.parse(
167344
+ String(await dbg.cdp.evaluate(makeNetworkLogReadScript(0, 0, port)))
167345
+ );
167346
+ return {
167347
+ layer: "js",
167348
+ armed: false,
167349
+ total: interceptorInstalled ? total : 0,
167350
+ ...prior ? {} : { reason: NOT_STARTED2 }
167351
+ };
167352
+ } catch (err) {
167353
+ const uncounted = `the app's JS runtime paused capture, but did not answer the count of its requests: ${errorMessage4(err)}`;
167354
+ return {
167355
+ layer: "js",
167356
+ armed: false,
167357
+ total: 0,
167358
+ reason: prior ? uncounted : `${uncounted}; ${NOT_STARTED2}`
167359
+ };
167360
+ }
167361
+ }
167362
+ async function appRuns(udid, bundleId) {
167363
+ const { platform } = resolveDevice(udid);
167364
+ try {
167365
+ if (platform === "android") {
167366
+ return (await readAppProcesses(udid, bundleId)).processes.length > 0;
167367
+ }
167368
+ if (platform === "ios") return (await localIosHost.listRunningBundleIds(udid)).has(bundleId);
167369
+ if (platform === "ios-remote") {
167370
+ let timer;
167371
+ const late = new Promise((resolve21) => {
167372
+ timer = setTimeout(() => resolve21(void 0), SIMCTL_SPAWN_TIMEOUT_MS);
167373
+ });
167374
+ try {
167375
+ return (await Promise.race([remoteIosHost.listRunningBundleIds(udid), late]))?.has(
167376
+ bundleId
167377
+ );
167378
+ } finally {
167379
+ clearTimeout(timer);
167380
+ }
167381
+ }
167382
+ } catch {
167383
+ }
167384
+ return void 0;
167385
+ }
167386
+ async function stopIosLayer(registry2, device, bundleId, port) {
167387
+ if (!isInjectableBundleId(bundleId)) {
167388
+ return {
167389
+ layer: "ios-native",
167390
+ armed: false,
167391
+ total: 0,
167392
+ reason: `${bundleId} is an Apple system app, which native network capture never covers`
167393
+ };
167394
+ }
167395
+ const ref = nativeDevtoolsRef(device);
167396
+ if (!isLiveService(registry2, ref.urn)) {
167397
+ return { layer: "ios-native", armed: false, total: 0, reason: NOT_STARTED2 };
167398
+ }
167399
+ const api = await registry2.resolveService(ref.urn, ref.options);
167400
+ if (!api.isNetworkCaptureStarted(bundleId) && !api.isNetworkCaptureStopped(bundleId)) {
167401
+ return { layer: "ios-native", armed: false, total: 0, reason: NOT_STARTED2 };
167402
+ }
167403
+ const { confirmed, reason: reason2 } = await api.stopNetworkCapture(bundleId);
167404
+ return {
167405
+ layer: "ios-native",
167406
+ armed: !confirmed,
167407
+ total: api.networkRecords(bundleId)?.records(port).length ?? 0,
167408
+ ...reason2 ? { reason: reason2 } : {}
167409
+ };
167410
+ }
167411
+ async function stopMacosLayer(registry2, device, bundleId, port) {
167412
+ const ref = macosAppRef(device);
167413
+ const app = requireMacosAppOfBundle(
167414
+ { macosApp: await registry2.resolveService(ref.urn, ref.options) },
167415
+ device,
167416
+ "network-capture-stop",
167417
+ bundleId
167418
+ );
167419
+ if (!app.isNetworkCaptureStarted() && !app.isNetworkCaptureStopped()) {
167420
+ return { layer: "macos-native", armed: false, total: 0, reason: NOT_STARTED2 };
167421
+ }
167422
+ const { confirmed, reason: reason2 } = await app.stopNetworkCapture();
167423
+ return {
167424
+ layer: "macos-native",
167425
+ armed: !confirmed,
167426
+ total: app.networkRecords().records(port).length,
167427
+ ...reason2 ? { reason: reason2 } : {}
167428
+ };
167429
+ }
167430
+ async function stopAndroidLayer(registry2, device, bundleId, port) {
167431
+ const ref = androidNetworkInspectorRef(device, bundleId, port);
167432
+ if (!isLiveService(registry2, ref.urn)) {
167433
+ return { layer: "android-native", armed: false, total: 0, reason: NOT_STARTED2 };
167434
+ }
167435
+ const api = await registry2.resolveService(ref.urn, ref.options);
167436
+ if (!api.isStarted() && !api.isStopped()) {
167437
+ return { layer: "android-native", armed: false, total: 0, reason: NOT_STARTED2 };
167438
+ }
167439
+ const { confirmed, reason: reason2 } = await api.stopCapture();
167440
+ return {
167441
+ layer: "android-native",
167442
+ armed: !confirmed,
167443
+ total: api.records(port).length,
167444
+ ...reason2 ? { reason: reason2 } : {}
167445
+ };
167446
+ }
167447
+
165674
167448
  // ../tool-server/src/tools/describe/index.ts
165675
167449
  init_zod();
165676
167450
 
@@ -167255,7 +169029,7 @@ init_zod();
167255
169029
  init_src2();
167256
169030
 
167257
169031
  // ../tool-server/src/utils/debugger/runtime-device.ts
167258
- var import_node_crypto16 = require("node:crypto");
169032
+ var import_node_crypto17 = require("node:crypto");
167259
169033
  var import_node_child_process46 = require("node:child_process");
167260
169034
  var import_node_util35 = require("node:util");
167261
169035
  init_adb();
@@ -167268,7 +169042,7 @@ async function findRuntimeDevices(cdp, {
167268
169042
  awaitSerials = [],
167269
169043
  waitSerials = []
167270
169044
  } = {}) {
167271
- const marker = `argent-device-probe:${(0, import_node_crypto16.randomUUID)()}`;
169045
+ const marker = `argent-device-probe:${(0, import_node_crypto17.randomUUID)()}`;
167272
169046
  const logged = await cdp.evaluate(
167273
169047
  `(function () {
167274
169048
  if (typeof nativeLoggingHook !== "function") return false;
@@ -167432,7 +169206,7 @@ function bootstrapFailureMessage(bootstrap) {
167432
169206
  // ../tool-server/src/utils/profiler-shared/network-capture-warning.ts
167433
169207
  var CAPTURE_COST = "It can slow the app, so the timings in this profile can differ from a run without it.";
167434
169208
  function agentSentence(platform, one, where = "") {
167435
- return platform === "android" ? `Argent attaches its in-app agent to the processes of ${one ? "that app" : "these apps"}${where}.` : `Argent's in-app agent captures the requests of ${one ? "that app's" : "these apps'"} processes${where}.`;
169209
+ return platform === "android" ? `Argent's in-app agent can run in the processes of ${one ? "that app" : "these apps"}${where}.` : `Argent's in-app agent captures the requests of ${one ? "that app's" : "these apps'"} processes${where}.`;
167436
169210
  }
167437
169211
  function nativeNetworkCaptureWarning(deviceId, runtimeApp, runtimeDevices = { found: [], unresolved: [] }) {
167438
169212
  try {
@@ -167448,7 +169222,7 @@ function nativeNetworkCaptureWarning(deviceId, runtimeApp, runtimeDevices = { fo
167448
169222
  if (packages.length === 0) return logicalDeviceWarning(deviceId, runtimeApp);
167449
169223
  const apps = packages.join(", ");
167450
169224
  const one = packages.length === 1;
167451
- const remedy = platform === "android" ? `call native-network-logs with stop: true for ${one ? "that app" : "each of these apps"}` : "call stop-all-simulator-servers for this device";
169225
+ const remedy = `call network-capture-stop for ${one ? "that app" : "each of these apps"}`;
167452
169226
  return `Native network capture is on for ${apps} on this device: ${agentSentence(platform, one)} ${CAPTURE_COST} To profile without it, stop this profile, ${remedy}, then restart-app and profile again.`;
167453
169227
  } catch {
167454
169228
  return void 0;
@@ -167458,7 +169232,8 @@ function foundDeviceWarning({ found, unresolved }, runtimeApp) {
167458
169232
  const iosApps = found.length === 1 ? liveIosNetworkCaptures(found[0]) : [];
167459
169233
  if (iosApps.length > 0) {
167460
169234
  const [udid] = found;
167461
- return `Native network capture is on for ${iosApps.join(", ")} on ${udid}, the device this profile runs on: ${agentSentence("ios", iosApps.length === 1)} ${CAPTURE_COST} To profile without it, stop this profile, call stop-all-simulator-servers for ${udid}, then restart-app on ${udid} and profile again.`;
169235
+ const one = iosApps.length === 1;
169236
+ return `Native network capture is on for ${iosApps.join(", ")} on ${udid}, the device this profile runs on: ${agentSentence("ios", one)} ${CAPTURE_COST} To profile without it, stop this profile, call network-capture-stop with udid ${udid} for ${one ? "that app" : "each of these apps"}, then restart-app on ${udid} and profile again.`;
167462
169237
  }
167463
169238
  const captures = found.map((device) => ({ device, packages: liveAndroidNetworkCaptures(device) })).filter(({ packages }) => packages.length > 0);
167464
169239
  const appId = runtimeApp?.platform === "android" ? runtimeApp.appId : void 0;
@@ -167470,22 +169245,22 @@ function foundDeviceWarning({ found, unresolved }, runtimeApp) {
167470
169245
  const apps = [...new Set(captures.flatMap(({ packages }) => packages))].sort();
167471
169246
  const where = captures.length === 1 ? `${first.device}, the device this profile runs on` : `${captures.map(({ device }) => device).join(" and ")}, adb serials of the device this profile runs on`;
167472
169247
  sentences.push(
167473
- `Native network capture is on for ${apps.join(", ")} on ${where}: Argent attaches its in-app agent to the processes of ${apps.length === 1 ? "that app" : "these apps"}.`
169248
+ `Native network capture is on for ${apps.join(", ")} on ${where}: ` + agentSentence("android", apps.length === 1)
167474
169249
  );
167475
169250
  }
167476
169251
  if (appId && maybe.length > 0) {
167477
169252
  const one = maybe.length === 1;
167478
169253
  sentences.push(
167479
- `Native network capture is ${first ? "also " : ""}on for ${appId} on ${maybe.join(", ")}, ${one ? "which" : "each of which"} may also be the device this profile runs on: ${one ? "its logcat" : "their logcats"} could not be read to tell. Argent attaches its in-app agent to the processes of that app there.`
169254
+ `Native network capture is ${first ? "also " : ""}on for ${appId} on ${maybe.join(", ")}, ${one ? "which" : "each of which"} may also be the device this profile runs on: ${one ? "its logcat" : "their logcats"} could not be read to tell. ` + agentSentence("android", true, " there")
167480
169255
  );
167481
169256
  }
167482
169257
  const stops = [
167483
169258
  ...captures.flatMap(({ device, packages }) => packages.map((app) => ({ app, device }))),
167484
169259
  ...appId ? maybe.map((device) => ({ app: appId, device })) : []
167485
169260
  ];
167486
- const stop = first && captures.length === 1 && maybe.length === 0 ? `with udid ${first.device} and stop: true for ${first.packages.length === 1 ? "that app" : "each of these apps"}` : `with stop: true for ${stops.map(({ app, device }) => `${app} with udid ${device}`).join(", ")}`;
169261
+ const stop = first && captures.length === 1 && maybe.length === 0 ? `with udid ${first.device} for ${first.packages.length === 1 ? "that app" : "each of these apps"}` : `for ${stops.map(({ app, device }) => `${app} with udid ${device}`).join(", ")}`;
167487
169262
  const restart = first?.device ?? found[0];
167488
- return `${sentences.join(" ")} ${CAPTURE_COST} To profile without it, stop this profile, call native-network-logs ${stop}, then restart-app on ${restart} and profile again.`;
169263
+ return `${sentences.join(" ")} ${CAPTURE_COST} To profile without it, stop this profile, call network-capture-stop ${stop}, then restart-app on ${restart} and profile again.`;
167489
169264
  }
167490
169265
  function logicalDeviceWarning(deviceId, runtimeApp) {
167491
169266
  const appId = runtimeApp?.appId;
@@ -167496,7 +169271,7 @@ function logicalDeviceWarning(deviceId, runtimeApp) {
167496
169271
  if (devices2.length === 0) return void 0;
167497
169272
  const one = devices2.length === 1;
167498
169273
  const those = one ? "that device" : "each of those devices";
167499
- const remedy = platform === "android" ? `call native-network-logs with stop: true for ${appId} on ${those}` : `call stop-all-simulator-servers for ${those}`;
169274
+ const remedy = `call network-capture-stop for ${appId} on ${those}`;
167500
169275
  return `Native network capture is on for ${appId} on ${devices2.join(", ")}, ${one ? "which" : "one of which"} may be the device this profile runs on: its device_id is a Metro logicalDeviceId, which does not say which device it is. ${agentSentence(platform, true, " there")} ${CAPTURE_COST} To profile without it, stop this profile, ${remedy}, then restart-app and profile again.`;
167501
169276
  }
167502
169277
 
@@ -167586,7 +169361,7 @@ function createReactProfilerStartTool(registry2) {
167586
169361
  description: `Record Hermes CPU samples and React commits during an interaction.<flag:macos-apps> For a Mac app, use a Debug build that loads JavaScript from Metro: react-native-macos 0.76+, or React Native built for Mac Catalyst. The profiler connects without debugger-connect.</flag:macos-apps>
167587
169362
  On an iOS simulator, Android device<flag:macos-apps>, or Mac app</flag:macos-apps>, call native-profiler-start in parallel on the same target for a combined report, unless the user declines native profiling.
167588
169363
  After starting, ask the user to perform the interaction to profile, then call react-profiler-stop.
167589
- Returns { started_at, startedAtEpochMs, hermes_version, detected_architecture }. On iOS and Android, a warning names the apps with native network capture on (started by native-network-logs): their timings in the profile can differ. If a session is already running, returns { already_running: true, mine, owner, \u2026 } instead, without clobbering its data, unless it is another tool-server's stale run, has no owner record, or is a lost run of this tool-server: start replaces those. mine: true means this tool-server started the run: if it is yours, call react-profiler-stop. With stale: true it may be another agent's: follow the note. Otherwise, BEFORE OVERTAKING with { force: true }, ask the user for approval first, as how_to_reclaim explains. A start that replaces a run reports it in took_over.
169364
+ Returns { started_at, startedAtEpochMs, hermes_version, detected_architecture }. On iOS and Android, a warning names the apps with native network capture on (started by network-capture-start): their timings in the profile can differ. If a session is already running, returns { already_running: true, mine, owner, \u2026 } instead, without clobbering its data, unless it is another tool-server's stale run, has no owner record, or is a lost run of this tool-server: start replaces those. mine: true means this tool-server started the run: if it is yours, call react-profiler-stop. With stale: true it may be another agent's: follow the note. Otherwise, BEFORE OVERTAKING with { force: true }, ask the user for approval first, as how_to_reclaim explains. A start that replaces a run reports it in took_over.
167590
169365
  Fails if the Hermes runtime is not reachable or the Metro CDP connection cannot be established.`,
167591
169366
  zodSchema: zodSchema45,
167592
169367
  interaction: {
@@ -175935,7 +177710,7 @@ var nativeProfilerStartTool = {
175935
177710
  longRunning: true,
175936
177711
  description: `Start native profiling. Instruments records CPU, hangs, and leaks on iOS<flag:macos-apps> and Mac apps</flag:macos-apps>. Perfetto records CPU, jank, and memory growth on Android.
175937
177712
  Start the target app first for an attach recording. Wait for this call to return before reproducing the scenario, then call native-profiler-stop while the app is still running.
175938
- On iOS and Android, a warning names apps whose timings may be affected by native network capture.<flag:macos-apps> On a Mac app, a warning says when the app runs with malloc stack logging. Launch the app through Argent and use a development-signed build. If signing blocks profiling in a background session such as SSH, try the "Time Profiler" template for CPU and hangs without leak checks.
177713
+ On iOS and Android, a warning names apps whose timings may be affected by native network capture (started by network-capture-start).<flag:macos-apps> On a Mac app, a warning says when the app runs with malloc stack logging. Launch the app through Argent and use a development-signed build. If signing blocks profiling in a background session such as SSH, try the "Time Profiler" template for CPU and hangs without leak checks.
175939
177714
  With malloc stack logging off, Argent blocks the bundled template if it detects a WebKit heap or the check fails. Use "Time Profiler" to keep the app's state, or set malloc_stack_logging to true to restart the app and record leaks with the bundled template. With logging off, other templates that use the Allocations instrument, including "Leaks" and "Allocations", can freeze an affected app.</flag:macos-apps>`,
175940
177715
  zodSchema: zodSchema53,
175941
177716
  interaction: {
@@ -176115,7 +177890,7 @@ var import_node_child_process48 = require("node:child_process");
176115
177890
  var import_node_util38 = require("node:util");
176116
177891
  var fsp5 = __toESM(require("node:fs/promises"));
176117
177892
  var path49 = __toESM(require("node:path"));
176118
- var import_node_crypto17 = require("node:crypto");
177893
+ var import_node_crypto18 = require("node:crypto");
176119
177894
  init_src2();
176120
177895
 
176121
177896
  // ../tool-server/src/utils/ios-launch-time/workflow.ts
@@ -176698,7 +178473,7 @@ async function measurePreparedLaunch(context2, ctx) {
176698
178473
  const runnerSigning = context2.simulator ? null : await resolveRunnerSigningConfig(context2.deviceId);
176699
178474
  const runnerBundleId = runnerSigning?.appBundleId ?? "com.argent.runner.tsimulator";
176700
178475
  const testBundleId = runnerSigning?.testBundleId ?? `${runnerBundleId}.uitests`;
176701
- const runnerBuildKey = (0, import_node_crypto17.createHash)("sha256").update(
178476
+ const runnerBuildKey = (0, import_node_crypto18.createHash)("sha256").update(
176702
178477
  [
176703
178478
  // Builds for two simulators, or two iPhones, are the same build.
176704
178479
  context2.simulator ? "iOS Simulator" : "iOS",
@@ -176837,7 +178612,7 @@ async function measurePreparedLaunch(context2, ctx) {
176837
178612
 
176838
178613
  // ../tool-server/src/tools/profiler/native-profiler/launch-analysis/profile.ts
176839
178614
  var import_node_child_process49 = require("node:child_process");
176840
- var import_node_crypto18 = require("node:crypto");
178615
+ var import_node_crypto19 = require("node:crypto");
176841
178616
  var import_node_util39 = require("node:util");
176842
178617
  var fsp6 = __toESM(require("node:fs/promises"));
176843
178618
  var path50 = __toESM(require("node:path"));
@@ -177085,7 +178860,7 @@ var TABLE_XPATH = (schema) => `/trace-toc/run[@number="1"]/data/table[@schema="$
177085
178860
  async function writeProfilerSession(xml) {
177086
178861
  const debugDir = await getDebugDir();
177087
178862
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
177088
- const sessionId = `${timestamp}-launch-${(0, import_node_crypto18.randomUUID)()}`;
178863
+ const sessionId = `${timestamp}-launch-${(0, import_node_crypto19.randomUUID)()}`;
177089
178864
  const cpuXmlPath = path50.join(debugDir, `native-profiler-${sessionId}_raw_cpu.xml`);
177090
178865
  await fsp6.writeFile(cpuXmlPath, xml, { flag: "wx" });
177091
178866
  return { sessionId, cpuXmlPath };
@@ -177425,7 +179200,7 @@ init_zod();
177425
179200
  var import_node_child_process50 = require("node:child_process");
177426
179201
  var fs62 = __toESM(require("node:fs"));
177427
179202
  var path51 = __toESM(require("node:path"));
177428
- var import_node_crypto19 = require("node:crypto");
179203
+ var import_node_crypto20 = require("node:crypto");
177429
179204
  var import_node_util40 = require("node:util");
177430
179205
  init_src2();
177431
179206
  init_capability();
@@ -177641,7 +179416,7 @@ async function setAudioInput(session, source) {
177641
179416
  } else {
177642
179417
  removeFiles(dir, `in-${process.pid}-`);
177643
179418
  feeder = new InputFeeder(
177644
- path51.join(dir, `in-${process.pid}-${(0, import_node_crypto19.randomUUID)().slice(0, 8)}.ring`),
179419
+ path51.join(dir, `in-${process.pid}-${(0, import_node_crypto20.randomUUID)().slice(0, 8)}.ring`),
177645
179420
  feederSource
177646
179421
  );
177647
179422
  feeder.start();
@@ -181714,6 +183489,10 @@ var PORT_KEYED_NAMESPACES = [
181714
183489
  REACT_PROFILER_SESSION_NAMESPACE
181715
183490
  ];
181716
183491
  var APP_KEYED_NAMESPACES = [ANDROID_NETWORK_INSPECTOR_NAMESPACE];
183492
+ var NATIVE_ID_KEYED_NAMESPACES = [
183493
+ ...APP_KEYED_NAMESPACES,
183494
+ NATIVE_DEVTOOLS_NAMESPACE
183495
+ ];
181717
183496
  var DEVICE_OWNED_NAMESPACES = [
181718
183497
  SIMULATOR_SERVER_NAMESPACE,
181719
183498
  IOS_DEVICE_RUNNER_NAMESPACE,
@@ -181754,7 +183533,7 @@ function deviceIdOwningUrn(urn, namespaces, deviceIds) {
181754
183533
  if (portion === void 0) continue;
181755
183534
  const tail = portion.toLowerCase();
181756
183535
  const owner = deviceIds.find((id) => {
181757
- const spellings = APP_KEYED_NAMESPACES.includes(namespace) ? [id, externalNativeId(id)] : [id];
183536
+ const spellings = NATIVE_ID_KEYED_NAMESPACES.includes(namespace) ? [id, externalNativeId(id)] : [id];
181758
183537
  return spellings.some((spelling) => {
181759
183538
  const lower = spelling.toLowerCase();
181760
183539
  return URN_SUFFIXES.some((suffix) => tail === `${lower}${suffix}`);
@@ -181774,6 +183553,13 @@ function deviceIdOfUrn(urn, namespaces) {
181774
183553
  }
181775
183554
  return void 0;
181776
183555
  }
183556
+ function isProviderOwnedUrn(urn) {
183557
+ if (isExternalDeviceUrn(urn)) return true;
183558
+ const portion = deviceIdOfUrn(urn, [NATIVE_DEVTOOLS_NAMESPACE]);
183559
+ if (portion === void 0) return false;
183560
+ const suffix = URN_SUFFIXES.find((s) => s !== "" && portion.endsWith(s)) ?? "";
183561
+ return externalClaimForNativeId(portion.slice(0, portion.length - suffix.length)) !== void 0;
183562
+ }
181777
183563
  function unnameableSessionUrns(urns) {
181778
183564
  return urns.filter((urn) => isLogicalKeyedDevice(deviceIdOfUrn(urn, PORT_KEYED_NAMESPACES)));
181779
183565
  }
@@ -181787,7 +183573,7 @@ var zodSchema65 = external_exports.object({
181787
183573
  function createStopSimulatorServerTool(registry2) {
181788
183574
  return {
181789
183575
  id: "stop-simulator-server",
181790
- description: `Stop the transport session for a specific device (iOS simulator / Android: simulator-server process; physical iOS: the on-device runner; Chromium: CDP WebSocket) and free its resources; on a TV target it also reaps that device's TV-control daemons. Use to restart a wedged transport, or when the user is done with one device but wants to keep others running - not just because a task on it finished, since the next task on that device would start cold again. On iOS / Android / TV it deliberately leaves this device's native-devtools, accessibility, profiler and debugger services running - to drain those as well, use stop-all-simulator-servers with \`devices\`. On CHROMIUM, stopping the transport also ends the JS-runtime debugger session and its captured console history - reconnect with debugger-connect afterwards.<flag:macos-apps> On a Mac app it also ends the native-network-logs capture and drops its log; call native-network-logs again to restart it.</flag:macos-apps> Returns { stopped, udid }; \`stopped\` is false, not an error, when no session is open for the id.`,
183576
+ description: `Stop the transport session for a specific device (iOS simulator / Android: simulator-server process; physical iOS: the on-device runner; Chromium: CDP WebSocket) and free its resources; on a TV target it also reaps that device's TV-control daemons. Use to restart a wedged transport, or when the user is done with one device but wants to keep others running - not just because a task on it finished, since the next task on that device would start cold again. On iOS / Android / TV it deliberately leaves this device's native-devtools, accessibility, profiler and debugger services running - to drain those as well, use stop-all-simulator-servers with \`devices\`. On CHROMIUM, stopping the transport also ends the JS-runtime debugger session and its captured console history - reconnect with debugger-connect afterwards.<flag:macos-apps> On a Mac app it also ends the network capture and drops the requests it recorded; call network-capture-start to capture again.</flag:macos-apps> Returns { stopped, udid }; \`stopped\` is false, not an error, when no session is open for the id.`,
181791
183577
  zodSchema: zodSchema65,
181792
183578
  interaction: {
181793
183579
  startedMsg: ({ params }) => `Stopping simulator server for ${params.udid}`,
@@ -181823,7 +183609,6 @@ function createStopSimulatorServerTool(registry2) {
181823
183609
  // ../tool-server/src/tools/simulator/stop-all-simulator-servers.ts
181824
183610
  init_zod();
181825
183611
  init_src2();
181826
- init_external_devices();
181827
183612
  var zodSchema66 = external_exports.object({
181828
183613
  devices: external_exports.array(external_exports.string()).optional().describe(
181829
183614
  "Ids of the devices THIS session used (iOS UDID / Android serial / Chromium id), to scope the teardown to."
@@ -181832,7 +183617,7 @@ var zodSchema66 = external_exports.object({
181832
183617
  function createStopAllSimulatorServersTool(registry2) {
181833
183618
  return {
181834
183619
  id: "stop-all-simulator-servers",
181835
- description: `Stop the services a device owns - simulator-server processes (iOS + Android), native devtools, the iOS accessibility service, TV-control daemons, Chromium CDP sessions, screen recordings, native profiler sessions, Android native network capture (started by native-network-logs), and JS-runtime debugger sessions along with the network inspectors and React profiler sessions that ride on them - freeing their spawned processes, sockets and ports. Call this when the user asks to clean up or ends the session, or when a skill tells you to recycle a device's services mid-flow - not just because a task finished, since the next task reuses these services and would start cold again. To end only the native network capture of one app, call native-network-logs with stop: true instead.
183620
+ description: `Stop the services a device owns - simulator-server processes (iOS + Android), native devtools, the iOS accessibility service, TV-control daemons, Chromium CDP sessions, screen recordings, native profiler sessions, native network capture with the requests it recorded, and JS-runtime debugger sessions along with the network inspectors and React profiler sessions that ride on them - freeing their spawned processes, sockets and ports. Network capture started by network-capture-start ends here too, with the requests it recorded, except in a JS runtime this call does not reach, for example after Metro restarted: this call does not connect to it again, so its JS capture keeps recording and keeps its requests, and the result does not say so. A later network-capture-stop that reaches that runtime stops the recording. Call this when the user asks to clean up or ends the session, or when a skill tells you to recycle a device's services mid-flow - not just because a task finished, since the next task reuses these services and would start cold again. To stop the network capture of one app and keep its requests, call network-capture-stop instead.
181836
183621
  PASS \`devices\` with the device ids this session used: one tool-server serves every agent, subagent and CLI call using this argent install, and an unscoped call tears down THEIR devices too. Omit \`devices\` only when a machine-wide cleanup is what you actually want. An EMPTY array stops nothing; it does not ask for the machine-wide sweep.
181837
183622
  A JS-runtime debugger session is keyed by the id you called \`debugger-connect\` with. On a Metro serving two or more devices that id can be a \`logicalDeviceId\`: connect refuses a serial, or a simulator udid it cannot match to one Metro device by name, and tells you to re-target with the \`logicalDeviceId\` it returns. A scope built from \`list-devices\` ids cannot reach that session. Pass any such \`logicalDeviceId\` in \`devices\` ALONGSIDE the device id.
181838
183623
  Returns { stopped }: the URNs of the live services that were shut down; empty means nothing was still running. { unmatched }, present only when a supplied id owns no service here, lists those ids, so a typo or a device NAME passed instead of an id does not read as a clean machine. It is NOT proof the id is wrong: a Vega device you only booted and drove with the remote registers no service and lands here, as does any device this session never started anything on. { left_running } lists the URNs of live debugger sessions (and the network inspectors / React profiler sessions riding on them) whose id no device scope can name; re-call with the id after each URN's \`<namespace>:<port>:\` prefix to reap them. { aborted: true } means the request was cancelled part-way: the rest was left untouched and \`unmatched\` / \`left_running\` were not computed.
@@ -181869,43 +183654,52 @@ Fails if the input has an unknown key (e.g. \`udids\` instead of \`devices\`); o
181869
183654
  async execute(_services, params, ctx) {
181870
183655
  const devices2 = params.devices;
181871
183656
  const scoped = devices2 !== void 0;
181872
- const snapshot = registry2.getSnapshot();
181873
- const stopped = [];
181874
- const matchedIds = /* @__PURE__ */ new Set();
181875
- const survivors = [];
181876
- let aborted2 = false;
181877
- for (const [urn, entry] of snapshot.services) {
181878
- if (ctx?.signal?.aborted) {
181879
- aborted2 = true;
181880
- break;
183657
+ return withCaptureSweep(scoped ? devices2 : void 0, { signal: ctx?.signal }, async () => {
183658
+ if (ctx?.signal?.aborted) return { stopped: [], aborted: true };
183659
+ const stopped = [];
183660
+ const matchedIds = /* @__PURE__ */ new Set();
183661
+ const survivors = [];
183662
+ let aborted2 = false;
183663
+ const paused = await pauseJsCapturesOf(registry2, scoped ? devices2 : void 0);
183664
+ const snapshot = registry2.getSnapshot();
183665
+ for (const [urn, entry] of snapshot.services) {
183666
+ if (ctx?.signal?.aborted) {
183667
+ aborted2 = true;
183668
+ break;
183669
+ }
183670
+ const matchedId = scoped ? deviceIdOwningUrn(urn, DEVICE_OWNED_NAMESPACES, devices2) : void 0;
183671
+ const matches2 = scoped ? matchedId !== void 0 : isDeviceServiceUrn(urn, DEVICE_OWNED_NAMESPACES);
183672
+ if (matchedId !== void 0) matchedIds.add(matchedId.toLowerCase());
183673
+ if (matches2 && entry.state !== "IDLE" /* IDLE */) {
183674
+ const wasLive = isLiveServiceState(entry.state);
183675
+ await registry2.disposeService(urn);
183676
+ if (wasLive && !isProviderOwnedUrn(urn)) stopped.push(urn);
183677
+ } else if (scoped && isLiveServiceState(entry.state) && isDeviceServiceUrn(urn, PORT_KEYED_NAMESPACES)) {
183678
+ survivors.push(urn);
183679
+ }
181881
183680
  }
181882
- const matchedId = scoped ? deviceIdOwningUrn(urn, DEVICE_OWNED_NAMESPACES, devices2) : void 0;
181883
- const matches2 = scoped ? matchedId !== void 0 : isDeviceServiceUrn(urn, DEVICE_OWNED_NAMESPACES);
181884
- if (matchedId !== void 0) matchedIds.add(matchedId.toLowerCase());
181885
- if (matches2 && entry.state !== "IDLE" /* IDLE */) {
181886
- const wasLive = isLiveServiceState(entry.state);
181887
- await registry2.disposeService(urn);
181888
- if (wasLive && !isExternalDeviceUrn(urn)) stopped.push(urn);
181889
- } else if (scoped && isLiveServiceState(entry.state) && isDeviceServiceUrn(urn, PORT_KEYED_NAMESPACES)) {
181890
- survivors.push(urn);
183681
+ if (aborted2) {
183682
+ forgetJsCaptures(paused);
183683
+ return { stopped, aborted: true };
181891
183684
  }
181892
- }
181893
- if (aborted2) return { stopped, aborted: true };
181894
- if (!scoped) return { stopped };
181895
- const seen = /* @__PURE__ */ new Set();
181896
- const unmatched = devices2.filter((id) => {
181897
- const key2 = id.toLowerCase();
181898
- if (matchedIds.has(key2) || seen.has(key2)) return false;
181899
- seen.add(key2);
181900
- return true;
183685
+ forgetJsCapturesOf(scoped ? devices2 : void 0, paused);
183686
+ forgetNativeUnavailableOf(scoped ? devices2 : void 0);
183687
+ if (!scoped) return { stopped };
183688
+ const seen = /* @__PURE__ */ new Set();
183689
+ const unmatched = devices2.filter((id) => {
183690
+ const key2 = id.toLowerCase();
183691
+ if (matchedIds.has(key2) || seen.has(key2)) return false;
183692
+ seen.add(key2);
183693
+ return true;
183694
+ });
183695
+ const leftRunning = unnameableSessionUrns(survivors);
183696
+ const result = {
183697
+ stopped
183698
+ };
183699
+ if (unmatched.length > 0) result.unmatched = unmatched;
183700
+ if (leftRunning.length > 0) result.left_running = leftRunning;
183701
+ return result;
181901
183702
  });
181902
- const leftRunning = unnameableSessionUrns(survivors);
181903
- const result = {
181904
- stopped
181905
- };
181906
- if (unmatched.length > 0) result.unmatched = unmatched;
181907
- if (leftRunning.length > 0) result.left_running = leftRunning;
181908
- return result;
181909
183703
  }
181910
183704
  };
181911
183705
  }
@@ -188485,7 +190279,7 @@ var FlowScriptExecutor = class {
188485
190279
  );
188486
190280
  } catch (err) {
188487
190281
  const queuedMs2 = Date.now() - queueStarted;
188488
- return err instanceof ScriptCancelledError ? emptyResult({ kind: "cancelled", message: err.message }, { queuedMs: queuedMs2 }) : emptyResult({ kind: "queue", message: errorMessage4(err) }, { queuedMs: queuedMs2 });
190282
+ return err instanceof ScriptCancelledError ? emptyResult({ kind: "cancelled", message: err.message }, { queuedMs: queuedMs2 }) : emptyResult({ kind: "queue", message: errorMessage5(err) }, { queuedMs: queuedMs2 });
188489
190283
  }
188490
190284
  const queuedMs = Date.now() - queueStarted;
188491
190285
  try {
@@ -188597,7 +190391,7 @@ var FlowScriptExecutor = class {
188597
190391
  } catch (err) {
188598
190392
  const kind = err instanceof ScriptSetupError ? err.kind : "spawn";
188599
190393
  return emptyResult(
188600
- { kind, message: errorMessage4(err) },
190394
+ { kind, message: errorMessage5(err) },
188601
190395
  { notes, durationMs: Date.now() - startedAt }
188602
190396
  );
188603
190397
  }
@@ -188657,7 +190451,7 @@ var FlowScriptExecutor = class {
188657
190451
  child = (0, import_node_child_process52.fork)(scriptPath, [], forkOptions);
188658
190452
  } catch (err) {
188659
190453
  return emptyResult(
188660
- { kind: "spawn", message: `Could not start the script process: ${errorMessage4(err)}` },
190454
+ { kind: "spawn", message: `Could not start the script process: ${errorMessage5(err)}` },
188661
190455
  { notes, durationMs: Date.now() - startedAt }
188662
190456
  );
188663
190457
  }
@@ -188673,7 +190467,7 @@ var FlowScriptExecutor = class {
188673
190467
  (resolve21) => {
188674
190468
  child.once("exit", (code, signal) => resolve21({ code, signal }));
188675
190469
  child.once("error", (err) => {
188676
- spawnProblem ??= `Could not start the script process: ${errorMessage4(err)}`;
190470
+ spawnProblem ??= `Could not start the script process: ${errorMessage5(err)}`;
188677
190471
  resolve21({ code: null, signal: null });
188678
190472
  });
188679
190473
  }
@@ -188720,11 +190514,11 @@ var FlowScriptExecutor = class {
188720
190514
  try {
188721
190515
  child.send(message, (err) => {
188722
190516
  if (!err) return;
188723
- protocolProblem ??= `The script runner closed its channel before the request arrived: ${errorMessage4(err)}`;
190517
+ protocolProblem ??= `The script runner closed its channel before the request arrived: ${errorMessage5(err)}`;
188724
190518
  void stop();
188725
190519
  });
188726
190520
  } catch (err) {
188727
- protocolProblem ??= `The script runner could not be given its request: ${errorMessage4(err)}`;
190521
+ protocolProblem ??= `The script runner could not be given its request: ${errorMessage5(err)}`;
188728
190522
  void stop();
188729
190523
  }
188730
190524
  const exit = await exited;
@@ -188869,7 +190663,7 @@ function commitOutput(outputJson) {
188869
190663
  try {
188870
190664
  parsed2 = JSON.parse(outputJson);
188871
190665
  } catch (err) {
188872
- return failed2("output", `The script's output did not parse: ${errorMessage4(err)}`);
190666
+ return failed2("output", `The script's output did not parse: ${errorMessage5(err)}`);
188873
190667
  }
188874
190668
  if (typeof parsed2 !== "object" || parsed2 === null || Array.isArray(parsed2)) {
188875
190669
  return failed2("output", "The script's output was not an object.");
@@ -188995,7 +190789,7 @@ function encodeRequestOutput(output2) {
188995
190789
  } catch (err) {
188996
190790
  throw new ScriptSetupError(
188997
190791
  "invalid",
188998
- `The e2e test output could not be encoded for the script: ${errorMessage4(err)}`
190792
+ `The e2e test output could not be encoded for the script: ${errorMessage5(err)}`
188999
190793
  );
189000
190794
  }
189001
190795
  if (typeof encoded !== "string") {
@@ -189394,7 +191188,7 @@ function emptyResult(failure2, extras = {}) {
189394
191188
  notes: extras.notes ?? []
189395
191189
  };
189396
191190
  }
189397
- function errorMessage4(err) {
191191
+ function errorMessage5(err) {
189398
191192
  if (err instanceof Error) return formatErrorForAgent(err) || String(err);
189399
191193
  return typeof err === "string" ? err : describeUnknown(err);
189400
191194
  }
@@ -189968,7 +191762,7 @@ init_device_info();
189968
191762
  init_capability();
189969
191763
 
189970
191764
  // ../tool-server/src/tools/flows/flow-visual.ts
189971
- var import_node_crypto20 = require("node:crypto");
191765
+ var import_node_crypto21 = require("node:crypto");
189972
191766
  var fs79 = __toESM(require("node:fs/promises"));
189973
191767
  var os25 = __toESM(require("node:os"));
189974
191768
  var path65 = __toESM(require("node:path"));
@@ -192092,7 +193886,7 @@ async function runSnapshot(env, opts) {
192092
193886
  });
192093
193887
  let captureWarned = shot.warning !== void 0 ? { warning: shot.warning } : {};
192094
193888
  const { w, h } = await pngDimensions(shot.image.hostPath);
192095
- const cropSuffix = opts.cropOn === void 0 ? "" : `-crop-${(0, import_node_crypto20.createHash)("sha256").update(cropIdentity(opts.cropOn)).digest("hex").slice(0, 8)}`;
193889
+ const cropSuffix = opts.cropOn === void 0 ? "" : `-crop-${(0, import_node_crypto21.createHash)("sha256").update(cropIdentity(opts.cropOn)).digest("hex").slice(0, 8)}`;
192096
193890
  const keyFor = (width, height) => `${opts.name}__${authoringPlatform(env.device.platform)}-${width}x${height}${cropSuffix}`;
192097
193891
  const baselineFor = (file2) => opts.clientFlowPath === void 0 ? path65.join(baselineDir(opts.flowsDir, opts.flowName), file2) : clientBaselinePath(opts.clientFlowPath, opts.flowName, file2);
192098
193892
  const snapshotKey = keyFor(w, h);
@@ -194655,9 +196449,9 @@ var dismissUpdateTool = {
194655
196449
  };
194656
196450
 
194657
196451
  // ../tool-server/src/tools/screenshot-diff/index.ts
194658
- var import_node_crypto21 = __toESM(require("node:crypto"));
196452
+ var import_node_crypto22 = __toESM(require("node:crypto"));
194659
196453
  var import_promises23 = __toESM(require("fs/promises"));
194660
- var import_node_os18 = __toESM(require("node:os"));
196454
+ var import_node_os19 = __toESM(require("node:os"));
194661
196455
  var import_path9 = __toESM(require("path"));
194662
196456
  init_zod();
194663
196457
  init_src2();
@@ -194809,9 +196603,9 @@ async function resolveOutputDir(params, options) {
194809
196603
  }
194810
196604
  }
194811
196605
  const dir = import_path9.default.join(
194812
- import_node_os18.default.tmpdir(),
196606
+ import_node_os19.default.tmpdir(),
194813
196607
  "argent-screenshot-diff",
194814
- import_node_crypto21.default.randomBytes(6).toString("hex")
196608
+ import_node_crypto22.default.randomBytes(6).toString("hex")
194815
196609
  );
194816
196610
  await import_promises23.default.mkdir(dir, { recursive: true });
194817
196611
  return dir;
@@ -194916,7 +196710,7 @@ async function captureIosDeviceLiveInput(params) {
194916
196710
  return writeLivePng(params.outputDir, params.name, png);
194917
196711
  }
194918
196712
  async function writeLivePng(outputDir, name, png) {
194919
- const suffix = import_node_crypto21.default.randomBytes(4).toString("hex");
196713
+ const suffix = import_node_crypto22.default.randomBytes(4).toString("hex");
194920
196714
  const destination = import_path9.default.join(outputDir, `${name}-${suffix}.live.png`);
194921
196715
  await import_promises23.default.mkdir(outputDir, { recursive: true });
194922
196716
  await import_promises23.default.writeFile(destination, png);
@@ -194934,7 +196728,7 @@ async function captureHarmonyLiveInput(params) {
194934
196728
  }
194935
196729
  await ensureDep("hdc");
194936
196730
  const captured = await captureHarmonyScreenshotPng({ connectKey: params.connectKey, scale: 1 });
194937
- const suffix = import_node_crypto21.default.randomBytes(4).toString("hex");
196731
+ const suffix = import_node_crypto22.default.randomBytes(4).toString("hex");
194938
196732
  const destination = import_path9.default.join(params.outputDir, `${params.name}-${suffix}.live.png`);
194939
196733
  try {
194940
196734
  await import_promises23.default.mkdir(params.outputDir, { recursive: true });
@@ -194957,7 +196751,7 @@ async function captureLiveInput(params) {
194957
196751
  captureScreenshot2,
194958
196752
  params.peekFor?.(params.device)
194959
196753
  );
194960
- const suffix = import_node_crypto21.default.randomBytes(4).toString("hex");
196754
+ const suffix = import_node_crypto22.default.randomBytes(4).toString("hex");
194961
196755
  const destination = import_path9.default.join(params.outputDir, `${params.name}-${suffix}.live.png`);
194962
196756
  await import_promises23.default.mkdir(params.outputDir, { recursive: true });
194963
196757
  await import_promises23.default.copyFile(capture.path, destination);
@@ -195973,6 +197767,8 @@ function createRegistry() {
195973
197767
  registry2.registerTool(createDebuggerLogRegistryTool(registry2));
195974
197768
  registry2.registerTool(networkLogsTool);
195975
197769
  registry2.registerTool(networkRequestTool);
197770
+ registry2.registerTool(createNetworkCaptureStartTool(registry2));
197771
+ registry2.registerTool(createNetworkCaptureStopTool(registry2));
195976
197772
  registry2.registerTool(createDescribeTool(registry2));
195977
197773
  registry2.registerTool(createUiTreeTool(registry2));
195978
197774
  registry2.registerTool(createForegroundAppTool(registry2));
@@ -196182,6 +197978,7 @@ function createPreviewWindowManager(opts = {}) {
196182
197978
 
196183
197979
  // ../tool-server/src/index.ts
196184
197980
  var PROCESS_TIMEOUT_MS = 5e3;
197981
+ var EXIT_CAPTURE_WAIT_MS = 2e3;
196185
197982
  var DEFAULT_PORT = "3001";
196186
197983
  var DEFAULT_HOST = "127.0.0.1";
196187
197984
  var DEFAULT_IDLE_TIMEOUT_MINUTES = "0";
@@ -196270,7 +198067,7 @@ function start() {
196270
198067
  attachRegistryLogger(registry2);
196271
198068
  let eventLog = null;
196272
198069
  if (isFlagEnabled("tool-server-event-log")) {
196273
- const eventLogPath = process.env.ARGENT_EVENT_LOG || path71.join((0, import_node_os19.homedir)(), ".argent", "tool-server-events.jsonl");
198070
+ const eventLogPath = process.env.ARGENT_EVENT_LOG || path71.join((0, import_node_os20.homedir)(), ".argent", "tool-server-events.jsonl");
196274
198071
  try {
196275
198072
  eventLog = createToolServerEventLog({ filePath: eventLogPath });
196276
198073
  } catch (err) {
@@ -196382,12 +198179,16 @@ function start() {
196382
198179
  previewWindow.dispose();
196383
198180
  updateChecker.dispose();
196384
198181
  httpHandle.dispose();
196385
- try {
196386
- await registry2.dispose();
196387
- } catch (err) {
196388
- process.stderr.write(`[tool-server] registry dispose failed: ${String(err)}
198182
+ await withCaptureSweep(void 0, { maxMs: EXIT_CAPTURE_WAIT_MS }, async () => {
198183
+ await pauseJsCapturesOf(registry2, void 0, { atExit: true }).catch(() => {
198184
+ });
198185
+ try {
198186
+ await registry2.dispose();
198187
+ } catch (err) {
198188
+ process.stderr.write(`[tool-server] registry dispose failed: ${String(err)}
196389
198189
  `);
196390
- }
198190
+ }
198191
+ });
196391
198192
  try {
196392
198193
  await eventLog?.dispose();
196393
198194
  } catch (err) {