claude-chrome-android 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
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
- // src/import-meta-shim.js
31
+ // bridge/src/import-meta-shim.js
32
32
  var import_meta_url;
33
33
  var init_import_meta_shim = __esm({
34
- "src/import-meta-shim.js"() {
34
+ "bridge/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"];
@@ -46,6 +46,7 @@ var require_constants = __commonJS({
46
46
  if (hasBlob) BINARY_TYPES.push("blob");
47
47
  module2.exports = {
48
48
  BINARY_TYPES,
49
+ CLOSE_TIMEOUT: 3e4,
49
50
  EMPTY_BUFFER: Buffer.alloc(0),
50
51
  GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
51
52
  hasBlob,
@@ -59,9 +60,9 @@ var require_constants = __commonJS({
59
60
  }
60
61
  });
61
62
 
62
- // ../../../node_modules/node-gyp-build/node-gyp-build.js
63
+ // ../../node_modules/node-gyp-build/node-gyp-build.js
63
64
  var require_node_gyp_build = __commonJS({
64
- "../../../node_modules/node-gyp-build/node-gyp-build.js"(exports2, module2) {
65
+ "../../node_modules/node-gyp-build/node-gyp-build.js"(exports2, module2) {
65
66
  init_import_meta_shim();
66
67
  var fs = require("fs");
67
68
  var path = require("path");
@@ -229,9 +230,9 @@ var require_node_gyp_build = __commonJS({
229
230
  }
230
231
  });
231
232
 
232
- // ../../../node_modules/node-gyp-build/index.js
233
+ // ../../node_modules/node-gyp-build/index.js
233
234
  var require_node_gyp_build2 = __commonJS({
234
- "../../../node_modules/node-gyp-build/index.js"(exports2, module2) {
235
+ "../../node_modules/node-gyp-build/index.js"(exports2, module2) {
235
236
  init_import_meta_shim();
236
237
  var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
237
238
  if (typeof runtimeRequire.addon === "function") {
@@ -242,9 +243,9 @@ var require_node_gyp_build2 = __commonJS({
242
243
  }
243
244
  });
244
245
 
245
- // ../../../node_modules/bufferutil/fallback.js
246
+ // ../../node_modules/bufferutil/fallback.js
246
247
  var require_fallback = __commonJS({
247
- "../../../node_modules/bufferutil/fallback.js"(exports2, module2) {
248
+ "../../node_modules/bufferutil/fallback.js"(exports2, module2) {
248
249
  "use strict";
249
250
  init_import_meta_shim();
250
251
  var mask = (source, mask2, output, offset, length) => {
@@ -262,9 +263,9 @@ var require_fallback = __commonJS({
262
263
  }
263
264
  });
264
265
 
265
- // ../../../node_modules/bufferutil/index.js
266
+ // ../../node_modules/bufferutil/index.js
266
267
  var require_bufferutil = __commonJS({
267
- "../../../node_modules/bufferutil/index.js"(exports2, module2) {
268
+ "../../node_modules/bufferutil/index.js"(exports2, module2) {
268
269
  "use strict";
269
270
  init_import_meta_shim();
270
271
  try {
@@ -275,9 +276,9 @@ var require_bufferutil = __commonJS({
275
276
  }
276
277
  });
277
278
 
278
- // ../../../node_modules/ws/lib/buffer-util.js
279
+ // ../../node_modules/ws/lib/buffer-util.js
279
280
  var require_buffer_util = __commonJS({
280
- "../../../node_modules/ws/lib/buffer-util.js"(exports2, module2) {
281
+ "../../node_modules/ws/lib/buffer-util.js"(exports2, module2) {
281
282
  "use strict";
282
283
  init_import_meta_shim();
283
284
  var { EMPTY_BUFFER } = require_constants();
@@ -351,9 +352,9 @@ var require_buffer_util = __commonJS({
351
352
  }
352
353
  });
353
354
 
354
- // ../../../node_modules/ws/lib/limiter.js
355
+ // ../../node_modules/ws/lib/limiter.js
355
356
  var require_limiter = __commonJS({
356
- "../../../node_modules/ws/lib/limiter.js"(exports2, module2) {
357
+ "../../node_modules/ws/lib/limiter.js"(exports2, module2) {
357
358
  "use strict";
358
359
  init_import_meta_shim();
359
360
  var kDone = /* @__PURE__ */ Symbol("kDone");
@@ -402,9 +403,9 @@ var require_limiter = __commonJS({
402
403
  }
403
404
  });
404
405
 
405
- // ../../../node_modules/ws/lib/permessage-deflate.js
406
+ // ../../node_modules/ws/lib/permessage-deflate.js
406
407
  var require_permessage_deflate = __commonJS({
407
- "../../../node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
408
+ "../../node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
408
409
  "use strict";
409
410
  init_import_meta_shim();
410
411
  var zlib = require("zlib");
@@ -786,9 +787,9 @@ var require_permessage_deflate = __commonJS({
786
787
  }
787
788
  });
788
789
 
789
- // ../../../node_modules/utf-8-validate/fallback.js
790
+ // ../../node_modules/utf-8-validate/fallback.js
790
791
  var require_fallback2 = __commonJS({
791
- "../../../node_modules/utf-8-validate/fallback.js"(exports2, module2) {
792
+ "../../node_modules/utf-8-validate/fallback.js"(exports2, module2) {
792
793
  "use strict";
793
794
  init_import_meta_shim();
794
795
  function isValidUTF8(buf) {
@@ -824,9 +825,9 @@ var require_fallback2 = __commonJS({
824
825
  }
825
826
  });
826
827
 
827
- // ../../../node_modules/utf-8-validate/index.js
828
+ // ../../node_modules/utf-8-validate/index.js
828
829
  var require_utf_8_validate = __commonJS({
829
- "../../../node_modules/utf-8-validate/index.js"(exports2, module2) {
830
+ "../../node_modules/utf-8-validate/index.js"(exports2, module2) {
830
831
  "use strict";
831
832
  init_import_meta_shim();
832
833
  try {
@@ -837,9 +838,9 @@ var require_utf_8_validate = __commonJS({
837
838
  }
838
839
  });
839
840
 
840
- // ../../../node_modules/ws/lib/validation.js
841
+ // ../../node_modules/ws/lib/validation.js
841
842
  var require_validation = __commonJS({
842
- "../../../node_modules/ws/lib/validation.js"(exports2, module2) {
843
+ "../../node_modules/ws/lib/validation.js"(exports2, module2) {
843
844
  "use strict";
844
845
  init_import_meta_shim();
845
846
  var { isUtf8 } = require("buffer");
@@ -1039,9 +1040,9 @@ var require_validation = __commonJS({
1039
1040
  }
1040
1041
  });
1041
1042
 
1042
- // ../../../node_modules/ws/lib/receiver.js
1043
+ // ../../node_modules/ws/lib/receiver.js
1043
1044
  var require_receiver = __commonJS({
1044
- "../../../node_modules/ws/lib/receiver.js"(exports2, module2) {
1045
+ "../../node_modules/ws/lib/receiver.js"(exports2, module2) {
1045
1046
  "use strict";
1046
1047
  init_import_meta_shim();
1047
1048
  var { Writable } = require("stream");
@@ -1632,9 +1633,9 @@ var require_receiver = __commonJS({
1632
1633
  }
1633
1634
  });
1634
1635
 
1635
- // ../../../node_modules/ws/lib/sender.js
1636
+ // ../../node_modules/ws/lib/sender.js
1636
1637
  var require_sender = __commonJS({
1637
- "../../../node_modules/ws/lib/sender.js"(exports2, module2) {
1638
+ "../../node_modules/ws/lib/sender.js"(exports2, module2) {
1638
1639
  "use strict";
1639
1640
  init_import_meta_shim();
1640
1641
  var { Duplex } = require("stream");
@@ -2121,9 +2122,9 @@ var require_sender = __commonJS({
2121
2122
  }
2122
2123
  });
2123
2124
 
2124
- // ../../../node_modules/ws/lib/event-target.js
2125
+ // ../../node_modules/ws/lib/event-target.js
2125
2126
  var require_event_target = __commonJS({
2126
- "../../../node_modules/ws/lib/event-target.js"(exports2, module2) {
2127
+ "../../node_modules/ws/lib/event-target.js"(exports2, module2) {
2127
2128
  "use strict";
2128
2129
  init_import_meta_shim();
2129
2130
  var { kForOnEventAttribute, kListener } = require_constants();
@@ -2351,9 +2352,9 @@ var require_event_target = __commonJS({
2351
2352
  }
2352
2353
  });
2353
2354
 
2354
- // ../../../node_modules/ws/lib/extension.js
2355
+ // ../../node_modules/ws/lib/extension.js
2355
2356
  var require_extension = __commonJS({
2356
- "../../../node_modules/ws/lib/extension.js"(exports2, module2) {
2357
+ "../../node_modules/ws/lib/extension.js"(exports2, module2) {
2357
2358
  "use strict";
2358
2359
  init_import_meta_shim();
2359
2360
  var { tokenChars } = require_validation();
@@ -2505,9 +2506,9 @@ var require_extension = __commonJS({
2505
2506
  }
2506
2507
  });
2507
2508
 
2508
- // ../../../node_modules/ws/lib/websocket.js
2509
+ // ../../node_modules/ws/lib/websocket.js
2509
2510
  var require_websocket = __commonJS({
2510
- "../../../node_modules/ws/lib/websocket.js"(exports2, module2) {
2511
+ "../../node_modules/ws/lib/websocket.js"(exports2, module2) {
2511
2512
  "use strict";
2512
2513
  init_import_meta_shim();
2513
2514
  var EventEmitter = require("events");
@@ -2524,6 +2525,7 @@ var require_websocket = __commonJS({
2524
2525
  var { isBlob } = require_validation();
2525
2526
  var {
2526
2527
  BINARY_TYPES,
2528
+ CLOSE_TIMEOUT,
2527
2529
  EMPTY_BUFFER,
2528
2530
  GUID,
2529
2531
  kForOnEventAttribute,
@@ -2537,7 +2539,6 @@ var require_websocket = __commonJS({
2537
2539
  } = require_event_target();
2538
2540
  var { format, parse } = require_extension();
2539
2541
  var { toBuffer } = require_buffer_util();
2540
- var closeTimeout = 30 * 1e3;
2541
2542
  var kAborted = /* @__PURE__ */ Symbol("kAborted");
2542
2543
  var protocolVersions = [8, 13];
2543
2544
  var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
@@ -2583,6 +2584,7 @@ var require_websocket = __commonJS({
2583
2584
  initAsClient(this, address, protocols, options);
2584
2585
  } else {
2585
2586
  this._autoPong = options.autoPong;
2587
+ this._closeTimeout = options.closeTimeout;
2586
2588
  this._isServer = true;
2587
2589
  }
2588
2590
  }
@@ -2984,6 +2986,7 @@ var require_websocket = __commonJS({
2984
2986
  const opts = {
2985
2987
  allowSynchronousEvents: true,
2986
2988
  autoPong: true,
2989
+ closeTimeout: CLOSE_TIMEOUT,
2987
2990
  protocolVersion: protocolVersions[1],
2988
2991
  maxPayload: 100 * 1024 * 1024,
2989
2992
  skipUTF8Validation: false,
@@ -3001,6 +3004,7 @@ var require_websocket = __commonJS({
3001
3004
  port: void 0
3002
3005
  };
3003
3006
  websocket._autoPong = opts.autoPong;
3007
+ websocket._closeTimeout = opts.closeTimeout;
3004
3008
  if (!protocolVersions.includes(opts.protocolVersion)) {
3005
3009
  throw new RangeError(
3006
3010
  `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
@@ -3343,7 +3347,7 @@ var require_websocket = __commonJS({
3343
3347
  function setCloseTimer(websocket) {
3344
3348
  websocket._closeTimer = setTimeout(
3345
3349
  websocket._socket.destroy.bind(websocket._socket),
3346
- closeTimeout
3350
+ websocket._closeTimeout
3347
3351
  );
3348
3352
  }
3349
3353
  function socketOnClose() {
@@ -3352,8 +3356,8 @@ var require_websocket = __commonJS({
3352
3356
  this.removeListener("data", socketOnData);
3353
3357
  this.removeListener("end", socketOnEnd);
3354
3358
  websocket._readyState = WebSocket3.CLOSING;
3355
- let chunk;
3356
- if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
3359
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3360
+ const chunk = this.read(this._readableState.length);
3357
3361
  websocket._receiver.write(chunk);
3358
3362
  }
3359
3363
  websocket._receiver.end();
@@ -3389,9 +3393,9 @@ var require_websocket = __commonJS({
3389
3393
  }
3390
3394
  });
3391
3395
 
3392
- // ../../../node_modules/ws/lib/stream.js
3396
+ // ../../node_modules/ws/lib/stream.js
3393
3397
  var require_stream = __commonJS({
3394
- "../../../node_modules/ws/lib/stream.js"(exports2, module2) {
3398
+ "../../node_modules/ws/lib/stream.js"(exports2, module2) {
3395
3399
  "use strict";
3396
3400
  init_import_meta_shim();
3397
3401
  var WebSocket3 = require_websocket();
@@ -3488,9 +3492,9 @@ var require_stream = __commonJS({
3488
3492
  }
3489
3493
  });
3490
3494
 
3491
- // ../../../node_modules/ws/lib/subprotocol.js
3495
+ // ../../node_modules/ws/lib/subprotocol.js
3492
3496
  var require_subprotocol = __commonJS({
3493
- "../../../node_modules/ws/lib/subprotocol.js"(exports2, module2) {
3497
+ "../../node_modules/ws/lib/subprotocol.js"(exports2, module2) {
3494
3498
  "use strict";
3495
3499
  init_import_meta_shim();
3496
3500
  var { tokenChars } = require_validation();
@@ -3534,9 +3538,9 @@ var require_subprotocol = __commonJS({
3534
3538
  }
3535
3539
  });
3536
3540
 
3537
- // ../../../node_modules/ws/lib/websocket-server.js
3541
+ // ../../node_modules/ws/lib/websocket-server.js
3538
3542
  var require_websocket_server = __commonJS({
3539
- "../../../node_modules/ws/lib/websocket-server.js"(exports2, module2) {
3543
+ "../../node_modules/ws/lib/websocket-server.js"(exports2, module2) {
3540
3544
  "use strict";
3541
3545
  init_import_meta_shim();
3542
3546
  var EventEmitter = require("events");
@@ -3547,7 +3551,7 @@ var require_websocket_server = __commonJS({
3547
3551
  var PerMessageDeflate = require_permessage_deflate();
3548
3552
  var subprotocol = require_subprotocol();
3549
3553
  var WebSocket3 = require_websocket();
3550
- var { GUID, kWebSocket } = require_constants();
3554
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3551
3555
  var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3552
3556
  var RUNNING = 0;
3553
3557
  var CLOSING = 1;
@@ -3566,6 +3570,9 @@ var require_websocket_server = __commonJS({
3566
3570
  * pending connections
3567
3571
  * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3568
3572
  * track clients
3573
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3574
+ * wait for the closing handshake to finish after `websocket.close()` is
3575
+ * called
3569
3576
  * @param {Function} [options.handleProtocols] A hook to handle protocols
3570
3577
  * @param {String} [options.host] The hostname where to bind the server
3571
3578
  * @param {Number} [options.maxPayload=104857600] The maximum allowed message
@@ -3594,6 +3601,7 @@ var require_websocket_server = __commonJS({
3594
3601
  perMessageDeflate: false,
3595
3602
  handleProtocols: null,
3596
3603
  clientTracking: true,
3604
+ closeTimeout: CLOSE_TIMEOUT,
3597
3605
  verifyClient: null,
3598
3606
  noServer: false,
3599
3607
  backlog: null,
@@ -3924,10 +3932,10 @@ var require_websocket_server = __commonJS({
3924
3932
  }
3925
3933
  });
3926
3934
 
3927
- // ../../../node_modules/ws/wrapper.mjs
3935
+ // ../../node_modules/ws/wrapper.mjs
3928
3936
  var import_stream, import_receiver, import_sender, import_websocket, import_websocket_server;
3929
3937
  var init_wrapper = __esm({
3930
- "../../../node_modules/ws/wrapper.mjs"() {
3938
+ "../../node_modules/ws/wrapper.mjs"() {
3931
3939
  init_import_meta_shim();
3932
3940
  import_stream = __toESM(require_stream(), 1);
3933
3941
  import_receiver = __toESM(require_receiver(), 1);
@@ -3937,7 +3945,7 @@ var init_wrapper = __esm({
3937
3945
  }
3938
3946
  });
3939
3947
 
3940
- // ../compat.ts
3948
+ // compat.ts
3941
3949
  async function fileExists(path) {
3942
3950
  if (IS_BUN) {
3943
3951
  return Bun.file(path).exists();
@@ -4192,7 +4200,7 @@ function createNodeServer(config) {
4192
4200
  }
4193
4201
  var import_promises, import_node_fs, import_node_stream, cp, http, IS_BUN;
4194
4202
  var init_compat = __esm({
4195
- "../compat.ts"() {
4203
+ "compat.ts"() {
4196
4204
  init_import_meta_shim();
4197
4205
  import_promises = require("node:fs/promises");
4198
4206
  import_node_fs = require("node:fs");
@@ -4204,11 +4212,14 @@ var init_compat = __esm({
4204
4212
  }
4205
4213
  });
4206
4214
 
4207
- // ../claude-chrome-bridge.ts
4215
+ // claude-chrome-bridge.ts
4208
4216
  var claude_chrome_bridge_exports = {};
4217
+ function adb(...args2) {
4218
+ return ADB_SERIAL ? [ADB_PATH, "-s", ADB_SERIAL, ...args2] : [ADB_PATH, ...args2];
4219
+ }
4209
4220
  function adbNotify(tag, title, text) {
4210
4221
  try {
4211
- runDetached([ADB_PATH, "shell", "cmd", "notification", "post", "-t", title, tag, text]);
4222
+ runDetached(adb("shell", "cmd", "notification", "post", "-t", title, tag, text));
4212
4223
  } catch {
4213
4224
  }
4214
4225
  }
@@ -4549,6 +4560,16 @@ function encodeGIF(frames, delayMs) {
4549
4560
  }
4550
4561
  return result;
4551
4562
  }
4563
+ function drainToolQueue() {
4564
+ if (pendingToolQueue.length === 0) return;
4565
+ const next = pendingToolQueue[0];
4566
+ for (const client of wsClients) {
4567
+ try {
4568
+ client.send(next.requestJson);
4569
+ } catch {
4570
+ }
4571
+ }
4572
+ }
4552
4573
  function spawnNativeHost() {
4553
4574
  if (nativeHost) {
4554
4575
  log("warn", "Native host already running, killing first");
@@ -4842,9 +4863,9 @@ function shutdown() {
4842
4863
  log("info", "Bridge stopped");
4843
4864
  process.exit(0);
4844
4865
  }
4845
- 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, 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, nativeHost, stdoutDecoder, wsClients, server, TEST_PAGE_HTML;
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;
4846
4867
  var init_claude_chrome_bridge = __esm({
4847
- "../claude-chrome-bridge.ts"() {
4868
+ "claude-chrome-bridge.ts"() {
4848
4869
  init_import_meta_shim();
4849
4870
  import_path = require("path");
4850
4871
  import_node_zlib = require("node:zlib");
@@ -4869,6 +4890,21 @@ var init_claude_chrome_bridge = __esm({
4869
4890
  TERMUX_PREFIX = "/data/data/com.termux/files/usr";
4870
4891
  TERMUX_BIN = `${TERMUX_PREFIX}/bin`;
4871
4892
  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
+ })();
4872
4908
  REPO_CLI = (0, import_path.resolve)(SCRIPT_DIR, "cli.js");
4873
4909
  BUN_GLOBAL_CLI = (0, import_path.resolve)(
4874
4910
  process.env.HOME ?? "~",
@@ -4950,10 +4986,10 @@ var init_claude_chrome_bridge = __esm({
4950
4986
  if (this.state === "connecting") return false;
4951
4987
  this.state = "connecting";
4952
4988
  try {
4953
- const pidResult = runSync([ADB_PATH, "shell", "pidof", "com.microsoft.emmx.canary"]);
4989
+ const pidResult = runSync(adb("shell", "pidof", "com.microsoft.emmx.canary"));
4954
4990
  const pidStr = pidResult.stdout.toString().trim().split(/\s+/)[0];
4955
4991
  if (!pidStr || pidResult.exitCode !== 0) {
4956
- log("debug", "CDP: Edge not running or ADB unavailable");
4992
+ log("debug", `CDP: Edge not running or ADB unavailable (exit=${pidResult.exitCode}, stderr=${pidResult.stderr?.toString().trim()}, serial=${ADB_SERIAL || "default"})`);
4957
4993
  this.state = "disconnected";
4958
4994
  return false;
4959
4995
  }
@@ -4972,7 +5008,7 @@ var init_claude_chrome_bridge = __esm({
4972
5008
  let versionData = null;
4973
5009
  for (const socketName of socketCandidates) {
4974
5010
  const fwdResult = runSync(
4975
- [ADB_PATH, "forward", `tcp:${CDP_PORT}`, `localabstract:${socketName}`]
5011
+ adb("forward", `tcp:${CDP_PORT}`, `localabstract:${socketName}`)
4976
5012
  );
4977
5013
  if (fwdResult.exitCode !== 0) continue;
4978
5014
  try {
@@ -4981,7 +5017,7 @@ var init_claude_chrome_bridge = __esm({
4981
5017
  log("info", `CDP: Edge version \u2014 ${versionData["Browser"] ?? "unknown"}, pkg: ${versionData["Android-Package"] ?? "unknown"} (socket: ${socketName})`);
4982
5018
  break;
4983
5019
  } catch {
4984
- runSync([ADB_PATH, "forward", "--remove", `tcp:${CDP_PORT}`]);
5020
+ runSync(adb("forward", "--remove", `tcp:${CDP_PORT}`));
4985
5021
  }
4986
5022
  }
4987
5023
  if (!versionData) {
@@ -5236,9 +5272,9 @@ var init_claude_chrome_bridge = __esm({
5236
5272
  }
5237
5273
  try {
5238
5274
  const tmpPath = "/data/data/com.termux/files/usr/tmp/cdp-screencap.png";
5239
- const cap = runSync([ADB_PATH, "shell", "screencap", "-p", "/sdcard/cdp-screencap.png"]);
5275
+ const cap = runSync(adb("shell", "screencap", "-p", "/sdcard/cdp-screencap.png"));
5240
5276
  if (cap.exitCode === 0) {
5241
- const pull = runSync([ADB_PATH, "pull", "/sdcard/cdp-screencap.png", tmpPath]);
5277
+ const pull = runSync(adb("pull", "/sdcard/cdp-screencap.png", tmpPath));
5242
5278
  if (pull.exitCode === 0 && await fileExists(tmpPath)) {
5243
5279
  const { readFile: rf } = await import("node:fs/promises");
5244
5280
  const buf = await rf(tmpPath);
@@ -5469,7 +5505,7 @@ var init_claude_chrome_bridge = __esm({
5469
5505
  /** Re-check Edge PID — reconnect if changed (Edge restarted) */
5470
5506
  async recheckPid() {
5471
5507
  try {
5472
- const pidResult = runSync([ADB_PATH, "shell", "pidof", "com.microsoft.emmx.canary"]);
5508
+ const pidResult = runSync(adb("shell", "pidof", "com.microsoft.emmx.canary"));
5473
5509
  const pidStr = pidResult.stdout.toString().trim().split(/\s+/)[0];
5474
5510
  const newPid = parseInt(pidStr, 10);
5475
5511
  if (isNaN(newPid)) {
@@ -5510,7 +5546,7 @@ var init_claude_chrome_bridge = __esm({
5510
5546
  p.reject(new Error("CDP cleanup"));
5511
5547
  });
5512
5548
  this.pending.clear();
5513
- runSync([ADB_PATH, "forward", "--remove", `tcp:${CDP_PORT}`]);
5549
+ runSync(adb("forward", "--remove", `tcp:${CDP_PORT}`));
5514
5550
  log("info", "CDP: cleaned up");
5515
5551
  }
5516
5552
  };
@@ -5521,6 +5557,8 @@ var init_claude_chrome_bridge = __esm({
5521
5557
  for (let j = 0; j < 8; j++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
5522
5558
  crc32Table[i] = c;
5523
5559
  }
5560
+ pendingToolQueue = [];
5561
+ HTTP_TOOL_TIMEOUT_MS = 3e4;
5524
5562
  nativeHost = null;
5525
5563
  stdoutDecoder = new NativeMessageDecoder();
5526
5564
  wsClients = /* @__PURE__ */ new Set();
@@ -5672,6 +5710,44 @@ var init_claude_chrome_bridge = __esm({
5672
5710
  headers: { "Content-Type": "text/html; charset=utf-8" }
5673
5711
  });
5674
5712
  }
5713
+ if (url.pathname === "/tool" && req.method === "POST") {
5714
+ if (wsClients.size === 0) {
5715
+ return new Response(
5716
+ JSON.stringify({ error: "No extension connected" }),
5717
+ { status: 503, headers: { "Content-Type": "application/json" } }
5718
+ );
5719
+ }
5720
+ try {
5721
+ const body = await req.json();
5722
+ const toolRequest = JSON.stringify({
5723
+ type: "tool_request",
5724
+ method: body.method,
5725
+ params: body.params ?? {}
5726
+ });
5727
+ const queuePos = pendingToolQueue.length;
5728
+ log("info", `HTTP /tool: ${body.method} (queue pos ${queuePos})`);
5729
+ const result = await new Promise((resolve3) => {
5730
+ 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();
5736
+ }, HTTP_TOOL_TIMEOUT_MS);
5737
+ pendingToolQueue.push({ requestJson: toolRequest, resolve: resolve3, timeout });
5738
+ if (pendingToolQueue.length === 1) drainToolQueue();
5739
+ });
5740
+ return new Response(
5741
+ JSON.stringify(result),
5742
+ { headers: { "Content-Type": "application/json" } }
5743
+ );
5744
+ } catch (err) {
5745
+ return new Response(
5746
+ JSON.stringify({ error: err.message }),
5747
+ { status: 500, headers: { "Content-Type": "application/json" } }
5748
+ );
5749
+ }
5750
+ }
5675
5751
  if (url.pathname === "/ws" || url.pathname === "/") {
5676
5752
  if (BRIDGE_TOKEN) {
5677
5753
  const token = url.searchParams.get("token") ?? req.headers.get("x-bridge-token") ?? "";
@@ -5714,6 +5790,15 @@ var init_claude_chrome_bridge = __esm({
5714
5790
  }
5715
5791
  }
5716
5792
  }
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;
5801
+ }
5717
5802
  if (parsed.type === "tool_response" && "method" in parsed) {
5718
5803
  delete parsed.method;
5719
5804
  const fixed = JSON.stringify(parsed);
@@ -5773,10 +5858,22 @@ var init_claude_chrome_bridge = __esm({
5773
5858
  log("info", `Claude Chrome Bridge v${BRIDGE_VERSION} started on ws://${WS_HOST}:${WS_PORT}`);
5774
5859
  log("info", `CLI path: ${CLI_PATH}`);
5775
5860
  log("info", `Auth: ${BRIDGE_TOKEN ? "token required" : "open (localhost only)"}`);
5776
- cdpManager.connect().then((ok) => {
5777
- if (ok) log("info", `CDP: ready (${JSON.stringify(cdpManager.getStatus())})`);
5778
- else log("info", "CDP: not available (ADB/Edge not running \u2014 will use extension fallback)");
5779
- });
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
+ }
5874
+ }
5875
+ log("info", "CDP: not available after retries (ADB/Edge not running \u2014 will use extension fallback)");
5876
+ })();
5780
5877
  log("info", "Waiting for WebSocket connections...");
5781
5878
  adbNotify("cfc-bridge", `CFC Bridge v${BRIDGE_VERSION}`, `Running on :${WS_PORT} (PID ${process.pid})`);
5782
5879
  TEST_PAGE_HTML = `<!DOCTYPE html>
@@ -5891,7 +5988,7 @@ var init_claude_chrome_bridge = __esm({
5891
5988
  }
5892
5989
  });
5893
5990
 
5894
- // src/cli.ts
5991
+ // bridge/src/cli.ts
5895
5992
  init_import_meta_shim();
5896
5993
  var import_path2 = require("path");
5897
5994
  var import_fs = require("fs");
@@ -5906,8 +6003,11 @@ var PKG_VERSION = (() => {
5906
6003
  })();
5907
6004
  var WS_PORT2 = parseInt(process.env.BRIDGE_PORT ?? "18963", 10);
5908
6005
  var WS_HOST2 = "127.0.0.1";
5909
- var HEALTH_URL = `http://${WS_HOST2}:${WS_PORT2}/health`;
5910
- var SHUTDOWN_URL = `http://${WS_HOST2}:${WS_PORT2}/shutdown`;
6006
+ var BRIDGE_URL = process.env.BRIDGE_URL ?? `http://${WS_HOST2}:${WS_PORT2}`;
6007
+ var HEALTH_URL = `${BRIDGE_URL}/health`;
6008
+ var SHUTDOWN_URL = `${BRIDGE_URL}/shutdown`;
6009
+ var TOOL_URL = `${BRIDGE_URL}/tool`;
6010
+ var TOOL_TIMEOUT_MS = 3e4;
5911
6011
  async function fetchWithTimeout(url, opts = {}) {
5912
6012
  const { timeout = 3e3, ...fetchOpts } = opts;
5913
6013
  const controller = new AbortController();
@@ -5936,8 +6036,9 @@ CFC Bridge \u2014 connects Claude Code CLI to Chrome/Edge on Android via WebSock
5936
6036
 
5937
6037
  Usage:
5938
6038
  claude-chrome-android Start the bridge server
6039
+ claude-chrome-android --mcp MCP server mode (spawned by Claude Code)
5939
6040
  claude-chrome-android --stop Stop a running bridge
5940
- claude-chrome-android --setup Create ~/bin/termux-url-opener + verify deps
6041
+ claude-chrome-android --setup Register MCP server in Claude Code + create url-opener
5941
6042
  claude-chrome-android --version Print version
5942
6043
  claude-chrome-android --help Show this help
5943
6044
 
@@ -5951,18 +6052,14 @@ async function cmdStop() {
5951
6052
  console.log("Stopping bridge...");
5952
6053
  try {
5953
6054
  const res = await fetchWithTimeout(SHUTDOWN_URL, { method: "POST", timeout: 3e3 });
5954
- if (res.ok) {
5955
- console.log("Shutdown request accepted");
5956
- }
6055
+ if (res.ok) console.log("Shutdown request accepted");
5957
6056
  } catch {
5958
6057
  }
5959
6058
  await new Promise((r) => setTimeout(r, 800));
5960
6059
  if (await isBridgeAlive()) {
5961
6060
  console.log("Bridge didn't stop gracefully, attempting pkill...");
5962
6061
  const { spawnSync: spawnSync2 } = await import("child_process");
5963
- const result = spawnSync2("pkill", ["-f", "(bun|node).*claude-chrome"], {
5964
- stdio: "ignore"
5965
- });
6062
+ spawnSync2("pkill", ["-f", "(bun|node).*claude-chrome"], { stdio: "ignore" });
5966
6063
  await new Promise((r) => setTimeout(r, 500));
5967
6064
  if (await isBridgeAlive()) {
5968
6065
  console.error("Bridge is still running. Kill manually: pkill -f claude-chrome-bridge");
@@ -5984,15 +6081,43 @@ async function cmdSetup() {
5984
6081
  const { spawnSync: spawnSync2 } = await import("child_process");
5985
6082
  const bunCheck = spawnSync2("bun", ["--version"], { stdio: "pipe", encoding: "utf-8" });
5986
6083
  if (bunCheck.status === 0) {
5987
- console.log(`Bun: ${bunCheck.stdout.trim()} (will prefer bun for performance)`);
5988
- } else {
5989
- console.log("Bun: not found (will use Node.js)");
6084
+ console.log(`Bun: ${bunCheck.stdout.trim()}`);
5990
6085
  }
5991
- const claudeCheck = spawnSync2("which", ["claude"], { stdio: "pipe", encoding: "utf-8" });
5992
- if (claudeCheck.status === 0) {
5993
- console.log(`Claude CLI: ${claudeCheck.stdout.trim()}`);
6086
+ const claudeDir = (0, import_path2.resolve)(process.env.HOME ?? "~", ".claude");
6087
+ const settingsPath = (0, import_path2.resolve)(claudeDir, "settings.json");
6088
+ const cliPath = typeof __filename !== "undefined" ? __filename : "";
6089
+ let mcpCommand;
6090
+ let mcpArgs;
6091
+ if (cliPath && (0, import_fs.existsSync)(cliPath)) {
6092
+ mcpCommand = "node";
6093
+ mcpArgs = [cliPath, "--mcp"];
5994
6094
  } else {
5995
- console.warn("Warning: Claude Code CLI not found. Install with: npm i -g @anthropic-ai/claude-code");
6095
+ mcpCommand = "npx";
6096
+ mcpArgs = ["claude-chrome-android", "--mcp"];
6097
+ }
6098
+ try {
6099
+ if (!(0, import_fs.existsSync)(claudeDir)) {
6100
+ (0, import_fs.mkdirSync)(claudeDir, { recursive: true });
6101
+ }
6102
+ let settings = {};
6103
+ if ((0, import_fs.existsSync)(settingsPath)) {
6104
+ settings = JSON.parse((0, import_fs.readFileSync)(settingsPath, "utf-8"));
6105
+ }
6106
+ const mcpServers = settings.mcpServers ?? {};
6107
+ const existing = mcpServers["cfc-bridge"];
6108
+ const desired = { command: mcpCommand, args: mcpArgs };
6109
+ const changed = !existing || existing.command !== desired.command || JSON.stringify(existing.args) !== JSON.stringify(desired.args);
6110
+ if (changed) {
6111
+ mcpServers["cfc-bridge"] = desired;
6112
+ settings.mcpServers = mcpServers;
6113
+ (0, import_fs.writeFileSync)(settingsPath, JSON.stringify(settings, null, 2) + "\n");
6114
+ console.log(`Registered MCP server "cfc-bridge" in ${settingsPath}`);
6115
+ console.log(` command: ${mcpCommand} ${mcpArgs.join(" ")}`);
6116
+ } else {
6117
+ console.log(`MCP server already registered in ${settingsPath}`);
6118
+ }
6119
+ } catch (err) {
6120
+ console.error(`Failed to register MCP server: ${err.message}`);
5996
6121
  }
5997
6122
  const binDir = (0, import_path2.resolve)(process.env.HOME ?? "/data/data/com.termux/files/home", "bin");
5998
6123
  if (!(0, import_fs.existsSync)(binDir)) {
@@ -6004,105 +6129,171 @@ Created ${binDir}/`);
6004
6129
  const urlOpenerExists = (0, import_fs.existsSync)(urlOpenerPath);
6005
6130
  const urlOpenerScript = `#!/data/data/com.termux/files/usr/bin/bash
6006
6131
  # termux-url-opener \u2014 handles URLs shared to Termux via Android share menu
6007
- # Called by TermuxFileReceiverActivity with the shared URL as $1
6008
- #
6009
6132
  # Generated by: claude-chrome-android --setup v${PKG_VERSION}
6010
- # NOTE: TermuxFileReceiverActivity runs this in a terminal session managed by
6011
- # TermuxService. When the script exits, the session closes and SIGHUP is sent
6012
- # to the process group. We use setsid to escape the process group.
6013
6133
 
6014
6134
  set -euo pipefail
6015
-
6016
6135
  url="\${1:-}"
6017
-
6018
- # Debug log
6019
6136
  echo "[$(date +%H:%M:%S)] termux-url-opener: $url" >> "$PREFIX/tmp/url-opener.log"
6020
6137
 
6021
6138
  case "$url" in
6022
6139
  *cfcbridge*/start*)
6023
- # CFC bridge deep-link from the Chrome/Edge extension
6024
6140
  BRIDGE_LOG="$PREFIX/tmp/bridge.log"
6025
-
6026
6141
  if pgrep -f "(bun|node).*claude-chrome" > /dev/null 2>&1; then
6027
6142
  echo "[$(date +%H:%M:%S)] bridge already running" >> "$PREFIX/tmp/url-opener.log"
6028
6143
  exit 0
6029
6144
  fi
6030
-
6031
- # Prefer bun (faster startup), fallback to node
6032
6145
  RUNTIME=""
6033
- if [[ -x "$HOME/.bun/bin/bun" ]]; then
6034
- RUNTIME="$HOME/.bun/bin/bun"
6035
- elif command -v bun > /dev/null 2>&1; then
6036
- RUNTIME="$(command -v bun)"
6037
- elif command -v node > /dev/null 2>&1; then
6038
- RUNTIME="$(command -v node)"
6039
- fi
6040
-
6041
- if [[ -z "$RUNTIME" ]]; then
6042
- echo "[$(date +%H:%M:%S)] ERROR: neither bun nor node found" >> "$PREFIX/tmp/url-opener.log"
6043
- exit 1
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)"
6044
6149
  fi
6045
-
6046
- # Find the bridge script \u2014 check npx cache, repo checkout, or run via npx
6150
+ if [[ -z "$RUNTIME" ]]; then exit 1; fi
6047
6151
  BRIDGE_SCRIPT=""
6048
- # 1. Local repo checkout
6049
6152
  if [[ -f "$HOME/git/termux-tools/claude-chrome-bridge.ts" ]]; then
6050
6153
  BRIDGE_SCRIPT="$HOME/git/termux-tools/claude-chrome-bridge.ts"
6051
6154
  fi
6052
- # 2. npm global install (bunx or npx)
6053
6155
  NPM_GLOBAL="$HOME/.npm/lib/node_modules/claude-chrome-android/dist/cli.js"
6054
6156
  BUN_GLOBAL="$HOME/.bun/install/global/node_modules/claude-chrome-android/dist/cli.js"
6055
- if [[ -z "$BRIDGE_SCRIPT" && -f "$NPM_GLOBAL" ]]; then
6056
- BRIDGE_SCRIPT="$NPM_GLOBAL"
6057
- elif [[ -z "$BRIDGE_SCRIPT" && -f "$BUN_GLOBAL" ]]; then
6058
- BRIDGE_SCRIPT="$BUN_GLOBAL"
6157
+ if [[ -z "$BRIDGE_SCRIPT" && -f "$NPM_GLOBAL" ]]; then BRIDGE_SCRIPT="$NPM_GLOBAL"
6158
+ elif [[ -z "$BRIDGE_SCRIPT" && -f "$BUN_GLOBAL" ]]; then BRIDGE_SCRIPT="$BUN_GLOBAL"
6059
6159
  fi
6060
-
6061
6160
  if [[ -n "$BRIDGE_SCRIPT" ]]; then
6062
- # setsid creates a new session leader \u2014 the child process survives when
6063
- # TermuxService kills this session's process group on script exit
6064
6161
  setsid nohup "$RUNTIME" "$BRIDGE_SCRIPT" > "$BRIDGE_LOG" 2>&1 &
6065
- echo "[$(date +%H:%M:%S)] bridge started PID=$!" >> "$PREFIX/tmp/url-opener.log"
6066
6162
  else
6067
- # Fallback: use npx to download and run on the fly
6068
6163
  setsid nohup npx claude-chrome-android > "$BRIDGE_LOG" 2>&1 &
6069
- echo "[$(date +%H:%M:%S)] bridge started via npx PID=$!" >> "$PREFIX/tmp/url-opener.log"
6070
6164
  fi
6071
- exit 0
6072
- ;;
6073
-
6165
+ exit 0 ;;
6074
6166
  *)
6075
- # Default: open URL in browser
6076
- if command -v termux-open-url > /dev/null 2>&1; then
6077
- termux-open-url "$url"
6078
- elif command -v xdg-open > /dev/null 2>&1; then
6079
- xdg-open "$url"
6080
- fi
6081
- ;;
6167
+ if command -v termux-open-url > /dev/null 2>&1; then termux-open-url "$url"
6168
+ elif command -v xdg-open > /dev/null 2>&1; then xdg-open "$url"
6169
+ fi ;;
6082
6170
  esac
6083
6171
  `;
6084
6172
  if (urlOpenerExists) {
6085
6173
  const existing = (0, import_fs.readFileSync)(urlOpenerPath, "utf-8");
6086
6174
  if (existing.includes("cfcbridge")) {
6087
- const backupPath = `${urlOpenerPath}.bak`;
6088
- (0, import_fs.writeFileSync)(backupPath, existing);
6089
- console.log(`
6090
- Backed up existing url-opener to ${backupPath}`);
6175
+ (0, import_fs.writeFileSync)(`${urlOpenerPath}.bak`, existing);
6176
+ console.log(`Backed up existing url-opener to ${urlOpenerPath}.bak`);
6091
6177
  }
6092
6178
  }
6093
6179
  (0, import_fs.writeFileSync)(urlOpenerPath, urlOpenerScript);
6094
6180
  (0, import_fs.chmodSync)(urlOpenerPath, 493);
6095
6181
  console.log(`${urlOpenerExists ? "Updated" : "Created"} ${urlOpenerPath}`);
6182
+ const dir = typeof __dirname !== "undefined" ? __dirname : (0, import_path2.dirname)(new URL(import_meta_url).pathname);
6183
+ const extVersion = (() => {
6184
+ const manifestCandidates = [
6185
+ (0, import_path2.resolve)(dir, "../../edge-claude-ext/manifest.json")
6186
+ // source repo
6187
+ ];
6188
+ for (const p of manifestCandidates) {
6189
+ try {
6190
+ return JSON.parse((0, import_fs.readFileSync)(p, "utf-8")).version;
6191
+ } catch {
6192
+ }
6193
+ }
6194
+ return PKG_VERSION;
6195
+ })();
6196
+ const crxCandidates = [
6197
+ (0, import_path2.resolve)(dir, "claude-code-bridge.crx"),
6198
+ // npm package (bridge/dist/)
6199
+ (0, import_path2.resolve)(dir, `../../dist/claude-code-bridge-v${extVersion}.crx`),
6200
+ // source repo
6201
+ (0, import_path2.resolve)(dir, "../../dist/claude-code-bridge-latest.crx")
6202
+ // source repo -latest
6203
+ ];
6204
+ let crxPath = crxCandidates.find((p) => (0, import_fs.existsSync)(p));
6205
+ if (!crxPath) {
6206
+ const buildScript = (0, import_path2.resolve)(dir, "../../scripts/build-crx.js");
6207
+ if ((0, import_fs.existsSync)(buildScript)) {
6208
+ console.log("\nBuilding CRX extension...");
6209
+ spawnSync2("node", [buildScript], { stdio: "inherit" });
6210
+ crxPath = crxCandidates.find((p) => (0, import_fs.existsSync)(p));
6211
+ }
6212
+ }
6213
+ if (!crxPath) {
6214
+ console.log("\nCRX not found. To install the extension manually:");
6215
+ console.log(" 1. Start the bridge: npx claude-chrome-android");
6216
+ console.log(" 2. Open http://127.0.0.1:18963/ext/crx in Edge");
6217
+ } else {
6218
+ const adbCheck = spawnSync2("adb", ["devices"], { stdio: "pipe", encoding: "utf-8" });
6219
+ const hasAdb = adbCheck.status === 0 && adbCheck.stdout.includes(" device");
6220
+ if (!hasAdb) {
6221
+ console.log(`
6222
+ CRX found at ${crxPath}`);
6223
+ console.log("ADB not available. To install the extension:");
6224
+ console.log(" 1. Start the bridge: npx claude-chrome-android");
6225
+ console.log(" 2. Open http://127.0.0.1:18963/ext/crx in Edge");
6226
+ } else {
6227
+ const http2 = await import("http");
6228
+ const crxBuf = (0, import_fs.readFileSync)(crxPath);
6229
+ const INSTALL_PORT = 18964;
6230
+ const crxServer = http2.createServer((_req, res) => {
6231
+ res.writeHead(200, {
6232
+ "Content-Type": "application/x-chrome-extension",
6233
+ "Content-Disposition": 'attachment; filename="claude-code-bridge.crx"',
6234
+ "Content-Length": String(crxBuf.length)
6235
+ });
6236
+ res.end(crxBuf);
6237
+ });
6238
+ await new Promise((resolve3) => {
6239
+ crxServer.listen(INSTALL_PORT, "127.0.0.1", resolve3);
6240
+ });
6241
+ console.log(`
6242
+ Serving CRX at http://127.0.0.1:${INSTALL_PORT}/ext.crx`);
6243
+ const edgePackages = [
6244
+ "com.microsoft.emmx.canary",
6245
+ "com.microsoft.emmx.dev",
6246
+ "com.microsoft.emmx.beta",
6247
+ "com.microsoft.emmx"
6248
+ ];
6249
+ let opened = false;
6250
+ for (const pkg of edgePackages) {
6251
+ const result = spawnSync2("adb", [
6252
+ "shell",
6253
+ "am",
6254
+ "start",
6255
+ "-a",
6256
+ "android.intent.action.VIEW",
6257
+ "-d",
6258
+ `http://127.0.0.1:${INSTALL_PORT}/ext.crx`,
6259
+ "-n",
6260
+ `${pkg}/com.microsoft.ruby.Main`
6261
+ ], { stdio: "pipe", encoding: "utf-8" });
6262
+ if (result.status === 0 && !result.stderr.includes("Error")) {
6263
+ console.log(`Opened CRX download in ${pkg}`);
6264
+ opened = true;
6265
+ break;
6266
+ }
6267
+ }
6268
+ if (!opened) {
6269
+ console.log("Could not open Edge automatically.");
6270
+ console.log(`Open this URL in Edge: http://127.0.0.1:${INSTALL_PORT}/ext.crx`);
6271
+ }
6272
+ console.log("Waiting 15s for download...");
6273
+ await new Promise((r) => setTimeout(r, 15e3));
6274
+ crxServer.close();
6275
+ spawnSync2("adb", [
6276
+ "shell",
6277
+ "am",
6278
+ "start",
6279
+ "-a",
6280
+ "android.intent.action.VIEW",
6281
+ "-d",
6282
+ "edge://extensions",
6283
+ "-n",
6284
+ "com.microsoft.emmx.canary/com.google.android.apps.chrome.IntentDispatcher"
6285
+ ], { stdio: "ignore" });
6286
+ console.log("Opened edge://extensions \u2014 verify the extension is listed.");
6287
+ console.log("Note: if prompted, tap 'Add extension' in the download notification.");
6288
+ }
6289
+ }
6096
6290
  console.log(`
6097
6291
  Setup complete!
6098
6292
 
6099
6293
  Next steps:
6100
- 1. Install the CRX extension in Chrome/Edge on your phone
6101
- 2. Start the bridge: npx claude-chrome-android
6102
- 3. Or use the extension's "Launch Bridge" button (shares to Termux)
6103
-
6104
- The bridge runs on ws://${WS_HOST2}:${WS_PORT2} and connects
6105
- Claude Code CLI to your browser via the Chrome extension.
6294
+ 1. Start the bridge: npx claude-chrome-android
6295
+ 2. Open a new Claude Code session \u2014 browser tools (mcp__cfc-bridge__*) will be available
6296
+ 3. Use ToolSearch to find and load cfc-bridge tools
6106
6297
  `);
6107
6298
  }
6108
6299
  async function cmdStart() {
@@ -6117,10 +6308,344 @@ async function cmdStart() {
6117
6308
  } catch (err) {
6118
6309
  console.error("Failed to start bridge:", err.message);
6119
6310
  console.error("\nIf you installed via npm, the bridge should be bundled in this file.");
6120
- console.error("Try rebuilding: cd bridge && node build.js");
6311
+ console.error("Try rebuilding: cd bridge && node build.cjs");
6121
6312
  process.exit(1);
6122
6313
  }
6123
6314
  }
6315
+ var MCP_TOOLS = [
6316
+ {
6317
+ name: "tabs_context_mcp",
6318
+ description: "Get context information about the current MCP tab group. Returns all tab IDs inside the group if it exists. CRITICAL: You must get the context at least once before using other browser automation tools so you know what tabs exist.",
6319
+ inputSchema: {
6320
+ type: "object",
6321
+ properties: { createIfEmpty: { type: "boolean", description: "Creates a new MCP tab group if none exists." } },
6322
+ required: []
6323
+ }
6324
+ },
6325
+ {
6326
+ name: "tabs_create_mcp",
6327
+ description: "Creates a new empty tab in the MCP tab group.",
6328
+ inputSchema: { type: "object", properties: {}, required: [] }
6329
+ },
6330
+ {
6331
+ name: "navigate",
6332
+ description: "Navigate to a URL, or go forward/back in browser history.",
6333
+ inputSchema: {
6334
+ type: "object",
6335
+ properties: {
6336
+ url: { type: "string", description: 'URL to navigate to. Use "forward" or "back" for history.' },
6337
+ tabId: { type: "number", description: "Tab ID to navigate." }
6338
+ },
6339
+ required: ["url", "tabId"]
6340
+ }
6341
+ },
6342
+ {
6343
+ name: "computer",
6344
+ description: "Use a mouse and keyboard to interact with a web browser, and take screenshots.\n* Consult a screenshot to determine coordinates before clicking.\n* Click buttons/icons in the center of the element.",
6345
+ inputSchema: {
6346
+ type: "object",
6347
+ properties: {
6348
+ action: {
6349
+ type: "string",
6350
+ enum: ["left_click", "right_click", "type", "screenshot", "wait", "scroll", "key", "left_click_drag", "double_click", "triple_click", "zoom", "scroll_to", "hover"],
6351
+ description: "The action to perform."
6352
+ },
6353
+ coordinate: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2, description: "(x, y) pixel coordinates." },
6354
+ text: { type: "string", description: "Text to type or key(s) to press." },
6355
+ duration: { type: "number", minimum: 0, maximum: 30, description: "Seconds to wait." },
6356
+ scroll_direction: { type: "string", enum: ["up", "down", "left", "right"], description: "Scroll direction." },
6357
+ scroll_amount: { type: "number", minimum: 1, maximum: 10, description: "Scroll ticks (default: 3)." },
6358
+ start_coordinate: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2, description: "Start coords for drag." },
6359
+ region: { type: "array", items: { type: "number" }, minItems: 4, maxItems: 4, description: "(x0,y0,x1,y1) for zoom." },
6360
+ repeat: { type: "number", minimum: 1, maximum: 100, description: "Key repeat count." },
6361
+ ref: { type: "string", description: "Element ref ID for scroll_to." },
6362
+ modifiers: { type: "string", description: 'Modifier keys: "ctrl", "shift", "alt", "cmd".' },
6363
+ tabId: { type: "number", description: "Tab ID." }
6364
+ },
6365
+ required: ["action", "tabId"]
6366
+ }
6367
+ },
6368
+ {
6369
+ name: "javascript_tool",
6370
+ description: "Execute JavaScript in the page context. Returns the last expression result.",
6371
+ inputSchema: {
6372
+ type: "object",
6373
+ properties: {
6374
+ action: { type: "string", description: "Must be 'javascript_exec'" },
6375
+ text: { type: "string", description: "JavaScript code. Don't use 'return'." },
6376
+ tabId: { type: "number", description: "Tab ID." }
6377
+ },
6378
+ required: ["action", "text", "tabId"]
6379
+ }
6380
+ },
6381
+ {
6382
+ name: "read_page",
6383
+ description: "Get accessibility tree of page elements. Filter for interactive elements or get all.",
6384
+ inputSchema: {
6385
+ type: "object",
6386
+ properties: {
6387
+ filter: { type: "string", enum: ["interactive", "all"], description: "Element filter." },
6388
+ tabId: { type: "number", description: "Tab ID." },
6389
+ depth: { type: "number", description: "Max tree depth (default: 15)." },
6390
+ ref_id: { type: "string", description: "Parent element ref to focus on." },
6391
+ max_chars: { type: "number", description: "Max output chars (default: 50000)." }
6392
+ },
6393
+ required: ["tabId"]
6394
+ }
6395
+ },
6396
+ {
6397
+ name: "find",
6398
+ description: 'Find elements by natural language (e.g., "search bar", "login button").',
6399
+ inputSchema: {
6400
+ type: "object",
6401
+ properties: {
6402
+ query: { type: "string", description: "What to find." },
6403
+ tabId: { type: "number", description: "Tab ID." }
6404
+ },
6405
+ required: ["query", "tabId"]
6406
+ }
6407
+ },
6408
+ {
6409
+ name: "form_input",
6410
+ description: "Set form element values using ref ID from read_page.",
6411
+ inputSchema: {
6412
+ type: "object",
6413
+ properties: {
6414
+ ref: { type: "string", description: "Element ref ID." },
6415
+ value: { type: ["string", "boolean", "number"], description: "Value to set." },
6416
+ tabId: { type: "number", description: "Tab ID." }
6417
+ },
6418
+ required: ["ref", "value", "tabId"]
6419
+ }
6420
+ },
6421
+ {
6422
+ name: "get_page_text",
6423
+ description: "Extract raw text content from the page.",
6424
+ inputSchema: {
6425
+ type: "object",
6426
+ properties: { tabId: { type: "number", description: "Tab ID." } },
6427
+ required: ["tabId"]
6428
+ }
6429
+ },
6430
+ {
6431
+ name: "read_console_messages",
6432
+ description: "Read browser console messages. Always provide a pattern to filter.",
6433
+ inputSchema: {
6434
+ type: "object",
6435
+ properties: {
6436
+ tabId: { type: "number", description: "Tab ID." },
6437
+ onlyErrors: { type: "boolean", description: "Errors only." },
6438
+ clear: { type: "boolean", description: "Clear after reading." },
6439
+ pattern: { type: "string", description: "Regex filter pattern." },
6440
+ limit: { type: "number", description: "Max messages (default: 100)." }
6441
+ },
6442
+ required: ["tabId"]
6443
+ }
6444
+ },
6445
+ {
6446
+ name: "read_network_requests",
6447
+ description: "Read HTTP network requests from a tab.",
6448
+ inputSchema: {
6449
+ type: "object",
6450
+ properties: {
6451
+ tabId: { type: "number", description: "Tab ID." },
6452
+ urlPattern: { type: "string", description: "URL substring filter." },
6453
+ clear: { type: "boolean", description: "Clear after reading." },
6454
+ limit: { type: "number", description: "Max requests (default: 100)." }
6455
+ },
6456
+ required: ["tabId"]
6457
+ }
6458
+ },
6459
+ {
6460
+ name: "resize_window",
6461
+ description: "Resize browser window.",
6462
+ inputSchema: {
6463
+ type: "object",
6464
+ properties: {
6465
+ width: { type: "number", description: "Width in pixels." },
6466
+ height: { type: "number", description: "Height in pixels." },
6467
+ tabId: { type: "number", description: "Tab ID." }
6468
+ },
6469
+ required: ["width", "height", "tabId"]
6470
+ }
6471
+ },
6472
+ {
6473
+ name: "gif_creator",
6474
+ description: "Record and export browser session GIFs.",
6475
+ inputSchema: {
6476
+ type: "object",
6477
+ properties: {
6478
+ action: { type: "string", enum: ["start_recording", "stop_recording", "export", "clear"], description: "Action." },
6479
+ tabId: { type: "number", description: "Tab ID." },
6480
+ download: { type: "boolean", description: "Download GIF on export." },
6481
+ filename: { type: "string", description: "GIF filename." },
6482
+ options: { type: "object", description: "GIF options." }
6483
+ },
6484
+ required: ["action", "tabId"]
6485
+ }
6486
+ },
6487
+ {
6488
+ name: "upload_image",
6489
+ description: "Upload a screenshot to a file input or drag & drop target.",
6490
+ inputSchema: {
6491
+ type: "object",
6492
+ properties: {
6493
+ imageId: { type: "string", description: "Screenshot ID." },
6494
+ ref: { type: "string", description: "Element ref ID." },
6495
+ coordinate: { type: "array", items: { type: "number" }, description: "Drop coords [x,y]." },
6496
+ tabId: { type: "number", description: "Tab ID." },
6497
+ filename: { type: "string", description: "Filename." }
6498
+ },
6499
+ required: ["imageId", "tabId"]
6500
+ }
6501
+ },
6502
+ {
6503
+ name: "update_plan",
6504
+ description: "Present a plan to the user for approval.",
6505
+ inputSchema: {
6506
+ type: "object",
6507
+ properties: {
6508
+ domains: { type: "array", items: { type: "string" }, description: "Domains to visit." },
6509
+ approach: { type: "array", items: { type: "string" }, description: "Steps to take." }
6510
+ },
6511
+ required: ["domains", "approach"]
6512
+ }
6513
+ },
6514
+ {
6515
+ name: "shortcuts_list",
6516
+ description: "List available shortcuts and workflows.",
6517
+ inputSchema: {
6518
+ type: "object",
6519
+ properties: { tabId: { type: "number", description: "Tab ID." } },
6520
+ required: ["tabId"]
6521
+ }
6522
+ },
6523
+ {
6524
+ name: "shortcuts_execute",
6525
+ description: "Execute a shortcut or workflow.",
6526
+ inputSchema: {
6527
+ type: "object",
6528
+ properties: {
6529
+ tabId: { type: "number", description: "Tab ID." },
6530
+ shortcutId: { type: "string", description: "Shortcut ID." },
6531
+ command: { type: "string", description: "Command name." }
6532
+ },
6533
+ required: ["tabId"]
6534
+ }
6535
+ },
6536
+ {
6537
+ name: "switch_browser",
6538
+ description: "Switch which Chrome browser is used for automation.",
6539
+ inputSchema: { type: "object", properties: {}, required: [] }
6540
+ }
6541
+ ];
6542
+ function mcpResult(id, result) {
6543
+ return { jsonrpc: "2.0", id, result };
6544
+ }
6545
+ function mcpError(id, code, message) {
6546
+ return { jsonrpc: "2.0", id, error: { code, message } };
6547
+ }
6548
+ function mcpSend(response) {
6549
+ process.stdout.write(JSON.stringify(response) + "\n");
6550
+ }
6551
+ async function callBridgeTool(method, params) {
6552
+ try {
6553
+ const resp = await fetch(TOOL_URL, {
6554
+ method: "POST",
6555
+ headers: { "Content-Type": "application/json" },
6556
+ body: JSON.stringify({ method, params }),
6557
+ signal: AbortSignal.timeout(TOOL_TIMEOUT_MS)
6558
+ });
6559
+ if (!resp.ok) {
6560
+ const body = await resp.text();
6561
+ return { error: `Bridge HTTP ${resp.status}: ${body}` };
6562
+ }
6563
+ const data = await resp.json();
6564
+ if (data.error) return { error: String(data.error) };
6565
+ return { result: data.result ?? data };
6566
+ } catch (err) {
6567
+ return { error: `Bridge unreachable: ${err.message}` };
6568
+ }
6569
+ }
6570
+ function formatToolResult(result) {
6571
+ if (!result || typeof result !== "object") {
6572
+ return [{ type: "text", text: JSON.stringify(result) }];
6573
+ }
6574
+ const r = result;
6575
+ if (Array.isArray(r.content)) return r.content;
6576
+ if (r.data && typeof r.data === "string" && r.media_type) {
6577
+ return [{ type: "image", source: { type: "base64", media_type: r.media_type, data: r.data } }];
6578
+ }
6579
+ if (r.result !== void 0) return formatToolResult(r.result);
6580
+ return [{ type: "text", text: JSON.stringify(result, null, 2) }];
6581
+ }
6582
+ async function handleMcpRequest(req) {
6583
+ if (req.id === void 0 || req.id === null) return;
6584
+ switch (req.method) {
6585
+ case "initialize":
6586
+ mcpSend(mcpResult(req.id, {
6587
+ protocolVersion: "2024-11-05",
6588
+ capabilities: { tools: {} },
6589
+ serverInfo: { name: "Claude in Chrome (Bridge)", version: PKG_VERSION }
6590
+ }));
6591
+ break;
6592
+ case "tools/list":
6593
+ mcpSend(mcpResult(req.id, { tools: MCP_TOOLS }));
6594
+ break;
6595
+ case "tools/call": {
6596
+ const toolName = req.params?.name ?? "";
6597
+ const toolArgs = req.params?.arguments ?? {};
6598
+ const tool = MCP_TOOLS.find((t) => t.name === toolName);
6599
+ if (!tool) {
6600
+ mcpSend(mcpResult(req.id, { content: [{ type: "text", text: `Unknown tool: ${toolName}` }], isError: true }));
6601
+ break;
6602
+ }
6603
+ const { result, error } = await callBridgeTool(toolName, toolArgs);
6604
+ if (error) {
6605
+ mcpSend(mcpResult(req.id, { content: [{ type: "text", text: error }], isError: true }));
6606
+ } else {
6607
+ mcpSend(mcpResult(req.id, { content: formatToolResult(result) }));
6608
+ }
6609
+ break;
6610
+ }
6611
+ default:
6612
+ mcpSend(mcpError(req.id, -32601, `Method not found: ${req.method}`));
6613
+ }
6614
+ }
6615
+ async function cmdMcp() {
6616
+ const log2 = (msg) => process.stderr.write(`[cfc-mcp] ${msg}
6617
+ `);
6618
+ log2(`MCP server v${PKG_VERSION} \u2014 bridge at ${BRIDGE_URL}`);
6619
+ try {
6620
+ const h = await fetch(HEALTH_URL, { signal: AbortSignal.timeout(2e3) });
6621
+ const d = await h.json();
6622
+ log2(`Bridge OK: clients=${d.clients}, v${d.version}`);
6623
+ } catch {
6624
+ log2("Bridge not reachable \u2014 tool calls will fail until bridge starts");
6625
+ }
6626
+ const decoder = new TextDecoder();
6627
+ let buffer = "";
6628
+ for await (const chunk of process.stdin) {
6629
+ buffer += typeof chunk === "string" ? chunk : decoder.decode(chunk);
6630
+ let idx;
6631
+ while ((idx = buffer.indexOf("\n")) !== -1) {
6632
+ const line = buffer.slice(0, idx).trim();
6633
+ buffer = buffer.slice(idx + 1);
6634
+ if (!line) continue;
6635
+ try {
6636
+ const req = JSON.parse(line);
6637
+ handleMcpRequest(req).catch((err) => {
6638
+ log2(`Error: ${req.method}: ${err.message}`);
6639
+ if (req.id != null) mcpSend(mcpError(req.id, -32603, err.message));
6640
+ });
6641
+ } catch (err) {
6642
+ log2(`Bad JSON-RPC: ${err.message}`);
6643
+ }
6644
+ }
6645
+ }
6646
+ log2("stdin closed");
6647
+ process.exit(0);
6648
+ }
6124
6649
  var args = process.argv.slice(2);
6125
6650
  var command = args[0] ?? "";
6126
6651
  switch (command) {
@@ -6138,6 +6663,9 @@ switch (command) {
6138
6663
  case "--setup":
6139
6664
  cmdSetup();
6140
6665
  break;
6666
+ case "--mcp":
6667
+ cmdMcp();
6668
+ break;
6141
6669
  case "":
6142
6670
  cmdStart();
6143
6671
  break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-chrome-android",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Claude Code Browser Bridge for Android — connects Claude Code CLI to Chrome/Edge via WebSocket",
5
5
  "author": "willstone",
6
6
  "license": "MIT",