claude-chrome-android 1.1.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -28,17 +28,17 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  mod
29
29
  ));
30
30
 
31
- // bridge/src/import-meta-shim.js
31
+ // src/import-meta-shim.js
32
32
  var import_meta_url;
33
33
  var init_import_meta_shim = __esm({
34
- "bridge/src/import-meta-shim.js"() {
34
+ "src/import-meta-shim.js"() {
35
35
  import_meta_url = typeof __filename !== "undefined" ? require("url").pathToFileURL(__filename).href : "";
36
36
  }
37
37
  });
38
38
 
39
- // ../../node_modules/ws/lib/constants.js
39
+ // node_modules/ws/lib/constants.js
40
40
  var require_constants = __commonJS({
41
- "../../node_modules/ws/lib/constants.js"(exports2, module2) {
41
+ "node_modules/ws/lib/constants.js"(exports2, module2) {
42
42
  "use strict";
43
43
  init_import_meta_shim();
44
44
  var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
@@ -50,235 +50,19 @@ var require_constants = __commonJS({
50
50
  EMPTY_BUFFER: Buffer.alloc(0),
51
51
  GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
52
52
  hasBlob,
53
- kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
54
- kListener: /* @__PURE__ */ Symbol("kListener"),
55
- kStatusCode: /* @__PURE__ */ Symbol("status-code"),
56
- kWebSocket: /* @__PURE__ */ Symbol("websocket"),
53
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
54
+ kListener: Symbol("kListener"),
55
+ kStatusCode: Symbol("status-code"),
56
+ kWebSocket: Symbol("websocket"),
57
57
  NOOP: () => {
58
58
  }
59
59
  };
60
60
  }
61
61
  });
62
62
 
63
- // ../../node_modules/node-gyp-build/node-gyp-build.js
64
- var require_node_gyp_build = __commonJS({
65
- "../../node_modules/node-gyp-build/node-gyp-build.js"(exports2, module2) {
66
- init_import_meta_shim();
67
- var fs = require("fs");
68
- var path = require("path");
69
- var os = require("os");
70
- var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
71
- var vars = process.config && process.config.variables || {};
72
- var prebuildsOnly = !!process.env.PREBUILDS_ONLY;
73
- var abi = process.versions.modules;
74
- var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node";
75
- var arch = process.env.npm_config_arch || os.arch();
76
- var platform = process.env.npm_config_platform || os.platform();
77
- var libc = process.env.LIBC || (isAlpine(platform) ? "musl" : "glibc");
78
- var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || "";
79
- var uv = (process.versions.uv || "").split(".")[0];
80
- module2.exports = load;
81
- function load(dir) {
82
- return runtimeRequire(load.resolve(dir));
83
- }
84
- load.resolve = load.path = function(dir) {
85
- dir = path.resolve(dir || ".");
86
- try {
87
- var name = runtimeRequire(path.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
88
- if (process.env[name + "_PREBUILD"]) dir = process.env[name + "_PREBUILD"];
89
- } catch (err) {
90
- }
91
- if (!prebuildsOnly) {
92
- var release = getFirst(path.join(dir, "build/Release"), matchBuild);
93
- if (release) return release;
94
- var debug = getFirst(path.join(dir, "build/Debug"), matchBuild);
95
- if (debug) return debug;
96
- }
97
- var prebuild = resolve3(dir);
98
- if (prebuild) return prebuild;
99
- var nearby = resolve3(path.dirname(process.execPath));
100
- if (nearby) return nearby;
101
- var target = [
102
- "platform=" + platform,
103
- "arch=" + arch,
104
- "runtime=" + runtime,
105
- "abi=" + abi,
106
- "uv=" + uv,
107
- armv ? "armv=" + armv : "",
108
- "libc=" + libc,
109
- "node=" + process.versions.node,
110
- process.versions.electron ? "electron=" + process.versions.electron : "",
111
- typeof __webpack_require__ === "function" ? "webpack=true" : ""
112
- // eslint-disable-line
113
- ].filter(Boolean).join(" ");
114
- throw new Error("No native build was found for " + target + "\n loaded from: " + dir + "\n");
115
- function resolve3(dir2) {
116
- var tuples = readdirSync(path.join(dir2, "prebuilds")).map(parseTuple);
117
- var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0];
118
- if (!tuple) return;
119
- var prebuilds = path.join(dir2, "prebuilds", tuple.name);
120
- var parsed = readdirSync(prebuilds).map(parseTags);
121
- var candidates = parsed.filter(matchTags(runtime, abi));
122
- var winner = candidates.sort(compareTags(runtime))[0];
123
- if (winner) return path.join(prebuilds, winner.file);
124
- }
125
- };
126
- function readdirSync(dir) {
127
- try {
128
- return fs.readdirSync(dir);
129
- } catch (err) {
130
- return [];
131
- }
132
- }
133
- function getFirst(dir, filter) {
134
- var files = readdirSync(dir).filter(filter);
135
- return files[0] && path.join(dir, files[0]);
136
- }
137
- function matchBuild(name) {
138
- return /\.node$/.test(name);
139
- }
140
- function parseTuple(name) {
141
- var arr = name.split("-");
142
- if (arr.length !== 2) return;
143
- var platform2 = arr[0];
144
- var architectures = arr[1].split("+");
145
- if (!platform2) return;
146
- if (!architectures.length) return;
147
- if (!architectures.every(Boolean)) return;
148
- return { name, platform: platform2, architectures };
149
- }
150
- function matchTuple(platform2, arch2) {
151
- return function(tuple) {
152
- if (tuple == null) return false;
153
- if (tuple.platform !== platform2) return false;
154
- return tuple.architectures.includes(arch2);
155
- };
156
- }
157
- function compareTuples(a, b) {
158
- return a.architectures.length - b.architectures.length;
159
- }
160
- function parseTags(file) {
161
- var arr = file.split(".");
162
- var extension = arr.pop();
163
- var tags = { file, specificity: 0 };
164
- if (extension !== "node") return;
165
- for (var i = 0; i < arr.length; i++) {
166
- var tag = arr[i];
167
- if (tag === "node" || tag === "electron" || tag === "node-webkit") {
168
- tags.runtime = tag;
169
- } else if (tag === "napi") {
170
- tags.napi = true;
171
- } else if (tag.slice(0, 3) === "abi") {
172
- tags.abi = tag.slice(3);
173
- } else if (tag.slice(0, 2) === "uv") {
174
- tags.uv = tag.slice(2);
175
- } else if (tag.slice(0, 4) === "armv") {
176
- tags.armv = tag.slice(4);
177
- } else if (tag === "glibc" || tag === "musl") {
178
- tags.libc = tag;
179
- } else {
180
- continue;
181
- }
182
- tags.specificity++;
183
- }
184
- return tags;
185
- }
186
- function matchTags(runtime2, abi2) {
187
- return function(tags) {
188
- if (tags == null) return false;
189
- if (tags.runtime && tags.runtime !== runtime2 && !runtimeAgnostic(tags)) return false;
190
- if (tags.abi && tags.abi !== abi2 && !tags.napi) return false;
191
- if (tags.uv && tags.uv !== uv) return false;
192
- if (tags.armv && tags.armv !== armv) return false;
193
- if (tags.libc && tags.libc !== libc) return false;
194
- return true;
195
- };
196
- }
197
- function runtimeAgnostic(tags) {
198
- return tags.runtime === "node" && tags.napi;
199
- }
200
- function compareTags(runtime2) {
201
- return function(a, b) {
202
- if (a.runtime !== b.runtime) {
203
- return a.runtime === runtime2 ? -1 : 1;
204
- } else if (a.abi !== b.abi) {
205
- return a.abi ? -1 : 1;
206
- } else if (a.specificity !== b.specificity) {
207
- return a.specificity > b.specificity ? -1 : 1;
208
- } else {
209
- return 0;
210
- }
211
- };
212
- }
213
- function isNwjs() {
214
- return !!(process.versions && process.versions.nw);
215
- }
216
- function isElectron() {
217
- if (process.versions && process.versions.electron) return true;
218
- if (process.env.ELECTRON_RUN_AS_NODE) return true;
219
- return typeof window !== "undefined" && window.process && window.process.type === "renderer";
220
- }
221
- function isAlpine(platform2) {
222
- return platform2 === "linux" && fs.existsSync("/etc/alpine-release");
223
- }
224
- load.parseTags = parseTags;
225
- load.matchTags = matchTags;
226
- load.compareTags = compareTags;
227
- load.parseTuple = parseTuple;
228
- load.matchTuple = matchTuple;
229
- load.compareTuples = compareTuples;
230
- }
231
- });
232
-
233
- // ../../node_modules/node-gyp-build/index.js
234
- var require_node_gyp_build2 = __commonJS({
235
- "../../node_modules/node-gyp-build/index.js"(exports2, module2) {
236
- init_import_meta_shim();
237
- var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
238
- if (typeof runtimeRequire.addon === "function") {
239
- module2.exports = runtimeRequire.addon.bind(runtimeRequire);
240
- } else {
241
- module2.exports = require_node_gyp_build();
242
- }
243
- }
244
- });
245
-
246
- // ../../node_modules/bufferutil/fallback.js
247
- var require_fallback = __commonJS({
248
- "../../node_modules/bufferutil/fallback.js"(exports2, module2) {
249
- "use strict";
250
- init_import_meta_shim();
251
- var mask = (source, mask2, output, offset, length) => {
252
- for (var i = 0; i < length; i++) {
253
- output[offset + i] = source[i] ^ mask2[i & 3];
254
- }
255
- };
256
- var unmask = (buffer, mask2) => {
257
- const length = buffer.length;
258
- for (var i = 0; i < length; i++) {
259
- buffer[i] ^= mask2[i & 3];
260
- }
261
- };
262
- module2.exports = { mask, unmask };
263
- }
264
- });
265
-
266
- // ../../node_modules/bufferutil/index.js
267
- var require_bufferutil = __commonJS({
268
- "../../node_modules/bufferutil/index.js"(exports2, module2) {
269
- "use strict";
270
- init_import_meta_shim();
271
- try {
272
- module2.exports = require_node_gyp_build2()(__dirname);
273
- } catch (e) {
274
- module2.exports = require_fallback();
275
- }
276
- }
277
- });
278
-
279
- // ../../node_modules/ws/lib/buffer-util.js
63
+ // node_modules/ws/lib/buffer-util.js
280
64
  var require_buffer_util = __commonJS({
281
- "../../node_modules/ws/lib/buffer-util.js"(exports2, module2) {
65
+ "node_modules/ws/lib/buffer-util.js"(exports2, module2) {
282
66
  "use strict";
283
67
  init_import_meta_shim();
284
68
  var { EMPTY_BUFFER } = require_constants();
@@ -337,7 +121,7 @@ var require_buffer_util = __commonJS({
337
121
  };
338
122
  if (!process.env.WS_NO_BUFFER_UTIL) {
339
123
  try {
340
- const bufferUtil = require_bufferutil();
124
+ const bufferUtil = require("bufferutil");
341
125
  module2.exports.mask = function(source, mask, output, offset, length) {
342
126
  if (length < 48) _mask(source, mask, output, offset, length);
343
127
  else bufferUtil.mask(source, mask, output, offset, length);
@@ -352,13 +136,13 @@ var require_buffer_util = __commonJS({
352
136
  }
353
137
  });
354
138
 
355
- // ../../node_modules/ws/lib/limiter.js
139
+ // node_modules/ws/lib/limiter.js
356
140
  var require_limiter = __commonJS({
357
- "../../node_modules/ws/lib/limiter.js"(exports2, module2) {
141
+ "node_modules/ws/lib/limiter.js"(exports2, module2) {
358
142
  "use strict";
359
143
  init_import_meta_shim();
360
- var kDone = /* @__PURE__ */ Symbol("kDone");
361
- var kRun = /* @__PURE__ */ Symbol("kRun");
144
+ var kDone = Symbol("kDone");
145
+ var kRun = Symbol("kRun");
362
146
  var Limiter = class {
363
147
  /**
364
148
  * Creates a new `Limiter`.
@@ -403,9 +187,9 @@ var require_limiter = __commonJS({
403
187
  }
404
188
  });
405
189
 
406
- // ../../node_modules/ws/lib/permessage-deflate.js
190
+ // node_modules/ws/lib/permessage-deflate.js
407
191
  var require_permessage_deflate = __commonJS({
408
- "../../node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
192
+ "node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
409
193
  "use strict";
410
194
  init_import_meta_shim();
411
195
  var zlib = require("zlib");
@@ -414,11 +198,11 @@ var require_permessage_deflate = __commonJS({
414
198
  var { kStatusCode } = require_constants();
415
199
  var FastBuffer = Buffer[Symbol.species];
416
200
  var TRAILER = Buffer.from([0, 0, 255, 255]);
417
- var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
418
- var kTotalLength = /* @__PURE__ */ Symbol("total-length");
419
- var kCallback = /* @__PURE__ */ Symbol("callback");
420
- var kBuffers = /* @__PURE__ */ Symbol("buffers");
421
- var kError = /* @__PURE__ */ Symbol("error");
201
+ var kPerMessageDeflate = Symbol("permessage-deflate");
202
+ var kTotalLength = Symbol("total-length");
203
+ var kCallback = Symbol("callback");
204
+ var kBuffers = Symbol("buffers");
205
+ var kError = Symbol("error");
422
206
  var zlibLimiter;
423
207
  var PerMessageDeflate = class {
424
208
  /**
@@ -787,60 +571,9 @@ var require_permessage_deflate = __commonJS({
787
571
  }
788
572
  });
789
573
 
790
- // ../../node_modules/utf-8-validate/fallback.js
791
- var require_fallback2 = __commonJS({
792
- "../../node_modules/utf-8-validate/fallback.js"(exports2, module2) {
793
- "use strict";
794
- init_import_meta_shim();
795
- function isValidUTF8(buf) {
796
- const len = buf.length;
797
- let i = 0;
798
- while (i < len) {
799
- if ((buf[i] & 128) === 0) {
800
- i++;
801
- } else if ((buf[i] & 224) === 192) {
802
- if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
803
- return false;
804
- }
805
- i += 2;
806
- } else if ((buf[i] & 240) === 224) {
807
- if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // overlong
808
- buf[i] === 237 && (buf[i + 1] & 224) === 160) {
809
- return false;
810
- }
811
- i += 3;
812
- } else if ((buf[i] & 248) === 240) {
813
- if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // overlong
814
- buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
815
- return false;
816
- }
817
- i += 4;
818
- } else {
819
- return false;
820
- }
821
- }
822
- return true;
823
- }
824
- module2.exports = isValidUTF8;
825
- }
826
- });
827
-
828
- // ../../node_modules/utf-8-validate/index.js
829
- var require_utf_8_validate = __commonJS({
830
- "../../node_modules/utf-8-validate/index.js"(exports2, module2) {
831
- "use strict";
832
- init_import_meta_shim();
833
- try {
834
- module2.exports = require_node_gyp_build2()(__dirname);
835
- } catch (e) {
836
- module2.exports = require_fallback2();
837
- }
838
- }
839
- });
840
-
841
- // ../../node_modules/ws/lib/validation.js
574
+ // node_modules/ws/lib/validation.js
842
575
  var require_validation = __commonJS({
843
- "../../node_modules/ws/lib/validation.js"(exports2, module2) {
576
+ "node_modules/ws/lib/validation.js"(exports2, module2) {
844
577
  "use strict";
845
578
  init_import_meta_shim();
846
579
  var { isUtf8 } = require("buffer");
@@ -1030,7 +763,7 @@ var require_validation = __commonJS({
1030
763
  };
1031
764
  } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
1032
765
  try {
1033
- const isValidUTF8 = require_utf_8_validate();
766
+ const isValidUTF8 = require("utf-8-validate");
1034
767
  module2.exports.isValidUTF8 = function(buf) {
1035
768
  return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
1036
769
  };
@@ -1040,9 +773,9 @@ var require_validation = __commonJS({
1040
773
  }
1041
774
  });
1042
775
 
1043
- // ../../node_modules/ws/lib/receiver.js
776
+ // node_modules/ws/lib/receiver.js
1044
777
  var require_receiver = __commonJS({
1045
- "../../node_modules/ws/lib/receiver.js"(exports2, module2) {
778
+ "node_modules/ws/lib/receiver.js"(exports2, module2) {
1046
779
  "use strict";
1047
780
  init_import_meta_shim();
1048
781
  var { Writable } = require("stream");
@@ -1633,9 +1366,9 @@ var require_receiver = __commonJS({
1633
1366
  }
1634
1367
  });
1635
1368
 
1636
- // ../../node_modules/ws/lib/sender.js
1369
+ // node_modules/ws/lib/sender.js
1637
1370
  var require_sender = __commonJS({
1638
- "../../node_modules/ws/lib/sender.js"(exports2, module2) {
1371
+ "node_modules/ws/lib/sender.js"(exports2, module2) {
1639
1372
  "use strict";
1640
1373
  init_import_meta_shim();
1641
1374
  var { Duplex } = require("stream");
@@ -1644,7 +1377,7 @@ var require_sender = __commonJS({
1644
1377
  var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1645
1378
  var { isBlob, isValidStatusCode } = require_validation();
1646
1379
  var { mask: applyMask, toBuffer } = require_buffer_util();
1647
- var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
1380
+ var kByteLength = Symbol("kByteLength");
1648
1381
  var maskBuffer = Buffer.alloc(4);
1649
1382
  var RANDOM_POOL_SIZE = 8 * 1024;
1650
1383
  var randomPool;
@@ -2122,20 +1855,20 @@ var require_sender = __commonJS({
2122
1855
  }
2123
1856
  });
2124
1857
 
2125
- // ../../node_modules/ws/lib/event-target.js
1858
+ // node_modules/ws/lib/event-target.js
2126
1859
  var require_event_target = __commonJS({
2127
- "../../node_modules/ws/lib/event-target.js"(exports2, module2) {
1860
+ "node_modules/ws/lib/event-target.js"(exports2, module2) {
2128
1861
  "use strict";
2129
1862
  init_import_meta_shim();
2130
1863
  var { kForOnEventAttribute, kListener } = require_constants();
2131
- var kCode = /* @__PURE__ */ Symbol("kCode");
2132
- var kData = /* @__PURE__ */ Symbol("kData");
2133
- var kError = /* @__PURE__ */ Symbol("kError");
2134
- var kMessage = /* @__PURE__ */ Symbol("kMessage");
2135
- var kReason = /* @__PURE__ */ Symbol("kReason");
2136
- var kTarget = /* @__PURE__ */ Symbol("kTarget");
2137
- var kType = /* @__PURE__ */ Symbol("kType");
2138
- var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
1864
+ var kCode = Symbol("kCode");
1865
+ var kData = Symbol("kData");
1866
+ var kError = Symbol("kError");
1867
+ var kMessage = Symbol("kMessage");
1868
+ var kReason = Symbol("kReason");
1869
+ var kTarget = Symbol("kTarget");
1870
+ var kType = Symbol("kType");
1871
+ var kWasClean = Symbol("kWasClean");
2139
1872
  var Event = class {
2140
1873
  /**
2141
1874
  * Create a new `Event`.
@@ -2352,9 +2085,9 @@ var require_event_target = __commonJS({
2352
2085
  }
2353
2086
  });
2354
2087
 
2355
- // ../../node_modules/ws/lib/extension.js
2088
+ // node_modules/ws/lib/extension.js
2356
2089
  var require_extension = __commonJS({
2357
- "../../node_modules/ws/lib/extension.js"(exports2, module2) {
2090
+ "node_modules/ws/lib/extension.js"(exports2, module2) {
2358
2091
  "use strict";
2359
2092
  init_import_meta_shim();
2360
2093
  var { tokenChars } = require_validation();
@@ -2506,9 +2239,9 @@ var require_extension = __commonJS({
2506
2239
  }
2507
2240
  });
2508
2241
 
2509
- // ../../node_modules/ws/lib/websocket.js
2242
+ // node_modules/ws/lib/websocket.js
2510
2243
  var require_websocket = __commonJS({
2511
- "../../node_modules/ws/lib/websocket.js"(exports2, module2) {
2244
+ "node_modules/ws/lib/websocket.js"(exports2, module2) {
2512
2245
  "use strict";
2513
2246
  init_import_meta_shim();
2514
2247
  var EventEmitter = require("events");
@@ -2539,7 +2272,7 @@ var require_websocket = __commonJS({
2539
2272
  } = require_event_target();
2540
2273
  var { format, parse } = require_extension();
2541
2274
  var { toBuffer } = require_buffer_util();
2542
- var kAborted = /* @__PURE__ */ Symbol("kAborted");
2275
+ var kAborted = Symbol("kAborted");
2543
2276
  var protocolVersions = [8, 13];
2544
2277
  var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2545
2278
  var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
@@ -3393,9 +3126,9 @@ var require_websocket = __commonJS({
3393
3126
  }
3394
3127
  });
3395
3128
 
3396
- // ../../node_modules/ws/lib/stream.js
3129
+ // node_modules/ws/lib/stream.js
3397
3130
  var require_stream = __commonJS({
3398
- "../../node_modules/ws/lib/stream.js"(exports2, module2) {
3131
+ "node_modules/ws/lib/stream.js"(exports2, module2) {
3399
3132
  "use strict";
3400
3133
  init_import_meta_shim();
3401
3134
  var WebSocket3 = require_websocket();
@@ -3492,9 +3225,9 @@ var require_stream = __commonJS({
3492
3225
  }
3493
3226
  });
3494
3227
 
3495
- // ../../node_modules/ws/lib/subprotocol.js
3228
+ // node_modules/ws/lib/subprotocol.js
3496
3229
  var require_subprotocol = __commonJS({
3497
- "../../node_modules/ws/lib/subprotocol.js"(exports2, module2) {
3230
+ "node_modules/ws/lib/subprotocol.js"(exports2, module2) {
3498
3231
  "use strict";
3499
3232
  init_import_meta_shim();
3500
3233
  var { tokenChars } = require_validation();
@@ -3538,9 +3271,9 @@ var require_subprotocol = __commonJS({
3538
3271
  }
3539
3272
  });
3540
3273
 
3541
- // ../../node_modules/ws/lib/websocket-server.js
3274
+ // node_modules/ws/lib/websocket-server.js
3542
3275
  var require_websocket_server = __commonJS({
3543
- "../../node_modules/ws/lib/websocket-server.js"(exports2, module2) {
3276
+ "node_modules/ws/lib/websocket-server.js"(exports2, module2) {
3544
3277
  "use strict";
3545
3278
  init_import_meta_shim();
3546
3279
  var EventEmitter = require("events");
@@ -3932,10 +3665,10 @@ var require_websocket_server = __commonJS({
3932
3665
  }
3933
3666
  });
3934
3667
 
3935
- // ../../node_modules/ws/wrapper.mjs
3668
+ // node_modules/ws/wrapper.mjs
3936
3669
  var import_stream, import_receiver, import_sender, import_websocket, import_websocket_server;
3937
3670
  var init_wrapper = __esm({
3938
- "../../node_modules/ws/wrapper.mjs"() {
3671
+ "node_modules/ws/wrapper.mjs"() {
3939
3672
  init_import_meta_shim();
3940
3673
  import_stream = __toESM(require_stream(), 1);
3941
3674
  import_receiver = __toESM(require_receiver(), 1);
@@ -3945,7 +3678,7 @@ var init_wrapper = __esm({
3945
3678
  }
3946
3679
  });
3947
3680
 
3948
- // compat.ts
3681
+ // ../compat.ts
3949
3682
  async function fileExists(path) {
3950
3683
  if (IS_BUN) {
3951
3684
  return Bun.file(path).exists();
@@ -4200,7 +3933,7 @@ function createNodeServer(config) {
4200
3933
  }
4201
3934
  var import_promises, import_node_fs, import_node_stream, cp, http, IS_BUN;
4202
3935
  var init_compat = __esm({
4203
- "compat.ts"() {
3936
+ "../compat.ts"() {
4204
3937
  init_import_meta_shim();
4205
3938
  import_promises = require("node:fs/promises");
4206
3939
  import_node_fs = require("node:fs");
@@ -4212,10 +3945,37 @@ var init_compat = __esm({
4212
3945
  }
4213
3946
  });
4214
3947
 
4215
- // claude-chrome-bridge.ts
3948
+ // ../claude-chrome-bridge.ts
4216
3949
  var claude_chrome_bridge_exports = {};
3950
+ function getAdbSerial() {
3951
+ const now = Date.now();
3952
+ if (now - _adbSerialTs < ADB_SERIAL_TTL_MS) return _adbSerial;
3953
+ _adbSerialTs = now;
3954
+ try {
3955
+ const result = runSync([ADB_PATH, "devices"]);
3956
+ const lines = result.stdout.toString().trim().split("\n").filter((l) => l.endsWith(" device"));
3957
+ if (lines.length <= 1) {
3958
+ _adbSerial = "";
3959
+ return _adbSerial;
3960
+ }
3961
+ for (const line of lines) {
3962
+ const serial = line.split(" ")[0];
3963
+ const check = runSync([ADB_PATH, "-s", serial, "shell", "pidof", "com.microsoft.emmx.canary"]);
3964
+ if (check.exitCode === 0 && check.stdout.toString().trim()) {
3965
+ _adbSerial = serial;
3966
+ return _adbSerial;
3967
+ }
3968
+ }
3969
+ _adbSerial = lines[0]?.split(" ")[0] ?? "";
3970
+ return _adbSerial;
3971
+ } catch {
3972
+ _adbSerial = "";
3973
+ return _adbSerial;
3974
+ }
3975
+ }
4217
3976
  function adb(...args2) {
4218
- return ADB_SERIAL ? [ADB_PATH, "-s", ADB_SERIAL, ...args2] : [ADB_PATH, ...args2];
3977
+ const serial = getAdbSerial();
3978
+ return serial ? [ADB_PATH, "-s", serial, ...args2] : [ADB_PATH, ...args2];
4219
3979
  }
4220
3980
  function adbNotify(tag, title, text) {
4221
3981
  try {
@@ -4560,15 +4320,36 @@ function encodeGIF(frames, delayMs) {
4560
4320
  }
4561
4321
  return result;
4562
4322
  }
4563
- function drainToolQueue() {
4564
- if (pendingToolQueue.length === 0) return;
4565
- const next = pendingToolQueue[0];
4323
+ function sendToolRequest(requestId, requestJson) {
4324
+ let sent = false;
4566
4325
  for (const client of wsClients) {
4567
4326
  try {
4568
- client.send(next.requestJson);
4327
+ client.send(requestJson);
4328
+ sent = true;
4569
4329
  } catch {
4570
4330
  }
4571
4331
  }
4332
+ return sent;
4333
+ }
4334
+ function drainTabQueue(tabId) {
4335
+ const queue = busyTabs.get(tabId);
4336
+ if (!queue || queue.length === 0) {
4337
+ busyTabs.delete(tabId);
4338
+ return;
4339
+ }
4340
+ const next = queue.shift();
4341
+ if (queue.length === 0) busyTabs.delete(tabId);
4342
+ pendingToolMap.set(next.requestId, {
4343
+ resolve: next.resolve,
4344
+ timeout: next.timeout,
4345
+ tabId: next.tabId
4346
+ });
4347
+ const sent = sendToolRequest(next.requestId, next.requestJson);
4348
+ if (!sent) {
4349
+ pendingToolMap.delete(next.requestId);
4350
+ clearTimeout(next.timeout);
4351
+ next.resolve({ type: "tool_response", error: "All bridge clients disconnected before dispatch" });
4352
+ }
4572
4353
  }
4573
4354
  function spawnNativeHost() {
4574
4355
  if (nativeHost) {
@@ -4622,8 +4403,8 @@ function spawnNativeHost() {
4622
4403
  log("error", "stderr read error:", err);
4623
4404
  }
4624
4405
  };
4625
- readStdout();
4626
- readStderr();
4406
+ readStdout().catch((err) => log("error", "readStdout unhandled:", err));
4407
+ readStderr().catch((err) => log("error", "readStderr unhandled:", err));
4627
4408
  nativeHost.exited.then((code) => {
4628
4409
  log("warn", `Native host exited with code ${code}`);
4629
4410
  nativeHost = null;
@@ -4651,7 +4432,17 @@ function handleNativeMessage(json) {
4651
4432
  cdpManager.evaluateJS(code, tabId).then((cdpResult) => {
4652
4433
  const response = JSON.stringify({ type: "tool_response", result: cdpResult });
4653
4434
  log("debug", `CDP\u2192native: ${response.slice(0, 200)}`);
4654
- sendToNativeHost(response);
4435
+ try {
4436
+ sendToNativeHost(response);
4437
+ } catch (e) {
4438
+ log("warn", `sendToNativeHost failed after CDP eval: ${e.message}`);
4439
+ for (const client of wsClients) {
4440
+ try {
4441
+ client.send(outJson);
4442
+ } catch {
4443
+ }
4444
+ }
4445
+ }
4655
4446
  }).catch((err) => {
4656
4447
  log("warn", `CDP eval failed, forwarding to extension: ${err.message}`);
4657
4448
  for (const client of wsClients) {
@@ -4668,12 +4459,22 @@ function handleNativeMessage(json) {
4668
4459
  log("info", `CDP: intercepting computer screenshot (tab ${tabId ?? "active"})`);
4669
4460
  cdpManager.captureScreenshot(tabId).then((cdpResult) => {
4670
4461
  if (cdpResult.data) {
4671
- sendToNativeHost(JSON.stringify({
4672
- type: "tool_response",
4673
- result: {
4674
- content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: cdpResult.data } }]
4462
+ try {
4463
+ sendToNativeHost(JSON.stringify({
4464
+ type: "tool_response",
4465
+ result: {
4466
+ content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: cdpResult.data } }]
4467
+ }
4468
+ }));
4469
+ } catch (e) {
4470
+ log("warn", `sendToNativeHost failed after CDP screenshot: ${e.message}`);
4471
+ for (const client of wsClients) {
4472
+ try {
4473
+ client.send(outJson);
4474
+ } catch {
4475
+ }
4675
4476
  }
4676
- }));
4477
+ }
4677
4478
  } else {
4678
4479
  log("warn", `CDP screenshot failed: ${cdpResult.error}`);
4679
4480
  for (const client of wsClients) {
@@ -4721,12 +4522,22 @@ function handleNativeMessage(json) {
4721
4522
  const croppedRGBA = cropPixels(rgba, width, height, cropX, cropY, cropW, cropH);
4722
4523
  const pngBuf = encodePNG(croppedRGBA, cropW, cropH);
4723
4524
  const b64 = pngBuf.toString("base64");
4724
- sendToNativeHost(JSON.stringify({
4725
- type: "tool_response",
4726
- result: {
4727
- content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: b64 } }]
4525
+ try {
4526
+ sendToNativeHost(JSON.stringify({
4527
+ type: "tool_response",
4528
+ result: {
4529
+ content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: b64 } }]
4530
+ }
4531
+ }));
4532
+ } catch (e) {
4533
+ log("warn", `sendToNativeHost failed after CDP zoom: ${e.message}`);
4534
+ for (const client of wsClients) {
4535
+ try {
4536
+ client.send(outJson);
4537
+ } catch {
4538
+ }
4728
4539
  }
4729
- }));
4540
+ }
4730
4541
  } catch (cropErr) {
4731
4542
  log("warn", `CDP zoom crop failed: ${cropErr.message}`);
4732
4543
  for (const client of wsClients) {
@@ -4764,10 +4575,20 @@ function handleNativeMessage(json) {
4764
4575
  log("info", `CDP: intercepting computer ${action} (tab ${tabId ?? "active"})`);
4765
4576
  cdpManager.dispatchComputerAction(action, parsed.params ?? {}, tabId).then((cdpResult) => {
4766
4577
  if (cdpResult.result) {
4767
- sendToNativeHost(JSON.stringify({
4768
- type: "tool_response",
4769
- result: { result: cdpResult.result }
4770
- }));
4578
+ try {
4579
+ sendToNativeHost(JSON.stringify({
4580
+ type: "tool_response",
4581
+ result: { result: cdpResult.result }
4582
+ }));
4583
+ } catch (e) {
4584
+ log("warn", `sendToNativeHost failed after CDP ${action}: ${e.message}`);
4585
+ for (const client of wsClients) {
4586
+ try {
4587
+ client.send(outJson);
4588
+ } catch {
4589
+ }
4590
+ }
4591
+ }
4771
4592
  } else {
4772
4593
  log("warn", `CDP ${action} failed: ${cdpResult.error}`);
4773
4594
  for (const client of wsClients) {
@@ -4793,7 +4614,17 @@ function handleNativeMessage(json) {
4793
4614
  if (width && height) {
4794
4615
  log("info", `CDP: intercepting resize_window (${width}\xD7${height})`);
4795
4616
  cdpManager.setDeviceMetrics(width, height, parsed.params?.tabId).then((r) => {
4796
- sendToNativeHost(JSON.stringify({ type: "tool_response", result: r }));
4617
+ try {
4618
+ sendToNativeHost(JSON.stringify({ type: "tool_response", result: r }));
4619
+ } catch (e) {
4620
+ log("warn", `sendToNativeHost failed after CDP resize: ${e.message}`);
4621
+ for (const client of wsClients) {
4622
+ try {
4623
+ client.send(outJson);
4624
+ } catch {
4625
+ }
4626
+ }
4627
+ }
4797
4628
  }).catch(() => {
4798
4629
  for (const client of wsClients) {
4799
4630
  try {
@@ -4812,10 +4643,14 @@ function handleNativeMessage(json) {
4812
4643
  const cdpRequests = cdpManager.getNetworkRequests(tabId, since, typeFilter);
4813
4644
  if (cdpRequests.length > 0) {
4814
4645
  log("info", `CDP: returning ${cdpRequests.length} network requests`);
4815
- sendToNativeHost(JSON.stringify({
4816
- type: "tool_response",
4817
- result: { result: cdpRequests, count: cdpRequests.length, source: "cdp" }
4818
- }));
4646
+ try {
4647
+ sendToNativeHost(JSON.stringify({
4648
+ type: "tool_response",
4649
+ result: { result: cdpRequests, count: cdpRequests.length, source: "cdp" }
4650
+ }));
4651
+ } catch (e) {
4652
+ log("warn", `sendToNativeHost failed for network requests: ${e.message}`);
4653
+ }
4819
4654
  return;
4820
4655
  }
4821
4656
  }
@@ -4858,14 +4693,15 @@ function shutdown() {
4858
4693
  nativeHost = null;
4859
4694
  }
4860
4695
  cdpManager.cleanup();
4696
+ cdpManager.stopReconnectForShutdown();
4861
4697
  adbNotify("cfc-bridge", "CFC Bridge stopped", "Bridge is no longer running");
4862
4698
  server.stop();
4863
4699
  log("info", "Bridge stopped");
4864
4700
  process.exit(0);
4865
4701
  }
4866
- var import_path, import_node_zlib, SCRIPT_DIR, MANIFEST_PATH, BRIDGE_VERSION, WS_PORT, WS_HOST, BRIDGE_TOKEN, MAX_MESSAGE_SIZE, RECONNECT_DELAY_MS, HEARTBEAT_INTERVAL_MS, TERMUX_PREFIX, TERMUX_BIN, ADB_PATH, ADB_SERIAL, REPO_CLI, BUN_GLOBAL_CLI, NPM_GLOBAL_CLI, CLI_PATH, RUNTIME_PATH, LOG_LEVEL, LOG_PRIORITY, NativeMessageDecoder, CDP_PORT, CDP_PID_CHECK_INTERVAL_MS, CDP_TARGET_CACHE_TTL_MS, CDP_TIMEOUT_MS, CdpManager, cdpManager, crc32Table, pendingToolQueue, HTTP_TOOL_TIMEOUT_MS, nativeHost, stdoutDecoder, wsClients, server, TEST_PAGE_HTML;
4702
+ var import_path, import_node_zlib, SCRIPT_DIR, MANIFEST_PATH, BRIDGE_VERSION, WS_PORT, WS_HOST, BRIDGE_TOKEN, MAX_MESSAGE_SIZE, RECONNECT_DELAY_MS, HEARTBEAT_INTERVAL_MS, TERMUX_PREFIX, TERMUX_BIN, ADB_PATH, _adbSerial, _adbSerialTs, ADB_SERIAL_TTL_MS, REPO_CLI, BUN_GLOBAL_CLI, NPM_GLOBAL_CLI, CLI_PATH, RUNTIME_PATH, LOG_LEVEL, LOG_PRIORITY, NativeMessageDecoder, CDP_PORT, CDP_PID_CHECK_INTERVAL_MS, CDP_MAX_BACKOFF_ATTEMPTS, CDP_TARGET_CACHE_TTL_MS, CDP_TIMEOUT_MS, CdpManager, cdpManager, crc32Table, toolRequestCounter, pendingToolMap, busyTabs, HTTP_TOOL_TIMEOUT_MS, lastToolName, lastToolTime, nativeHost, stdoutDecoder, wsClients, server, TEST_PAGE_HTML;
4867
4703
  var init_claude_chrome_bridge = __esm({
4868
- "claude-chrome-bridge.ts"() {
4704
+ "../claude-chrome-bridge.ts"() {
4869
4705
  init_import_meta_shim();
4870
4706
  import_path = require("path");
4871
4707
  import_node_zlib = require("node:zlib");
@@ -4890,21 +4726,9 @@ var init_claude_chrome_bridge = __esm({
4890
4726
  TERMUX_PREFIX = "/data/data/com.termux/files/usr";
4891
4727
  TERMUX_BIN = `${TERMUX_PREFIX}/bin`;
4892
4728
  ADB_PATH = `${TERMUX_BIN}/adb`;
4893
- ADB_SERIAL = (() => {
4894
- try {
4895
- const result = runSync([ADB_PATH, "devices"]);
4896
- const lines = result.stdout.toString().trim().split("\n").filter((l) => l.endsWith(" device"));
4897
- if (lines.length <= 1) return "";
4898
- for (const line of lines) {
4899
- const serial = line.split(" ")[0];
4900
- const check = runSync([ADB_PATH, "-s", serial, "shell", "pidof", "com.microsoft.emmx.canary"]);
4901
- if (check.exitCode === 0 && check.stdout.toString().trim()) return serial;
4902
- }
4903
- return lines[0]?.split(" ")[0] ?? "";
4904
- } catch {
4905
- return "";
4906
- }
4907
- })();
4729
+ _adbSerial = "";
4730
+ _adbSerialTs = 0;
4731
+ ADB_SERIAL_TTL_MS = 3e4;
4908
4732
  REPO_CLI = (0, import_path.resolve)(SCRIPT_DIR, "cli.js");
4909
4733
  BUN_GLOBAL_CLI = (0, import_path.resolve)(
4910
4734
  process.env.HOME ?? "~",
@@ -4954,7 +4778,8 @@ var init_claude_chrome_bridge = __esm({
4954
4778
  }
4955
4779
  };
4956
4780
  CDP_PORT = parseInt(process.env.CDP_PORT ?? "9223", 10);
4957
- CDP_PID_CHECK_INTERVAL_MS = 6e4;
4781
+ CDP_PID_CHECK_INTERVAL_MS = 3e4;
4782
+ CDP_MAX_BACKOFF_ATTEMPTS = 10;
4958
4783
  CDP_TARGET_CACHE_TTL_MS = 1e4;
4959
4784
  CDP_TIMEOUT_MS = 15e3;
4960
4785
  CdpManager = class {
@@ -4974,8 +4799,14 @@ var init_claude_chrome_bridge = __esm({
4974
4799
  targetsLastFetched = 0;
4975
4800
  /** Cached CDP targets */
4976
4801
  cachedTargets = [];
4977
- /** PID recheck interval handle */
4802
+ /** PID recheck interval handle (active when connected) */
4978
4803
  pidCheckTimer = null;
4804
+ /** Reconnect interval handle (active when disconnected) */
4805
+ reconnectTimer = null;
4806
+ /** Exponential backoff reconnect attempts counter */
4807
+ reconnectBackoffAttempts = 0;
4808
+ /** Exponential backoff timer handle */
4809
+ backoffTimer = null;
4979
4810
  /** Sessions where Network domain has been enabled */
4980
4811
  networkEnabledSessions = /* @__PURE__ */ new Set();
4981
4812
  /** Network request events per sessionId */
@@ -4986,19 +4817,13 @@ var init_claude_chrome_bridge = __esm({
4986
4817
  if (this.state === "connecting") return false;
4987
4818
  this.state = "connecting";
4988
4819
  try {
4989
- const pidResult = runSync(adb("shell", "pidof", "com.microsoft.emmx.canary"));
4990
- const pidStr = pidResult.stdout.toString().trim().split(/\s+/)[0];
4991
- if (!pidStr || pidResult.exitCode !== 0) {
4992
- log("debug", `CDP: Edge not running or ADB unavailable (exit=${pidResult.exitCode}, stderr=${pidResult.stderr?.toString().trim()}, serial=${ADB_SERIAL || "default"})`);
4993
- this.state = "disconnected";
4994
- return false;
4995
- }
4996
- this.edgePid = parseInt(pidStr, 10);
4820
+ this.edgePid = this.getEdgePid();
4997
4821
  if (isNaN(this.edgePid)) {
4998
- log("warn", `CDP: invalid PID "${pidStr}"`);
4822
+ log("debug", "CDP: Edge not running or ADB unavailable");
4999
4823
  this.state = "disconnected";
5000
4824
  return false;
5001
4825
  }
4826
+ const existingForward = this.checkExistingForward();
5002
4827
  const socketCandidates = [
5003
4828
  `chrome_devtools_remote_${this.edgePid}`,
5004
4829
  // Chrome convention (PID-suffixed)
@@ -5006,20 +4831,31 @@ var init_claude_chrome_bridge = __esm({
5006
4831
  // Edge Android convention (plain)
5007
4832
  ];
5008
4833
  let versionData = null;
5009
- for (const socketName of socketCandidates) {
5010
- const fwdResult = runSync(
5011
- adb("forward", `tcp:${CDP_PORT}`, `localabstract:${socketName}`)
5012
- );
5013
- if (fwdResult.exitCode !== 0) continue;
4834
+ if (existingForward) {
5014
4835
  try {
5015
4836
  const resp = await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`);
5016
4837
  versionData = await resp.json();
5017
- log("info", `CDP: Edge version \u2014 ${versionData["Browser"] ?? "unknown"}, pkg: ${versionData["Android-Package"] ?? "unknown"} (socket: ${socketName})`);
5018
- break;
4838
+ log("debug", `CDP: reusing existing ADB forward on port ${CDP_PORT}`);
5019
4839
  } catch {
5020
4840
  runSync(adb("forward", "--remove", `tcp:${CDP_PORT}`));
5021
4841
  }
5022
4842
  }
4843
+ if (!versionData) {
4844
+ for (const socketName of socketCandidates) {
4845
+ const fwdResult = runSync(
4846
+ adb("forward", `tcp:${CDP_PORT}`, `localabstract:${socketName}`)
4847
+ );
4848
+ if (fwdResult.exitCode !== 0) continue;
4849
+ try {
4850
+ const resp = await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`);
4851
+ versionData = await resp.json();
4852
+ log("info", `CDP: Edge version \u2014 ${versionData["Browser"] ?? "unknown"}, pkg: ${versionData["Android-Package"] ?? "unknown"} (socket: ${socketName})`);
4853
+ break;
4854
+ } catch {
4855
+ runSync(adb("forward", "--remove", `tcp:${CDP_PORT}`));
4856
+ }
4857
+ }
4858
+ }
5023
4859
  if (!versionData) {
5024
4860
  log("warn", "CDP: no working DevTools socket found");
5025
4861
  this.state = "disconnected";
@@ -5027,6 +4863,9 @@ var init_claude_chrome_bridge = __esm({
5027
4863
  }
5028
4864
  const wsUrl = versionData.webSocketDebuggerUrl?.replace(/^ws:\/\/[^/]+/, `ws://127.0.0.1:${CDP_PORT}`) ?? `ws://127.0.0.1:${CDP_PORT}/devtools/browser`;
5029
4865
  await this.connectWebSocket(wsUrl);
4866
+ this.reconnectBackoffAttempts = 0;
4867
+ this.cancelBackoff();
4868
+ this.stopReconnectTimer();
5030
4869
  if (!this.pidCheckTimer) {
5031
4870
  this.pidCheckTimer = setInterval(() => this.recheckPid(), CDP_PID_CHECK_INTERVAL_MS);
5032
4871
  }
@@ -5062,11 +4901,20 @@ var init_claude_chrome_bridge = __esm({
5062
4901
  this.ws = null;
5063
4902
  this.sessionMap.clear();
5064
4903
  this.tabTargetMap.clear();
4904
+ if (this.pending.size > 0) {
4905
+ log("warn", `CDP: rejecting ${this.pending.size} pending commands on WS close`);
4906
+ this.pending.forEach((p) => {
4907
+ clearTimeout(p.timer);
4908
+ p.reject(new Error("CDP WebSocket closed"));
4909
+ });
4910
+ this.pending.clear();
4911
+ }
4912
+ this.scheduleExpBackoff();
5065
4913
  });
5066
4914
  this.ws.addEventListener("message", (ev) => {
5067
4915
  try {
5068
4916
  const data = JSON.parse(String(ev.data));
5069
- if (data.id !== void 0) {
4917
+ if (typeof data.id === "number") {
5070
4918
  const p = this.pending.get(data.id);
5071
4919
  if (p) {
5072
4920
  clearTimeout(p.timer);
@@ -5080,7 +4928,13 @@ var init_claude_chrome_bridge = __esm({
5080
4928
  if (sessionId) {
5081
4929
  const p = data.params;
5082
4930
  const resp = p.response;
5083
- if (!this.networkEvents.has(sessionId)) this.networkEvents.set(sessionId, []);
4931
+ if (!this.networkEvents.has(sessionId)) {
4932
+ if (this.networkEvents.size >= 20) {
4933
+ const oldestKey = this.networkEvents.keys().next().value;
4934
+ if (oldestKey) this.networkEvents.delete(oldestKey);
4935
+ }
4936
+ this.networkEvents.set(sessionId, []);
4937
+ }
5084
4938
  const buf = this.networkEvents.get(sessionId);
5085
4939
  buf.push({
5086
4940
  url: resp?.url ?? "",
@@ -5089,7 +4943,7 @@ var init_claude_chrome_bridge = __esm({
5089
4943
  type: p.type ?? "other",
5090
4944
  timestamp: Date.now()
5091
4945
  });
5092
- if (buf.length > 500) buf.shift();
4946
+ if (buf.length > 200) buf.shift();
5093
4947
  }
5094
4948
  }
5095
4949
  } catch {
@@ -5098,8 +4952,13 @@ var init_claude_chrome_bridge = __esm({
5098
4952
  });
5099
4953
  });
5100
4954
  }
5101
- /** Send a CDP command and await its response */
5102
- sendCommand(method, params = {}, sessionId) {
4955
+ /** Send a CDP command and await its response. Tries one reconnect if disconnected. */
4956
+ async sendCommand(method, params = {}, sessionId) {
4957
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
4958
+ log("debug", `CDP: sendCommand(${method}) \u2014 not connected, attempting reconnect`);
4959
+ const ok = await this.connect();
4960
+ if (!ok) throw new Error("CDP not connected");
4961
+ }
5103
4962
  return new Promise((resolve3, reject) => {
5104
4963
  if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
5105
4964
  reject(new Error("CDP not connected"));
@@ -5502,29 +5361,105 @@ var init_claude_chrome_bridge = __esm({
5502
5361
  targets: this.cachedTargets.filter((t) => t.type === "page").length
5503
5362
  };
5504
5363
  }
5505
- /** Re-check Edge PID — reconnect if changed (Edge restarted) */
5506
- async recheckPid() {
5507
- try {
5508
- const pidResult = runSync(adb("shell", "pidof", "com.microsoft.emmx.canary"));
5509
- const pidStr = pidResult.stdout.toString().trim().split(/\s+/)[0];
5510
- const newPid = parseInt(pidStr, 10);
5511
- if (isNaN(newPid)) {
5512
- if (this.state === "connected") {
5513
- log("info", "CDP: Edge no longer running, disconnecting");
5514
- this.cleanup();
5515
- }
5516
- return;
5364
+ /** Schedule exponential backoff reconnect: 2s, 4s, 8s, 16s, max 30s */
5365
+ scheduleExpBackoff() {
5366
+ if (this.backoffTimer) return;
5367
+ if (this.reconnectBackoffAttempts >= CDP_MAX_BACKOFF_ATTEMPTS) {
5368
+ log("info", `CDP: backoff exhausted (${CDP_MAX_BACKOFF_ATTEMPTS} attempts), falling back to PID timer`);
5369
+ this.reconnectBackoffAttempts = 0;
5370
+ this.startReconnectTimer();
5371
+ return;
5372
+ }
5373
+ const delay = Math.min(2e3 * Math.pow(2, this.reconnectBackoffAttempts), 3e4);
5374
+ this.reconnectBackoffAttempts++;
5375
+ log("debug", `CDP: backoff reconnect in ${delay}ms (attempt ${this.reconnectBackoffAttempts}/${CDP_MAX_BACKOFF_ATTEMPTS})`);
5376
+ this.backoffTimer = setTimeout(async () => {
5377
+ this.backoffTimer = null;
5378
+ const ok = await this.connect();
5379
+ if (!ok && this.state === "disconnected") {
5380
+ this.scheduleExpBackoff();
5517
5381
  }
5518
- if (newPid !== this.edgePid && this.state === "connected") {
5519
- log("info", `CDP: Edge PID changed ${this.edgePid} \u2192 ${newPid}, reconnecting`);
5382
+ }, delay);
5383
+ }
5384
+ /** Cancel pending backoff timer */
5385
+ cancelBackoff() {
5386
+ if (this.backoffTimer) {
5387
+ clearTimeout(this.backoffTimer);
5388
+ this.backoffTimer = null;
5389
+ }
5390
+ }
5391
+ /** Check if an ADB forward for our CDP port already exists */
5392
+ checkExistingForward() {
5393
+ try {
5394
+ const result = runSync(adb("forward", "--list"));
5395
+ const lines = result.stdout.toString().trim().split("\n");
5396
+ return lines.some((l) => l.includes(`tcp:${CDP_PORT}`));
5397
+ } catch {
5398
+ return false;
5399
+ }
5400
+ }
5401
+ /**
5402
+ * Get Edge PID — tries local `pidof` first (works on-device without ADB),
5403
+ * falls back to `adb shell pidof` if local fails.
5404
+ * Returns NaN if Edge is not running or both methods fail.
5405
+ */
5406
+ getEdgePid() {
5407
+ try {
5408
+ const local = runSync(["pidof", "com.microsoft.emmx.canary"]);
5409
+ const pid = parseInt(local.stdout.toString().trim().split(/\s+/)[0], 10);
5410
+ if (!isNaN(pid)) return pid;
5411
+ } catch {
5412
+ }
5413
+ try {
5414
+ const remote = runSync(adb("shell", "pidof", "com.microsoft.emmx.canary"));
5415
+ const pid = parseInt(remote.stdout.toString().trim().split(/\s+/)[0], 10);
5416
+ if (!isNaN(pid)) return pid;
5417
+ } catch {
5418
+ }
5419
+ return NaN;
5420
+ }
5421
+ /** Re-check Edge PID — reconnect if changed, or attempt connect if disconnected */
5422
+ async recheckPid() {
5423
+ const newPid = this.getEdgePid();
5424
+ if (isNaN(newPid)) {
5425
+ if (this.state === "connected") {
5426
+ log("info", "CDP: Edge no longer running, disconnecting");
5520
5427
  this.cleanup();
5521
- await this.connect();
5522
5428
  }
5523
- } catch {
5429
+ return;
5430
+ }
5431
+ if (this.state === "disconnected") {
5432
+ log("info", `CDP: Edge running (PID ${newPid}), attempting reconnect`);
5433
+ await this.connect();
5434
+ return;
5435
+ }
5436
+ if (newPid !== this.edgePid && this.state === "connected") {
5437
+ log("info", `CDP: Edge PID changed ${this.edgePid} \u2192 ${newPid}, reconnecting`);
5438
+ this.cleanup();
5439
+ await this.connect();
5440
+ }
5441
+ }
5442
+ /** Start periodic reconnect timer (runs when disconnected) */
5443
+ startReconnectTimer() {
5444
+ if (this.reconnectTimer) return;
5445
+ this.reconnectTimer = setInterval(() => this.recheckPid(), CDP_PID_CHECK_INTERVAL_MS);
5446
+ log("debug", `CDP: reconnect timer started (every ${CDP_PID_CHECK_INTERVAL_MS / 1e3}s)`);
5447
+ }
5448
+ /** Stop the reconnect timer (called when connection succeeds) */
5449
+ stopReconnectTimer() {
5450
+ if (this.reconnectTimer) {
5451
+ clearInterval(this.reconnectTimer);
5452
+ this.reconnectTimer = null;
5524
5453
  }
5525
5454
  }
5526
- /** Clean up CDP connection and ADB forward */
5455
+ /** Stop reconnect timer and cancel backoff for final shutdown */
5456
+ stopReconnectForShutdown() {
5457
+ this.stopReconnectTimer();
5458
+ this.cancelBackoff();
5459
+ }
5460
+ /** Clean up CDP connection and ADB forward, restart reconnect timer */
5527
5461
  cleanup() {
5462
+ this.cancelBackoff();
5528
5463
  if (this.pidCheckTimer) {
5529
5464
  clearInterval(this.pidCheckTimer);
5530
5465
  this.pidCheckTimer = null;
@@ -5548,6 +5483,7 @@ var init_claude_chrome_bridge = __esm({
5548
5483
  this.pending.clear();
5549
5484
  runSync(adb("forward", "--remove", `tcp:${CDP_PORT}`));
5550
5485
  log("info", "CDP: cleaned up");
5486
+ this.startReconnectTimer();
5551
5487
  }
5552
5488
  };
5553
5489
  cdpManager = new CdpManager();
@@ -5557,8 +5493,12 @@ var init_claude_chrome_bridge = __esm({
5557
5493
  for (let j = 0; j < 8; j++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
5558
5494
  crc32Table[i] = c;
5559
5495
  }
5560
- pendingToolQueue = [];
5496
+ toolRequestCounter = 0;
5497
+ pendingToolMap = /* @__PURE__ */ new Map();
5498
+ busyTabs = /* @__PURE__ */ new Map();
5561
5499
  HTTP_TOOL_TIMEOUT_MS = 3e4;
5500
+ lastToolName = null;
5501
+ lastToolTime = null;
5562
5502
  nativeHost = null;
5563
5503
  stdoutDecoder = new NativeMessageDecoder();
5564
5504
  wsClients = /* @__PURE__ */ new Set();
@@ -5575,7 +5515,9 @@ var init_claude_chrome_bridge = __esm({
5575
5515
  nativeHost: nativeHost !== null,
5576
5516
  clients: wsClients.size,
5577
5517
  uptime: process.uptime(),
5578
- cdp: cdpManager.getStatus()
5518
+ cdp: cdpManager.getStatus(),
5519
+ lastTool: lastToolName,
5520
+ lastToolTime
5579
5521
  }),
5580
5522
  { headers: { "Content-Type": "application/json" } }
5581
5523
  );
@@ -5719,23 +5661,54 @@ var init_claude_chrome_bridge = __esm({
5719
5661
  }
5720
5662
  try {
5721
5663
  const body = await req.json();
5664
+ const requestId = `req_${++toolRequestCounter}_${Date.now()}`;
5665
+ const tabId = body.params?.tabId || 0;
5722
5666
  const toolRequest = JSON.stringify({
5723
5667
  type: "tool_request",
5724
5668
  method: body.method,
5725
- params: body.params ?? {}
5669
+ params: body.params ?? {},
5670
+ requestId
5726
5671
  });
5727
- const queuePos = pendingToolQueue.length;
5728
- log("info", `HTTP /tool: ${body.method} (queue pos ${queuePos})`);
5672
+ lastToolName = body.method;
5673
+ lastToolTime = (/* @__PURE__ */ new Date()).toISOString();
5674
+ const MAX_PENDING_TOOLS = 50;
5675
+ const totalQueued = pendingToolMap.size + Array.from(busyTabs.values()).reduce((acc, arr) => acc + arr.length, 0);
5676
+ if (totalQueued >= MAX_PENDING_TOOLS) {
5677
+ return new Response(
5678
+ JSON.stringify({ error: "Too many pending tool requests" }),
5679
+ { status: 429, headers: { "Content-Type": "application/json" } }
5680
+ );
5681
+ }
5682
+ const tabBusy = [...pendingToolMap.values()].some((e) => e.tabId === tabId);
5683
+ log("info", `HTTP /tool: ${body.method} [${requestId}] tab=${tabId} busy=${tabBusy} pending=${pendingToolMap.size}`);
5729
5684
  const result = await new Promise((resolve3) => {
5685
+ let settled = false;
5686
+ const safeResolve = (val) => {
5687
+ if (settled) return;
5688
+ settled = true;
5689
+ resolve3(val);
5690
+ };
5730
5691
  const timeout = setTimeout(() => {
5731
- const idx = pendingToolQueue.findIndex((e) => e.resolve === resolve3);
5732
- const wasHead = idx === 0;
5733
- if (idx !== -1) pendingToolQueue.splice(idx, 1);
5734
- resolve3({ type: "tool_response", error: "Tool call timed out (30s)" });
5735
- if (wasHead) drainToolQueue();
5692
+ if (pendingToolMap.has(requestId)) {
5693
+ pendingToolMap.delete(requestId);
5694
+ drainTabQueue(tabId);
5695
+ } else {
5696
+ const queue = busyTabs.get(tabId);
5697
+ if (queue) {
5698
+ const idx = queue.findIndex((e) => e.requestId === requestId);
5699
+ if (idx !== -1) queue.splice(idx, 1);
5700
+ if (queue.length === 0) busyTabs.delete(tabId);
5701
+ }
5702
+ }
5703
+ safeResolve({ type: "tool_response", error: "Tool call timed out (30s)" });
5736
5704
  }, HTTP_TOOL_TIMEOUT_MS);
5737
- pendingToolQueue.push({ requestJson: toolRequest, resolve: resolve3, timeout });
5738
- if (pendingToolQueue.length === 1) drainToolQueue();
5705
+ if (tabBusy) {
5706
+ if (!busyTabs.has(tabId)) busyTabs.set(tabId, []);
5707
+ busyTabs.get(tabId).push({ requestJson: toolRequest, resolve: safeResolve, timeout, requestId, tabId });
5708
+ } else {
5709
+ pendingToolMap.set(requestId, { resolve: safeResolve, timeout, tabId });
5710
+ sendToolRequest(requestId, toolRequest);
5711
+ }
5739
5712
  });
5740
5713
  return new Response(
5741
5714
  JSON.stringify(result),
@@ -5781,6 +5754,10 @@ var init_claude_chrome_bridge = __esm({
5781
5754
  try {
5782
5755
  const parsed = JSON.parse(json);
5783
5756
  log("debug", `WS message type: ${parsed.type}`);
5757
+ if (parsed.type === "ping") {
5758
+ ws.send(JSON.stringify({ type: "pong" }));
5759
+ return;
5760
+ }
5784
5761
  if (parsed.type === "tool_response" && parsed.result?.result?.tabs) {
5785
5762
  const tabs = parsed.result.result.tabs;
5786
5763
  log("debug", `CDP: caching ${tabs.length} tab URLs from tabs_context_mcp`);
@@ -5790,14 +5767,31 @@ var init_claude_chrome_bridge = __esm({
5790
5767
  }
5791
5768
  }
5792
5769
  }
5793
- if (parsed.type === "tool_response" && pendingToolQueue.length > 0) {
5794
- const { resolve: resolve3, timeout } = pendingToolQueue.shift();
5795
- clearTimeout(timeout);
5796
- if ("method" in parsed) delete parsed.method;
5797
- log("debug", `HTTP /tool response (${pendingToolQueue.length} queued): ${json.slice(0, 200)}`);
5798
- resolve3(parsed);
5799
- drainToolQueue();
5800
- return;
5770
+ if (parsed.type === "tool_response" && pendingToolMap.size > 0) {
5771
+ let matched = false;
5772
+ if (parsed.requestId && pendingToolMap.has(parsed.requestId)) {
5773
+ const entry = pendingToolMap.get(parsed.requestId);
5774
+ pendingToolMap.delete(parsed.requestId);
5775
+ clearTimeout(entry.timeout);
5776
+ if ("method" in parsed) delete parsed.method;
5777
+ log("debug", `HTTP /tool response [${parsed.requestId}] (${pendingToolMap.size} pending): ${json.slice(0, 200)}`);
5778
+ entry.resolve(parsed);
5779
+ drainTabQueue(entry.tabId);
5780
+ matched = true;
5781
+ } else if (!parsed.requestId) {
5782
+ const firstKey = pendingToolMap.keys().next().value;
5783
+ if (firstKey) {
5784
+ const entry = pendingToolMap.get(firstKey);
5785
+ pendingToolMap.delete(firstKey);
5786
+ clearTimeout(entry.timeout);
5787
+ if ("method" in parsed) delete parsed.method;
5788
+ log("debug", `HTTP /tool response (FIFO fallback, ${pendingToolMap.size} pending): ${json.slice(0, 200)}`);
5789
+ entry.resolve(parsed);
5790
+ drainTabQueue(entry.tabId);
5791
+ matched = true;
5792
+ }
5793
+ }
5794
+ if (matched) return;
5801
5795
  }
5802
5796
  if (parsed.type === "tool_response" && "method" in parsed) {
5803
5797
  delete parsed.method;
@@ -5858,22 +5852,14 @@ var init_claude_chrome_bridge = __esm({
5858
5852
  log("info", `Claude Chrome Bridge v${BRIDGE_VERSION} started on ws://${WS_HOST}:${WS_PORT}`);
5859
5853
  log("info", `CLI path: ${CLI_PATH}`);
5860
5854
  log("info", `Auth: ${BRIDGE_TOKEN ? "token required" : "open (localhost only)"}`);
5861
- (async () => {
5862
- const CDP_RETRY_ATTEMPTS = 5;
5863
- const CDP_RETRY_DELAY_MS = 1e4;
5864
- for (let attempt = 1; attempt <= CDP_RETRY_ATTEMPTS; attempt++) {
5865
- const ok = await cdpManager.connect();
5866
- if (ok) {
5867
- log("info", `CDP: ready (${JSON.stringify(cdpManager.getStatus())})`);
5868
- return;
5869
- }
5870
- if (attempt < CDP_RETRY_ATTEMPTS) {
5871
- log("info", `CDP: attempt ${attempt}/${CDP_RETRY_ATTEMPTS} failed \u2014 retrying in ${CDP_RETRY_DELAY_MS / 1e3}s`);
5872
- await new Promise((r) => setTimeout(r, CDP_RETRY_DELAY_MS));
5873
- }
5855
+ cdpManager.connect().then((ok) => {
5856
+ if (ok) {
5857
+ log("info", `CDP: ready (${JSON.stringify(cdpManager.getStatus())})`);
5858
+ } else {
5859
+ log("info", "CDP: not available at startup \u2014 reconnect timer will retry periodically");
5860
+ cdpManager.startReconnectTimer();
5874
5861
  }
5875
- log("info", "CDP: not available after retries (ADB/Edge not running \u2014 will use extension fallback)");
5876
- })();
5862
+ });
5877
5863
  log("info", "Waiting for WebSocket connections...");
5878
5864
  adbNotify("cfc-bridge", `CFC Bridge v${BRIDGE_VERSION}`, `Running on :${WS_PORT} (PID ${process.pid})`);
5879
5865
  TEST_PAGE_HTML = `<!DOCTYPE html>
@@ -5988,7 +5974,7 @@ var init_claude_chrome_bridge = __esm({
5988
5974
  }
5989
5975
  });
5990
5976
 
5991
- // bridge/src/cli.ts
5977
+ // src/cli.ts
5992
5978
  init_import_meta_shim();
5993
5979
  var import_path2 = require("path");
5994
5980
  var import_fs = require("fs");
@@ -6138,16 +6124,29 @@ echo "[$(date +%H:%M:%S)] termux-url-opener: $url" >> "$PREFIX/tmp/url-opener.lo
6138
6124
  case "$url" in
6139
6125
  *cfcbridge*/start*)
6140
6126
  BRIDGE_LOG="$PREFIX/tmp/bridge.log"
6141
- if pgrep -f "(bun|node).*claude-chrome" > /dev/null 2>&1; then
6127
+ # Health-check the bridge directly \u2014 avoids pgrep self-match
6128
+ if curl -sf --connect-timeout 2 http://127.0.0.1:18963/health > /dev/null 2>&1; then
6142
6129
  echo "[$(date +%H:%M:%S)] bridge already running" >> "$PREFIX/tmp/url-opener.log"
6143
6130
  exit 0
6144
6131
  fi
6132
+ # Find a JS runtime that can actually execute code.
6133
+ # bun on Termux uses a C wrapper (bun-termux) that may fail if its
6134
+ # shim library is missing \u2014 test with a real eval, not just --version.
6135
+ _try_runtime() {
6136
+ "$1" -e "process.exit(0)" > /dev/null 2>&1
6137
+ }
6145
6138
  RUNTIME=""
6146
- if [[ -x "$HOME/.bun/bin/bun" ]]; then RUNTIME="$HOME/.bun/bin/bun"
6147
- elif command -v bun > /dev/null 2>&1; then RUNTIME="$(command -v bun)"
6148
- elif command -v node > /dev/null 2>&1; then RUNTIME="$(command -v node)"
6139
+ if [[ -x "$HOME/.bun/bin/bun" ]] && _try_runtime "$HOME/.bun/bin/bun"; then
6140
+ RUNTIME="$HOME/.bun/bin/bun"
6141
+ elif command -v bun > /dev/null 2>&1 && _try_runtime bun; then
6142
+ RUNTIME="$(command -v bun)"
6143
+ elif command -v node > /dev/null 2>&1 && _try_runtime node; then
6144
+ RUNTIME="$(command -v node)"
6145
+ fi
6146
+ if [[ -z "$RUNTIME" ]]; then
6147
+ echo "[$(date +%H:%M:%S)] no working JS runtime found" >> "$PREFIX/tmp/url-opener.log"
6148
+ exit 1
6149
6149
  fi
6150
- if [[ -z "$RUNTIME" ]]; then exit 1; fi
6151
6150
  BRIDGE_SCRIPT=""
6152
6151
  if [[ -f "$HOME/git/termux-tools/claude-chrome-bridge.ts" ]]; then
6153
6152
  BRIDGE_SCRIPT="$HOME/git/termux-tools/claude-chrome-bridge.ts"
@@ -6560,7 +6559,13 @@ async function callBridgeTool(method, params) {
6560
6559
  const body = await resp.text();
6561
6560
  return { error: `Bridge HTTP ${resp.status}: ${body}` };
6562
6561
  }
6563
- const data = await resp.json();
6562
+ const text = await resp.text();
6563
+ let data;
6564
+ try {
6565
+ data = JSON.parse(text);
6566
+ } catch {
6567
+ return { error: `Bridge returned non-JSON: ${text.slice(0, 200)}` };
6568
+ }
6564
6569
  if (data.error) return { error: String(data.error) };
6565
6570
  return { result: data.result ?? data };
6566
6571
  } catch (err) {
@@ -6625,8 +6630,15 @@ async function cmdMcp() {
6625
6630
  }
6626
6631
  const decoder = new TextDecoder();
6627
6632
  let buffer = "";
6633
+ const MAX_BUFFER_SIZE = 10 * 1024 * 1024;
6628
6634
  for await (const chunk of process.stdin) {
6629
6635
  buffer += typeof chunk === "string" ? chunk : decoder.decode(chunk);
6636
+ if (buffer.length > MAX_BUFFER_SIZE) {
6637
+ log2(`WARN: MCP buffer exceeded ${MAX_BUFFER_SIZE} bytes, discarding`);
6638
+ buffer = "";
6639
+ mcpSend(mcpError(0, -32600, "Request too large"));
6640
+ continue;
6641
+ }
6630
6642
  let idx;
6631
6643
  while ((idx = buffer.indexOf("\n")) !== -1) {
6632
6644
  const line = buffer.slice(0, idx).trim();