@swmansion/argent 0.34.1-next.46 → 0.34.1-next.48

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_NO_CAPTURE_START_STOP, 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";
@@ -79744,13 +79744,20 @@ var init_capability = __esm({
79744
79744
  MACOS_APPS_FLAG_OFF_REASON = "the macos-apps flag is off. Run: argent enable macos-apps";
79745
79745
  MACOS_POINTER_ONLY = "a Mac app takes mouse input: use gesture-drag to drag and gesture-scroll to scroll";
79746
79746
  MACOS_NO_TRACKPAD_GESTURES = "a Mac app has no trackpad gesture input: use the app's own zoom or rotate controls with gesture-tap or keyboard";
79747
+ MACOS_NO_CAPTURE_START_STOP = "a Mac app's network capture has no start or stop: native-network-logs turns it on at its first call, and stop-simulator-server or stop-all-simulator-servers for the app ends it and drops its log";
79747
79748
  MACOS_REFUSAL_REASONS = {
79748
79749
  "gesture-swipe": MACOS_POINTER_ONLY,
79749
79750
  "gesture-custom": MACOS_POINTER_ONLY,
79750
79751
  "gesture-pinch": MACOS_NO_TRACKPAD_GESTURES,
79751
79752
  "gesture-rotate": MACOS_NO_TRACKPAD_GESTURES,
79752
79753
  "button": "a Mac app has no hardware buttons: use keyboard for key presses",
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
+ "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)",
79755
+ "network-capture-start": MACOS_NO_CAPTURE_START_STOP,
79756
+ "network-capture-stop": MACOS_NO_CAPTURE_START_STOP
79757
+ };
79758
+ NO_CAPTURE_START_STOP_REASONS = {
79759
+ vega: "a Vega app's network capture has no start or stop: view-network-logs turns it on at its first call",
79760
+ 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"
79754
79761
  };
79755
79762
  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
79763
  MACOS_CATALYST_REFUSAL_REASONS = {
@@ -97887,7 +97894,7 @@ __export(index_exports, {
97887
97894
  });
97888
97895
  module.exports = __toCommonJS(index_exports);
97889
97896
  var path71 = __toESM(require("node:path"));
97890
- var import_node_os19 = require("node:os");
97897
+ var import_node_os20 = require("node:os");
97891
97898
  init_src();
97892
97899
  init_src2();
97893
97900
 
@@ -101443,7 +101450,7 @@ function isCi(env = process.env) {
101443
101450
  var SESSION_ID = (0, import_node_crypto3.randomUUID)();
101444
101451
  function readCliVersion() {
101445
101452
  if (true) {
101446
- return "0.34.1-next.46";
101453
+ return "0.34.1-next.48";
101447
101454
  }
101448
101455
  return "0.0.0";
101449
101456
  }
@@ -123839,6 +123846,140 @@ function createNdjsonCdpRequester(socket, options) {
123839
123846
  init_src2();
123840
123847
  init_external_devices();
123841
123848
 
123849
+ // ../tool-server/src/utils/debugger/device-alias.ts
123850
+ var logicalIdToConnectId = /* @__PURE__ */ new Map();
123851
+ function rememberDeviceAlias(logicalDeviceId, connectDeviceId) {
123852
+ if (!logicalDeviceId || logicalDeviceId === connectDeviceId) return;
123853
+ logicalIdToConnectId.set(logicalDeviceId, connectDeviceId);
123854
+ }
123855
+ function canonicalDeviceId(deviceId) {
123856
+ if (!deviceId) return deviceId;
123857
+ return logicalIdToConnectId.get(deviceId) ?? deviceId;
123858
+ }
123859
+ function deviceIdsOf(deviceId) {
123860
+ const connectId = canonicalDeviceId(deviceId) ?? deviceId;
123861
+ const logicalIds = [...logicalIdToConnectId].filter(([, aliased]) => aliased === connectId).map(([logicalId]) => logicalId);
123862
+ return [.../* @__PURE__ */ new Set([deviceId, connectId, ...logicalIds])];
123863
+ }
123864
+ function forgetDeviceAlias(logicalDeviceId) {
123865
+ if (logicalDeviceId) logicalIdToConnectId.delete(logicalDeviceId);
123866
+ }
123867
+ var logicalKeyedConnectIds = /* @__PURE__ */ new Set();
123868
+ function rememberLogicalKeyedDevice(logicalDeviceId, connectDeviceId) {
123869
+ if (logicalDeviceId && logicalDeviceId === connectDeviceId) {
123870
+ logicalKeyedConnectIds.add(connectDeviceId.toLowerCase());
123871
+ }
123872
+ }
123873
+ function isLogicalKeyedDevice(deviceId) {
123874
+ return deviceId !== void 0 && logicalKeyedConnectIds.has(deviceId.toLowerCase());
123875
+ }
123876
+ function forgetLogicalKeyedDevice(connectDeviceId) {
123877
+ logicalKeyedConnectIds.delete(connectDeviceId.toLowerCase());
123878
+ }
123879
+
123880
+ // ../tool-server/src/utils/native-network-record.ts
123881
+ init_external_devices();
123882
+ function deviceKeyOf(deviceId) {
123883
+ return externalNativeId(canonicalDeviceId(deviceId) ?? deviceId);
123884
+ }
123885
+ var MAX_RECORDS = 2e3;
123886
+ var RECORD_CHARS_BUDGET = 32 * 1024 * 1024;
123887
+ var MAX_VALUE_CHARS = 64 * 1024;
123888
+ var MAX_HEADERS = 256;
123889
+ var MAX_HEADER_MAP_CHARS = 256 * 1024;
123890
+ var MAX_LAYER_ID_CHARS = 200;
123891
+ var MAX_CACHED_BODIES = 64;
123892
+ var NOT_RECONNECTED = "the agent did not reconnect after its connection dropped, so this request's final events never arrived";
123893
+ var PROCESS_ENDED = "the app process ended before the request finished";
123894
+ var PROCESS_GONE = "the app process that made the request is gone";
123895
+ function isOpen(record2) {
123896
+ return record2.state === "pending" || record2.state === "headers";
123897
+ }
123898
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
123899
+ var ANDROID_EMULATOR_HOST = "10.0.2.2";
123900
+ var DEFAULT_PORTS = {
123901
+ "http:": 80,
123902
+ "ws:": 80,
123903
+ "https:": 443,
123904
+ "wss:": 443
123905
+ };
123906
+ function isMetroTraffic(url2, metroPort2, { androidEmulatorHost = false } = {}) {
123907
+ let parsed2;
123908
+ try {
123909
+ parsed2 = new URL(url2);
123910
+ } catch {
123911
+ return false;
123912
+ }
123913
+ const port = parsed2.port === "" ? DEFAULT_PORTS[parsed2.protocol] : Number(parsed2.port);
123914
+ const host = parsed2.hostname;
123915
+ const isHost = LOOPBACK_HOSTS.has(host) || androidEmulatorHost && host === ANDROID_EMULATOR_HOST;
123916
+ return isHost && port === metroPort2;
123917
+ }
123918
+ function capString(value, max = MAX_VALUE_CHARS) {
123919
+ return value.length > max ? `${value.slice(0, max)}\u2026[${value.length - max} more chars]` : value;
123920
+ }
123921
+ function headerMap(value) {
123922
+ const headers = {};
123923
+ let kept = 0;
123924
+ let chars = 0;
123925
+ let left = 0;
123926
+ for (const [name, v] of Object.entries(asObject(value))) {
123927
+ if (typeof v !== "string" && typeof v !== "number" && typeof v !== "boolean") continue;
123928
+ const key2 = capString(name, 1024);
123929
+ const text = capString(String(v));
123930
+ if (kept >= MAX_HEADERS || chars + key2.length + text.length > MAX_HEADER_MAP_CHARS) {
123931
+ left++;
123932
+ continue;
123933
+ }
123934
+ headers[key2] = text;
123935
+ kept++;
123936
+ chars += key2.length + text.length;
123937
+ }
123938
+ if (left > 0) headers["(not kept)"] = `${left} more headers`;
123939
+ return headers;
123940
+ }
123941
+ function mapChars(map2) {
123942
+ let chars = 0;
123943
+ for (const [name, value] of Object.entries(map2 ?? {})) chars += name.length + value.length;
123944
+ return chars;
123945
+ }
123946
+ function recordSize(record2) {
123947
+ let chars = record2.request.url.length + record2.request.method.length + mapChars(record2.request.headers) + mapChars(record2.request.wireHeaders) + (record2.errorText?.length ?? 0) + 256;
123948
+ if (record2.response) {
123949
+ chars += record2.response.url.length + record2.response.statusText.length + record2.response.mimeType.length + mapChars(record2.response.headers);
123950
+ }
123951
+ for (const hop of record2.redirects ?? []) {
123952
+ chars += hop.url.length + hop.statusText.length + mapChars(hop.headers) + mapChars(hop.requestHeaders);
123953
+ }
123954
+ return chars;
123955
+ }
123956
+ function toBody(result, kind) {
123957
+ const r = asObject(result);
123958
+ const text = kind === "response" ? r.body : r.postData;
123959
+ if (r.bodyAvailable === false || typeof text !== "string") {
123960
+ return unavailable(
123961
+ kind === "response" ? "the agent holds no body for this response" : "the agent holds no body for this request"
123962
+ );
123963
+ }
123964
+ const incomplete = kind === "post" && r.incomplete === true;
123965
+ return {
123966
+ available: true,
123967
+ body: text,
123968
+ base64Encoded: r.base64Encoded === true,
123969
+ truncated: r.wasTruncated === true || incomplete,
123970
+ ...incomplete ? { incomplete } : {}
123971
+ };
123972
+ }
123973
+ function unavailable(reason2) {
123974
+ return { available: false, body: "", base64Encoded: false, truncated: false, reason: reason2 };
123975
+ }
123976
+ function asObject(value) {
123977
+ return typeof value === "object" && value !== null ? value : {};
123978
+ }
123979
+ function asString2(value) {
123980
+ return typeof value === "string" ? value : "";
123981
+ }
123982
+
123842
123983
  // ../tool-server/src/utils/ios-host.ts
123843
123984
  var import_node_child_process15 = require("node:child_process");
123844
123985
  var import_node_events = require("node:events");
@@ -124536,144 +124677,13 @@ async function withKeyedLock(locks, key2, fn) {
124536
124677
  return run2;
124537
124678
  }
124538
124679
 
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
124680
  // ../tool-server/src/blueprints/ios-network-records.ts
124674
124681
  var RUN_TAG = (0, import_node_crypto7.randomBytes)(2).toString("hex");
124675
124682
  var IOS_NATIVE_REQUEST_ID = /^ios-[0-9a-f]{4}-\d+$/;
124676
124683
  var nextRecordNumber = 1;
124684
+ function lastIosRecordNumber() {
124685
+ return nextRecordNumber - 1;
124686
+ }
124677
124687
  var POST_DATA_WAIT_MS = 5e3;
124678
124688
  var POST_DATA_TIMEOUT_MS = 2 ** 31 - 1;
124679
124689
  var RESPONSE_BODY_TIMEOUT_MS = 1e4;
@@ -124685,7 +124695,7 @@ var CONNECTION_CLOSED = "the agent's connection closed before this body was read
124685
124695
  var REQUEST_BODY_GONE = "the agent holds no body for this request";
124686
124696
  var BODY_NO_LONGER_HELD = "the agent no longer holds this body";
124687
124697
  var NO_RESPONSE_BODY = "the response has no body";
124688
- function createIosNetworkRecords(state3, link) {
124698
+ function createIosNetworkRecords(state3, link, recording = () => true) {
124689
124699
  const records = [];
124690
124700
  let recordChars = 0;
124691
124701
  const recordSizes = /* @__PURE__ */ new WeakMap();
@@ -124919,7 +124929,7 @@ function createIosNetworkRecords(state3, link) {
124919
124929
  if (!layerId || layerId.length > MAX_LAYER_ID_CHARS) return;
124920
124930
  if (method === "Network.requestWillBeSent") {
124921
124931
  if (p.redirectResponse !== void 0 && p.redirectResponse !== null) return;
124922
- startRecord(connection, layerId, p);
124932
+ if (recording()) startRecord(connection, layerId, p);
124923
124933
  return;
124924
124934
  }
124925
124935
  const record2 = byLayerId.get(keyOf(connection, layerId));
@@ -125026,15 +125036,20 @@ function findIosNativeRecord(id) {
125026
125036
  }
125027
125037
  return void 0;
125028
125038
  }
125039
+ function hasIosNetworkCapture() {
125040
+ return [...liveCaptures].some(
125041
+ (captures) => (captures.startedBundleIds ?? captures.bundleIds).size > 0 || captures.stoppedBundleIds.size > 0
125042
+ );
125043
+ }
125029
125044
  function capturing(captures, bundleId) {
125030
- return captures.bundleIds.has(bundleId) && captures.stores.has(bundleId);
125045
+ return (captures.bundleIds.has(bundleId) || captures.unconfirmedStopBundleIds?.has(bundleId) === true) && captures.stores.has(bundleId);
125031
125046
  }
125032
125047
  function liveIosNetworkCaptures(deviceId) {
125033
125048
  const key2 = deviceKeyOf(deviceId);
125034
125049
  const bundleIds = /* @__PURE__ */ new Set();
125035
125050
  for (const captures of liveCaptures) {
125036
125051
  if (deviceKeyOf(captures.udid) !== key2) continue;
125037
- for (const bundleId of captures.bundleIds) {
125052
+ for (const bundleId of [...captures.bundleIds, ...captures.unconfirmedStopBundleIds ?? []]) {
125038
125053
  if (capturing(captures, bundleId)) bundleIds.add(bundleId);
125039
125054
  }
125040
125055
  }
@@ -125103,17 +125118,20 @@ function isNativeDevtoolsBlockResult(toolId, result) {
125103
125118
  const status = result.status;
125104
125119
  return typeof status === "string" && NATIVE_DEVTOOLS_BLOCK_STATUSES.has(status);
125105
125120
  }
125121
+ function nonInjectableError(bundleId) {
125122
+ return new FailureError(
125123
+ `${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,
125124
+ {
125125
+ error_code: FAILURE_CODES.NATIVE_DEVTOOLS_NOT_INJECTABLE,
125126
+ failure_stage: "native_devtools_precheck",
125127
+ failure_area: "tool_server",
125128
+ error_kind: "validation"
125129
+ }
125130
+ );
125131
+ }
125106
125132
  async function precheckNativeDevtools(api, udid, bundleId) {
125107
125133
  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
- );
125134
+ throw nonInjectableError(bundleId);
125117
125135
  }
125118
125136
  const existing = api.getInitFailure();
125119
125137
  if (existing?.givenUp) return buildInitFailedResult(udid, existing);
@@ -125153,11 +125171,15 @@ async function precheckNativeDevtools(api, udid, bundleId) {
125153
125171
  function nativeDevtoolsRef(device, { transport = "unix" } = {}) {
125154
125172
  const transportSuffix = transport === "tcp" ? ":tcp" : "";
125155
125173
  return {
125156
- urn: `${NATIVE_DEVTOOLS_NAMESPACE}:${device.id}${transportSuffix}`,
125174
+ // A provider's `ext:` id and its raw udid name one app connection and one
125175
+ // capture, so both key the service by the udid, as the simulator watcher does.
125176
+ urn: `${NATIVE_DEVTOOLS_NAMESPACE}:${deviceKeyOf(device.id)}${transportSuffix}`,
125157
125177
  options: { device, transport }
125158
125178
  };
125159
125179
  }
125160
125180
  var NETWORK_ENABLE_TIMEOUT_MS = 5e3;
125181
+ var NETWORK_DISABLE_TIMEOUT_MS = 5e3;
125182
+ var DISPOSE_DISABLE_TIMEOUT_MS = 1e3;
125161
125183
  var LAUNCH_ARM_WAIT_MS = 5e3;
125162
125184
  var LENT_HANDSHAKE_PROMPT_MS = 1e3;
125163
125185
  var WAITING_FOR_ENABLE = "waiting for the agent to acknowledge Network.enable";
@@ -125217,7 +125239,7 @@ function bindNativeDevtoolsUnixSocket(server, socketPath) {
125217
125239
  var nativeDevtoolsBlueprint = {
125218
125240
  namespace: NATIVE_DEVTOOLS_NAMESPACE,
125219
125241
  getURN(device) {
125220
- return `${NATIVE_DEVTOOLS_NAMESPACE}:${device.id}`;
125242
+ return nativeDevtoolsRef(device).urn;
125221
125243
  },
125222
125244
  async factory(_deps, _payload, options) {
125223
125245
  const opts = options;
@@ -125273,6 +125295,9 @@ var nativeDevtoolsBlueprint = {
125273
125295
  let inFlight4 = null;
125274
125296
  let envRetired = false;
125275
125297
  const activatedBundleIds = /* @__PURE__ */ new Set();
125298
+ const stoppedBundleIds = /* @__PURE__ */ new Set();
125299
+ const unconfirmedStopBundleIds = /* @__PURE__ */ new Set();
125300
+ const captureMarks = /* @__PURE__ */ new Map();
125276
125301
  const captureGaps = /* @__PURE__ */ new Set();
125277
125302
  const networkConditions = /* @__PURE__ */ new Map();
125278
125303
  const providerCapture = /* @__PURE__ */ new Map();
@@ -125370,7 +125395,7 @@ var nativeDevtoolsBlueprint = {
125370
125395
  connectionWaiters.add(check3);
125371
125396
  });
125372
125397
  };
125373
- const enableOn = (conn) => {
125398
+ const enableOn = (bundleId, conn) => {
125374
125399
  if (conn.armed && !lentSocketPath) return Promise.resolve(true);
125375
125400
  if (conn.enabling) return conn.enabling;
125376
125401
  delete conn.enableFailure;
@@ -125380,6 +125405,7 @@ var nativeDevtoolsBlueprint = {
125380
125405
  {
125381
125406
  timeoutMs: NETWORK_ENABLE_TIMEOUT_MS,
125382
125407
  onResult: (result) => {
125408
+ if (stoppedBundleIds.has(bundleId)) return;
125383
125409
  conn.armed = !lentSocketPath || result?.enabled === true;
125384
125410
  if (!conn.armed) conn.enableFailure = PROVIDER_CAPTURE_OFF;
125385
125411
  wakeConnectionWaiters();
@@ -125391,7 +125417,7 @@ var nativeDevtoolsBlueprint = {
125391
125417
  if (conn.socket.destroyed || disposed) return false;
125392
125418
  const timedOut3 = getFailureSignal(err)?.error_kind === "timeout";
125393
125419
  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`;
125420
+ 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
125421
  process.stderr.write(`[native-devtools ${udid.slice(0, 8)}] ${conn.enableFailure}
125396
125422
  `);
125397
125423
  wakeConnectionWaiters();
@@ -125414,7 +125440,8 @@ var nativeDevtoolsBlueprint = {
125414
125440
  return {
125415
125441
  armed: conn.armed,
125416
125442
  ...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 } : {}
125443
+ // A failure is the answer to the request still on its way, which settles just after.
125444
+ ...conn.armed ? {} : conn.enableFailure ? { note: conn.enableFailure } : conn.enabling ? { note: lentSocketPath ? WAITING_FOR_CAPTURE_STATE : WAITING_FOR_ENABLE } : {}
125418
125445
  };
125419
125446
  };
125420
125447
  const readConnectionPid = async (bundleId, conn) => {
@@ -125446,7 +125473,10 @@ var nativeDevtoolsBlueprint = {
125446
125473
  const closeConnection = (bundleId, conn) => {
125447
125474
  conn.cdp.close();
125448
125475
  conn.armed = false;
125449
- if (connections2.get(bundleId) === conn) connections2.delete(bundleId);
125476
+ if (connections2.get(bundleId) === conn) {
125477
+ connections2.delete(bundleId);
125478
+ unconfirmedStopBundleIds.delete(bundleId);
125479
+ }
125450
125480
  connectionCloses += 1;
125451
125481
  wakeConnectionWaiters();
125452
125482
  void settleClosedConnection(bundleId, conn);
@@ -125514,7 +125544,7 @@ var nativeDevtoolsBlueprint = {
125514
125544
  };
125515
125545
  const armOn = (bundleId, conn) => {
125516
125546
  const sendsEnable = !lentSocketPath && !conn.armed && !conn.enabling;
125517
- const arming = enableOn(conn);
125547
+ const arming = enableOn(bundleId, conn);
125518
125548
  if (sendsEnable) reapplyStoredThrottle(bundleId);
125519
125549
  return arming;
125520
125550
  };
@@ -125578,20 +125608,27 @@ var nativeDevtoolsBlueprint = {
125578
125608
  const app = bundleId;
125579
125609
  networkStores.set(
125580
125610
  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
- })
125611
+ createIosNetworkRecords(
125612
+ () => captureState(app),
125613
+ {
125614
+ liveConnection: () => connections2.get(app)?.index,
125615
+ request: (index, method, params, timeoutMs) => {
125616
+ const live = connections2.get(app);
125617
+ return live?.index === index ? live.cdp.request(method, params, { timeoutMs }) : Promise.reject(closedBeforeRequest(app, method));
125618
+ }
125619
+ },
125620
+ () => !stoppedBundleIds.has(app)
125621
+ )
125588
125622
  );
125589
125623
  }
125590
125624
  if (lentSocketPath && performance.now() - lentConnectedAt < LENT_HANDSHAKE_PROMPT_MS) {
125591
125625
  captureGaps.add(bundleId);
125592
125626
  }
125593
125627
  if (activatedBundleIds.has(bundleId)) {
125594
- if (!lentSocketPath) captureGaps.delete(bundleId);
125628
+ if (!lentSocketPath) {
125629
+ captureGaps.delete(bundleId);
125630
+ conn.launchRecorded = true;
125631
+ }
125595
125632
  void armOn(bundleId, conn);
125596
125633
  } else {
125597
125634
  reapplyStoredThrottle(bundleId);
@@ -125735,14 +125772,67 @@ var nativeDevtoolsBlueprint = {
125735
125772
  if (processAgeMs < NATIVE_DEVTOOLS_CONNECT_BUDGET_MS) return "connecting";
125736
125773
  return "unregistered";
125737
125774
  },
125738
- activateNetworkInspection(bundleId) {
125775
+ startNetworkCapture(bundleId, metroPort2, waitForConnectionMs = 0) {
125776
+ stoppedBundleIds.delete(bundleId);
125777
+ unconfirmedStopBundleIds.delete(bundleId);
125778
+ captureMarks.set(bundleId, { lastRecord: lastIosRecordNumber(), metroPort: metroPort2 });
125739
125779
  const startedNow = !activatedBundleIds.has(bundleId);
125740
125780
  activatedBundleIds.add(bundleId);
125741
125781
  const conn = connections2.get(bundleId);
125742
- if (!conn) return Promise.resolve(false);
125743
- if (startedNow && !lentSocketPath) captureGaps.add(bundleId);
125782
+ if (!conn) {
125783
+ return waitForConnection(() => {
125784
+ const next = connections2.get(bundleId);
125785
+ return next?.armed === true || next?.enableFailure !== void 0;
125786
+ }, waitForConnectionMs).then(() => connections2.get(bundleId)?.armed === true);
125787
+ }
125788
+ if (startedNow && !lentSocketPath && !conn.launchRecorded) captureGaps.add(bundleId);
125744
125789
  return armOn(bundleId, conn);
125745
125790
  },
125791
+ async stopNetworkCapture(bundleId) {
125792
+ stoppedBundleIds.add(bundleId);
125793
+ activatedBundleIds.delete(bundleId);
125794
+ captureGaps.delete(bundleId);
125795
+ const conn = connections2.get(bundleId);
125796
+ if (!conn) return { confirmed: true };
125797
+ conn.armed = false;
125798
+ conn.enabling = void 0;
125799
+ delete conn.enableFailure;
125800
+ wakeConnectionWaiters();
125801
+ if (lentSocketPath) {
125802
+ return {
125803
+ confirmed: true,
125804
+ reason: "the device provider keeps its own capture setting for the app; argent records none of its new requests"
125805
+ };
125806
+ }
125807
+ const disabling = conn.cdp.request(
125808
+ "Network.disable",
125809
+ {},
125810
+ { timeoutMs: NETWORK_DISABLE_TIMEOUT_MS }
125811
+ );
125812
+ reapplyStoredThrottle(bundleId);
125813
+ try {
125814
+ await disabling;
125815
+ unconfirmedStopBundleIds.delete(bundleId);
125816
+ return { confirmed: true };
125817
+ } catch (err) {
125818
+ if (conn.socket.destroyed || disposed) return { confirmed: true };
125819
+ if (stoppedBundleIds.has(bundleId)) unconfirmedStopBundleIds.add(bundleId);
125820
+ const timedOut3 = getFailureSignal(err)?.error_kind === "timeout";
125821
+ const detail = err instanceof Error ? err.message : String(err);
125822
+ return {
125823
+ confirmed: false,
125824
+ 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`
125825
+ };
125826
+ }
125827
+ },
125828
+ isNetworkCaptureStarted: (bundleId) => activatedBundleIds.has(bundleId),
125829
+ isNetworkCaptureStopped: (bundleId) => stoppedBundleIds.has(bundleId),
125830
+ networkCaptureMark: (bundleId) => captureMarks.get(bundleId),
125831
+ async refreshLentNetworkCapture(bundleId) {
125832
+ if (!lentSocketPath || !activatedBundleIds.has(bundleId)) return;
125833
+ const conn = connections2.get(bundleId);
125834
+ if (conn) await enableOn(bundleId, conn);
125835
+ },
125746
125836
  async setNetworkConditions(bundleId, throttle) {
125747
125837
  const previous = networkConditions.get(bundleId) ?? null;
125748
125838
  storeThrottle(bundleId, throttle);
@@ -125763,28 +125853,42 @@ var nativeDevtoolsBlueprint = {
125763
125853
  takeCaptureGap: (bundleId) => captureGaps.delete(bundleId),
125764
125854
  networkRecords: (bundleId) => networkStores.get(bundleId),
125765
125855
  async networkCaptureAfterLaunch(bundleId) {
125766
- if (!activatedBundleIds.has(bundleId) || lentSocketPath) return void 0;
125856
+ if (lentSocketPath) return void 0;
125857
+ const stoppedNote = `native network capture is stopped for ${bundleId} (network-capture-stop); this process runs without it until network-capture-start`;
125858
+ if (stoppedBundleIds.has(bundleId) && !unconfirmedStopBundleIds.has(bundleId)) {
125859
+ return stoppedNote;
125860
+ }
125861
+ if (!activatedBundleIds.has(bundleId) && !unconfirmedStopBundleIds.has(bundleId)) {
125862
+ return void 0;
125863
+ }
125767
125864
  let closes = connectionCloses;
125768
125865
  const inspection = await host.inspectRunningApp(udid, bundleId).catch(() => null);
125769
125866
  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
125867
  const pid = inspection?.process?.pid;
125773
125868
  const ofLaunch = () => {
125774
125869
  const conn = connections2.get(bundleId);
125775
125870
  return conn && (pid === void 0 || conn.pid === pid) ? conn : void 0;
125776
125871
  };
125872
+ const noteWhenStopped = () => {
125873
+ const conn = unconfirmedStopBundleIds.has(bundleId) ? ofLaunch() : void 0;
125874
+ if (!conn) return stoppedNote;
125875
+ const pidText2 = conn.pid !== void 0 ? ` (pid ${conn.pid})` : "";
125876
+ 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`;
125877
+ };
125878
+ if (stoppedBundleIds.has(bundleId)) return noteWhenStopped();
125879
+ 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`;
125880
+ if (inspection?.running === false) return gone;
125777
125881
  const running = inspection?.process;
125778
125882
  if (running && !ofLaunch()) {
125779
125883
  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`;
125884
+ 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
125885
  }
125782
125886
  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`;
125887
+ 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
125888
  }
125785
125889
  }
125786
125890
  const asked = ofLaunch();
125787
- if (asked && !asked.armed && !asked.enabling) void enableOn(asked);
125891
+ if (asked && !asked.armed && !asked.enabling) void enableOn(bundleId, asked);
125788
125892
  let exited = false;
125789
125893
  const watchExit = () => {
125790
125894
  if (closes === connectionCloses) return;
@@ -125807,18 +125911,20 @@ var nativeDevtoolsBlueprint = {
125807
125911
  connectionWaiters.delete(watchExit);
125808
125912
  }
125809
125913
  if (disposed) return void 0;
125914
+ if (stoppedBundleIds.has(bundleId)) return noteWhenStopped();
125810
125915
  if (exited) return gone;
125811
125916
  let launched = ofLaunch();
125812
125917
  if (!launched) {
125813
125918
  const now = await host.inspectRunningApp(udid, bundleId).catch(() => null);
125814
125919
  if (disposed) return void 0;
125920
+ if (stoppedBundleIds.has(bundleId)) return noteWhenStopped();
125815
125921
  if (now?.running === false) return gone;
125816
125922
  launched = ofLaunch();
125817
125923
  }
125818
125924
  const shownPid = pid ?? launched?.pid;
125819
125925
  const pidText = shownPid !== void 0 ? ` (pid ${shownPid})` : "";
125820
125926
  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`;
125927
+ return `native network capture is armed for ${bundleId}${pidText}; network-capture-stop ends it`;
125822
125928
  }
125823
125929
  if (launched?.enableFailure !== void 0) {
125824
125930
  return `native network capture is on for ${bundleId}, but its process${pidText} is not armed: ${launched.enableFailure}`;
@@ -125872,6 +125978,9 @@ var nativeDevtoolsBlueprint = {
125872
125978
  udid,
125873
125979
  // A lent agent's capture is its provider's, so argent has none on there.
125874
125980
  bundleIds: lentSocketPath ? /* @__PURE__ */ new Set() : activatedBundleIds,
125981
+ startedBundleIds: activatedBundleIds,
125982
+ stoppedBundleIds,
125983
+ unconfirmedStopBundleIds,
125875
125984
  stores: networkStores
125876
125985
  });
125877
125986
  return {
@@ -125879,6 +125988,14 @@ var nativeDevtoolsBlueprint = {
125879
125988
  dispose: async () => {
125880
125989
  disposed = true;
125881
125990
  unregisterCaptures();
125991
+ wakeConnectionWaiters();
125992
+ if (!lentSocketPath) {
125993
+ await Promise.all(
125994
+ [...connections2].filter(([app]) => activatedBundleIds.has(app) || stoppedBundleIds.has(app)).map(
125995
+ ([, { cdp }]) => cdp.request("Network.disable", {}, { timeoutMs: DISPOSE_DISABLE_TIMEOUT_MS }).catch(() => void 0)
125996
+ )
125997
+ );
125998
+ }
125882
125999
  if (lentSocketPath) await releaseLentThrottles();
125883
126000
  for (const { socket, cdp } of connections2.values()) {
125884
126001
  cdp.close();
@@ -125886,6 +126003,9 @@ var nativeDevtoolsBlueprint = {
125886
126003
  }
125887
126004
  connections2.clear();
125888
126005
  activatedBundleIds.clear();
126006
+ stoppedBundleIds.clear();
126007
+ unconfirmedStopBundleIds.clear();
126008
+ captureMarks.clear();
125889
126009
  captureGaps.clear();
125890
126010
  networkStores.clear();
125891
126011
  wakeConnectionWaiters();
@@ -126326,7 +126446,7 @@ function subcommandForDevice(device) {
126326
126446
  }
126327
126447
  return device.kind === "device" ? "android_device" : "android";
126328
126448
  }
126329
- var EMULATOR_NOT_DISCOVERED = /not found among running emulators|Failed to find any running emulator/;
126449
+ var EMULATOR_NOT_DISCOVERED = /not found among running emulators|Failed to find any running emulator|transport error[\s\S]*tcp connect error: (?:Connection refused|[^\n]*actively refused)/;
126330
126450
  var FIRST_FRAME_TIMEOUT_MS = 5e3;
126331
126451
  async function waitForFirstFrame(streamUrl) {
126332
126452
  if (!streamUrl) return;
@@ -128037,7 +128157,7 @@ var os9 = __toESM(require("node:os"));
128037
128157
  function metroOriginCandidates(wsUrl) {
128038
128158
  const { protocol, host, port } = new URL(wsUrl);
128039
128159
  const scheme = protocol === "wss:" ? "https://" : "http://";
128040
- const at = (hostname4) => `${scheme}${bracketed(hostname4)}${port ? `:${port}` : ""}`;
128160
+ const at = (hostname5) => `${scheme}${bracketed(hostname5)}${port ? `:${port}` : ""}`;
128041
128161
  const candidates = [
128042
128162
  scheme + host.replace("localhost", "127.0.0.1"),
128043
128163
  at("localhost"),
@@ -128066,8 +128186,8 @@ async function expoManifestOrigin(wsUrl) {
128066
128186
  function lanAddresses() {
128067
128187
  return Object.values(os9.networkInterfaces()).flat().filter((address) => address && !address.internal && address.family === "IPv4").map((address) => address.address);
128068
128188
  }
128069
- function bracketed(hostname4) {
128070
- return hostname4.includes(":") && !hostname4.startsWith("[") ? `[${hostname4}]` : hostname4;
128189
+ function bracketed(hostname5) {
128190
+ return hostname5.includes(":") && !hostname5.startsWith("[") ? `[${hostname5}]` : hostname5;
128071
128191
  }
128072
128192
 
128073
128193
  // ../tool-server/src/utils/debugger/scripts/await-promise.ts
@@ -148086,8 +148206,8 @@ function isAllowedSourceMapURL(raw) {
148086
148206
  }
148087
148207
  if (parsed2.protocol !== "http:" && parsed2.protocol !== "https:") return false;
148088
148208
  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);
148209
+ const hostname5 = parsed2.hostname.startsWith("[") && parsed2.hostname.endsWith("]") ? parsed2.hostname.slice(1, -1) : parsed2.hostname;
148210
+ return ALLOWED_SOURCE_MAP_HOSTS.has(hostname5);
148091
148211
  }
148092
148212
  var MAX_SOURCE_MAP_BYTES = 64 * 1024 * 1024;
148093
148213
  async function drainCappedBody(res, maxBytes = MAX_SOURCE_MAP_BYTES) {
@@ -148690,9 +148810,9 @@ function trackDebuggerOutcome(tool, outcome, params, ctx) {
148690
148810
  ...ctx?.toolInvocationId ? { tool_invocation_id: ctx.toolInvocationId } : {}
148691
148811
  });
148692
148812
  }
148693
- async function resolveDebuggerService(registry2, params) {
148813
+ async function resolveDebuggerService(registry2, params, options) {
148694
148814
  const ref = debuggerServiceRef(params);
148695
- return typeof ref === "string" ? registry2.resolveService(ref) : registry2.resolveService(ref.urn, ref.options);
148815
+ return typeof ref === "string" ? registry2.resolveService(ref, options) : registry2.resolveService(ref.urn, ref.options);
148696
148816
  }
148697
148817
  function isDebuggerNotConnectedResult(toolId, result) {
148698
148818
  return (toolId === "debugger-status" || toolId === "debugger-log-registry") && typeof result === "object" && result !== null && result.status === "not_connected";
@@ -149041,8 +149161,8 @@ function createHttpApp(registry2, options) {
149041
149161
  res.status(400).json({ error: "Missing Host header" });
149042
149162
  return;
149043
149163
  }
149044
- const hostname4 = extractHostname(host);
149045
- if (!allowedHostnames.has(hostname4)) {
149164
+ const hostname5 = extractHostname(host);
149165
+ if (!allowedHostnames.has(hostname5)) {
149046
149166
  res.status(403).json({
149047
149167
  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
149168
  });
@@ -149951,11 +150071,16 @@ var ARM_PROCESS_CHECK_MS = 500;
149951
150071
  var RECHECK_DELAYS_MS = [500, 1e3, 2e3, 4e3, 8e3];
149952
150072
  var ENABLE_TIMEOUT_MS = 6e4;
149953
150073
  var DISABLE_TIMEOUT_MS = 1e3;
150074
+ var STOP_DISABLE_TIMEOUT_MS = 5e3;
149954
150075
  var SESSION_REMOVE_TIMEOUT_MS = 5e3;
149955
150076
  var AGENT_BINARIES_MISSING_REASON = "agent binaries not present in this build";
149956
150077
  var AGENT_GONE_REASON = "the agent that recorded the request is no longer in the app, as after an emulator snapshot load";
149957
150078
  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.";
150079
+ var STOPPED_BEFORE_FINISH = "capture stopped before the request finished";
150080
+ var DROPPED_NOTE = "the agent's connection dropped; it reconnects by itself while the app runs";
150081
+ var NOT_RECONNECTED_NOTE = "the agent's connection dropped, and it did not reconnect; network-capture-start connects it again";
150082
+ var STOPPED_NOTE = "capture stopped by network-capture-stop; network-capture-start turns it on again";
150083
+ 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
150084
  var LOGGED_DETAIL_EVENTS = /* @__PURE__ */ new Set(["interceptor_installed", "interceptor_failed"]);
149960
150085
  var RUN_TAG2 = (0, import_node_crypto13.randomBytes)(2).toString("hex");
149961
150086
  var ANDROID_NATIVE_REQUEST_ID = /^android-[0-9a-f]{4}-\d+$/;
@@ -149971,8 +150096,14 @@ function findAndroidNativeRecord(id) {
149971
150096
  }
149972
150097
  return void 0;
149973
150098
  }
150099
+ function hasAndroidNetworkCapture() {
150100
+ return allHandles().some((handle) => handle.isLive() || handle.isStopped());
150101
+ }
150102
+ function stoppedLaunchNote(packageName) {
150103
+ return `native network capture is stopped for ${packageName} (network-capture-stop); this process runs without it until network-capture-start`;
150104
+ }
149974
150105
  function liveAndroidNetworkCaptures(deviceId) {
149975
- return [...liveInspectors.get(deviceKeyOf(deviceId)) ?? []].filter((handle) => handle.isLive()).map((handle) => handle.packageName).sort();
150106
+ return [...liveInspectors.get(deviceKeyOf(deviceId)) ?? []].filter((handle) => handle.mayIntercept()).map((handle) => handle.packageName).sort();
149976
150107
  }
149977
150108
  function liveAndroidNetworkCaptureSerials() {
149978
150109
  return liveCaptureSerials(() => true);
@@ -149981,13 +150112,15 @@ function liveAndroidNetworkCaptureDevices(packageName) {
149981
150112
  return liveCaptureSerials((handle) => handle.packageName === packageName);
149982
150113
  }
149983
150114
  function liveCaptureSerials(matches2) {
149984
- const serials = allHandles().filter((handle) => matches2(handle) && handle.isLive()).map((handle) => handle.serial);
150115
+ const serials = allHandles().filter((handle) => matches2(handle) && handle.mayIntercept()).map((handle) => handle.serial);
149985
150116
  return [...new Set(serials)].sort();
149986
150117
  }
149987
150118
  async function attachAndroidNetworkInspectorToLaunch(deviceId, packageName) {
149988
150119
  try {
149989
150120
  for (const handle of liveInspectors.get(deviceKeyOf(deviceId)) ?? []) {
149990
- if (handle.packageName !== packageName || !handle.isLive()) continue;
150121
+ if (handle.packageName !== packageName) continue;
150122
+ if (handle.isStopped()) return await handle.stoppedLaunch();
150123
+ if (!handle.isLive()) continue;
149991
150124
  return await handle.attachLaunch();
149992
150125
  }
149993
150126
  } catch (err) {
@@ -150060,6 +150193,11 @@ function createInspector(serial, packageName, initialMetroPort) {
150060
150193
  let metroPort2 = initialMetroPort;
150061
150194
  let disposed = false;
150062
150195
  let live = false;
150196
+ let stopped = false;
150197
+ let stops = 0;
150198
+ let notAttached = false;
150199
+ let mark;
150200
+ let unavailableReason;
150063
150201
  let ready2 = false;
150064
150202
  let gates = null;
150065
150203
  let appUser = 0;
@@ -150072,6 +150210,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150072
150210
  let sessionPort = 0;
150073
150211
  const attachedProcesses = /* @__PURE__ */ new Set();
150074
150212
  let note;
150213
+ let startNote;
150075
150214
  let awaiting = null;
150076
150215
  const pendingSockets = /* @__PURE__ */ new Set();
150077
150216
  const connections2 = [];
@@ -150082,20 +150221,21 @@ function createInspector(serial, packageName, initialMetroPort) {
150082
150221
  const bodies = /* @__PURE__ */ new Map();
150083
150222
  const cleared = /* @__PURE__ */ new WeakSet();
150084
150223
  const lostOnly = /* @__PURE__ */ new WeakSet();
150224
+ const failedAtStopTimeout = /* @__PURE__ */ new WeakSet();
150085
150225
  const hops = /* @__PURE__ */ new WeakMap();
150086
150226
  const startArrivals = /* @__PURE__ */ new WeakMap();
150087
150227
  const armWaiters = /* @__PURE__ */ new Set();
150088
150228
  const attachLock = /* @__PURE__ */ new Map();
150089
150229
  const tunnelLock = /* @__PURE__ */ new Map();
150090
150230
  const rechecks = /* @__PURE__ */ new Map();
150231
+ const missedStop = /* @__PURE__ */ new Set();
150091
150232
  const user = () => appUser;
150092
150233
  const checkpoint = () => {
150093
- if (disposed) throw new InspectorStopped();
150234
+ if (disposed || stopped) throw new InspectorStopped();
150094
150235
  };
150095
150236
  const notAttachable = (reason2) => ({
150096
150237
  status: "not_attachable",
150097
- reason: reason2,
150098
- fallback: JS_LAYER_FALLBACK
150238
+ reason: reason2
150099
150239
  });
150100
150240
  function sessionLine(port) {
150101
150241
  return `${JSON.stringify({ v: PROTOCOL_VERSION, port, secret })}
@@ -150188,7 +150328,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150188
150328
  );
150189
150329
  if (other) {
150190
150330
  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}.`,
150331
+ `${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
150332
  {
150193
150333
  error_code: FAILURE_CODES.ANDROID_NETWORK_INSPECTOR_DEVICE_IN_USE,
150194
150334
  failure_stage: "android_network_inspector_device_identity",
@@ -150255,7 +150395,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150255
150395
  }
150256
150396
  async function assertReverse() {
150257
150397
  await withKeyedLock(tunnelLock, "tunnel", async () => {
150258
- checkpoint();
150398
+ if (disposed) throw new InspectorStopped();
150259
150399
  if (devicePort !== 0) {
150260
150400
  try {
150261
150401
  await adbReverse(serial, devicePort, hostPort, { timeoutMs: 1e4 });
@@ -150283,7 +150423,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150283
150423
  } catch (err) {
150284
150424
  if (!isPortTaken(err)) throw err;
150285
150425
  log(`device port ${port} is taken; trying another`);
150286
- checkpoint();
150426
+ if (disposed) throw new InspectorStopped();
150287
150427
  continue;
150288
150428
  }
150289
150429
  devicePort = port;
@@ -150345,8 +150485,9 @@ function createInspector(serial, packageName, initialMetroPort) {
150345
150485
  }
150346
150486
  if (copy === "loaded") {
150347
150487
  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`;
150488
+ 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
150489
  awaiting = { key: key2, note, since };
150490
+ notAttached = false;
150350
150491
  log(`pid ${proc.pid} already has the agent loaded`);
150351
150492
  return "loaded";
150352
150493
  }
@@ -150356,7 +150497,12 @@ function createInspector(serial, packageName, initialMetroPort) {
150356
150497
  }
150357
150498
  log(`pid ${proc.pid} lost the agent, as after an emulator snapshot load; attaching again`);
150358
150499
  }
150359
- checkpoint();
150500
+ try {
150501
+ checkpoint();
150502
+ } catch (err) {
150503
+ attachedProcesses.delete(key2);
150504
+ throw err;
150505
+ }
150360
150506
  const dir = agentDirFor(packageName, user());
150361
150507
  const agentOptions = `jar=${dir}/${JAR_NAME},pkg=${packageName}`;
150362
150508
  try {
@@ -150369,13 +150515,14 @@ function createInspector(serial, packageName, initialMetroPort) {
150369
150515
  } catch (err) {
150370
150516
  attachedProcesses.delete(key2);
150371
150517
  checkpoint();
150372
- note = `attach-agent failed for pid ${proc.pid} (${firstLine3(adbFailureDetail(err))}); the next native-network-logs call or launch tries again`;
150518
+ note = `attach-agent failed for pid ${proc.pid} (${firstLine3(adbFailureDetail(err))}); the next launch or network-capture-start tries again`;
150373
150519
  log(note);
150374
150520
  return "attach_failed";
150375
150521
  }
150376
150522
  checkpoint();
150377
150523
  note = `attached to pid ${proc.pid}; waiting for the agent to connect`;
150378
150524
  awaiting = { key: key2, note, since };
150525
+ notAttached = false;
150379
150526
  log(`attached the agent to pid ${proc.pid}`);
150380
150527
  return "attached";
150381
150528
  }
@@ -150570,6 +150717,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150570
150717
  phase = "ready";
150571
150718
  conn = openConnection(socket, cdp, send, handshake);
150572
150719
  sendMetroPort(conn);
150720
+ if (missedStop.delete(handshake.instance)) conn.afterMissedStop = true;
150573
150721
  enableNetwork(conn);
150574
150722
  return;
150575
150723
  }
@@ -150600,6 +150748,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150600
150748
  function openConnection(socket, cdp, send, handshake) {
150601
150749
  const key2 = `${handshake.pid}:${handshake.startTime}`;
150602
150750
  if (awaiting?.key === key2) awaiting = null;
150751
+ notAttached = false;
150603
150752
  for (const c of connections2) {
150604
150753
  if (c.closed || c.instance !== handshake.instance) continue;
150605
150754
  c.closed = true;
@@ -150620,6 +150769,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150620
150769
  armed: false,
150621
150770
  closed: false,
150622
150771
  droppedEvents: 0,
150772
+ enabling: false,
150623
150773
  byLayerId: /* @__PURE__ */ new Map()
150624
150774
  };
150625
150775
  const dropped = [...connections2].reverse().find((c) => c.closed && c.instance === handshake.instance && !c.resumedBy && !c.agentGone);
@@ -150653,15 +150803,27 @@ function createInspector(serial, packageName, initialMetroPort) {
150653
150803
  return max;
150654
150804
  }
150655
150805
  function enableNetwork(conn) {
150806
+ conn.enabling = true;
150807
+ conn.disabled = false;
150808
+ const stopsBefore = stops;
150809
+ const stale = () => stops !== stopsBefore;
150656
150810
  conn.cdp.request(
150657
150811
  "Network.enable",
150658
150812
  {},
150659
- { timeoutMs: ENABLE_TIMEOUT_MS, onResult: (result) => onEnabled(conn, result) }
150813
+ {
150814
+ timeoutMs: ENABLE_TIMEOUT_MS,
150815
+ onResult: (result) => {
150816
+ if (stale() && !stopped) return;
150817
+ conn.enabling = false;
150818
+ onEnabled(conn, result);
150819
+ }
150820
+ }
150660
150821
  ).catch((err) => {
150661
- if (conn.closed || disposed) {
150822
+ if (conn.closed || disposed || stale()) {
150662
150823
  log(`Network.enable on connection ${conn.index} failed: ${errorMessage3(err)}`);
150663
150824
  return;
150664
150825
  }
150826
+ conn.enabling = false;
150665
150827
  if (getFailureSignal(err)?.error_kind === "timeout") {
150666
150828
  connectionClosed(
150667
150829
  conn,
@@ -150676,6 +150838,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150676
150838
  }
150677
150839
  function onEnabled(conn, result) {
150678
150840
  if (conn.closed || disposed) return;
150841
+ conn.afterMissedStop = false;
150679
150842
  const r = asObject(result);
150680
150843
  const capture = parseCapture(r.capture);
150681
150844
  if (capture) conn.capture = capture;
@@ -150692,10 +150855,55 @@ function createInspector(serial, packageName, initialMetroPort) {
150692
150855
  }
150693
150856
  }
150694
150857
  }
150858
+ if (stopped) {
150859
+ void disableOn(conn, STOP_DISABLE_TIMEOUT_MS);
150860
+ return;
150861
+ }
150695
150862
  conn.armed = true;
150696
150863
  note = void 0;
150697
150864
  for (const wake of armWaiters) wake();
150698
150865
  }
150866
+ function disableOn(conn, timeoutMs) {
150867
+ return conn.cdp.request(
150868
+ "Network.disable",
150869
+ {},
150870
+ {
150871
+ timeoutMs,
150872
+ onResult: () => {
150873
+ if (stopped) conn.disabled = true;
150874
+ failStopped(conn);
150875
+ }
150876
+ }
150877
+ ).then(
150878
+ () => {
150879
+ conn.stopUnconfirmed = false;
150880
+ return true;
150881
+ },
150882
+ (err) => {
150883
+ if (conn.closed || disposed) return true;
150884
+ log(`Network.disable on connection ${conn.index} failed: ${errorMessage3(err)}`);
150885
+ if (stopped) conn.stopUnconfirmed = true;
150886
+ if (stopped && getFailureSignal(err)?.error_kind === "timeout") failStopped(conn, true);
150887
+ return false;
150888
+ }
150889
+ );
150890
+ }
150891
+ function failStopped(conn, settleLater = false) {
150892
+ const open5 = [];
150893
+ for (let c = conn; c; c = c.resumes) {
150894
+ for (const record2 of c.byLayerId.values()) {
150895
+ if (isOpen(record2) || lostOnly.has(record2)) open5.push(record2);
150896
+ }
150897
+ }
150898
+ for (const record2 of open5) {
150899
+ lostOnly.delete(record2);
150900
+ if (settleLater) failedAtStopTimeout.add(record2);
150901
+ record2.state = "failed";
150902
+ record2.errorText = STOPPED_BEFORE_FINISH;
150903
+ cleared.delete(record2);
150904
+ }
150905
+ for (const record2 of open5) resize(record2);
150906
+ }
150699
150907
  function onStatus(conn, payload) {
150700
150908
  const event2 = asString2(payload.event);
150701
150909
  if (event2 === "capture") {
@@ -150717,7 +150925,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150717
150925
  if (disposed) return;
150718
150926
  log(`agent connection ${conn.index} closed${why ? `: ${why}` : ""}`);
150719
150927
  if (!connections2.some((c) => !c.closed)) {
150720
- note = "the agent's connection dropped; it reconnects by itself while the app runs";
150928
+ note = DROPPED_NOTE;
150721
150929
  }
150722
150930
  const running = rechecks.get(conn.processKey);
150723
150931
  if (running) {
@@ -150752,7 +150960,13 @@ function createInspector(serial, packageName, initialMetroPort) {
150752
150960
  const running = runningKeys(read);
150753
150961
  if (!running.has(key2)) {
150754
150962
  failOrphans(running);
150755
- if (!connections2.some((c) => !c.closed)) note = afterExitNote(read);
150963
+ if (!connections2.some((c) => !c.closed)) {
150964
+ const next = processOfUser(read, read.user ?? appUser);
150965
+ if (!next || !attachedProcesses.has(processKey(next))) {
150966
+ note = afterExitNote(read);
150967
+ notAttached = true;
150968
+ }
150969
+ }
150756
150970
  return;
150757
150971
  }
150758
150972
  await assertReverse().catch(() => {
@@ -150765,18 +150979,21 @@ function createInspector(serial, packageName, initialMetroPort) {
150765
150979
  if (isOpen(record2)) markLost(record2, NOT_RECONNECTED);
150766
150980
  }
150767
150981
  }
150982
+ if (note === DROPPED_NOTE && !connections2.some((c) => !c.closed)) {
150983
+ note = NOT_RECONNECTED_NOTE;
150984
+ }
150768
150985
  } finally {
150769
150986
  if (rechecks.get(key2) === recheck) rechecks.delete(key2);
150770
150987
  if (recheck.restart && !disposed && !reconnected()) void recheckAfterDrop(key2);
150771
150988
  }
150772
150989
  }
150773
150990
  function afterExitNote(read) {
150774
- const trigger = "launch-app, restart-app or the next native-network-logs call attaches the agent";
150775
150991
  const foreground = read.user ?? appUser;
150776
- if (!processOfUser(read, foreground)) {
150777
- return `${packageName} exited; ${trigger} to its new process`;
150992
+ const next = processOfUser(read, foreground);
150993
+ if (!next) {
150994
+ 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
150995
  }
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}`;
150996
+ 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
150997
  }
150781
150998
  function fold2(conn, method, params) {
150782
150999
  if (typeof params !== "object" || params === null) return;
@@ -150806,7 +151023,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150806
151023
  case "Network.responseReceived": {
150807
151024
  revive(record2);
150808
151025
  const r = asObject(p.response);
150809
- record2.state = "headers";
151026
+ if (!failedAtStopTimeout.has(record2)) record2.state = "headers";
150810
151027
  record2.response = {
150811
151028
  url: capString(asString2(r.url)) || hops.get(record2)?.url || record2.request.url,
150812
151029
  status: typeof r.status === "number" ? r.status : 0,
@@ -150820,6 +151037,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150820
151037
  }
150821
151038
  case "Network.loadingFinished":
150822
151039
  revive(record2);
151040
+ if (failedAtStopTimeout.delete(record2)) delete record2.errorText;
150823
151041
  cleared.delete(record2);
150824
151042
  record2.state = "complete";
150825
151043
  if (typeof p.encodedDataLength === "number") record2.encodedDataLength = p.encodedDataLength;
@@ -150827,6 +151045,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150827
151045
  break;
150828
151046
  case "Network.loadingFailed":
150829
151047
  revive(record2);
151048
+ failedAtStopTimeout.delete(record2);
150830
151049
  cleared.delete(record2);
150831
151050
  record2.state = "failed";
150832
151051
  record2.errorText = capString(asString2(p.errorText)) || "Unknown error";
@@ -150887,6 +151106,7 @@ function createInspector(serial, packageName, initialMetroPort) {
150887
151106
  );
150888
151107
  break;
150889
151108
  }
151109
+ if (stopped || conn.afterMissedStop) return;
150890
151110
  const req = asObject(p.request);
150891
151111
  const startedAt = typeof p.wallTime === "number" ? p.wallTime * 1e3 : typeof p.timestamp === "number" ? p.timestamp * 1e3 : Date.now();
150892
151112
  const record2 = {
@@ -150916,7 +151136,9 @@ function createInspector(serial, packageName, initialMetroPort) {
150916
151136
  if (own2) return own2;
150917
151137
  for (let dropped = conn.resumes; dropped; dropped = dropped.resumes) {
150918
151138
  const record2 = dropped.byLayerId.get(layerId);
150919
- if (record2 && (isOpen(record2) || lostOnly.has(record2))) return record2;
151139
+ if (record2 && (isOpen(record2) || lostOnly.has(record2) || failedAtStopTimeout.has(record2))) {
151140
+ return record2;
151141
+ }
150920
151142
  }
150921
151143
  return void 0;
150922
151144
  }
@@ -151014,6 +151236,7 @@ function createInspector(serial, packageName, initialMetroPort) {
151014
151236
  return fetched;
151015
151237
  }
151016
151238
  function failOrphans(running) {
151239
+ for (const c of connections2) if (!running.has(c.processKey)) c.ended = true;
151017
151240
  for (const record2 of records) {
151018
151241
  if (!isOpen(record2) && !lostOnly.has(record2)) continue;
151019
151242
  const conn = byId.get(record2.id)?.conn;
@@ -151034,42 +151257,148 @@ function createInspector(serial, packageName, initialMetroPort) {
151034
151257
  function armedFor(key2) {
151035
151258
  return connections2.some((c) => c.armed && !c.closed && c.processKey === key2);
151036
151259
  }
151037
- async function ensureAttached(port) {
151260
+ async function attachCurrent() {
151261
+ const blocked = await prepare();
151262
+ if (blocked) return { blocked };
151263
+ const read = await readAppProcesses(serial, packageName);
151264
+ checkpoint();
151265
+ const switched = await followUser(read.user);
151266
+ if (switched) return { blocked: switched };
151267
+ const current = processOfUser(read, user());
151268
+ failOrphans(runningKeys(read));
151269
+ if (!current) {
151270
+ if (!armedConnection()) {
151271
+ 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`;
151272
+ }
151273
+ return { current: null };
151274
+ }
151275
+ if (await attach(current) !== "attached") await refreshAgentReason(current);
151276
+ if (!ready2) {
151277
+ const again = await prepare();
151278
+ if (again) return { blocked: again };
151279
+ }
151280
+ return { current };
151281
+ }
151282
+ async function startCapture2(port) {
151038
151283
  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;
151284
+ let found = { stopped, mark, live };
151285
+ const unavailableStart = (reason2) => {
151286
+ if (found.stopped) stopped = true;
151287
+ if (!found.live) live = false;
151288
+ mark = found.mark;
151289
+ unavailableReason = reason2;
151290
+ note = reason2;
151291
+ startNote = reason2;
151292
+ return { result: { armed: false, unavailable: true, reason: reason2 } };
151293
+ };
151294
+ const attached = await withKeyedLock(
151295
+ attachLock,
151296
+ "attach",
151297
+ async () => {
151298
+ if (disposed) return { result: { armed: false, reason: "capture was disposed" } };
151299
+ found = { stopped, mark, live };
151300
+ mark = { lastRecord: nextRecordNumber2 - 1, metroPort: port };
151301
+ stopped = false;
151302
+ notAttached = false;
151303
+ if (note === startNote || note === NOT_RECONNECTED_NOTE) note = awaiting?.note;
151304
+ try {
151305
+ const outcome = await attachCurrent();
151306
+ if ("blocked" in outcome) return unavailableStart(outcome.blocked.reason);
151307
+ live = true;
151308
+ unavailableReason = void 0;
151309
+ for (const conn2 of connections2) {
151310
+ if (!conn2.closed && !conn2.armed && !conn2.enabling) enableNetwork(conn2);
151311
+ }
151312
+ return outcome;
151313
+ } catch (err) {
151314
+ if (err instanceof InspectorStopped) {
151315
+ return {
151316
+ result: { armed: false, reason: disposed ? "capture was disposed" : STOPPED_NOTE }
151317
+ };
151060
151318
  }
151319
+ if (isUnavailableFailure(err)) return unavailableStart(errorMessage3(err));
151320
+ live = true;
151321
+ unavailableReason = void 0;
151322
+ const reason2 = isOwnFailure(err) ? errorMessage3(err) : `adb did not answer (${firstLine3(adbFailureDetail(err))}); the next launch or network-capture-start tries again`;
151323
+ log(reason2);
151324
+ note = reason2;
151325
+ startNote = reason2;
151326
+ return { result: { armed: false, reason: reason2 } };
151061
151327
  }
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
151328
  }
151329
+ );
151330
+ if ("result" in attached) return attached.result;
151331
+ if (!attached.current) {
151332
+ return {
151333
+ armed: false,
151334
+ reason: shownNote() ?? `${packageName} is not running; launch-app or restart-app attaches the agent to its next process`
151335
+ };
151336
+ }
151337
+ const key2 = processKey(attached.current);
151338
+ await waitForArmed(key2, ARM_WAIT_MS);
151339
+ if (disposed) return { armed: false, reason: "capture was disposed" };
151340
+ if (stopped) return { armed: false, reason: STOPPED_NOTE };
151341
+ const conn = connections2.find((c) => c.armed && !c.closed && c.processKey === key2);
151342
+ if (!conn) {
151343
+ const reason2 = await refreshAgentReason(attached.current);
151344
+ note ??= `waiting for the agent in pid ${attached.current.pid}${reason2 ? `: ${reason2}` : ""}`;
151345
+ return { armed: false, reason: shownNote() ?? note };
151346
+ }
151347
+ if (conn.capture?.state === "unavailable") {
151348
+ const { result } = unavailableStart(
151349
+ `capture unavailable${conn.capture.detail ? `: ${conn.capture.detail}` : ""}`
151350
+ );
151351
+ if (stopped) {
151352
+ void stopCapture2();
151353
+ unavailableReason = result.reason;
151354
+ }
151355
+ return result;
151356
+ }
151357
+ return { armed: true };
151358
+ }
151359
+ async function stopCapture2() {
151360
+ if (disposed) return { confirmed: true };
151361
+ stopped = true;
151362
+ live = false;
151363
+ notAttached = false;
151364
+ unavailableReason = void 0;
151365
+ stops++;
151366
+ for (const conn of connections2) {
151367
+ conn.armed = false;
151368
+ conn.enabling = false;
151369
+ conn.stopUnconfirmed = false;
151370
+ }
151371
+ for (const wake of armWaiters) wake();
151372
+ return withKeyedLock(attachLock, "attach", async () => {
151373
+ if (disposed) return { confirmed: true };
151374
+ const answers = await Promise.all(
151375
+ connections2.filter((c) => !c.closed).map((c) => disableOn(c, STOP_DISABLE_TIMEOUT_MS))
151376
+ );
151377
+ const reasons = [];
151378
+ if (answers.some((answered) => !answered)) {
151379
+ reasons.push(
151380
+ `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`
151381
+ );
151382
+ }
151383
+ if (await awayAtStop()) reasons.push(AWAY_AT_STOP);
151384
+ return reasons.length === 0 ? { confirmed: true } : { confirmed: false, reason: reasons.join("; ") };
151071
151385
  });
151072
151386
  }
151387
+ function isAway(c) {
151388
+ return c.closed && !c.resumedBy && !c.agentGone && !c.ended && !c.disabled;
151389
+ }
151390
+ async function awayAtStop() {
151391
+ const away = () => connections2.filter(isAway);
151392
+ if (away().length === 0) return false;
151393
+ try {
151394
+ const read = await readAppProcesses(serial, packageName, STOP_DISABLE_TIMEOUT_MS);
151395
+ failOrphans(runningKeys(read));
151396
+ if (away().length > 0) await assertReverse();
151397
+ } catch {
151398
+ }
151399
+ for (const c of away()) missedStop.add(c.instance);
151400
+ return away().length > 0;
151401
+ }
151073
151402
  async function attachLaunch() {
151074
151403
  if (!live || disposed) return void 0;
151075
151404
  let outcome;
@@ -151093,36 +151422,54 @@ function createInspector(serial, packageName, initialMetroPort) {
151093
151422
  }
151094
151423
  });
151095
151424
  } catch (err) {
151096
- if (err instanceof InspectorStopped || disposed) return void 0;
151425
+ if (disposed) return void 0;
151426
+ if (err instanceof InspectorStopped) return stoppedLaunchNote(packageName);
151097
151427
  return `native network capture could not follow this launch of ${packageName}: ${firstLine3(isOwnFailure(err) ? errorMessage3(err) : adbFailureDetail(err))}`;
151098
151428
  }
151099
151429
  if (outcome.kind === "attached") await waitForArmed(processKey(outcome.proc), ARM_WAIT_MS);
151100
151430
  const reason2 = "proc" in outcome && !armedFor(processKey(outcome.proc)) ? await refreshAgentReason(outcome.proc) : void 0;
151101
151431
  if (disposed) return void 0;
151432
+ if (stopped) return stoppedLaunchNote(packageName);
151102
151433
  return launchNote(outcome, reason2);
151103
151434
  }
151435
+ function unconfirmedStop() {
151436
+ if (!stopped) return void 0;
151437
+ return connections2.find((c) => !c.closed && c.stopUnconfirmed) ?? connections2.find((c) => missedStop.has(c.instance) && isAway(c));
151438
+ }
151439
+ async function stoppedLaunch() {
151440
+ const conn = unconfirmedStop();
151441
+ if (!conn) return stoppedLaunchNote(packageName);
151442
+ const read = await readAppProcesses(serial, packageName).catch(() => null);
151443
+ if (read) failOrphans(runningKeys(read));
151444
+ const current = read ? processOfUser(read, user()) : null;
151445
+ if (unconfirmedStop() !== conn) return stoppedLaunchNote(packageName);
151446
+ if (read && (!current || processKey(current) !== conn.processKey)) {
151447
+ return stoppedLaunchNote(packageName);
151448
+ }
151449
+ 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`;
151450
+ }
151104
151451
  function launchNote(outcome, reason2) {
151105
151452
  switch (outcome.kind) {
151106
151453
  case "blocked":
151107
151454
  return `native network capture cannot follow ${packageName}: ${outcome.reason}`;
151108
151455
  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`;
151456
+ 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
151457
  case "copy_failed":
151111
151458
  case "attach_failed":
151112
151459
  return `native network capture could not follow this launch: ${note ?? "the attach failed"}`;
151113
151460
  default: {
151114
151461
  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}` : ""}`;
151462
+ 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
151463
  }
151117
151464
  }
151118
151465
  }
151119
151466
  async function waitForArmed(key2, timeoutMs) {
151120
151467
  const deadline = Date.now() + timeoutMs;
151121
- while (!disposed && !armedFor(key2)) {
151468
+ while (!disposed && !stopped && !armedFor(key2)) {
151122
151469
  const left = deadline - Date.now();
151123
151470
  if (left <= 0) return;
151124
151471
  const woken = await nextArmEvent(Math.min(ARM_PROCESS_CHECK_MS, left));
151125
- if (woken || disposed || armedFor(key2)) continue;
151472
+ if (woken || disposed || stopped || armedFor(key2)) continue;
151126
151473
  const readTimeoutMs = deadline - Date.now();
151127
151474
  if (readTimeoutMs <= 0) return;
151128
151475
  try {
@@ -151147,15 +151494,22 @@ function createInspector(serial, packageName, initialMetroPort) {
151147
151494
  }
151148
151495
  const api = {
151149
151496
  packageName,
151150
- ensureAttached,
151497
+ startCapture: startCapture2,
151498
+ stopCapture: stopCapture2,
151499
+ isStarted: () => live && !disposed,
151500
+ isStopped: () => stopped && !disposed,
151501
+ unavailableReason: () => unavailableReason,
151502
+ captureMark: () => mark,
151151
151503
  state() {
151152
151504
  const conn = armedConnection();
151153
151505
  return {
151154
151506
  armed: Boolean(conn),
151507
+ ...stopped ? { stopped: true } : {},
151508
+ ...!conn && notAttached && !stopped ? { notAttached: true } : {},
151155
151509
  ...conn ? { process: { pid: conn.pid, startTime: conn.startTime } } : {},
151156
151510
  ...conn?.capture ? { capture: { ...conn.capture } } : {},
151157
151511
  ...conn && conn.droppedEvents > 0 ? { droppedEvents: conn.droppedEvents } : {},
151158
- ...!conn && note ? { note: shownNote() } : {}
151512
+ ...!conn && note && !stopped ? { note: shownNote() } : {}
151159
151513
  };
151160
151514
  },
151161
151515
  records: (port) => records.filter(
@@ -151174,7 +151528,10 @@ function createInspector(serial, packageName, initialMetroPort) {
151174
151528
  packageName,
151175
151529
  hardwareKey: null,
151176
151530
  isLive: () => live && !disposed,
151177
- attachLaunch
151531
+ isStopped: () => stopped && !disposed,
151532
+ mayIntercept: () => !disposed && (live || unconfirmedStop() !== void 0),
151533
+ attachLaunch,
151534
+ stoppedLaunch
151178
151535
  };
151179
151536
  return {
151180
151537
  handle,
@@ -151300,6 +151657,10 @@ function agentFiles() {
151300
151657
  function isAgentAbi(abi) {
151301
151658
  return AGENT_ABIS.includes(abi);
151302
151659
  }
151660
+ function isUnavailableFailure(err) {
151661
+ const code = getFailureSignal(err)?.error_code;
151662
+ 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;
151663
+ }
151303
151664
  function isOwnFailure(err) {
151304
151665
  const code = getFailureSignal(err)?.error_code;
151305
151666
  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 +151821,119 @@ Fails if the simulator server is not running for the given UDID.`,
151460
151821
  init_zod();
151461
151822
  init_src2();
151462
151823
  init_device_info();
151463
- init_external_devices();
151824
+
151825
+ // ../tool-server/src/tools/network/network-capture.ts
151826
+ init_zod();
151827
+ init_src2();
151828
+
151829
+ // ../tool-server/src/utils/bundle-id.ts
151830
+ var BUNDLE_ID_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
151831
+ var BUNDLE_ID_MESSAGE = "bundleId may only contain letters, digits, '.', '_' and '-', and may not start with '-' or '.'";
151832
+
151833
+ // ../tool-server/src/tools/network/network-capture.ts
151834
+ init_device_info();
151835
+ var captureSchema = external_exports.object({
151836
+ udid: external_exports.string().describe("Device ID from list-devices: an iOS simulator UDID or Android serial"),
151837
+ bundleId: external_exports.string().regex(BUNDLE_ID_PATTERN, BUNDLE_ID_MESSAGE).describe("App bundle ID on iOS or package name on Android"),
151838
+ port: metroPortField.describe(
151839
+ "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."
151840
+ ),
151841
+ logicalDeviceId: external_exports.string().min(1).optional().describe(
151842
+ "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."
151843
+ )
151844
+ });
151845
+ var CAPTURE_CAPABILITY = {
151846
+ apple: { simulator: true },
151847
+ appleRemote: { simulator: true },
151848
+ android: { emulator: true, device: true }
151849
+ };
151850
+ var captureLocks = /* @__PURE__ */ new Map();
151851
+ var captureSweeps = /* @__PURE__ */ new Set();
151852
+ function lockDevice(udid) {
151853
+ return deviceKeyOf(udid).toLowerCase();
151854
+ }
151855
+ var nativeUnavailable = /* @__PURE__ */ new Map();
151856
+ function nativeUnavailableKey(udid, bundleId) {
151857
+ return `${lockDevice(udid)}:${bundleId}`;
151858
+ }
151859
+ function setNativeUnavailable(udid, bundleId, reason2) {
151860
+ if (reason2 === void 0) nativeUnavailable.delete(nativeUnavailableKey(udid, bundleId));
151861
+ else nativeUnavailable.set(nativeUnavailableKey(udid, bundleId), reason2);
151862
+ }
151863
+ function nativeUnavailableReason(udid, bundleId) {
151864
+ return nativeUnavailable.get(nativeUnavailableKey(udid, bundleId));
151865
+ }
151866
+ function forgetNativeUnavailableOf(devices2) {
151867
+ const covered = devices2 && new Set(devices2.map(lockDevice));
151868
+ for (const key2 of nativeUnavailable.keys()) {
151869
+ if (!covered || covered.has(key2.slice(0, key2.lastIndexOf(":")))) nativeUnavailable.delete(key2);
151870
+ }
151871
+ }
151872
+ function withCaptureLock(udid, bundleId, fn) {
151873
+ const device = lockDevice(udid);
151874
+ const sweeps = [...captureSweeps].filter((sweep) => !sweep.devices || sweep.devices.has(device)).map((sweep) => sweep.done);
151875
+ return withKeyedLock(captureLocks, `${device}:${bundleId}`, async () => {
151876
+ await Promise.all(sweeps);
151877
+ return fn();
151878
+ });
151879
+ }
151880
+ async function withCaptureSweep(devices2, wait, fn) {
151881
+ const covered = devices2 && new Set(devices2.map(lockDevice));
151882
+ const underWay = [...captureLocks].filter(([key2]) => !covered || covered.has(key2.slice(0, key2.lastIndexOf(":")))).map(([, held]) => held);
151883
+ let end;
151884
+ const sweep = { devices: covered, done: new Promise((resolve21) => end = resolve21) };
151885
+ captureSweeps.add(sweep);
151886
+ try {
151887
+ await settleWithin(Promise.all(underWay), wait.maxMs, wait.signal);
151888
+ return await fn();
151889
+ } finally {
151890
+ captureSweeps.delete(sweep);
151891
+ end();
151892
+ }
151893
+ }
151894
+ async function runLayers(layers) {
151895
+ const settled = await Promise.allSettled(layers);
151896
+ const failed3 = settled.find((s) => s.status === "rejected");
151897
+ if (failed3) throw failed3.reason;
151898
+ return settled.map((s) => s.value);
151899
+ }
151900
+ function isLiveService(registry2, urn) {
151901
+ const state3 = registry2.getSnapshot().services.get(urn)?.state;
151902
+ return state3 !== void 0 && isLiveServiceState(state3);
151903
+ }
151904
+ async function resolveJsRuntime(registry2, udid, logicalDeviceId, port) {
151905
+ if (logicalDeviceId !== void 0 && classifyDevice(udid) === "ios-remote") {
151906
+ await proxyStart(udid, port);
151907
+ }
151908
+ return resolveDebuggerService(
151909
+ registry2,
151910
+ { port, device_id: logicalDeviceId ?? udid },
151911
+ { physicalDeviceId: udid }
151912
+ );
151913
+ }
151914
+ function jsNotReached(reason2, port, err) {
151915
+ const detail = errorMessage4(err);
151916
+ switch (reason2) {
151917
+ case "metro_not_running":
151918
+ return `Metro is not running on port ${port}; start it, or pass the port of the app's Metro`;
151919
+ case "device_mismatch": {
151920
+ const listed = /connected to Metro on port \d+: (.+?)\. Re-target/.exec(detail)?.[1];
151921
+ 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`;
151922
+ }
151923
+ case "no_app_connected":
151924
+ return `no app is connected to Metro on port ${port} yet`;
151925
+ case void 0:
151926
+ return `the JS debugger could not connect: ${detail}`;
151927
+ default:
151928
+ return `the app's JS runtime did not answer (${reason2}: ${detail})`;
151929
+ }
151930
+ }
151931
+ function otherPortHint(bundleId, port) {
151932
+ return `this device has network capture for ${bundleId} on Metro port ${port}: pass port ${port}`;
151933
+ }
151934
+ function errorMessage4(err) {
151935
+ return err instanceof Error ? err.message : String(err);
151936
+ }
151464
151937
 
151465
151938
  // ../tool-server/src/tools/native-devtools/macos-view-hierarchy.ts
151466
151939
  init_zod();
@@ -151634,17 +152107,21 @@ var zodSchema4 = external_exports.object({
151634
152107
  clear: external_exports.boolean().optional().default(false).describe(
151635
152108
  "Clear the log after reading. On iOS and Android, the IDs of cleared requests still work in view-network-request-details"
151636
152109
  ),
151637
- stop: external_exports.boolean().optional().describe(
151638
- "Android only: turn native capture off for this app instead of listing. Other apps keep theirs."
152110
+ // Declared so this non-strict object refuses the old stop instead of stripping it: the read
152111
+ // would succeed while capture records on.
152112
+ stop: external_exports.never({
152113
+ 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"
152114
+ }).optional().describe(
152115
+ "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
152116
  )
151640
152117
  });
151641
152118
  function createNativeNetworkLogsTool(registry2) {
151642
152119
  return {
151643
152120
  id: "native-network-logs",
151644
152121
  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}`
152122
+ startedMsg: ({ params }) => `Reading native network activity for ${params.bundleId}`,
152123
+ completedMsg: ({ params }) => `Read native network activity for ${params.bundleId}`,
152124
+ failedMsg: ({ params, failureSignal: failureSignal2 }) => `Failed to read native network activity for ${params.bundleId}: ${failureSignal2.error_code}`
151648
152125
  },
151649
152126
  capability: {
151650
152127
  apple: { simulator: true },
@@ -151655,34 +152132,29 @@ function createNativeNetworkLogsTool(registry2) {
151655
152132
  description: `Retrieve network requests captured at the native level: NSURLProtocol on iOS, OkHttp on Android.
151656
152133
  Use when inspecting native-level HTTP traffic that view-network-logs cannot see: requests that never pass through JS XMLHttpRequest or fetch.
151657
152134
  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.
152135
+ 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, except on a device whose devtools agent argent attached to.
152136
+ On iOS and Android 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; 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.
152137
+ 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.
152138
+ <flag:macos-apps>On a Mac app it returns { status, count, events } instead: NSURLSession events, react-native-macos fetch included, each with URL, method, status, headers and timing, and no ids. There the first call starts capture, with no network-capture-start. Capture stays on across restart-app, with a new log per process, and requests sent while the app starts can be missing.
151662
152139
  </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.
152140
+ 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).
152141
+ 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
152142
  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.`,
152143
+ 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
152144
  zodSchema: zodSchema4,
151670
152145
  services: (params) => {
151671
152146
  const device = resolveDevice(params.udid);
151672
- if (params.stop) return {};
151673
152147
  if (device.platform === "macos") return macosAppServices(device);
152148
+ const live = (urn) => isLiveService(registry2, urn);
151674
152149
  if (device.platform === "android") {
151675
152150
  const port = metroPort({ device_id: params.udid, port: params.port });
151676
- return { androidNetwork: androidNetworkInspectorRef(device, params.bundleId, port) };
152151
+ const ref2 = androidNetworkInspectorRef(device, params.bundleId, port);
152152
+ return live(ref2.urn) ? { androidNetwork: ref2 } : {};
151677
152153
  }
151678
- return { nativeDevtools: nativeDevtoolsRef(device) };
152154
+ const ref = nativeDevtoolsRef(device);
152155
+ return live(ref.urn) ? { nativeDevtools: ref } : {};
151679
152156
  },
151680
152157
  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
152158
  const device = resolveDevice(params.udid);
151687
152159
  if (device.platform === "macos") {
151688
152160
  const app = requireMacosAppOfBundle(
@@ -151696,27 +152168,91 @@ When status is not_attachable, use view-network-logs and do not retry.`,
151696
152168
  if (params.clear) app.clearNetworkLog();
151697
152169
  return { status: "ok", count: events.length, events };
151698
152170
  }
151699
- await ensureDeps(device.platform === "ios-remote" ? ["sim-remote"] : ["xcrun"]);
152171
+ const port = metroPort({ device_id: params.udid, port: params.port });
152172
+ if (device.platform === "android") {
152173
+ const api2 = services.androidNetwork;
152174
+ if (!api2 || !api2.isStarted() && !api2.isStopped()) {
152175
+ const reason2 = api2?.unavailableReason() ?? nativeUnavailableReason(device.id, params.bundleId);
152176
+ return reason2 ? {
152177
+ ...unavailableListing("android-native", reason2),
152178
+ capture: "unavailable",
152179
+ captureDetail: reason2
152180
+ } : notStarted("android-native", params.bundleId);
152181
+ }
152182
+ return listAndroidNative(api2, params, port);
152183
+ }
152184
+ if (!isInjectableBundleId(params.bundleId)) throw nonInjectableError(params.bundleId);
151700
152185
  const api = services.nativeDevtools;
152186
+ const unavailable3 = nativeUnavailableReason(device.id, params.bundleId);
152187
+ if (api?.isNetworkCaptureStopped(params.bundleId)) {
152188
+ const store2 = api.networkRecords(params.bundleId);
152189
+ const listing2 = listNative("ios-native", store2?.records(port) ?? [], params.limit, {
152190
+ armed: false,
152191
+ state: "stopped",
152192
+ detail: stoppedDetail(
152193
+ liveIosNetworkCaptures(params.udid).includes(params.bundleId),
152194
+ unavailable3
152195
+ )
152196
+ });
152197
+ if (params.clear) store2?.clear();
152198
+ return { ...listing2, stopped: true };
152199
+ }
152200
+ if (!api?.isNetworkCaptureStarted(params.bundleId)) {
152201
+ return unavailable3 ? unavailableListing("ios-native", unavailable3) : notStarted("ios-native", params.bundleId);
152202
+ }
152203
+ await ensureDeps(device.platform === "ios-remote" ? ["sim-remote"] : ["xcrun"]);
151701
152204
  const blocked = await precheckNativeDevtools(api, params.udid, params.bundleId);
151702
- const arming = api.activateNetworkInspection(params.bundleId);
151703
152205
  if (blocked) return blocked;
151704
152206
  if (!api.isConnected(params.bundleId)) throw notConnected(api, params.bundleId);
151705
- await arming;
152207
+ await api.refreshLentNetworkCapture(params.bundleId);
151706
152208
  const store = api.networkRecords(params.bundleId);
151707
152209
  if (!store) throw notConnected(api, params.bundleId);
151708
- const all = store.records(metroPort({ device_id: params.udid, port: params.port }));
152210
+ const all = store.records(port);
151709
152211
  const state3 = store.state();
151710
152212
  const detail = [];
151711
152213
  if (state3.pid !== void 0) detail.push(`pid ${state3.pid}`);
151712
152214
  if (state3.note) detail.push(state3.note);
151713
152215
  if (api.takeCaptureGap(params.bundleId)) detail.push(captureGapNote(api.armsEnv));
151714
- const listing = listNative("ios-native", all, params.limit, state3.armed, detail);
152216
+ const listing = listNative("ios-native", all, params.limit, {
152217
+ armed: state3.armed,
152218
+ state: state3.armed ? "armed" : "not armed",
152219
+ detail
152220
+ });
151715
152221
  if (params.clear) store.clear();
151716
152222
  return listing;
151717
152223
  }
151718
152224
  };
151719
152225
  }
152226
+ var STOPPED_DETAIL = "capture stopped by network-capture-stop; network-capture-start turns it on again";
152227
+ function stoppedDetail(mayIntercept, unavailableReason) {
152228
+ const stopped = unavailableReason ? `capture stopped by network-capture-stop; a later network-capture-start found the layer unavailable: ${unavailableReason}` : STOPPED_DETAIL;
152229
+ return mayIntercept ? [
152230
+ stopped,
152231
+ "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"
152232
+ ] : [stopped];
152233
+ }
152234
+ function notStarted(layer, bundleId) {
152235
+ return {
152236
+ status: "ok",
152237
+ header: `${layer}: not started, 0 requests (network capture is off for ${bundleId}; call network-capture-start for it, then repeat the action)`,
152238
+ armed: false,
152239
+ started: false,
152240
+ count: 0,
152241
+ total: 0,
152242
+ requests: []
152243
+ };
152244
+ }
152245
+ function unavailableListing(layer, reason2) {
152246
+ return {
152247
+ status: "ok",
152248
+ header: `${layer}: unavailable, 0 requests (${reason2})`,
152249
+ armed: false,
152250
+ started: false,
152251
+ count: 0,
152252
+ total: 0,
152253
+ requests: []
152254
+ };
152255
+ }
151720
152256
  function notConnected(api, bundleId) {
151721
152257
  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
152258
  return new FailureError(`Native devtools not connected for bundleId: ${bundleId}. ${remedy}`, {
@@ -151727,77 +152263,42 @@ function notConnected(api, bundleId) {
151727
152263
  });
151728
152264
  }
151729
152265
  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";
152266
+ 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";
151731
152267
  }
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
- };
151767
- }
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;
152268
+ function listAndroidNative(api, params, port) {
151772
152269
  const all = api.records(port);
151773
152270
  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
- );
152271
+ const unavailable3 = state3.stopped ? api.unavailableReason() : void 0;
152272
+ const listing = listNative("android-native", all, params.limit, {
152273
+ armed: state3.armed,
152274
+ state: state3.stopped ? "stopped" : state3.armed ? "armed" : state3.notAttached ? "not attached" : "not armed",
152275
+ detail: state3.stopped ? stoppedDetail(
152276
+ liveAndroidNetworkCaptures(params.udid).includes(params.bundleId),
152277
+ unavailable3
152278
+ ) : headerDetail(state3)
152279
+ });
151781
152280
  if (params.clear) api.clear();
151782
152281
  return {
151783
152282
  ...listing,
152283
+ ...state3.stopped ? { stopped: true } : {},
152284
+ ...unavailable3 ? { started: false, capture: "unavailable", captureDetail: unavailable3 } : {},
151784
152285
  ...state3.capture ? { capture: state3.capture.state } : {},
151785
152286
  ...state3.capture?.detail ? { captureDetail: state3.capture.detail } : {}
151786
152287
  };
151787
152288
  }
151788
- function listNative(layer, all, limit, armed, detail) {
152289
+ function listNative(layer, all, limit, shape) {
151789
152290
  const shown = limit === 0 ? [] : all.slice(-limit);
151790
152291
  const noun = all.length === 1 ? "request" : "requests";
151791
152292
  return {
151792
152293
  status: "ok",
151793
- header: `${layer}: ${armed ? "armed" : "not armed"}, ${all.length} ${noun}` + (detail.length > 0 ? ` (${detail.join("; ")})` : ""),
151794
- armed,
152294
+ header: `${layer}: ${shape.state}, ${all.length} ${noun}` + (shape.detail.length > 0 ? ` (${shape.detail.join("; ")})` : ""),
152295
+ armed: shape.armed,
151795
152296
  count: shown.length,
151796
152297
  total: all.length,
151797
152298
  requests: shown.map(toRequestLine)
151798
152299
  };
151799
152300
  }
151800
- function headerDetail(state3, callNote) {
152301
+ function headerDetail(state3) {
151801
152302
  const parts2 = [];
151802
152303
  if (state3.process) parts2.push(`pid ${state3.process.pid}`);
151803
152304
  const capture = state3.capture;
@@ -151810,15 +152311,12 @@ function headerDetail(state3, callNote) {
151810
152311
  );
151811
152312
  }
151812
152313
  if (capture?.state === "unavailable") {
151813
- parts2.push(
151814
- `capture unavailable${capture.detail ? `: ${capture.detail}` : ""}; use view-network-logs`
151815
- );
152314
+ parts2.push(`capture unavailable${capture.detail ? `: ${capture.detail}` : ""}`);
151816
152315
  }
151817
152316
  if (state3.droppedEvents) {
151818
152317
  parts2.push(`${state3.droppedEvents} events were lost while the agent was disconnected`);
151819
152318
  }
151820
152319
  if (state3.note) parts2.push(state3.note);
151821
- if (callNote) parts2.push(callNote);
151822
152320
  return parts2;
151823
152321
  }
151824
152322
  function toRequestLine(record2) {
@@ -152719,12 +153217,13 @@ var jsRuntimeDebuggerBlueprint = {
152719
153217
  error_kind: "validation"
152720
153218
  });
152721
153219
  }
153220
+ const physicalDeviceId = typeof options?.physicalDeviceId === "string" && options.physicalDeviceId ? options.physicalDeviceId : deviceId;
152722
153221
  if (classifyDevice(deviceId) === "ios-remote") {
152723
153222
  await proxyStart(deviceId, port);
152724
153223
  }
152725
- await assertExternalCapability(JS_RUNTIME_DEBUGGER_NAMESPACE, deviceId, "js-debugger");
153224
+ await assertExternalCapability(JS_RUNTIME_DEBUGGER_NAMESPACE, physicalDeviceId, "js-debugger");
152726
153225
  const metro = await discoverMetro(port).catch((error63) => {
152727
- const published = publishedMetroPort(deviceId, port);
153226
+ const published = publishedMetroPort(physicalDeviceId, port);
152728
153227
  if (published !== void 0 && error63 instanceof FailureError) {
152729
153228
  error63.message += ` The provider offering this device publishes Metro on port ${published} \u2014 omit the 'port' parameter to use it.`;
152730
153229
  }
@@ -152735,8 +153234,8 @@ var jsRuntimeDebuggerBlueprint = {
152735
153234
  deviceId,
152736
153235
  simulatorName: await simulatorNameOnSharedMetro(deviceId, metro.targets)
152737
153236
  });
152738
- const onPublishedBundler = publishedMetroPort(deviceId, port) === void 0;
152739
- const proxied = onPublishedBundler ? externalJsDebuggerUrl(deviceId) : void 0;
153237
+ const onPublishedBundler = publishedMetroPort(physicalDeviceId, port) === void 0;
153238
+ const proxied = onPublishedBundler ? externalJsDebuggerUrl(physicalDeviceId) : void 0;
152740
153239
  const cdp = new CDPClient(proxied ?? selected.webSocketUrl, {
152741
153240
  awaitPromisesInApp: !selected.legacyInspector
152742
153241
  });
@@ -152871,14 +153370,22 @@ var jsRuntimeDebuggerBlueprint = {
152871
153370
  init_src2();
152872
153371
 
152873
153372
  // ../tool-server/src/utils/debugger/scripts/network-interceptor.ts
153373
+ var import_node_crypto15 = require("node:crypto");
153374
+ var import_node_os12 = require("node:os");
153375
+ init_src3();
152874
153376
  var BINARY_BODY_TYPES = /^(image\/(?!svg)|audio\/|video\/|font\/|application\/(octet-stream|pdf|zip|gzip|wasm|x-protobuf)$)/;
152875
153377
  var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
152876
153378
  var g = globalThis;
152877
- if (g.__argent_network_v2) return JSON.stringify({ installed: false, reason: 'already installed' });
153379
+ if (g.__argent_network_v3) return JSON.stringify({ installed: false, reason: 'already installed' });
153380
+ // A runtime can be reached before its bundle runs, and the bundle sets up XMLHttpRequest. An
153381
+ // install then would patch nothing yet keep its guard, so this context would never record.
153382
+ if (typeof g.XMLHttpRequest !== 'function') return JSON.stringify({ installed: false, reason: 'no XMLHttpRequest yet' });
153383
+ g.__argent_network_v3 = true;
153384
+ // An older tool-server installs only where this flag is unset, so it never replaces this script.
152878
153385
  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.
153386
+ // An older script, injected by an older tool-server before an upgrade, stays installed until
153387
+ // the app reloads. Its wrappers keep the buffers below in a closure, so empty them and stop
153388
+ // them from growing: they then still read each response, but keep nothing.
152882
153389
  if (g.__argent_network_installed && Array.isArray(g.__argent_network_log)) {
152883
153390
  var oldLog = g.__argent_network_log;
152884
153391
  oldLog.length = 0;
@@ -152903,6 +153410,15 @@ var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
152903
153410
  g.__argent_network_log = log;
152904
153411
  g.__argent_network_by_id = byId;
152905
153412
  var nextId = 1;
153413
+ // Only an identity: a new JS context gets another one, and its ids start at 1 again.
153414
+ var installToken = Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10);
153415
+ g.__argent_network_install = installToken;
153416
+ g.__argent_network_mark = function() {
153417
+ return JSON.stringify({ install: installToken, lastId: nextId - 1 });
153418
+ };
153419
+ function paused() {
153420
+ return g.__argent_network_paused === true;
153421
+ }
152906
153422
  var bufferedChars = 0;
152907
153423
  // Above zero while an XHR is sent: the request React Native's network module gets then is the
152908
153424
  // XHR's, which has its record.
@@ -152923,6 +153439,13 @@ var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
152923
153439
  }
152924
153440
  }
152925
153441
 
153442
+ // A request in flight keeps its record object, but adds to the buffer only while byId has it.
153443
+ g.__argent_network_clear = function() {
153444
+ log.length = 0;
153445
+ for (var key in byId) delete byId[key];
153446
+ bufferedChars = 0;
153447
+ };
153448
+
152926
153449
  // Runs on the app's JS thread for every text response. The loop costs about 200 ms per MiB in
152927
153450
  // Hermes with a debugger attached, so the native checks go first.
152928
153451
  function utf8Length(text) {
@@ -153416,6 +153939,10 @@ var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
153416
153939
  xhrSending--;
153417
153940
  }
153418
153941
  if (!slot || !slot.headers) return result;
153942
+ if (paused()) {
153943
+ slot.headers = null;
153944
+ return result;
153945
+ }
153419
153946
  var rec = createRecord(isFetchXhr(this, slot) ? 'Fetch' : 'XHR', slot.method, slot.url, slot.headers, body, startedAt);
153420
153947
  slot.headers = null;
153421
153948
  listen(this, rec);
@@ -153640,7 +154167,7 @@ var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
153640
154167
  var startedAt = Date.now();
153641
154168
  var promise = origStart.apply(this, arguments);
153642
154169
  var response = responses.get(this);
153643
- if (!response || !promise || typeof promise.then !== 'function') return promise;
154170
+ if (!response || !promise || typeof promise.then !== 'function' || paused()) return promise;
153644
154171
  try {
153645
154172
  var rec = createRecord('Fetch', String((init && init.method) || 'GET').toUpperCase(), String(url),
153646
154173
  lowerCaseHeaders(init && init.headers), body, startedAt);
@@ -153881,7 +154408,7 @@ var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
153881
154408
  var origSendRequest = networking.sendRequest;
153882
154409
  var origAbortRequest = networking.abortRequest;
153883
154410
  networking.sendRequest = function(method, trackingName, url, headers, data, responseType, incrementalUpdates, timeout, callback) {
153884
- if (xhrSending || typeof callback !== 'function') return origSendRequest.apply(this, arguments);
154411
+ if (xhrSending || typeof callback !== 'function' || paused()) return origSendRequest.apply(this, arguments);
153885
154412
  var watcher = null;
153886
154413
  try { watcher = watchRequest(networking, method, url, headers, data, responseType); } catch (e) {}
153887
154414
  if (!watcher) return origSendRequest.apply(this, arguments);
@@ -153908,6 +154435,62 @@ var NETWORK_INTERCEPTOR_SCRIPT = `(function() {
153908
154435
 
153909
154436
  return JSON.stringify({ installed: true });
153910
154437
  })()`;
154438
+ var NETWORK_CAPTURE_MARK_SCRIPT = `(function() {
154439
+ var g = globalThis;
154440
+ return typeof g.__argent_network_mark === 'function' ? g.__argent_network_mark() : JSON.stringify({ install: null });
154441
+ })()`;
154442
+ var HOLDER = JSON.stringify((0, import_node_crypto15.randomUUID)());
154443
+ function holderRecord(capturing2) {
154444
+ return JSON.stringify({ capturing: capturing2, pid: process.pid, host: (0, import_node_os12.hostname)() });
154445
+ }
154446
+ function makeNetworkCaptureControlScript(paused) {
154447
+ return `(function() {
154448
+ var g = globalThis;
154449
+ g.__argent_network_paused = ${paused ? "true" : "false"};${paused ? `
154450
+ var holders = g.__argent_network_holders;
154451
+ if (holders && Object.prototype.hasOwnProperty.call(holders, ${HOLDER})) holders[${HOLDER}] = ${holderRecord(false)};` : `
154452
+ (g.__argent_network_holders = g.__argent_network_holders || {})[${HOLDER}] = ${holderRecord(true)};`}
154453
+ return JSON.stringify({ installed: typeof g.__argent_network_mark === 'function' });
154454
+ })()`;
154455
+ }
154456
+ var NETWORK_CAPTURE_END_SCRIPT = `(function() {
154457
+ var g = globalThis;
154458
+ g.__argent_network_paused = true;
154459
+ if (g.__argent_network_holders) delete g.__argent_network_holders[${HOLDER}];
154460
+ if (typeof g.__argent_network_clear === 'function') g.__argent_network_clear();
154461
+ })()`;
154462
+ function makeNetworkCaptureReleaseScript(exited) {
154463
+ return `(function() {
154464
+ var g = globalThis;
154465
+ var holders = g.__argent_network_holders;
154466
+ var readers = false;
154467
+ if (holders) {
154468
+ delete holders[${HOLDER}];
154469
+ var exited = ${JSON.stringify(exited)};
154470
+ for (var i = 0; i < exited.length; i++) delete holders[exited[i]];
154471
+ for (var key in holders) {
154472
+ if (!Object.prototype.hasOwnProperty.call(holders, key)) continue;
154473
+ if (holders[key].capturing) return JSON.stringify({ holders: holders });
154474
+ readers = true;
154475
+ }
154476
+ }
154477
+ g.__argent_network_paused = true;
154478
+ if (!readers && typeof g.__argent_network_clear === 'function') g.__argent_network_clear();
154479
+ return JSON.stringify({ holders: holders || {} });
154480
+ })()`;
154481
+ }
154482
+ function exitedHolders(answer) {
154483
+ let holders;
154484
+ try {
154485
+ holders = JSON.parse(String(answer)).holders;
154486
+ } catch {
154487
+ return [];
154488
+ }
154489
+ return Object.keys(holders).filter((key2) => {
154490
+ const { pid, host } = holders[key2];
154491
+ return host === (0, import_node_os12.hostname)() && typeof pid === "number" && !isProcessAlive(pid);
154492
+ });
154493
+ }
153911
154494
  function makeNetworkLogReadScript(start2, limit, metroPort2) {
153912
154495
  return `(function() {
153913
154496
  var log = globalThis.__argent_network_log;
@@ -153950,13 +154533,18 @@ function makeNetworkLogReadScript(start2, limit, metroPort2) {
153950
154533
  });
153951
154534
  }
153952
154535
 
153953
- return JSON.stringify({ entries: entries, total: total, interceptorInstalled: true });
154536
+ return JSON.stringify({
154537
+ entries: entries,
154538
+ total: total,
154539
+ interceptorInstalled: true,
154540
+ paused: globalThis.__argent_network_paused === true
154541
+ });
153954
154542
  })()`;
153955
154543
  }
153956
154544
  function makeNetworkDetailReadScript(requestId) {
153957
154545
  return `(function() {
153958
154546
  var byId = globalThis.__argent_network_by_id;
153959
- if (!byId) return JSON.stringify({ error: 'Network interceptor not installed' });
154547
+ if (!byId) return JSON.stringify({ error: 'Network interceptor not installed', installed: false });
153960
154548
  var entry = byId[${JSON.stringify(requestId)}];
153961
154549
  if (!entry) return JSON.stringify({ error: 'Request not found' });
153962
154550
  if (typeof globalThis.__argent_network_decode === 'function') globalThis.__argent_network_decode(entry);
@@ -153981,7 +154569,187 @@ function makeNetworkDetailReadScript(requestId) {
153981
154569
  }
153982
154570
 
153983
154571
  // ../tool-server/src/blueprints/network-inspector.ts
154572
+ init_device_info();
154573
+ init_external_devices();
153984
154574
  var NETWORK_INSPECTOR_NAMESPACE = "NetworkInspector";
154575
+ var jsCaptures = /* @__PURE__ */ new Map();
154576
+ var jsUnavailable = /* @__PURE__ */ new Map();
154577
+ function splitPayload(payload) {
154578
+ const at = payload.indexOf(":");
154579
+ return { port: Number(payload.slice(0, at)), device: payload.slice(at + 1) };
154580
+ }
154581
+ function sameDevice(a, b) {
154582
+ return externalNativeId(a).toLowerCase() === externalNativeId(b).toLowerCase();
154583
+ }
154584
+ function jsCapturePayload(port, device) {
154585
+ return `${port}:${device}`;
154586
+ }
154587
+ function storedPayload(payload) {
154588
+ const { port, device } = splitPayload(payload);
154589
+ return payloadsOf([device]).find((key2) => splitPayload(key2).port === port);
154590
+ }
154591
+ function jsCapture(payload) {
154592
+ const key2 = storedPayload(payload);
154593
+ return key2 === void 0 ? void 0 : jsCaptures.get(key2);
154594
+ }
154595
+ function forgetJsCapture(device, bundleId) {
154596
+ for (const [payload, capture] of jsCaptures) {
154597
+ if (capture.bundleId === bundleId && sameDevice(splitPayload(payload).device, device)) {
154598
+ jsCaptures.delete(payload);
154599
+ }
154600
+ }
154601
+ for (const [payload, found] of jsUnavailable) {
154602
+ if (found.bundleId === bundleId && sameDevice(splitPayload(payload).device, device)) {
154603
+ jsUnavailable.delete(payload);
154604
+ }
154605
+ }
154606
+ }
154607
+ function setJsCapture(payload, capture) {
154608
+ forgetJsCapture(splitPayload(payload).device, capture.bundleId);
154609
+ const held = storedPayload(payload);
154610
+ if (held !== void 0) jsCaptures.delete(held);
154611
+ const unavailable3 = unavailablePayload(payload);
154612
+ if (unavailable3 !== void 0) jsUnavailable.delete(unavailable3);
154613
+ jsCaptures.set(payload, capture);
154614
+ }
154615
+ function unavailablePayload(payload) {
154616
+ const { port, device } = splitPayload(payload);
154617
+ return [...jsUnavailable.keys()].find((key2) => {
154618
+ const at = splitPayload(key2);
154619
+ return at.port === port && sameDevice(at.device, device);
154620
+ });
154621
+ }
154622
+ function setJsUnavailable(payload, bundleId, reason2) {
154623
+ const held = unavailablePayload(payload);
154624
+ if (held !== void 0) jsUnavailable.delete(held);
154625
+ jsUnavailable.set(payload, { bundleId, reason: reason2 });
154626
+ }
154627
+ function jsUnavailableOn(payload) {
154628
+ const key2 = unavailablePayload(payload);
154629
+ return key2 === void 0 ? void 0 : jsUnavailable.get(key2);
154630
+ }
154631
+ function jsCapturesOn(device) {
154632
+ const found = [];
154633
+ for (const [payload, capture] of jsCaptures) {
154634
+ const { port, device: of } = splitPayload(payload);
154635
+ if (sameDevice(of, device)) found.push({ ...capture, port });
154636
+ }
154637
+ return found;
154638
+ }
154639
+ function findJsCapture(device, bundleId) {
154640
+ return jsCapturesOn(device).find((capture) => capture.bundleId === bundleId);
154641
+ }
154642
+ function payloadsOf(devices2) {
154643
+ return [...jsCaptures.keys()].filter((payload) => {
154644
+ const { device } = splitPayload(payload);
154645
+ return !devices2 || devices2.some((id) => sameDevice(id, device));
154646
+ });
154647
+ }
154648
+ function forgetJsCapturesOf(devices2, paused) {
154649
+ for (const payload of jsUnavailable.keys()) {
154650
+ const { device } = splitPayload(payload);
154651
+ if (!devices2 || devices2.some((id) => sameDevice(id, device))) jsUnavailable.delete(payload);
154652
+ }
154653
+ for (const payload of payloadsOf(devices2)) {
154654
+ const capture = jsCaptures.get(payload);
154655
+ if (paused && !paused.has(payload) && capture.installed && !capture.paused) {
154656
+ jsCaptures.set(payload, {
154657
+ bundleId: capture.bundleId,
154658
+ intent: "stopped",
154659
+ ...capture.mark ? { mark: capture.mark } : {},
154660
+ installed: true,
154661
+ ...capture.physicalDeviceId ? { physicalDeviceId: capture.physicalDeviceId } : {}
154662
+ });
154663
+ } else {
154664
+ jsCaptures.delete(payload);
154665
+ }
154666
+ }
154667
+ }
154668
+ function forgetJsCaptures(payloads) {
154669
+ for (const payload of payloads) jsCaptures.delete(payload);
154670
+ }
154671
+ var PAUSE_BEFORE_FORGET_TIMEOUT_MS = 1e3;
154672
+ async function pauseJsCapturesOf(registry2, devices2, { atExit = false } = {}) {
154673
+ const services = registry2.getSnapshot().services;
154674
+ const paused = /* @__PURE__ */ new Set();
154675
+ await Promise.all(
154676
+ payloadsOf(devices2).map(async (payload) => {
154677
+ const urn = `${JS_RUNTIME_DEBUGGER_NAMESPACE}:${payload}`;
154678
+ const state3 = services.get(urn)?.state;
154679
+ if (state3 === void 0 || !isLiveServiceState(state3)) return;
154680
+ const { bundleId } = jsCaptures.get(payload);
154681
+ const pause = (async () => {
154682
+ const dbg = await registry2.resolveService(urn);
154683
+ const appId = dbg.runtimeApp?.appId;
154684
+ if (appId !== void 0 && appId !== bundleId) return false;
154685
+ const options = { timeout: PAUSE_BEFORE_FORGET_TIMEOUT_MS };
154686
+ if (!atExit) {
154687
+ await dbg.cdp.evaluate(NETWORK_CAPTURE_END_SCRIPT, options);
154688
+ return true;
154689
+ }
154690
+ const left = await dbg.cdp.evaluate(makeNetworkCaptureReleaseScript([]), options);
154691
+ const exited = exitedHolders(left);
154692
+ if (exited.length > 0) {
154693
+ await dbg.cdp.evaluate(makeNetworkCaptureReleaseScript(exited), options);
154694
+ }
154695
+ return true;
154696
+ })();
154697
+ let timer;
154698
+ const late = new Promise((resolve21) => {
154699
+ timer = setTimeout(() => resolve21(false), PAUSE_BEFORE_FORGET_TIMEOUT_MS);
154700
+ });
154701
+ try {
154702
+ if (await Promise.race([pause, late])) paused.add(payload);
154703
+ } catch {
154704
+ } finally {
154705
+ clearTimeout(timer);
154706
+ }
154707
+ })
154708
+ );
154709
+ return paused;
154710
+ }
154711
+ var NO_XHR_YET = "no XMLHttpRequest yet";
154712
+ async function installNetworkInterceptor(cdp, payload, runtimeApp) {
154713
+ const { device } = splitPayload(payload);
154714
+ if (resolveDevice(device).platform === "vega") {
154715
+ return parseInstall(await cdp.evaluate(NETWORK_INTERCEPTOR_SCRIPT));
154716
+ }
154717
+ const capture = jsCapture(payload);
154718
+ if (capture?.intent !== "started") {
154719
+ return { installed: false, reason: `capture is ${capture ? "stopped" : "not started"}` };
154720
+ }
154721
+ if (runtimeApp?.appId !== void 0 && runtimeApp.appId !== capture.bundleId) {
154722
+ return { installed: false, reason: `the JS runtime is ${runtimeApp.appId}'s` };
154723
+ }
154724
+ const before = capture.installed;
154725
+ capture.installed = true;
154726
+ try {
154727
+ await cdp.evaluate(makeNetworkCaptureControlScript(false));
154728
+ } catch (err) {
154729
+ if (neverSent(err)) capture.installed = before;
154730
+ throw err;
154731
+ }
154732
+ const install = parseInstall(await cdp.evaluate(NETWORK_INTERCEPTOR_SCRIPT));
154733
+ if (install.installed || install.reason === "already installed") return { installed: true };
154734
+ if (install.reason === NO_XHR_YET) capture.installed = before;
154735
+ return install;
154736
+ }
154737
+ function neverSent(err) {
154738
+ const code = getFailureSignal(err)?.error_code;
154739
+ return code === FAILURE_CODES.DEBUGGER_CDP_NOT_CONNECTED || code === FAILURE_CODES.JS_RUNTIME_PAUSED;
154740
+ }
154741
+ function parseInstall(raw) {
154742
+ try {
154743
+ const parsed2 = JSON.parse(String(raw));
154744
+ if (parsed2.installed === true) return { installed: true };
154745
+ return {
154746
+ installed: false,
154747
+ reason: typeof parsed2.reason === "string" ? parsed2.reason : "unknown"
154748
+ };
154749
+ } catch {
154750
+ return { installed: false, reason: `unexpected answer: ${String(raw).slice(0, 200)}` };
154751
+ }
154752
+ }
153985
154753
  var networkInspectorBlueprint = {
153986
154754
  namespace: NETWORK_INSPECTOR_NAMESPACE,
153987
154755
  // payload is "port:deviceId"
@@ -153991,10 +154759,10 @@ var networkInspectorBlueprint = {
153991
154759
  getDependencies(payload) {
153992
154760
  return { debugger: `JsRuntimeDebugger:${payload}` };
153993
154761
  },
153994
- async factory(deps, _payload) {
154762
+ async factory(deps, payload) {
153995
154763
  const debuggerApi = deps.debugger;
153996
154764
  const cdp = debuggerApi.cdp;
153997
- await cdp.evaluate(NETWORK_INTERCEPTOR_SCRIPT).catch((err) => {
154765
+ await installNetworkInterceptor(cdp, payload, debuggerApi.runtimeApp).catch((err) => {
153998
154766
  const msg = err instanceof Error ? err.message : String(err);
153999
154767
  process.stderr.write(
154000
154768
  `[NetworkInspector:${debuggerApi.port}] NETWORK_INTERCEPTOR_SCRIPT failed (non-fatal): ${msg}
@@ -154867,7 +155635,7 @@ function clearLostProfilerRun(port, deviceId) {
154867
155635
  var import_node_child_process34 = require("node:child_process");
154868
155636
  var import_node_fs16 = require("node:fs");
154869
155637
  var import_promises14 = require("node:fs/promises");
154870
- var import_node_os14 = require("node:os");
155638
+ var import_node_os15 = require("node:os");
154871
155639
  var import_node_path19 = require("node:path");
154872
155640
  var import_node_util24 = require("node:util");
154873
155641
  init_zod();
@@ -154914,7 +155682,7 @@ async function listEmulatorPidsForAvd(avdName) {
154914
155682
 
154915
155683
  // ../tool-server/src/utils/linux-preflight.ts
154916
155684
  var fs43 = __toESM(require("node:fs"));
154917
- var import_node_os12 = require("node:os");
155685
+ var import_node_os13 = require("node:os");
154918
155686
  var import_node_path17 = require("node:path");
154919
155687
  var import_ini2 = __toESM(require_ini());
154920
155688
  function linuxBootDiagnostics(avdName) {
@@ -154943,7 +155711,7 @@ function checkKvm() {
154943
155711
  var MIN_RAM_MB = 4096;
154944
155712
  var MIN_HEAP_MB = 512;
154945
155713
  function checkAvdSizing(avdName) {
154946
- const configPath = (0, import_node_path17.join)((0, import_node_os12.homedir)(), ".android", "avd", `${avdName}.avd`, "config.ini");
155714
+ const configPath = (0, import_node_path17.join)((0, import_node_os13.homedir)(), ".android", "avd", `${avdName}.avd`, "config.ini");
154947
155715
  let content;
154948
155716
  try {
154949
155717
  content = fs43.readFileSync(configPath, "utf8");
@@ -154979,7 +155747,7 @@ function readMb(config2, key2) {
154979
155747
  // ../tool-server/src/utils/simulator-app-launch.ts
154980
155748
  var import_node_child_process32 = require("node:child_process");
154981
155749
  var import_node_fs15 = __toESM(require("node:fs"));
154982
- var import_node_os13 = __toESM(require("node:os"));
155750
+ var import_node_os14 = __toESM(require("node:os"));
154983
155751
  var import_node_path18 = __toESM(require("node:path"));
154984
155752
  var import_node_util23 = require("node:util");
154985
155753
  var execFileAsync23 = (0, import_node_util23.promisify)(import_node_child_process32.execFile);
@@ -154988,7 +155756,7 @@ var LAUNCH_WATCH_MS = 1e4;
154988
155756
  var LAUNCH_POLL_MS = 250;
154989
155757
  var launchLocks = /* @__PURE__ */ new Map();
154990
155758
  function verdictFilePath() {
154991
- return import_node_path18.default.join(import_node_os13.default.homedir(), ".argent", "simulator-app-launch.json");
155759
+ return import_node_path18.default.join(import_node_os14.default.homedir(), ".argent", "simulator-app-launch.json");
154992
155760
  }
154993
155761
  function loadVerdicts() {
154994
155762
  try {
@@ -155847,7 +156615,7 @@ async function attemptBoot(params) {
155847
156615
  let stdio = "ignore";
155848
156616
  if (process.platform === "win32") {
155849
156617
  const safeName = params.avdName.replace(/[^\w.-]/g, "_");
155850
- const logPath = (0, import_node_path19.join)((0, import_node_os14.tmpdir)(), `argent-emulator-${safeName}.log`);
156618
+ const logPath = (0, import_node_path19.join)((0, import_node_os15.tmpdir)(), `argent-emulator-${safeName}.log`);
155851
156619
  emulatorLogFd = (0, import_node_fs16.openSync)(logPath, "w");
155852
156620
  stdio = ["ignore", emulatorLogFd, emulatorLogFd];
155853
156621
  }
@@ -156376,11 +157144,11 @@ async function startHarmonyEmulator(instanceName) {
156376
157144
  });
156377
157145
  }
156378
157146
  try {
156379
- for (const entry of (0, import_node_fs16.readdirSync)((0, import_node_os14.tmpdir)())) {
157147
+ for (const entry of (0, import_node_fs16.readdirSync)((0, import_node_os15.tmpdir)())) {
156380
157148
  if (!entry.startsWith("argent-harmony-") || !entry.endsWith(".log")) continue;
156381
157149
  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 });
157150
+ if (Date.now() - (0, import_node_fs16.statSync)((0, import_node_path19.join)((0, import_node_os15.tmpdir)(), entry)).mtimeMs > HARMONY_LOG_TTL_MS) {
157151
+ (0, import_node_fs16.rmSync)((0, import_node_path19.join)((0, import_node_os15.tmpdir)(), entry), { force: true });
156384
157152
  }
156385
157153
  } catch {
156386
157154
  }
@@ -156388,7 +157156,7 @@ async function startHarmonyEmulator(instanceName) {
156388
157156
  } catch {
156389
157157
  }
156390
157158
  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`);
157159
+ const logPath = (0, import_node_path19.join)((0, import_node_os15.tmpdir)(), `argent-harmony-${safeName}-${process.hrtime.bigint()}.log`);
156392
157160
  let logFd;
156393
157161
  try {
156394
157162
  logFd = (0, import_node_fs16.openSync)(logPath, "w");
@@ -156495,7 +157263,7 @@ async function waitForHarmonyTarget(before, deadline, checkAlive, expected) {
156495
157263
  }
156496
157264
  }
156497
157265
  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`);
157266
+ const probePath = (0, import_node_path19.join)((0, import_node_os15.tmpdir)(), `argent-harmony-bootprobe-${process.hrtime.bigint()}.json`);
156499
157267
  let inFlight4 = null;
156500
157268
  try {
156501
157269
  for (; ; ) {
@@ -156964,10 +157732,6 @@ function dispatchByPlatform(opts) {
156964
157732
  };
156965
157733
  }
156966
157734
 
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
157735
  // ../tool-server/src/tools/launch-app/platforms/ios.ts
156972
157736
  var import_node_child_process35 = require("node:child_process");
156973
157737
  var import_node_util25 = require("node:util");
@@ -157478,7 +158242,7 @@ function createLaunchAppTool(registry2) {
157478
158242
  longRunning: true,
157479
158243
  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
158244
  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>
158245
+ 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
158246
  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
158247
  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
158248
 
@@ -157778,7 +158542,7 @@ function createRestartAppTool(registry2) {
157778
158542
  longRunning: true,
157779
158543
  description: `Terminate then relaunch an app on iOS, Android, <flag:harmonyos>HarmonyOS, </flag:harmonyos><flag:macos-apps>macOS, </flag:macos-apps>or Vega.
157780
158544
  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>
158545
+ 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
158546
  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
158547
  zodSchema: zodSchema12,
157784
158548
  alwaysLoad: true,
@@ -159136,14 +159900,14 @@ function androidDevtoolsRotationPeek(registry2, device) {
159136
159900
 
159137
159901
  // ../tool-server/src/utils/vega-screen.ts
159138
159902
  var import_promises17 = require("node:fs/promises");
159139
- var import_node_os16 = require("node:os");
159903
+ var import_node_os17 = require("node:os");
159140
159904
  var import_node_path28 = require("node:path");
159141
159905
  var import_pngjs3 = __toESM(require_png());
159142
159906
  init_src2();
159143
159907
  init_adb();
159144
159908
 
159145
159909
  // ../tool-server/src/utils/emulator-console.ts
159146
- var import_node_os15 = require("node:os");
159910
+ var import_node_os16 = require("node:os");
159147
159911
  var import_node_path27 = require("node:path");
159148
159912
  init_adb();
159149
159913
  async function runEmuConsole(serial, args) {
@@ -159160,7 +159924,7 @@ function describeConsoleReply(stdout) {
159160
159924
  const lines = replyLines(stdout);
159161
159925
  const reply = lines.join("; ") || "empty reply";
159162
159926
  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");
159927
+ const tokenFile = (0, import_node_path27.join)((0, import_node_os16.homedir)(), ".emulator_console_auth_token");
159164
159928
  const fileKind = process.platform === "win32" ? "a file" : "a regular file, not a symlink,";
159165
159929
  return `${reply} (adb authenticates to the console with ${tokenFile}, which must be ${fileKind} holding the emulator's token)`;
159166
159930
  }
@@ -159175,7 +159939,7 @@ async function captureVegaScreenshotPng(opts = {}) {
159175
159939
  async function captureViaEmulatorConsole(opts) {
159176
159940
  const port = await discoverVegaConsolePort();
159177
159941
  const serial = `emulator-${port}`;
159178
- const outDir = await (0, import_promises17.mkdtemp)((0, import_node_path28.join)((0, import_node_os16.tmpdir)(), "vega-shot-"));
159942
+ const outDir = await (0, import_promises17.mkdtemp)((0, import_node_path28.join)((0, import_node_os17.tmpdir)(), "vega-shot-"));
159179
159943
  try {
159180
159944
  const { stdout } = await runAdb(["-s", serial, "emu", "screenrecord", "screenshot", outDir], {
159181
159945
  timeoutMs: 2e4
@@ -159197,7 +159961,7 @@ async function captureViaEmulatorConsole(opts) {
159197
159961
  decoded2,
159198
159962
  opts.scale ?? getScreenshotScaleOverride() ?? tvDefaultScale(decoded2.width, decoded2.height)
159199
159963
  );
159200
- const outPath = (0, import_node_path28.join)((0, import_node_os16.tmpdir)(), `vega-screenshot-${process.hrtime.bigint()}.png`);
159964
+ const outPath = (0, import_node_path28.join)((0, import_node_os17.tmpdir)(), `vega-screenshot-${process.hrtime.bigint()}.png`);
159201
159965
  await (0, import_promises17.writeFile)(outPath, import_pngjs3.PNG.sync.write(scaled));
159202
159966
  return outPath;
159203
159967
  } finally {
@@ -159208,7 +159972,7 @@ async function captureViaEmulatorConsole(opts) {
159208
159972
 
159209
159973
  // ../tool-server/src/utils/harmony-screen.ts
159210
159974
  var import_promises18 = require("node:fs/promises");
159211
- var import_node_os17 = require("node:os");
159975
+ var import_node_os18 = require("node:os");
159212
159976
  var import_node_path29 = require("node:path");
159213
159977
  var import_pngjs4 = __toESM(require_png());
159214
159978
  init_src2();
@@ -159230,12 +159994,12 @@ function decodeCapture(raw, connectKey) {
159230
159994
  }
159231
159995
  }
159232
159996
  async function captureHarmonyScreenshotPng(opts) {
159233
- const rawPath = (0, import_node_path29.join)((0, import_node_os17.tmpdir)(), `argent-harmony-raw-${process.hrtime.bigint()}.png`);
159997
+ const rawPath = (0, import_node_path29.join)((0, import_node_os18.tmpdir)(), `argent-harmony-raw-${process.hrtime.bigint()}.png`);
159234
159998
  try {
159235
159999
  await harmonyScreenCap(opts.connectKey, rawPath);
159236
160000
  const decoded2 = decodeCapture(await (0, import_promises18.readFile)(rawPath), opts.connectKey);
159237
160001
  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`);
160002
+ const outPath = (0, import_node_path29.join)((0, import_node_os18.tmpdir)(), `harmony-screenshot-${process.hrtime.bigint()}.png`);
159239
160003
  if (scaled === decoded2) {
159240
160004
  await (0, import_promises18.rename)(rawPath, outPath);
159241
160005
  } else {
@@ -163128,7 +163892,7 @@ init_device_info();
163128
163892
  init_capability();
163129
163893
 
163130
163894
  // ../tool-server/src/utils/sub-invoke.ts
163131
- var import_node_crypto15 = require("node:crypto");
163895
+ var import_node_crypto16 = require("node:crypto");
163132
163896
  init_src2();
163133
163897
  async function invokeSubTool(registry2, ctx, toolId, args, extra) {
163134
163898
  const signal = ctx?.signal;
@@ -163144,7 +163908,7 @@ async function invokeSubTool(registry2, ctx, toolId, args, extra) {
163144
163908
  if (!recordChildInvocation) {
163145
163909
  return signal || Object.keys(forwarded).length > 0 ? registry2.invokeTool(toolId, args, { ...signal ? { signal } : {}, ...forwarded }) : registry2.invokeTool(toolId, args);
163146
163910
  }
163147
- const toolInvocationId = (0, import_node_crypto15.randomUUID)();
163911
+ const toolInvocationId = (0, import_node_crypto16.randomUUID)();
163148
163912
  const release2 = recordChildInvocation(toolInvocationId, args);
163149
163913
  try {
163150
163914
  return await registry2.invokeTool(toolId, args, {
@@ -165062,6 +165826,41 @@ var ITEMS_PER_PAGE = 50;
165062
165826
  function notInstalled(installError) {
165063
165827
  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
165828
  }
165829
+ 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";
165830
+ 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";
165831
+ function jsReadPort(params) {
165832
+ if (params.port !== void 0) return params.port;
165833
+ const device = canonicalDeviceId(params.device_id);
165834
+ const provided = device ? jsCapturesOn(device).find(
165835
+ (capture) => capture.physicalDeviceId !== void 0 && metroPort({ device_id: capture.physicalDeviceId }) === capture.port
165836
+ ) : void 0;
165837
+ return provided?.port ?? metroPort(params);
165838
+ }
165839
+ function jsCaptureDebuggerRef(params, capture) {
165840
+ const urn = debuggerServiceRef({ ...params, port: jsReadPort(params) });
165841
+ return capture.physicalDeviceId && typeof urn === "string" ? { urn, options: { physicalDeviceId: capture.physicalDeviceId } } : urn;
165842
+ }
165843
+ function jsCaptureForRead(payload, runtimeApp) {
165844
+ const capture = jsCapture(payload);
165845
+ if (!capture) return void 0;
165846
+ if (runtimeApp?.appId !== void 0 && runtimeApp.appId !== capture.bundleId) return void 0;
165847
+ return capture;
165848
+ }
165849
+ function jsNotStarted(device, port, then = "call view-network-logs again", lead = "") {
165850
+ const elsewhere = jsCapturesOn(device).filter((capture) => capture.port !== port).map(
165851
+ (capture) => ` This device has network capture for ${capture.bundleId} on Metro port ${capture.port}: pass port ${capture.port} to read it.`
165852
+ ).join("");
165853
+ const unavailable3 = jsUnavailableOn(jsCapturePayload(port, device));
165854
+ 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;
165855
+ return `${lead}${head} ${then}.${elsewhere}`;
165856
+ }
165857
+ function jsNoLog(capture) {
165858
+ if (capture.intent === "stopped") {
165859
+ 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.`;
165860
+ }
165861
+ const native = "native-network-logs lists the requests of the native layer.";
165862
+ 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.`;
165863
+ }
165065
165864
  function formatBytes2(bytes) {
165066
165865
  return (0, import_bytes3.default)(bytes, { decimalPlaces: 1, unitSeparator: " " }) ?? `${bytes} B`;
165067
165866
  }
@@ -165178,7 +165977,7 @@ var networkLogsTool = {
165178
165977
  Returns a paginated list of requests with method, URL, status, resource type, size, and duration.
165179
165978
  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
165979
  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).
165980
+ 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
165981
  Use when inspecting outbound HTTP traffic or debugging API calls in the running app.
165183
165982
  Fails if the app is not connected (RN) or the device is not reachable (Chromium).`,
165184
165983
  zodSchema: zodSchema38,
@@ -165194,49 +165993,74 @@ Fails if the app is not connected (RN) or the device is not reachable (Chromium)
165194
165993
  if (device.platform === "chromium") {
165195
165994
  return { chromium: chromiumCdpRef(device) };
165196
165995
  }
165197
- return {
165198
- inspector: `NetworkInspector:${metroPort(params)}:${canonicalDeviceId(params.device_id)}`
165199
- };
165996
+ const payload = jsCapturePayload(jsReadPort(params), canonicalDeviceId(params.device_id));
165997
+ if (device.platform === "vega") return { inspector: `NetworkInspector:${payload}` };
165998
+ const capture = jsCapture(payload);
165999
+ return capture ? { debugger: jsCaptureDebuggerRef(params, capture) } : {};
165200
166000
  },
165201
166001
  async execute(services, params) {
165202
- if (resolveDevice(params.device_id).platform === "chromium") {
166002
+ const device = resolveDevice(params.device_id);
166003
+ if (device.platform === "chromium") {
165203
166004
  const chromium = services.chromium;
165204
166005
  return renderChromiumPage(chromium.server.network.requests(), params.pageIndex);
165205
166006
  }
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).`;
166007
+ const port = jsReadPort(params);
166008
+ if (device.platform === "vega") {
166009
+ const api = services.inspector;
166010
+ const installError = await api.cdp.evaluate(NETWORK_INTERCEPTOR_SCRIPT).then(
166011
+ () => void 0,
166012
+ (err) => err instanceof Error ? err.message : String(err)
166013
+ );
166014
+ return renderJsLog(api.cdp, port, params.pageIndex, {
166015
+ noLog: () => notInstalled(installError),
166016
+ 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)."
166017
+ });
165221
166018
  }
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")}`;
166019
+ const deviceId = canonicalDeviceId(params.device_id);
166020
+ const dbg = services.debugger;
166021
+ const capture = dbg && jsCaptureForRead(jsCapturePayload(port, deviceId), dbg.runtimeApp);
166022
+ if (!dbg || !capture) return jsNotStarted(deviceId, port);
166023
+ const stopped = capture.intent === "stopped";
166024
+ return renderJsLog(dbg.cdp, port, params.pageIndex, {
166025
+ noLog: () => jsNoLog(capture),
166026
+ 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.",
166027
+ headerNote: stopped ? "capture stopped" : void 0,
166028
+ // A start that does not reach the app's JS context keeps the pause of an earlier stop there.
166029
+ paused: stopped ? void 0 : {
166030
+ empty: `No network traffic captured. The app's ${PAUSED_BY_STOP}. Call network-capture-start, then repeat the action.`,
166031
+ headerNote: `the app's ${PAUSED_BY_STOP}, so call network-capture-start, then repeat the action`
166032
+ }
166033
+ });
165238
166034
  }
165239
166035
  };
166036
+ async function renderJsLog(cdp, port, pageIndexParam, texts) {
166037
+ const countRaw = await cdp.evaluate(makeNetworkLogReadScript(0, 0, port));
166038
+ const { total, interceptorInstalled, paused } = JSON.parse(countRaw);
166039
+ if (!interceptorInstalled) return texts.noLog();
166040
+ const shown = paused === true && texts.paused || texts;
166041
+ if (total === 0) return shown.empty;
166042
+ const pageCount = Math.ceil(total / ITEMS_PER_PAGE);
166043
+ const pageIndex = pageIndexParam === "latest" ? pageCount - 1 : pageIndexParam;
166044
+ if (pageIndex < 0 || pageIndex >= pageCount) {
166045
+ return `Page index out of range. Valid range: 0-${pageCount - 1} (${pageCount} pages, ${total} total requests).`;
166046
+ }
166047
+ const start2 = pageIndex * ITEMS_PER_PAGE;
166048
+ const raw = await cdp.evaluate(makeNetworkLogReadScript(start2, ITEMS_PER_PAGE, port));
166049
+ const data = JSON.parse(raw);
166050
+ if (!data.interceptorInstalled) return texts.noLog();
166051
+ const lines = data.entries.map(
166052
+ (entry) => formatEntry(
166053
+ entry.response ? {
166054
+ ...entry,
166055
+ response: { ...entry.response, statusText: reasonPhrase(entry.response.status) }
166056
+ } : entry
166057
+ )
166058
+ );
166059
+ const note = shown.headerNote ? `; ${shown.headerNote}` : "";
166060
+ return `=== NETWORK LOGS (page ${pageIndex + 1}/${pageCount}, ${data.total} total${note}) ===
166061
+
166062
+ ${lines.join("\n")}`;
166063
+ }
165240
166064
 
165241
166065
  // ../tool-server/src/tools/network/network-request.ts
165242
166066
  var zlib3 = __toESM(require("node:zlib"));
@@ -165312,7 +166136,7 @@ var networkRequestTool = {
165312
166136
  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.
165313
166137
  Returns request/response headers (sensitive headers redacted), status, timing, the request body, and optionally the response body.
165314
166138
  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.`,
166139
+ Returns an error message string if the requestId is not found; on iOS 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. ios- and android- IDs are not affected.`,
165316
166140
  zodSchema: zodSchema39,
165317
166141
  readOnly: true,
165318
166142
  interaction: {
@@ -165328,9 +166152,10 @@ Returns an error message string if the requestId is not found.`,
165328
166152
  return { chromium: chromiumCdpRef(device) };
165329
166153
  }
165330
166154
  if (nativeIdPlatform2(params.requestId)) return {};
165331
- return {
165332
- inspector: `NetworkInspector:${metroPort(params)}:${canonicalDeviceId(params.device_id)}`
165333
- };
166155
+ const payload = jsCapturePayload(jsReadPort(params), canonicalDeviceId(params.device_id));
166156
+ if (device.platform === "vega") return { inspector: `NetworkInspector:${payload}` };
166157
+ const capture = jsCapture(payload);
166158
+ return capture ? { debugger: jsCaptureDebuggerRef(params, capture) } : {};
165334
166159
  },
165335
166160
  async execute(services, params) {
165336
166161
  if (ANDROID_NATIVE_REQUEST_ID.test(params.requestId)) {
@@ -165394,13 +166219,34 @@ Returns an error message string if the requestId is not found.`,
165394
166219
  }
165395
166220
  const nativePlatform = nativeIdPlatform2(params.requestId);
165396
166221
  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
- });
166222
+ let cdp;
166223
+ let noLog;
166224
+ if (device.platform === "vega") {
166225
+ const api = services.inspector;
166226
+ await api.cdp.evaluate(NETWORK_INTERCEPTOR_SCRIPT).catch(() => {
166227
+ });
166228
+ cdp = api.cdp;
166229
+ } else {
166230
+ const port = jsReadPort(params);
166231
+ const deviceId = canonicalDeviceId(params.device_id);
166232
+ const dbg = services.debugger;
166233
+ const capture = dbg && jsCaptureForRead(jsCapturePayload(port, deviceId), dbg.runtimeApp);
166234
+ if (!dbg || !capture) {
166235
+ return jsNotStarted(
166236
+ deviceId,
166237
+ port,
166238
+ "list the requests with view-network-logs",
166239
+ `Request ${params.requestId} not found. `
166240
+ );
166241
+ }
166242
+ cdp = dbg.cdp;
166243
+ noLog = `Request ${params.requestId} not found. ${jsNoLog(capture)}`;
166244
+ }
165400
166245
  const script = makeNetworkDetailReadScript(params.requestId);
165401
- const raw = await api.cdp.evaluate(script);
166246
+ const raw = await cdp.evaluate(script);
165402
166247
  const data = JSON.parse(raw);
165403
166248
  if ("error" in data) {
166249
+ if (data.installed === false && noLog) return noLog;
165404
166250
  return `${data.error}. Use view-network-logs to list available requests.`;
165405
166251
  }
165406
166252
  const entry = data;
@@ -165454,7 +166300,11 @@ function isNativeRequestId(requestId) {
165454
166300
  function nativeNotFound(requestId, deviceId, layer) {
165455
166301
  const { platform } = resolveDevice(deviceId);
165456
166302
  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.`;
166303
+ if (platform === "chromium" || platform === "vega") {
166304
+ return `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.`;
166305
+ }
166306
+ const captured = layer === "android" ? hasAndroidNetworkCapture() : hasIosNetworkCapture();
166307
+ return captured ? `Request ${requestId} not found. Use native-network-logs to list the requests the ${layer === "android" ? "Android" : "iOS"} 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
166308
  }
165459
166309
  async function nativeRequestDetails(record2, bodies, includeBody) {
165460
166310
  const { wireHeaders } = record2.request;
@@ -165671,6 +166521,527 @@ function headerValue(headers, wanted) {
165671
166521
  return "";
165672
166522
  }
165673
166523
 
166524
+ // ../tool-server/src/tools/network/network-capture-start.ts
166525
+ init_src2();
166526
+ init_device_info();
166527
+ init_capability();
166528
+ var IOS_CONNECT_WAIT_MS = 5e3;
166529
+ var JS_ANSWER_WAIT_MS = 5e3;
166530
+ function createNetworkCaptureStartTool(registry2) {
166531
+ return {
166532
+ id: "network-capture-start",
166533
+ 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).
166534
+ Use when you are about to trigger requests you need to inspect, also as a step of an e2e test. Unlike native-network-logs and view-network-logs, which on iOS and Android 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.
166535
+ 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.
166536
+ Fails with NETWORK_CAPTURE_UNAVAILABLE when no layer can capture this app.`,
166537
+ zodSchema: captureSchema,
166538
+ capability: CAPTURE_CAPABILITY,
166539
+ interaction: {
166540
+ startedMsg: ({ params }) => `Starting network capture for ${params.bundleId}`,
166541
+ completedMsg: ({ params }) => `Started network capture for ${params.bundleId}`,
166542
+ failedMsg: ({ params, failureSignal: failureSignal2 }) => `Failed to start network capture for ${params.bundleId}: ${failureSignal2.error_code}`
166543
+ },
166544
+ // Each layer resolves its own service, so one that fails leaves the others running.
166545
+ services: () => ({}),
166546
+ async execute(_services, params) {
166547
+ const device = resolveDevice(params.udid);
166548
+ assertSupported("network-capture-start", CAPTURE_CAPABILITY, device);
166549
+ const port = metroPort({ device_id: params.udid, port: params.port });
166550
+ const layers = await withCaptureLock(params.udid, params.bundleId, async () => {
166551
+ if (device.platform === "ios-remote") await ensureDeps(["sim-remote"]);
166552
+ if (device.platform === "ios" && isInjectableBundleId(params.bundleId)) {
166553
+ await refuseWhileXcodeInstalls(registry2, device, params.bundleId);
166554
+ }
166555
+ return runLayers([
166556
+ device.platform !== "android" && !isInjectableBundleId(params.bundleId) ? Promise.resolve(
166557
+ unavailable2(
166558
+ "js",
166559
+ `${params.bundleId} is an Apple system app, which runs no React Native JS`
166560
+ )
166561
+ ) : startJsLayer(registry2, params.udid, params.logicalDeviceId, params.bundleId, port),
166562
+ device.platform === "android" ? startAndroidLayer(registry2, device, params.bundleId, port) : startIosLayer(registry2, device, params.bundleId, port)
166563
+ ]);
166564
+ });
166565
+ if (layers.every((layer) => layer.unavailable)) {
166566
+ const message = `Network capture cannot start for ${params.bundleId} on ${params.udid}: ` + layers.map((layer) => `${layer.layer}: ${layer.reason}`).join("; ");
166567
+ const missing = await missingNativeDep(device);
166568
+ if (missing && layers.some((layer) => layer.reason === missing.message)) {
166569
+ throw new DependencyMissingError(missing.missing, message);
166570
+ }
166571
+ throw new FailureError(message, {
166572
+ error_code: FAILURE_CODES.NETWORK_CAPTURE_UNAVAILABLE,
166573
+ failure_stage: "network_capture_start",
166574
+ failure_area: "tool_server",
166575
+ error_kind: "unsupported"
166576
+ });
166577
+ }
166578
+ return { status: "ok", layers };
166579
+ }
166580
+ };
166581
+ }
166582
+ function unavailable2(layer, reason2) {
166583
+ return { layer, armed: false, reason: reason2, unavailable: true };
166584
+ }
166585
+ async function missingNativeDep(device) {
166586
+ if (device.platform === "ios-remote") return void 0;
166587
+ try {
166588
+ await ensureDeps([device.platform === "android" ? "adb" : "xcrun"]);
166589
+ return void 0;
166590
+ } catch (err) {
166591
+ if (err instanceof DependencyMissingError) return err;
166592
+ throw err;
166593
+ }
166594
+ }
166595
+ async function refuseWhileXcodeInstalls(registry2, device, bundleId) {
166596
+ if (!xcodeFirstLaunchPending("simctl")) return;
166597
+ let api;
166598
+ try {
166599
+ const ref = nativeDevtoolsRef(device);
166600
+ api = await registry2.resolveService(ref.urn, ref.options);
166601
+ } catch {
166602
+ return;
166603
+ }
166604
+ if (api.armsEnv && !api.isConnected(bundleId)) throw new XcodeFirstLaunchPendingError("simctl");
166605
+ }
166606
+ async function startJsLayer(registry2, udid, logicalDeviceId, bundleId, port) {
166607
+ const jsDeviceId = logicalDeviceId ?? udid;
166608
+ const device = canonicalDeviceId(jsDeviceId) ?? jsDeviceId;
166609
+ const payload = jsCapturePayload(port, device);
166610
+ const found = findJsCapture(device, bundleId);
166611
+ const other = found && found.port !== port ? found : void 0;
166612
+ const installedHere = found !== void 0 && !other && found.installed;
166613
+ const recording = installedHere && found.paused !== true;
166614
+ let dbg;
166615
+ try {
166616
+ dbg = await resolveJsRuntime(registry2, udid, logicalDeviceId, port);
166617
+ } catch (err) {
166618
+ const reason2 = classifyNotConnected(err);
166619
+ const code = getFailureSignal(err)?.error_code;
166620
+ const lost = reason2 === "metro_not_running" || reason2 === "device_mismatch" || code === FAILURE_CODES.EXTERNAL_DEVICE_CAPABILITY_DENIED || code === FAILURE_CODES.EXTERNAL_DEVICE_UNAVAILABLE;
166621
+ if (other) {
166622
+ const text = `${jsNotReached(reason2, port, err)}; ${otherPortHint(bundleId, other.port)}`;
166623
+ return lost ? unavailable2("js", text) : { layer: "js", armed: false, reason: text };
166624
+ }
166625
+ if (lost && recording) {
166626
+ return {
166627
+ layer: "js",
166628
+ armed: false,
166629
+ 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`
166630
+ };
166631
+ }
166632
+ if (lost) {
166633
+ const text = jsNotReached(reason2, port, err);
166634
+ if (installedHere) return unavailable2("js", text);
166635
+ forgetJsCapture(device, bundleId);
166636
+ setJsUnavailable(payload, bundleId, text);
166637
+ return unavailable2("js", text);
166638
+ }
166639
+ setJsCapture(payload, {
166640
+ bundleId,
166641
+ intent: "started",
166642
+ mark: { install: null },
166643
+ installed: installedHere,
166644
+ physicalDeviceId: udid,
166645
+ ...installedHere && found?.paused ? { paused: true } : {}
166646
+ });
166647
+ return {
166648
+ layer: "js",
166649
+ armed: false,
166650
+ reason: `${jsNotReached(reason2, port, err)}; call network-capture-start again once the app runs`
166651
+ };
166652
+ }
166653
+ const appId = dbg.runtimeApp?.appId;
166654
+ if (appId !== void 0 && appId !== bundleId) {
166655
+ const notOurs = `the JS runtime on Metro port ${port} is ${appId}'s, not ${bundleId}'s`;
166656
+ if (recording) {
166657
+ return {
166658
+ layer: "js",
166659
+ armed: false,
166660
+ 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`
166661
+ };
166662
+ }
166663
+ if (other) return unavailable2("js", `${notOurs}; ${otherPortHint(bundleId, other.port)}`);
166664
+ const text = `${notOurs}; if that runtime is the app, pass bundleId ${appId}; otherwise pass the port of ${bundleId}'s Metro`;
166665
+ if (installedHere) return unavailable2("js", text);
166666
+ forgetJsCapture(device, bundleId);
166667
+ setJsUnavailable(payload, bundleId, text);
166668
+ return unavailable2("js", text);
166669
+ }
166670
+ const capture = {
166671
+ bundleId,
166672
+ intent: "started",
166673
+ installed: installedHere,
166674
+ physicalDeviceId: udid
166675
+ };
166676
+ setJsCapture(payload, capture);
166677
+ try {
166678
+ capture.mark = await readMark(dbg);
166679
+ } catch (err) {
166680
+ capture.mark = { install: null };
166681
+ if (installedHere && found?.paused) capture.paused = true;
166682
+ return {
166683
+ layer: "js",
166684
+ armed: false,
166685
+ reason: `the app's JS runtime did not answer (${errorMessage4(err)}); call network-capture-start again once it answers`
166686
+ };
166687
+ }
166688
+ try {
166689
+ const api = await registry2.resolveService(`NetworkInspector:${payload}`);
166690
+ const install = await installNetworkInterceptor(api.cdp, payload, dbg.runtimeApp);
166691
+ if (install.installed) return { layer: "js", armed: true };
166692
+ if (install.reason === NO_XHR_YET) {
166693
+ return {
166694
+ layer: "js",
166695
+ armed: false,
166696
+ reason: "the app's JavaScript has not loaded yet; call network-capture-start again once it has"
166697
+ };
166698
+ }
166699
+ return {
166700
+ layer: "js",
166701
+ armed: false,
166702
+ reason: `the interceptor did not install: ${install.reason}`
166703
+ };
166704
+ } catch (err) {
166705
+ return {
166706
+ layer: "js",
166707
+ armed: false,
166708
+ reason: `the interceptor did not install: ${errorMessage4(err)}`
166709
+ };
166710
+ }
166711
+ }
166712
+ async function readMark(dbg) {
166713
+ const answer = await dbg.cdp.evaluate(NETWORK_CAPTURE_MARK_SCRIPT, {
166714
+ timeout: JS_ANSWER_WAIT_MS
166715
+ });
166716
+ try {
166717
+ const parsed2 = JSON.parse(String(answer));
166718
+ return typeof parsed2.install === "string" && typeof parsed2.lastId === "number" ? { install: parsed2.install, lastId: parsed2.lastId } : { install: null };
166719
+ } catch {
166720
+ return { install: null };
166721
+ }
166722
+ }
166723
+ async function startIosLayer(registry2, device, bundleId, port) {
166724
+ if (!isInjectableBundleId(bundleId)) {
166725
+ return unavailable2(
166726
+ "ios-native",
166727
+ `${bundleId} is an Apple system app, which native network capture never covers`
166728
+ );
166729
+ }
166730
+ const notTurnedOn = (reason2) => {
166731
+ setNativeUnavailable(device.id, bundleId, reason2);
166732
+ return unavailable2("ios-native", reason2);
166733
+ };
166734
+ const missing = await missingNativeDep(device);
166735
+ if (missing) return notTurnedOn(missing.message);
166736
+ let api;
166737
+ try {
166738
+ const ref = nativeDevtoolsRef(device);
166739
+ api = await registry2.resolveService(ref.urn, ref.options);
166740
+ } catch (err) {
166741
+ return notTurnedOn(errorMessage4(err));
166742
+ }
166743
+ let block = null;
166744
+ if (!api.isConnected(bundleId)) {
166745
+ try {
166746
+ block = await precheckNativeDevtools(api, device.id, bundleId);
166747
+ } catch (err) {
166748
+ if (err instanceof XcodeFirstLaunchPendingError) throw err;
166749
+ return notTurnedOn(errorMessage4(err));
166750
+ }
166751
+ if (block?.status === "service_stale" || block?.status === "init_failed") {
166752
+ return notTurnedOn(block.message);
166753
+ }
166754
+ }
166755
+ setNativeUnavailable(device.id, bundleId);
166756
+ const armed = await api.startNetworkCapture(
166757
+ bundleId,
166758
+ port,
166759
+ // A lent agent says whether the provider has capture on only after it connects.
166760
+ block?.status === "connect_pending" || !api.armsEnv ? IOS_CONNECT_WAIT_MS : 0
166761
+ );
166762
+ if (armed) return { layer: "ios-native", armed: true };
166763
+ if (api.isConnected(bundleId)) {
166764
+ const note = api.networkRecords(bundleId)?.state().note;
166765
+ if (note === PROVIDER_CAPTURE_OFF) return unavailable2("ios-native", note);
166766
+ return {
166767
+ layer: "ios-native",
166768
+ armed: false,
166769
+ reason: note ?? "waiting for the agent to acknowledge Network.enable"
166770
+ };
166771
+ }
166772
+ if (!api.armsEnv) {
166773
+ return {
166774
+ layer: "ios-native",
166775
+ armed: false,
166776
+ reason: "the app has not connected through the device's devtools agent; it arms when it does"
166777
+ };
166778
+ }
166779
+ return {
166780
+ layer: "ios-native",
166781
+ armed: false,
166782
+ 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"
166783
+ };
166784
+ }
166785
+ async function startAndroidLayer(registry2, device, bundleId, port) {
166786
+ const notTurnedOn = (reason2) => {
166787
+ setNativeUnavailable(device.id, bundleId, reason2);
166788
+ return unavailable2("android-native", reason2);
166789
+ };
166790
+ const missing = await missingNativeDep(device);
166791
+ if (missing) return notTurnedOn(missing.message);
166792
+ let api;
166793
+ try {
166794
+ const ref = androidNetworkInspectorRef(device, bundleId, port);
166795
+ api = await registry2.resolveService(ref.urn, ref.options);
166796
+ } catch (err) {
166797
+ return notTurnedOn(errorMessage4(err));
166798
+ }
166799
+ setNativeUnavailable(device.id, bundleId);
166800
+ const started = await api.startCapture(port);
166801
+ if (started.unavailable) return unavailable2("android-native", started.reason ?? "unavailable");
166802
+ return {
166803
+ layer: "android-native",
166804
+ armed: started.armed,
166805
+ ...started.reason ? { reason: started.reason } : {}
166806
+ };
166807
+ }
166808
+
166809
+ // ../tool-server/src/tools/network/network-capture-stop.ts
166810
+ init_device_info();
166811
+ init_capability();
166812
+ var NOT_STARTED2 = "capture was not started for this app";
166813
+ var JS_ANSWER_WAIT_MS2 = 5e3;
166814
+ function createNetworkCaptureStopTool(registry2) {
166815
+ return {
166816
+ id: "network-capture-stop",
166817
+ description: `Stop network capture for an app on every layer and keep what was captured.
166818
+ 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).
166819
+ 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 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.
166820
+ 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.`,
166821
+ zodSchema: captureSchema,
166822
+ capability: CAPTURE_CAPABILITY,
166823
+ interaction: {
166824
+ startedMsg: ({ params }) => `Stopping network capture for ${params.bundleId}`,
166825
+ completedMsg: ({ params }) => `Stopped network capture for ${params.bundleId}`,
166826
+ failedMsg: ({ params, failureSignal: failureSignal2 }) => `Failed to stop network capture for ${params.bundleId}: ${failureSignal2.error_code}`
166827
+ },
166828
+ // A stop must not create the services it stops, so each layer looks them up itself.
166829
+ services: () => ({}),
166830
+ async execute(_services, params) {
166831
+ const device = resolveDevice(params.udid);
166832
+ assertSupported("network-capture-stop", CAPTURE_CAPABILITY, device);
166833
+ const port = metroPort({ device_id: params.udid, port: params.port });
166834
+ const layers = await withCaptureLock(
166835
+ params.udid,
166836
+ params.bundleId,
166837
+ () => runLayers([
166838
+ device.platform !== "android" && !isInjectableBundleId(params.bundleId) ? Promise.resolve({
166839
+ layer: "js",
166840
+ armed: false,
166841
+ total: 0,
166842
+ reason: `${params.bundleId} is an Apple system app, which runs no React Native JS`
166843
+ }) : stopJsLayer(registry2, params.udid, params.logicalDeviceId, params.bundleId, port),
166844
+ device.platform === "android" ? stopAndroidLayer(registry2, device, params.bundleId, port) : stopIosLayer(registry2, device, params.bundleId, port)
166845
+ ])
166846
+ );
166847
+ return { status: "ok", layers };
166848
+ }
166849
+ };
166850
+ }
166851
+ async function stopJsLayer(registry2, udid, logicalDeviceId, bundleId, port) {
166852
+ const jsDeviceId = logicalDeviceId ?? udid;
166853
+ const device = canonicalDeviceId(jsDeviceId) ?? jsDeviceId;
166854
+ const payload = jsCapturePayload(port, device);
166855
+ const prior = findJsCapture(device, bundleId);
166856
+ const kept = prior?.port === port ? prior : void 0;
166857
+ const other = prior && !kept ? prior : void 0;
166858
+ const otherArmed = other !== void 0 && (other.intent === "started" || other.installed && other.paused !== true);
166859
+ const here = jsCapture(payload);
166860
+ if (here && here.bundleId !== bundleId) {
166861
+ const stays = `the capture of ${here.bundleId} on Metro port ${port} stays as it is`;
166862
+ if (other) {
166863
+ return {
166864
+ layer: "js",
166865
+ armed: otherArmed,
166866
+ total: 0,
166867
+ reason: `${stays}; ${otherPortHint(bundleId, other.port)}`
166868
+ };
166869
+ }
166870
+ return { layer: "js", armed: false, total: 0, reason: `${NOT_STARTED2}; ${stays}` };
166871
+ }
166872
+ const storeStopped = (paused) => {
166873
+ const capture = {
166874
+ bundleId,
166875
+ intent: "stopped",
166876
+ ...kept?.mark ? { mark: kept.mark } : {},
166877
+ installed: kept?.installed ?? false,
166878
+ ...paused ? { paused: true } : {},
166879
+ physicalDeviceId: udid
166880
+ };
166881
+ setJsCapture(payload, capture);
166882
+ return capture;
166883
+ };
166884
+ const endedWithApp = async (stored2) => {
166885
+ if (await appRuns(udid, bundleId) !== false) return void 0;
166886
+ stored2.installed = false;
166887
+ return `${bundleId} is not running, so nothing records; while capture is stopped, its next JS runtime gets no interceptor`;
166888
+ };
166889
+ let dbg;
166890
+ try {
166891
+ dbg = await resolveJsRuntime(registry2, udid, logicalDeviceId, port);
166892
+ } catch (err) {
166893
+ const notReached = jsNotReached(classifyNotConnected(err), port, err);
166894
+ if (other) {
166895
+ return {
166896
+ layer: "js",
166897
+ armed: otherArmed,
166898
+ total: 0,
166899
+ reason: `${notReached}; ${otherPortHint(bundleId, other.port)}`
166900
+ };
166901
+ }
166902
+ if (!prior) {
166903
+ return { layer: "js", armed: false, total: 0, reason: `${notReached}; ${NOT_STARTED2}` };
166904
+ }
166905
+ const stored2 = storeStopped(kept?.paused === true);
166906
+ const unconfirmed = kept?.installed === true && kept.paused !== true;
166907
+ const ended = unconfirmed ? await endedWithApp(stored2) : void 0;
166908
+ if (ended) return { layer: "js", armed: false, total: 0, reason: `${notReached}; ${ended}` };
166909
+ return {
166910
+ layer: "js",
166911
+ armed: unconfirmed,
166912
+ total: 0,
166913
+ 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`
166914
+ };
166915
+ }
166916
+ const appId = dbg.runtimeApp?.appId;
166917
+ if (appId !== void 0 && appId !== bundleId) {
166918
+ const notOurs = `the JS runtime on Metro port ${port} is ${appId}'s, not ${bundleId}'s`;
166919
+ if (other) {
166920
+ return {
166921
+ layer: "js",
166922
+ armed: otherArmed,
166923
+ total: 0,
166924
+ reason: `${notOurs}, so nothing changed there; ${otherPortHint(bundleId, other.port)}`
166925
+ };
166926
+ }
166927
+ if (!kept) {
166928
+ return {
166929
+ layer: "js",
166930
+ armed: false,
166931
+ total: 0,
166932
+ reason: `${notOurs}, so nothing changed there; if that runtime is the app, pass bundleId ${appId}; otherwise pass the port of ${bundleId}'s Metro`
166933
+ };
166934
+ }
166935
+ const stored2 = storeStopped(kept.paused === true);
166936
+ const unconfirmed = kept.installed && kept.paused !== true;
166937
+ const ended = unconfirmed ? await endedWithApp(stored2) : void 0;
166938
+ if (ended) return { layer: "js", armed: false, total: 0, reason: `${notOurs}; ${ended}` };
166939
+ return {
166940
+ layer: "js",
166941
+ armed: unconfirmed,
166942
+ total: 0,
166943
+ 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`
166944
+ };
166945
+ }
166946
+ const stored = storeStopped(false);
166947
+ try {
166948
+ await dbg.cdp.evaluate(makeNetworkCaptureControlScript(true), { timeout: JS_ANSWER_WAIT_MS2 });
166949
+ } catch (err) {
166950
+ return {
166951
+ layer: "js",
166952
+ armed: true,
166953
+ total: 0,
166954
+ reason: `the app's JS runtime did not pause capture: ${errorMessage4(err)}`
166955
+ };
166956
+ }
166957
+ stored.paused = true;
166958
+ try {
166959
+ const { total, interceptorInstalled } = JSON.parse(
166960
+ String(await dbg.cdp.evaluate(makeNetworkLogReadScript(0, 0, port)))
166961
+ );
166962
+ return {
166963
+ layer: "js",
166964
+ armed: false,
166965
+ total: interceptorInstalled ? total : 0,
166966
+ ...prior ? {} : { reason: NOT_STARTED2 }
166967
+ };
166968
+ } catch (err) {
166969
+ const uncounted = `the app's JS runtime paused capture, but did not answer the count of its requests: ${errorMessage4(err)}`;
166970
+ return {
166971
+ layer: "js",
166972
+ armed: false,
166973
+ total: 0,
166974
+ reason: prior ? uncounted : `${uncounted}; ${NOT_STARTED2}`
166975
+ };
166976
+ }
166977
+ }
166978
+ async function appRuns(udid, bundleId) {
166979
+ const { platform } = resolveDevice(udid);
166980
+ try {
166981
+ if (platform === "android") {
166982
+ return (await readAppProcesses(udid, bundleId)).processes.length > 0;
166983
+ }
166984
+ if (platform === "ios") return (await localIosHost.listRunningBundleIds(udid)).has(bundleId);
166985
+ if (platform === "ios-remote") {
166986
+ let timer;
166987
+ const late = new Promise((resolve21) => {
166988
+ timer = setTimeout(() => resolve21(void 0), SIMCTL_SPAWN_TIMEOUT_MS);
166989
+ });
166990
+ try {
166991
+ return (await Promise.race([remoteIosHost.listRunningBundleIds(udid), late]))?.has(
166992
+ bundleId
166993
+ );
166994
+ } finally {
166995
+ clearTimeout(timer);
166996
+ }
166997
+ }
166998
+ } catch {
166999
+ }
167000
+ return void 0;
167001
+ }
167002
+ async function stopIosLayer(registry2, device, bundleId, port) {
167003
+ if (!isInjectableBundleId(bundleId)) {
167004
+ return {
167005
+ layer: "ios-native",
167006
+ armed: false,
167007
+ total: 0,
167008
+ reason: `${bundleId} is an Apple system app, which native network capture never covers`
167009
+ };
167010
+ }
167011
+ const ref = nativeDevtoolsRef(device);
167012
+ if (!isLiveService(registry2, ref.urn)) {
167013
+ return { layer: "ios-native", armed: false, total: 0, reason: NOT_STARTED2 };
167014
+ }
167015
+ const api = await registry2.resolveService(ref.urn, ref.options);
167016
+ if (!api.isNetworkCaptureStarted(bundleId) && !api.isNetworkCaptureStopped(bundleId)) {
167017
+ return { layer: "ios-native", armed: false, total: 0, reason: NOT_STARTED2 };
167018
+ }
167019
+ const { confirmed, reason: reason2 } = await api.stopNetworkCapture(bundleId);
167020
+ return {
167021
+ layer: "ios-native",
167022
+ armed: !confirmed,
167023
+ total: api.networkRecords(bundleId)?.records(port).length ?? 0,
167024
+ ...reason2 ? { reason: reason2 } : {}
167025
+ };
167026
+ }
167027
+ async function stopAndroidLayer(registry2, device, bundleId, port) {
167028
+ const ref = androidNetworkInspectorRef(device, bundleId, port);
167029
+ if (!isLiveService(registry2, ref.urn)) {
167030
+ return { layer: "android-native", armed: false, total: 0, reason: NOT_STARTED2 };
167031
+ }
167032
+ const api = await registry2.resolveService(ref.urn, ref.options);
167033
+ if (!api.isStarted() && !api.isStopped()) {
167034
+ return { layer: "android-native", armed: false, total: 0, reason: NOT_STARTED2 };
167035
+ }
167036
+ const { confirmed, reason: reason2 } = await api.stopCapture();
167037
+ return {
167038
+ layer: "android-native",
167039
+ armed: !confirmed,
167040
+ total: api.records(port).length,
167041
+ ...reason2 ? { reason: reason2 } : {}
167042
+ };
167043
+ }
167044
+
165674
167045
  // ../tool-server/src/tools/describe/index.ts
165675
167046
  init_zod();
165676
167047
 
@@ -167255,7 +168626,7 @@ init_zod();
167255
168626
  init_src2();
167256
168627
 
167257
168628
  // ../tool-server/src/utils/debugger/runtime-device.ts
167258
- var import_node_crypto16 = require("node:crypto");
168629
+ var import_node_crypto17 = require("node:crypto");
167259
168630
  var import_node_child_process46 = require("node:child_process");
167260
168631
  var import_node_util35 = require("node:util");
167261
168632
  init_adb();
@@ -167268,7 +168639,7 @@ async function findRuntimeDevices(cdp, {
167268
168639
  awaitSerials = [],
167269
168640
  waitSerials = []
167270
168641
  } = {}) {
167271
- const marker = `argent-device-probe:${(0, import_node_crypto16.randomUUID)()}`;
168642
+ const marker = `argent-device-probe:${(0, import_node_crypto17.randomUUID)()}`;
167272
168643
  const logged = await cdp.evaluate(
167273
168644
  `(function () {
167274
168645
  if (typeof nativeLoggingHook !== "function") return false;
@@ -167432,7 +168803,7 @@ function bootstrapFailureMessage(bootstrap) {
167432
168803
  // ../tool-server/src/utils/profiler-shared/network-capture-warning.ts
167433
168804
  var CAPTURE_COST = "It can slow the app, so the timings in this profile can differ from a run without it.";
167434
168805
  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}.`;
168806
+ 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
168807
  }
167437
168808
  function nativeNetworkCaptureWarning(deviceId, runtimeApp, runtimeDevices = { found: [], unresolved: [] }) {
167438
168809
  try {
@@ -167448,7 +168819,7 @@ function nativeNetworkCaptureWarning(deviceId, runtimeApp, runtimeDevices = { fo
167448
168819
  if (packages.length === 0) return logicalDeviceWarning(deviceId, runtimeApp);
167449
168820
  const apps = packages.join(", ");
167450
168821
  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";
168822
+ const remedy = `call network-capture-stop for ${one ? "that app" : "each of these apps"}`;
167452
168823
  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
168824
  } catch {
167454
168825
  return void 0;
@@ -167458,7 +168829,8 @@ function foundDeviceWarning({ found, unresolved }, runtimeApp) {
167458
168829
  const iosApps = found.length === 1 ? liveIosNetworkCaptures(found[0]) : [];
167459
168830
  if (iosApps.length > 0) {
167460
168831
  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.`;
168832
+ const one = iosApps.length === 1;
168833
+ 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
168834
  }
167463
168835
  const captures = found.map((device) => ({ device, packages: liveAndroidNetworkCaptures(device) })).filter(({ packages }) => packages.length > 0);
167464
168836
  const appId = runtimeApp?.platform === "android" ? runtimeApp.appId : void 0;
@@ -167470,22 +168842,22 @@ function foundDeviceWarning({ found, unresolved }, runtimeApp) {
167470
168842
  const apps = [...new Set(captures.flatMap(({ packages }) => packages))].sort();
167471
168843
  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
168844
  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"}.`
168845
+ `Native network capture is on for ${apps.join(", ")} on ${where}: ` + agentSentence("android", apps.length === 1)
167474
168846
  );
167475
168847
  }
167476
168848
  if (appId && maybe.length > 0) {
167477
168849
  const one = maybe.length === 1;
167478
168850
  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.`
168851
+ `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
168852
  );
167481
168853
  }
167482
168854
  const stops = [
167483
168855
  ...captures.flatMap(({ device, packages }) => packages.map((app) => ({ app, device }))),
167484
168856
  ...appId ? maybe.map((device) => ({ app: appId, device })) : []
167485
168857
  ];
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(", ")}`;
168858
+ 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
168859
  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.`;
168860
+ 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
168861
  }
167490
168862
  function logicalDeviceWarning(deviceId, runtimeApp) {
167491
168863
  const appId = runtimeApp?.appId;
@@ -167496,7 +168868,7 @@ function logicalDeviceWarning(deviceId, runtimeApp) {
167496
168868
  if (devices2.length === 0) return void 0;
167497
168869
  const one = devices2.length === 1;
167498
168870
  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}`;
168871
+ const remedy = `call network-capture-stop for ${appId} on ${those}`;
167500
168872
  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
168873
  }
167502
168874
 
@@ -167586,7 +168958,7 @@ function createReactProfilerStartTool(registry2) {
167586
168958
  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
168959
  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
168960
  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.
168961
+ 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
168962
  Fails if the Hermes runtime is not reachable or the Metro CDP connection cannot be established.`,
167591
168963
  zodSchema: zodSchema45,
167592
168964
  interaction: {
@@ -175935,7 +177307,7 @@ var nativeProfilerStartTool = {
175935
177307
  longRunning: true,
175936
177308
  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
177309
  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.
177310
+ 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
177311
  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
177312
  zodSchema: zodSchema53,
175941
177313
  interaction: {
@@ -176115,7 +177487,7 @@ var import_node_child_process48 = require("node:child_process");
176115
177487
  var import_node_util38 = require("node:util");
176116
177488
  var fsp5 = __toESM(require("node:fs/promises"));
176117
177489
  var path49 = __toESM(require("node:path"));
176118
- var import_node_crypto17 = require("node:crypto");
177490
+ var import_node_crypto18 = require("node:crypto");
176119
177491
  init_src2();
176120
177492
 
176121
177493
  // ../tool-server/src/utils/ios-launch-time/workflow.ts
@@ -176698,7 +178070,7 @@ async function measurePreparedLaunch(context2, ctx) {
176698
178070
  const runnerSigning = context2.simulator ? null : await resolveRunnerSigningConfig(context2.deviceId);
176699
178071
  const runnerBundleId = runnerSigning?.appBundleId ?? "com.argent.runner.tsimulator";
176700
178072
  const testBundleId = runnerSigning?.testBundleId ?? `${runnerBundleId}.uitests`;
176701
- const runnerBuildKey = (0, import_node_crypto17.createHash)("sha256").update(
178073
+ const runnerBuildKey = (0, import_node_crypto18.createHash)("sha256").update(
176702
178074
  [
176703
178075
  // Builds for two simulators, or two iPhones, are the same build.
176704
178076
  context2.simulator ? "iOS Simulator" : "iOS",
@@ -176837,7 +178209,7 @@ async function measurePreparedLaunch(context2, ctx) {
176837
178209
 
176838
178210
  // ../tool-server/src/tools/profiler/native-profiler/launch-analysis/profile.ts
176839
178211
  var import_node_child_process49 = require("node:child_process");
176840
- var import_node_crypto18 = require("node:crypto");
178212
+ var import_node_crypto19 = require("node:crypto");
176841
178213
  var import_node_util39 = require("node:util");
176842
178214
  var fsp6 = __toESM(require("node:fs/promises"));
176843
178215
  var path50 = __toESM(require("node:path"));
@@ -177085,7 +178457,7 @@ var TABLE_XPATH = (schema) => `/trace-toc/run[@number="1"]/data/table[@schema="$
177085
178457
  async function writeProfilerSession(xml) {
177086
178458
  const debugDir = await getDebugDir();
177087
178459
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
177088
- const sessionId = `${timestamp}-launch-${(0, import_node_crypto18.randomUUID)()}`;
178460
+ const sessionId = `${timestamp}-launch-${(0, import_node_crypto19.randomUUID)()}`;
177089
178461
  const cpuXmlPath = path50.join(debugDir, `native-profiler-${sessionId}_raw_cpu.xml`);
177090
178462
  await fsp6.writeFile(cpuXmlPath, xml, { flag: "wx" });
177091
178463
  return { sessionId, cpuXmlPath };
@@ -177425,7 +178797,7 @@ init_zod();
177425
178797
  var import_node_child_process50 = require("node:child_process");
177426
178798
  var fs62 = __toESM(require("node:fs"));
177427
178799
  var path51 = __toESM(require("node:path"));
177428
- var import_node_crypto19 = require("node:crypto");
178800
+ var import_node_crypto20 = require("node:crypto");
177429
178801
  var import_node_util40 = require("node:util");
177430
178802
  init_src2();
177431
178803
  init_capability();
@@ -177641,7 +179013,7 @@ async function setAudioInput(session, source) {
177641
179013
  } else {
177642
179014
  removeFiles(dir, `in-${process.pid}-`);
177643
179015
  feeder = new InputFeeder(
177644
- path51.join(dir, `in-${process.pid}-${(0, import_node_crypto19.randomUUID)().slice(0, 8)}.ring`),
179016
+ path51.join(dir, `in-${process.pid}-${(0, import_node_crypto20.randomUUID)().slice(0, 8)}.ring`),
177645
179017
  feederSource
177646
179018
  );
177647
179019
  feeder.start();
@@ -181714,6 +183086,10 @@ var PORT_KEYED_NAMESPACES = [
181714
183086
  REACT_PROFILER_SESSION_NAMESPACE
181715
183087
  ];
181716
183088
  var APP_KEYED_NAMESPACES = [ANDROID_NETWORK_INSPECTOR_NAMESPACE];
183089
+ var NATIVE_ID_KEYED_NAMESPACES = [
183090
+ ...APP_KEYED_NAMESPACES,
183091
+ NATIVE_DEVTOOLS_NAMESPACE
183092
+ ];
181717
183093
  var DEVICE_OWNED_NAMESPACES = [
181718
183094
  SIMULATOR_SERVER_NAMESPACE,
181719
183095
  IOS_DEVICE_RUNNER_NAMESPACE,
@@ -181754,7 +183130,7 @@ function deviceIdOwningUrn(urn, namespaces, deviceIds) {
181754
183130
  if (portion === void 0) continue;
181755
183131
  const tail = portion.toLowerCase();
181756
183132
  const owner = deviceIds.find((id) => {
181757
- const spellings = APP_KEYED_NAMESPACES.includes(namespace) ? [id, externalNativeId(id)] : [id];
183133
+ const spellings = NATIVE_ID_KEYED_NAMESPACES.includes(namespace) ? [id, externalNativeId(id)] : [id];
181758
183134
  return spellings.some((spelling) => {
181759
183135
  const lower = spelling.toLowerCase();
181760
183136
  return URN_SUFFIXES.some((suffix) => tail === `${lower}${suffix}`);
@@ -181774,6 +183150,13 @@ function deviceIdOfUrn(urn, namespaces) {
181774
183150
  }
181775
183151
  return void 0;
181776
183152
  }
183153
+ function isProviderOwnedUrn(urn) {
183154
+ if (isExternalDeviceUrn(urn)) return true;
183155
+ const portion = deviceIdOfUrn(urn, [NATIVE_DEVTOOLS_NAMESPACE]);
183156
+ if (portion === void 0) return false;
183157
+ const suffix = URN_SUFFIXES.find((s) => s !== "" && portion.endsWith(s)) ?? "";
183158
+ return externalClaimForNativeId(portion.slice(0, portion.length - suffix.length)) !== void 0;
183159
+ }
181777
183160
  function unnameableSessionUrns(urns) {
181778
183161
  return urns.filter((urn) => isLogicalKeyedDevice(deviceIdOfUrn(urn, PORT_KEYED_NAMESPACES)));
181779
183162
  }
@@ -181823,7 +183206,6 @@ function createStopSimulatorServerTool(registry2) {
181823
183206
  // ../tool-server/src/tools/simulator/stop-all-simulator-servers.ts
181824
183207
  init_zod();
181825
183208
  init_src2();
181826
- init_external_devices();
181827
183209
  var zodSchema66 = external_exports.object({
181828
183210
  devices: external_exports.array(external_exports.string()).optional().describe(
181829
183211
  "Ids of the devices THIS session used (iOS UDID / Android serial / Chromium id), to scope the teardown to."
@@ -181832,7 +183214,7 @@ var zodSchema66 = external_exports.object({
181832
183214
  function createStopAllSimulatorServersTool(registry2) {
181833
183215
  return {
181834
183216
  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.
183217
+ 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.<flag:macos-apps> On a Mac app it also ends the native-network-logs capture and drops its log; network-capture-stop does not apply there.</flag:macos-apps>
181836
183218
  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
183219
  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
183220
  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 +183251,52 @@ Fails if the input has an unknown key (e.g. \`udids\` instead of \`devices\`); o
181869
183251
  async execute(_services, params, ctx) {
181870
183252
  const devices2 = params.devices;
181871
183253
  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;
183254
+ return withCaptureSweep(scoped ? devices2 : void 0, { signal: ctx?.signal }, async () => {
183255
+ if (ctx?.signal?.aborted) return { stopped: [], aborted: true };
183256
+ const stopped = [];
183257
+ const matchedIds = /* @__PURE__ */ new Set();
183258
+ const survivors = [];
183259
+ let aborted2 = false;
183260
+ const paused = await pauseJsCapturesOf(registry2, scoped ? devices2 : void 0);
183261
+ const snapshot = registry2.getSnapshot();
183262
+ for (const [urn, entry] of snapshot.services) {
183263
+ if (ctx?.signal?.aborted) {
183264
+ aborted2 = true;
183265
+ break;
183266
+ }
183267
+ const matchedId = scoped ? deviceIdOwningUrn(urn, DEVICE_OWNED_NAMESPACES, devices2) : void 0;
183268
+ const matches2 = scoped ? matchedId !== void 0 : isDeviceServiceUrn(urn, DEVICE_OWNED_NAMESPACES);
183269
+ if (matchedId !== void 0) matchedIds.add(matchedId.toLowerCase());
183270
+ if (matches2 && entry.state !== "IDLE" /* IDLE */) {
183271
+ const wasLive = isLiveServiceState(entry.state);
183272
+ await registry2.disposeService(urn);
183273
+ if (wasLive && !isProviderOwnedUrn(urn)) stopped.push(urn);
183274
+ } else if (scoped && isLiveServiceState(entry.state) && isDeviceServiceUrn(urn, PORT_KEYED_NAMESPACES)) {
183275
+ survivors.push(urn);
183276
+ }
181881
183277
  }
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);
183278
+ if (aborted2) {
183279
+ forgetJsCaptures(paused);
183280
+ return { stopped, aborted: true };
181891
183281
  }
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;
183282
+ forgetJsCapturesOf(scoped ? devices2 : void 0, paused);
183283
+ forgetNativeUnavailableOf(scoped ? devices2 : void 0);
183284
+ if (!scoped) return { stopped };
183285
+ const seen = /* @__PURE__ */ new Set();
183286
+ const unmatched = devices2.filter((id) => {
183287
+ const key2 = id.toLowerCase();
183288
+ if (matchedIds.has(key2) || seen.has(key2)) return false;
183289
+ seen.add(key2);
183290
+ return true;
183291
+ });
183292
+ const leftRunning = unnameableSessionUrns(survivors);
183293
+ const result = {
183294
+ stopped
183295
+ };
183296
+ if (unmatched.length > 0) result.unmatched = unmatched;
183297
+ if (leftRunning.length > 0) result.left_running = leftRunning;
183298
+ return result;
181901
183299
  });
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
183300
  }
181910
183301
  };
181911
183302
  }
@@ -188485,7 +189876,7 @@ var FlowScriptExecutor = class {
188485
189876
  );
188486
189877
  } catch (err) {
188487
189878
  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 });
189879
+ return err instanceof ScriptCancelledError ? emptyResult({ kind: "cancelled", message: err.message }, { queuedMs: queuedMs2 }) : emptyResult({ kind: "queue", message: errorMessage5(err) }, { queuedMs: queuedMs2 });
188489
189880
  }
188490
189881
  const queuedMs = Date.now() - queueStarted;
188491
189882
  try {
@@ -188597,7 +189988,7 @@ var FlowScriptExecutor = class {
188597
189988
  } catch (err) {
188598
189989
  const kind = err instanceof ScriptSetupError ? err.kind : "spawn";
188599
189990
  return emptyResult(
188600
- { kind, message: errorMessage4(err) },
189991
+ { kind, message: errorMessage5(err) },
188601
189992
  { notes, durationMs: Date.now() - startedAt }
188602
189993
  );
188603
189994
  }
@@ -188657,7 +190048,7 @@ var FlowScriptExecutor = class {
188657
190048
  child = (0, import_node_child_process52.fork)(scriptPath, [], forkOptions);
188658
190049
  } catch (err) {
188659
190050
  return emptyResult(
188660
- { kind: "spawn", message: `Could not start the script process: ${errorMessage4(err)}` },
190051
+ { kind: "spawn", message: `Could not start the script process: ${errorMessage5(err)}` },
188661
190052
  { notes, durationMs: Date.now() - startedAt }
188662
190053
  );
188663
190054
  }
@@ -188673,7 +190064,7 @@ var FlowScriptExecutor = class {
188673
190064
  (resolve21) => {
188674
190065
  child.once("exit", (code, signal) => resolve21({ code, signal }));
188675
190066
  child.once("error", (err) => {
188676
- spawnProblem ??= `Could not start the script process: ${errorMessage4(err)}`;
190067
+ spawnProblem ??= `Could not start the script process: ${errorMessage5(err)}`;
188677
190068
  resolve21({ code: null, signal: null });
188678
190069
  });
188679
190070
  }
@@ -188720,11 +190111,11 @@ var FlowScriptExecutor = class {
188720
190111
  try {
188721
190112
  child.send(message, (err) => {
188722
190113
  if (!err) return;
188723
- protocolProblem ??= `The script runner closed its channel before the request arrived: ${errorMessage4(err)}`;
190114
+ protocolProblem ??= `The script runner closed its channel before the request arrived: ${errorMessage5(err)}`;
188724
190115
  void stop();
188725
190116
  });
188726
190117
  } catch (err) {
188727
- protocolProblem ??= `The script runner could not be given its request: ${errorMessage4(err)}`;
190118
+ protocolProblem ??= `The script runner could not be given its request: ${errorMessage5(err)}`;
188728
190119
  void stop();
188729
190120
  }
188730
190121
  const exit = await exited;
@@ -188869,7 +190260,7 @@ function commitOutput(outputJson) {
188869
190260
  try {
188870
190261
  parsed2 = JSON.parse(outputJson);
188871
190262
  } catch (err) {
188872
- return failed2("output", `The script's output did not parse: ${errorMessage4(err)}`);
190263
+ return failed2("output", `The script's output did not parse: ${errorMessage5(err)}`);
188873
190264
  }
188874
190265
  if (typeof parsed2 !== "object" || parsed2 === null || Array.isArray(parsed2)) {
188875
190266
  return failed2("output", "The script's output was not an object.");
@@ -188995,7 +190386,7 @@ function encodeRequestOutput(output2) {
188995
190386
  } catch (err) {
188996
190387
  throw new ScriptSetupError(
188997
190388
  "invalid",
188998
- `The e2e test output could not be encoded for the script: ${errorMessage4(err)}`
190389
+ `The e2e test output could not be encoded for the script: ${errorMessage5(err)}`
188999
190390
  );
189000
190391
  }
189001
190392
  if (typeof encoded !== "string") {
@@ -189394,7 +190785,7 @@ function emptyResult(failure2, extras = {}) {
189394
190785
  notes: extras.notes ?? []
189395
190786
  };
189396
190787
  }
189397
- function errorMessage4(err) {
190788
+ function errorMessage5(err) {
189398
190789
  if (err instanceof Error) return formatErrorForAgent(err) || String(err);
189399
190790
  return typeof err === "string" ? err : describeUnknown(err);
189400
190791
  }
@@ -189968,7 +191359,7 @@ init_device_info();
189968
191359
  init_capability();
189969
191360
 
189970
191361
  // ../tool-server/src/tools/flows/flow-visual.ts
189971
- var import_node_crypto20 = require("node:crypto");
191362
+ var import_node_crypto21 = require("node:crypto");
189972
191363
  var fs79 = __toESM(require("node:fs/promises"));
189973
191364
  var os25 = __toESM(require("node:os"));
189974
191365
  var path65 = __toESM(require("node:path"));
@@ -192092,7 +193483,7 @@ async function runSnapshot(env, opts) {
192092
193483
  });
192093
193484
  let captureWarned = shot.warning !== void 0 ? { warning: shot.warning } : {};
192094
193485
  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)}`;
193486
+ const cropSuffix = opts.cropOn === void 0 ? "" : `-crop-${(0, import_node_crypto21.createHash)("sha256").update(cropIdentity(opts.cropOn)).digest("hex").slice(0, 8)}`;
192096
193487
  const keyFor = (width, height) => `${opts.name}__${authoringPlatform(env.device.platform)}-${width}x${height}${cropSuffix}`;
192097
193488
  const baselineFor = (file2) => opts.clientFlowPath === void 0 ? path65.join(baselineDir(opts.flowsDir, opts.flowName), file2) : clientBaselinePath(opts.clientFlowPath, opts.flowName, file2);
192098
193489
  const snapshotKey = keyFor(w, h);
@@ -194655,9 +196046,9 @@ var dismissUpdateTool = {
194655
196046
  };
194656
196047
 
194657
196048
  // ../tool-server/src/tools/screenshot-diff/index.ts
194658
- var import_node_crypto21 = __toESM(require("node:crypto"));
196049
+ var import_node_crypto22 = __toESM(require("node:crypto"));
194659
196050
  var import_promises23 = __toESM(require("fs/promises"));
194660
- var import_node_os18 = __toESM(require("node:os"));
196051
+ var import_node_os19 = __toESM(require("node:os"));
194661
196052
  var import_path9 = __toESM(require("path"));
194662
196053
  init_zod();
194663
196054
  init_src2();
@@ -194809,9 +196200,9 @@ async function resolveOutputDir(params, options) {
194809
196200
  }
194810
196201
  }
194811
196202
  const dir = import_path9.default.join(
194812
- import_node_os18.default.tmpdir(),
196203
+ import_node_os19.default.tmpdir(),
194813
196204
  "argent-screenshot-diff",
194814
- import_node_crypto21.default.randomBytes(6).toString("hex")
196205
+ import_node_crypto22.default.randomBytes(6).toString("hex")
194815
196206
  );
194816
196207
  await import_promises23.default.mkdir(dir, { recursive: true });
194817
196208
  return dir;
@@ -194916,7 +196307,7 @@ async function captureIosDeviceLiveInput(params) {
194916
196307
  return writeLivePng(params.outputDir, params.name, png);
194917
196308
  }
194918
196309
  async function writeLivePng(outputDir, name, png) {
194919
- const suffix = import_node_crypto21.default.randomBytes(4).toString("hex");
196310
+ const suffix = import_node_crypto22.default.randomBytes(4).toString("hex");
194920
196311
  const destination = import_path9.default.join(outputDir, `${name}-${suffix}.live.png`);
194921
196312
  await import_promises23.default.mkdir(outputDir, { recursive: true });
194922
196313
  await import_promises23.default.writeFile(destination, png);
@@ -194934,7 +196325,7 @@ async function captureHarmonyLiveInput(params) {
194934
196325
  }
194935
196326
  await ensureDep("hdc");
194936
196327
  const captured = await captureHarmonyScreenshotPng({ connectKey: params.connectKey, scale: 1 });
194937
- const suffix = import_node_crypto21.default.randomBytes(4).toString("hex");
196328
+ const suffix = import_node_crypto22.default.randomBytes(4).toString("hex");
194938
196329
  const destination = import_path9.default.join(params.outputDir, `${params.name}-${suffix}.live.png`);
194939
196330
  try {
194940
196331
  await import_promises23.default.mkdir(params.outputDir, { recursive: true });
@@ -194957,7 +196348,7 @@ async function captureLiveInput(params) {
194957
196348
  captureScreenshot2,
194958
196349
  params.peekFor?.(params.device)
194959
196350
  );
194960
- const suffix = import_node_crypto21.default.randomBytes(4).toString("hex");
196351
+ const suffix = import_node_crypto22.default.randomBytes(4).toString("hex");
194961
196352
  const destination = import_path9.default.join(params.outputDir, `${params.name}-${suffix}.live.png`);
194962
196353
  await import_promises23.default.mkdir(params.outputDir, { recursive: true });
194963
196354
  await import_promises23.default.copyFile(capture.path, destination);
@@ -195973,6 +197364,8 @@ function createRegistry() {
195973
197364
  registry2.registerTool(createDebuggerLogRegistryTool(registry2));
195974
197365
  registry2.registerTool(networkLogsTool);
195975
197366
  registry2.registerTool(networkRequestTool);
197367
+ registry2.registerTool(createNetworkCaptureStartTool(registry2));
197368
+ registry2.registerTool(createNetworkCaptureStopTool(registry2));
195976
197369
  registry2.registerTool(createDescribeTool(registry2));
195977
197370
  registry2.registerTool(createUiTreeTool(registry2));
195978
197371
  registry2.registerTool(createForegroundAppTool(registry2));
@@ -196182,6 +197575,7 @@ function createPreviewWindowManager(opts = {}) {
196182
197575
 
196183
197576
  // ../tool-server/src/index.ts
196184
197577
  var PROCESS_TIMEOUT_MS = 5e3;
197578
+ var EXIT_CAPTURE_WAIT_MS = 2e3;
196185
197579
  var DEFAULT_PORT = "3001";
196186
197580
  var DEFAULT_HOST = "127.0.0.1";
196187
197581
  var DEFAULT_IDLE_TIMEOUT_MINUTES = "0";
@@ -196270,7 +197664,7 @@ function start() {
196270
197664
  attachRegistryLogger(registry2);
196271
197665
  let eventLog = null;
196272
197666
  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");
197667
+ const eventLogPath = process.env.ARGENT_EVENT_LOG || path71.join((0, import_node_os20.homedir)(), ".argent", "tool-server-events.jsonl");
196274
197668
  try {
196275
197669
  eventLog = createToolServerEventLog({ filePath: eventLogPath });
196276
197670
  } catch (err) {
@@ -196382,12 +197776,16 @@ function start() {
196382
197776
  previewWindow.dispose();
196383
197777
  updateChecker.dispose();
196384
197778
  httpHandle.dispose();
196385
- try {
196386
- await registry2.dispose();
196387
- } catch (err) {
196388
- process.stderr.write(`[tool-server] registry dispose failed: ${String(err)}
197779
+ await withCaptureSweep(void 0, { maxMs: EXIT_CAPTURE_WAIT_MS }, async () => {
197780
+ await pauseJsCapturesOf(registry2, void 0, { atExit: true }).catch(() => {
197781
+ });
197782
+ try {
197783
+ await registry2.dispose();
197784
+ } catch (err) {
197785
+ process.stderr.write(`[tool-server] registry dispose failed: ${String(err)}
196389
197786
  `);
196390
- }
197787
+ }
197788
+ });
196391
197789
  try {
196392
197790
  await eventLog?.dispose();
196393
197791
  } catch (err) {