claude-chrome-android 1.5.1 → 1.6.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.
package/dist/cli.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ "use strict";
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -11,6 +12,10 @@ var __esm = (fn, res) => function __init() {
11
12
  var __commonJS = (cb, mod) => function __require() {
12
13
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
14
  };
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
18
+ };
14
19
  var __copyProps = (to, from, except, desc) => {
15
20
  if (from && typeof from === "object" || typeof from === "function") {
16
21
  for (let key of __getOwnPropNames(from))
@@ -27,11 +32,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
32
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
33
  mod
29
34
  ));
35
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
36
 
31
37
  // src/import-meta-shim.js
32
38
  var import_meta_url;
33
39
  var init_import_meta_shim = __esm({
34
40
  "src/import-meta-shim.js"() {
41
+ "use strict";
35
42
  import_meta_url = typeof __filename !== "undefined" ? require("url").pathToFileURL(__filename).href : "";
36
43
  }
37
44
  });
@@ -317,7 +324,7 @@ var require_permessage_deflate = __commonJS({
317
324
  acceptAsServer(offers) {
318
325
  const opts = this._options;
319
326
  const accepted = offers.find((params) => {
320
- if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
327
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && (typeof params.client_max_window_bits === "number" ? opts.clientMaxWindowBits > params.client_max_window_bits : !params.client_max_window_bits)) {
321
328
  return false;
322
329
  }
323
330
  return true;
@@ -839,6 +846,7 @@ var require_receiver = __commonJS({
839
846
  this._opcode = 0;
840
847
  this._totalPayloadLength = 0;
841
848
  this._messageLength = 0;
849
+ this._numFragments = 0;
842
850
  this._fragments = [];
843
851
  this._errored = false;
844
852
  this._loop = false;
@@ -1189,23 +1197,23 @@ var require_receiver = __commonJS({
1189
1197
  this.controlMessage(data, cb);
1190
1198
  return;
1191
1199
  }
1200
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
1201
+ const error = this.createError(
1202
+ RangeError,
1203
+ "Too many message fragments",
1204
+ false,
1205
+ 1008,
1206
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1207
+ );
1208
+ cb(error);
1209
+ return;
1210
+ }
1192
1211
  if (this._compressed) {
1193
1212
  this._state = INFLATING;
1194
1213
  this.decompress(data, cb);
1195
1214
  return;
1196
1215
  }
1197
1216
  if (data.length) {
1198
- if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
1199
- const error = this.createError(
1200
- RangeError,
1201
- "Too many message fragments",
1202
- false,
1203
- 1008,
1204
- "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1205
- );
1206
- cb(error);
1207
- return;
1208
- }
1209
1217
  this._messageLength = this._totalPayloadLength;
1210
1218
  this._fragments.push(data);
1211
1219
  }
@@ -1235,17 +1243,6 @@ var require_receiver = __commonJS({
1235
1243
  cb(error);
1236
1244
  return;
1237
1245
  }
1238
- if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
1239
- const error = this.createError(
1240
- RangeError,
1241
- "Too many message fragments",
1242
- false,
1243
- 1008,
1244
- "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1245
- );
1246
- cb(error);
1247
- return;
1248
- }
1249
1246
  this._fragments.push(buf);
1250
1247
  }
1251
1248
  this.dataMessage(cb);
@@ -1268,6 +1265,7 @@ var require_receiver = __commonJS({
1268
1265
  this._totalPayloadLength = 0;
1269
1266
  this._messageLength = 0;
1270
1267
  this._fragmented = 0;
1268
+ this._numFragments = 0;
1271
1269
  this._fragments = [];
1272
1270
  if (this._opcode === 2) {
1273
1271
  let data;
@@ -2350,11 +2348,23 @@ var require_websocket = __commonJS({
2350
2348
  this._isServer = false;
2351
2349
  this._redirects = 0;
2352
2350
  if (protocols === void 0) {
2353
- protocols = [];
2351
+ if (!options || options.protocols === void 0) {
2352
+ protocols = [];
2353
+ } else if (Array.isArray(options.protocols)) {
2354
+ protocols = options.protocols;
2355
+ } else {
2356
+ protocols = [options.protocols];
2357
+ }
2354
2358
  } else if (!Array.isArray(protocols)) {
2355
2359
  if (typeof protocols === "object" && protocols !== null) {
2356
2360
  options = protocols;
2357
- protocols = [];
2361
+ if (options.protocols === void 0) {
2362
+ protocols = [];
2363
+ } else if (Array.isArray(options.protocols)) {
2364
+ protocols = options.protocols;
2365
+ } else {
2366
+ protocols = [options.protocols];
2367
+ }
2358
2368
  } else {
2359
2369
  protocols = [protocols];
2360
2370
  }
@@ -2551,7 +2561,6 @@ var require_websocket = __commonJS({
2551
2561
  }
2552
2562
  return;
2553
2563
  }
2554
- this._readyState = _WebSocket.CLOSING;
2555
2564
  this._sender.close(code, data, !this._isServer, (err) => {
2556
2565
  if (err) return;
2557
2566
  this._closeFrameSent = true;
@@ -2559,6 +2568,7 @@ var require_websocket = __commonJS({
2559
2568
  this._socket.end();
2560
2569
  }
2561
2570
  });
2571
+ this._readyState = _WebSocket.CLOSING;
2562
2572
  setCloseTimer(this);
2563
2573
  }
2564
2574
  /**
@@ -2772,8 +2782,8 @@ var require_websocket = __commonJS({
2772
2782
  autoPong: true,
2773
2783
  closeTimeout: CLOSE_TIMEOUT,
2774
2784
  protocolVersion: protocolVersions[1],
2775
- maxBufferedChunks: 1024 * 1024,
2776
- maxFragments: 128 * 1024,
2785
+ maxBufferedChunks: 256 * 1024,
2786
+ maxFragments: 16 * 1024,
2777
2787
  maxPayload: 100 * 1024 * 1024,
2778
2788
  skipUTF8Validation: false,
2779
2789
  perMessageDeflate: true,
@@ -2783,6 +2793,7 @@ var require_websocket = __commonJS({
2783
2793
  socketPath: void 0,
2784
2794
  hostname: void 0,
2785
2795
  protocol: void 0,
2796
+ protocols: void 0,
2786
2797
  timeout: void 0,
2787
2798
  method: "GET",
2788
2799
  host: void 0,
@@ -3363,9 +3374,9 @@ var require_websocket_server = __commonJS({
3363
3374
  * called
3364
3375
  * @param {Function} [options.handleProtocols] A hook to handle protocols
3365
3376
  * @param {String} [options.host] The hostname where to bind the server
3366
- * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of
3377
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
3367
3378
  * buffered data chunks
3368
- * @param {Number} [options.maxFragments=131072] The maximum number of message
3379
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
3369
3380
  * fragments
3370
3381
  * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3371
3382
  * size
@@ -3388,8 +3399,8 @@ var require_websocket_server = __commonJS({
3388
3399
  options = {
3389
3400
  allowSynchronousEvents: true,
3390
3401
  autoPong: true,
3391
- maxBufferedChunks: 1024 * 1024,
3392
- maxFragments: 128 * 1024,
3402
+ maxBufferedChunks: 256 * 1024,
3403
+ maxFragments: 16 * 1024,
3393
3404
  maxPayload: 100 * 1024 * 1024,
3394
3405
  skipUTF8Validation: false,
3395
3406
  perMessageDeflate: false,
@@ -3895,7 +3906,8 @@ function createBunServer(config) {
3895
3906
  });
3896
3907
  return {
3897
3908
  stop: () => server2.stop(),
3898
- port: server2.port
3909
+ // Bun types `server.port` as optional; a bound server always has one.
3910
+ port: server2.port ?? config.port
3899
3911
  };
3900
3912
  }
3901
3913
  function createNodeServer(config) {
@@ -4016,7 +4028,12 @@ var init_compat = __esm({
4016
4028
 
4017
4029
  // ../claude-chrome-bridge.ts
4018
4030
  var claude_chrome_bridge_exports = {};
4031
+ __export(claude_chrome_bridge_exports, {
4032
+ sendPenPoints: () => sendPenPoints,
4033
+ validatePenPoints: () => validatePenPoints
4034
+ });
4019
4035
  function getAdbSerial() {
4036
+ if (process.env.BRIDGE_ADB_SERIAL) return process.env.BRIDGE_ADB_SERIAL;
4020
4037
  const now = Date.now();
4021
4038
  if (now - _adbSerialTs < ADB_SERIAL_TTL_MS) return _adbSerial;
4022
4039
  _adbSerialTs = now;
@@ -4025,7 +4042,7 @@ function getAdbSerial() {
4025
4042
  const result = runSync([ADB_PATH, "devices"], { timeoutMs: ADB_CALL_TIMEOUT_MS });
4026
4043
  const lines = result.stdout.toString().trim().split("\n").filter((l) => l.endsWith(" device"));
4027
4044
  if (lines.length <= 1) {
4028
- _adbSerial = "";
4045
+ _adbSerial = lines[0]?.split(" ")[0] ?? "";
4029
4046
  return _adbSerial;
4030
4047
  }
4031
4048
  for (const line of lines) {
@@ -4043,9 +4060,9 @@ function getAdbSerial() {
4043
4060
  return _adbSerial;
4044
4061
  }
4045
4062
  }
4046
- function adb(...args2) {
4063
+ function adb(...args) {
4047
4064
  const serial = getAdbSerial();
4048
- return serial ? [ADB_PATH, "-s", serial, ...args2] : [ADB_PATH, ...args2];
4065
+ return serial ? [ADB_PATH, "-s", serial, ...args] : [ADB_PATH, ...args];
4049
4066
  }
4050
4067
  function adbNotify(tag, title, text) {
4051
4068
  try {
@@ -4068,12 +4085,12 @@ function findRuntime() {
4068
4085
  }
4069
4086
  return process.execPath;
4070
4087
  }
4071
- function log(level, msg, ...args2) {
4088
+ function log(level, msg, ...args) {
4072
4089
  if (LOG_PRIORITY[level] < LOG_PRIORITY[LOG_LEVEL]) return;
4073
4090
  const ts = (/* @__PURE__ */ new Date()).toISOString();
4074
4091
  const prefix = `[${ts}] [bridge:${level}]`;
4075
- if (level === "error") console.error(prefix, msg, ...args2);
4076
- else console.log(prefix, msg, ...args2);
4092
+ if (level === "error") console.error(prefix, msg, ...args);
4093
+ else console.log(prefix, msg, ...args);
4077
4094
  }
4078
4095
  function encodeNativeMessage(json) {
4079
4096
  const body = Buffer.from(json, "utf-8");
@@ -4084,6 +4101,89 @@ function encodeNativeMessage(json) {
4084
4101
  header.writeUInt32LE(body.length, 0);
4085
4102
  return Buffer.concat([header, body]);
4086
4103
  }
4104
+ function validatePenPoints(value) {
4105
+ if (!Array.isArray(value) || value.length < 1 || value.length > 512) {
4106
+ throw new Error("points must contain 1\u2013512 pen samples");
4107
+ }
4108
+ let previousTime = 0;
4109
+ return value.map((item, index) => {
4110
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
4111
+ throw new Error(`points[${index}] must be an object`);
4112
+ }
4113
+ const p = item;
4114
+ const number = (key, min, max, fallback) => {
4115
+ const v = p[key] === void 0 ? fallback : p[key];
4116
+ if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max) {
4117
+ throw new Error(`points[${index}].${key} must be finite and within ${min}\u2026${max}`);
4118
+ }
4119
+ return v;
4120
+ };
4121
+ const point = {
4122
+ x: number("x", 0, 1e5),
4123
+ y: number("y", 0, 1e5),
4124
+ pressure: number("pressure", 0, 1),
4125
+ tiltX: number("tiltX", -90, 90, 0),
4126
+ tiltY: number("tiltY", -90, 90, 0),
4127
+ twist: number("twist", 0, 359, 0),
4128
+ timeMs: number("timeMs", 0, 2e4, index * 8)
4129
+ };
4130
+ if (point.timeMs < previousTime) throw new Error("Sample times must be nondecreasing");
4131
+ previousTime = point.timeMs;
4132
+ return point;
4133
+ });
4134
+ }
4135
+ async function sendPenPoints(points, send) {
4136
+ const start = performance.now();
4137
+ let last = points[0];
4138
+ let pressed = false;
4139
+ let failure;
4140
+ try {
4141
+ for (let index = 0; index < points.length; index++) {
4142
+ const point = points[index];
4143
+ const delay = point.timeMs - (performance.now() - start);
4144
+ if (delay > 0) await new Promise((resolve3) => setTimeout(resolve3, delay));
4145
+ if (performance.now() - start > 25e3) throw new Error("Pen stroke exceeded 25 seconds; remaining samples cancelled");
4146
+ last = point;
4147
+ pressed = true;
4148
+ await send({
4149
+ type: index === 0 ? "mousePressed" : "mouseMoved",
4150
+ x: point.x,
4151
+ y: point.y,
4152
+ force: point.pressure,
4153
+ tiltX: point.tiltX,
4154
+ tiltY: point.tiltY,
4155
+ twist: point.twist,
4156
+ pointerType: "pen",
4157
+ button: "left",
4158
+ buttons: 1,
4159
+ clickCount: 1
4160
+ });
4161
+ }
4162
+ } catch (error) {
4163
+ failure = error;
4164
+ } finally {
4165
+ if (pressed) {
4166
+ try {
4167
+ await send({
4168
+ type: "mouseReleased",
4169
+ x: last.x,
4170
+ y: last.y,
4171
+ force: 0,
4172
+ tiltX: last.tiltX,
4173
+ tiltY: last.tiltY,
4174
+ twist: last.twist,
4175
+ pointerType: "pen",
4176
+ button: "left",
4177
+ buttons: 0,
4178
+ clickCount: 1
4179
+ });
4180
+ } catch (error) {
4181
+ failure = new Error(`${failure ? String(failure) + "; " : ""}Pen release failed: ${String(error)}`);
4182
+ }
4183
+ }
4184
+ }
4185
+ if (failure) throw failure;
4186
+ }
4087
4187
  function crc32(data) {
4088
4188
  let crc = 4294967295;
4089
4189
  for (let i = 0; i < data.length; i++) crc = crc32Table[(crc ^ data[i]) & 255] ^ crc >>> 8;
@@ -4194,6 +4294,22 @@ function encodePNG(rgba, width, height) {
4194
4294
  const sig = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
4195
4295
  return Buffer.concat([sig, writeChunk("IHDR", ihdr), idat, iend]);
4196
4296
  }
4297
+ function normalizeScreenshot(data) {
4298
+ let png = Buffer.from(data, "base64");
4299
+ let width = png.readUInt32BE(16);
4300
+ let height = png.readUInt32BE(20);
4301
+ if (width < 2e3 && height < 2e3 && png.length < 4e6) return data;
4302
+ let decoded = decodePNG(data);
4303
+ do {
4304
+ const factor = Math.min(0.9, 1999 / width, 1999 / height);
4305
+ decoded = scalePixels(decoded.rgba, width, height, Math.max(1, Math.floor(width * factor)));
4306
+ width = decoded.width;
4307
+ height = decoded.height;
4308
+ png = encodePNG(decoded.rgba, width, height);
4309
+ } while ((width >= 2e3 || height >= 2e3 || png.length >= 4e6) && width > 1 && height > 1);
4310
+ if (png.length >= 4e6 || width >= 2e3 || height >= 2e3) throw new Error("Screenshot exceeds output limits");
4311
+ return png.toString("base64");
4312
+ }
4197
4313
  function scalePixels(rgba, srcW, srcH, maxW) {
4198
4314
  if (srcW <= maxW) return { rgba, width: srcW, height: srcH };
4199
4315
  const scale = maxW / srcW;
@@ -4391,15 +4507,17 @@ function encodeGIF(frames, delayMs) {
4391
4507
  return result;
4392
4508
  }
4393
4509
  function sendToolRequest(requestId, requestJson) {
4394
- let sent = false;
4395
- for (const client of wsClients) {
4396
- try {
4397
- client.send(requestJson);
4398
- sent = true;
4399
- } catch {
4400
- }
4401
- }
4402
- return sent;
4510
+ if (wsClients.size === 0 && !cdpManager.isAvailable()) return false;
4511
+ handleNativeMessage(requestJson, (json) => {
4512
+ const entry = pendingToolMap.get(requestId);
4513
+ if (!entry) return true;
4514
+ pendingToolMap.delete(requestId);
4515
+ clearTimeout(entry.timeout);
4516
+ entry.resolve({ ...JSON.parse(json), requestId });
4517
+ drainTabQueue(entry.tabId);
4518
+ return true;
4519
+ });
4520
+ return true;
4403
4521
  }
4404
4522
  function rejectAllPendingTools(reason) {
4405
4523
  for (const [requestId, entry] of pendingToolMap) {
@@ -4498,7 +4616,7 @@ function spawnNativeHost() {
4498
4616
  }
4499
4617
  });
4500
4618
  }
4501
- function handleNativeMessage(json) {
4619
+ function handleNativeMessage(json, reply = sendToNativeHost) {
4502
4620
  log("debug", `native\u2192ws: ${json.slice(0, 200)}`);
4503
4621
  let outJson = json;
4504
4622
  try {
@@ -4517,7 +4635,7 @@ function handleNativeMessage(json) {
4517
4635
  const response = JSON.stringify({ type: "tool_response", result: cdpResult });
4518
4636
  log("debug", `CDP\u2192native: ${response.slice(0, 200)}`);
4519
4637
  try {
4520
- sendToNativeHost(response);
4638
+ reply(response);
4521
4639
  } catch (e) {
4522
4640
  log("warn", `sendToNativeHost failed after CDP eval: ${e.message}`);
4523
4641
  for (const client of wsClients) {
@@ -4544,7 +4662,7 @@ function handleNativeMessage(json) {
4544
4662
  cdpManager.captureScreenshot(tabId).then((cdpResult) => {
4545
4663
  if (cdpResult.data) {
4546
4664
  try {
4547
- sendToNativeHost(JSON.stringify({
4665
+ reply(JSON.stringify({
4548
4666
  type: "tool_response",
4549
4667
  result: {
4550
4668
  content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: cdpResult.data } }]
@@ -4607,7 +4725,7 @@ function handleNativeMessage(json) {
4607
4725
  const pngBuf = encodePNG(croppedRGBA, cropW, cropH);
4608
4726
  const b64 = pngBuf.toString("base64");
4609
4727
  try {
4610
- sendToNativeHost(JSON.stringify({
4728
+ reply(JSON.stringify({
4611
4729
  type: "tool_response",
4612
4730
  result: {
4613
4731
  content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: b64 } }]
@@ -4660,7 +4778,7 @@ function handleNativeMessage(json) {
4660
4778
  cdpManager.dispatchComputerAction(action, parsed.params ?? {}, tabId).then((cdpResult) => {
4661
4779
  if (cdpResult.result) {
4662
4780
  try {
4663
- sendToNativeHost(JSON.stringify({
4781
+ reply(JSON.stringify({
4664
4782
  type: "tool_response",
4665
4783
  result: { result: cdpResult.result }
4666
4784
  }));
@@ -4699,7 +4817,7 @@ function handleNativeMessage(json) {
4699
4817
  log("info", `CDP: intercepting resize_window (${width}\xD7${height})`);
4700
4818
  cdpManager.setDeviceMetrics(width, height, parsed.params?.tabId).then((r) => {
4701
4819
  try {
4702
- sendToNativeHost(JSON.stringify({ type: "tool_response", result: r }));
4820
+ reply(JSON.stringify({ type: "tool_response", result: r }));
4703
4821
  } catch (e) {
4704
4822
  log("warn", `sendToNativeHost failed after CDP resize: ${e.message}`);
4705
4823
  for (const client of wsClients) {
@@ -4728,7 +4846,7 @@ function handleNativeMessage(json) {
4728
4846
  if (cdpRequests.length > 0) {
4729
4847
  log("info", `CDP: returning ${cdpRequests.length} network requests`);
4730
4848
  try {
4731
- sendToNativeHost(JSON.stringify({
4849
+ reply(JSON.stringify({
4732
4850
  type: "tool_response",
4733
4851
  result: { result: cdpRequests, count: cdpRequests.length, source: "cdp" }
4734
4852
  }));
@@ -4789,6 +4907,7 @@ var init_claude_chrome_bridge = __esm({
4789
4907
  init_import_meta_shim();
4790
4908
  import_path = require("path");
4791
4909
  import_node_zlib = require("node:zlib");
4910
+ init_cli();
4792
4911
  init_compat();
4793
4912
  SCRIPT_DIR = IS_BUN ? globalThis.Bun.main ? (0, import_path.dirname)(globalThis.Bun.main) : (0, import_path.dirname)(new URL(import_meta_url).pathname) : (0, import_path.dirname)(new URL(import_meta_url).pathname);
4794
4913
  MANIFEST_PATH = (0, import_path.resolve)(SCRIPT_DIR, "edge-claude-ext/manifest.json");
@@ -4878,6 +4997,7 @@ var init_claude_chrome_bridge = __esm({
4878
4997
  CDP_TARGET_CACHE_TTL_MS = 1e4;
4879
4998
  CDP_TIMEOUT_MS = 15e3;
4880
4999
  CdpManager = class {
5000
+ penBusy = false;
4881
5001
  ws = null;
4882
5002
  edgePid = null;
4883
5003
  state = "disconnected";
@@ -4928,7 +5048,7 @@ var init_claude_chrome_bridge = __esm({
4928
5048
  let versionData = null;
4929
5049
  if (existingForward) {
4930
5050
  try {
4931
- const resp = await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`);
5051
+ const resp = await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`, { signal: AbortSignal.timeout(3e3) });
4932
5052
  versionData = await resp.json();
4933
5053
  log("debug", `CDP: reusing existing ADB forward on port ${CDP_PORT}`);
4934
5054
  } catch {
@@ -4942,7 +5062,7 @@ var init_claude_chrome_bridge = __esm({
4942
5062
  );
4943
5063
  if (fwdResult.exitCode !== 0) continue;
4944
5064
  try {
4945
- const resp = await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`);
5065
+ const resp = await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`, { signal: AbortSignal.timeout(3e3) });
4946
5066
  versionData = await resp.json();
4947
5067
  log("info", `CDP: Edge version \u2014 ${versionData["Browser"] ?? "unknown"}, pkg: ${versionData["Android-Package"] ?? "unknown"} (socket: ${socketName})`);
4948
5068
  break;
@@ -5203,26 +5323,45 @@ var init_claude_chrome_bridge = __esm({
5203
5323
  }
5204
5324
  }
5205
5325
  /**
5206
- * Capture a PNG screenshot. Tries CDP Page.captureScreenshot first, then
5207
- * falls back to ADB screencap (Edge Android doesn't support CDP screenshots).
5326
+ * Capture a PNG screenshot.
5327
+ *
5328
+ * Preferred path — CDP `Page.captureScreenshot`: captures the tab's own
5329
+ * renderer surface (the actual page content), so it works even when the Edge
5330
+ * app is backgrounded. `Page.bringToFront` is REQUIRED first: a backgrounded
5331
+ * renderer has no compositor surface and `captureScreenshot` fails with
5332
+ * "Internal error" until the tab is the active one — bringToFront wakes the
5333
+ * renderer without foregrounding the Edge app itself.
5334
+ *
5335
+ * Fallback — ADB `screencap`: grabs the whole device screen (so Edge must be
5336
+ * foregrounded to show the page). Used only when CDP is unavailable or the
5337
+ * renderer can't produce a frame.
5208
5338
  */
5209
5339
  async captureScreenshot(tabId) {
5210
- if (!this.isAvailable()) return { error: "CDP not available" };
5211
- try {
5212
- const targetId = await this.resolveTarget(tabId);
5213
- if (targetId) {
5214
- let sessionId = this.sessionMap.get(targetId);
5215
- if (!sessionId) {
5216
- const attach = await this.sendCommand("Target.attachToTarget", { targetId, flatten: true });
5217
- sessionId = attach.sessionId;
5218
- this.sessionMap.set(targetId, sessionId);
5219
- }
5220
- try {
5221
- await this.sendCommand("Page.bringToFront", {}, sessionId);
5222
- } catch {
5340
+ if (this.isAvailable()) {
5341
+ let targetId = null;
5342
+ try {
5343
+ targetId = await this.resolveTarget(tabId);
5344
+ if (targetId) {
5345
+ let sessionId = this.sessionMap.get(targetId);
5346
+ if (!sessionId) {
5347
+ const attach = await this.sendCommand("Target.attachToTarget", { targetId, flatten: true });
5348
+ sessionId = attach.sessionId;
5349
+ this.sessionMap.set(targetId, sessionId);
5350
+ }
5351
+ try {
5352
+ await this.sendCommand("Page.bringToFront", {}, sessionId);
5353
+ } catch {
5354
+ }
5355
+ const shot = await this.sendCommand("Page.captureScreenshot", { format: "png" }, sessionId);
5356
+ if (shot?.data) {
5357
+ log("info", `CDP: Page.captureScreenshot captured ~${Math.round(shot.data.length * 3 / 4)} bytes`);
5358
+ return { data: normalizeScreenshot(shot.data) };
5359
+ }
5223
5360
  }
5361
+ } catch (err) {
5362
+ if (targetId) this.sessionMap.delete(targetId);
5363
+ log("debug", `CDP: Page.captureScreenshot failed, falling back to ADB screencap \u2014 ${err.message}`);
5224
5364
  }
5225
- } catch {
5226
5365
  }
5227
5366
  try {
5228
5367
  const tmpPath = "/data/data/com.termux/files/usr/tmp/cdp-screencap.png";
@@ -5233,12 +5372,39 @@ var init_claude_chrome_bridge = __esm({
5233
5372
  const { readFile: rf } = await import("node:fs/promises");
5234
5373
  const buf = await rf(tmpPath);
5235
5374
  log("info", `CDP: ADB screencap captured ${buf.length} bytes`);
5236
- return { data: buf.toString("base64") };
5375
+ return { data: normalizeScreenshot(buf.toString("base64")) };
5237
5376
  }
5238
5377
  }
5239
5378
  } catch {
5240
5379
  }
5241
- return { error: "Screenshot not available (CDP Page.captureScreenshot unsupported on Android, ADB screencap failed)" };
5380
+ return { error: "Screenshot not available (CDP Page.captureScreenshot failed and ADB screencap failed)" };
5381
+ }
5382
+ /** Draw on an exact target; never guess the active page or downgrade to mouse. */
5383
+ async penStroke(params) {
5384
+ const points = validatePenPoints(params.points);
5385
+ const hasTarget = typeof params.targetId === "string" && params.targetId.length > 0;
5386
+ const hasTab = typeof params.tabId === "number" && Number.isSafeInteger(params.tabId) && params.tabId >= 0;
5387
+ if (hasTarget === hasTab) throw new Error("Specify exactly one targetId or tabId");
5388
+ if (!process.env.BRIDGE_ADB_SERIAL) throw new Error("Set BRIDGE_ADB_SERIAL to the intended device before using pen_stroke");
5389
+ if (!this.isAvailable()) throw new Error("CDP unavailable; pen strokes require a connected browser");
5390
+ if (this.penBusy) throw new Error("Another pen stroke is in progress; retry after it finishes");
5391
+ this.penBusy = true;
5392
+ try {
5393
+ await this.refreshTargets();
5394
+ const candidates = this.cachedTargets.filter((t) => t.type === "page" && (hasTarget ? t.targetId === params.targetId : t.url === this.tabUrlCache.get(params.tabId)));
5395
+ if (candidates.length !== 1) throw new Error("Pen target missing or ambiguous; refresh tabs or supply an exact CDP targetId");
5396
+ const targetId = candidates[0].targetId;
5397
+ let sessionId = this.sessionMap.get(targetId);
5398
+ if (!sessionId) {
5399
+ const attached = await this.sendCommand("Target.attachToTarget", { targetId, flatten: true });
5400
+ sessionId = attached.sessionId;
5401
+ this.sessionMap.set(targetId, sessionId);
5402
+ }
5403
+ await sendPenPoints(points, (event) => this.sendCommand("Input.dispatchMouseEvent", event, sessionId));
5404
+ return { samples: points.length, targetId };
5405
+ } finally {
5406
+ this.penBusy = false;
5407
+ }
5242
5408
  }
5243
5409
  /** Dispatch a computer tool action via CDP Input domain */
5244
5410
  async dispatchComputerAction(action, params, tabId) {
@@ -5453,6 +5619,8 @@ var init_claude_chrome_bridge = __esm({
5453
5619
  state: this.state,
5454
5620
  edgePid: this.edgePid,
5455
5621
  port: CDP_PORT,
5622
+ deviceSerial: process.env.BRIDGE_ADB_SERIAL ?? null,
5623
+ penBusy: this.penBusy,
5456
5624
  targets: this.cachedTargets.filter((t) => t.type === "page").length
5457
5625
  };
5458
5626
  }
@@ -5522,9 +5690,12 @@ var init_claude_chrome_bridge = __esm({
5522
5690
  /** Check if an ADB forward for our CDP port already exists */
5523
5691
  checkExistingForward() {
5524
5692
  try {
5525
- const result = runSync(adb("forward", "--list"));
5693
+ const result = runSync(adb("forward", "--list"), { timeoutMs: 3e3 });
5526
5694
  const lines = result.stdout.toString().trim().split("\n");
5527
- return lines.some((l) => l.includes(`tcp:${CDP_PORT}`));
5695
+ return lines.some((line) => {
5696
+ const [serial, local] = line.trim().split(/\s+/);
5697
+ return serial === getAdbSerial() && local === `tcp:${CDP_PORT}`;
5698
+ });
5528
5699
  } catch {
5529
5700
  return false;
5530
5701
  }
@@ -5535,14 +5706,14 @@ var init_claude_chrome_bridge = __esm({
5535
5706
  * Returns NaN if Edge is not running or both methods fail.
5536
5707
  */
5537
5708
  getEdgePid() {
5538
- try {
5709
+ if (!process.env.BRIDGE_ADB_SERIAL) try {
5539
5710
  const local = runSync(["pidof", "com.microsoft.emmx.canary"]);
5540
5711
  const pid = parseInt(local.stdout.toString().trim().split(/\s+/)[0], 10);
5541
5712
  if (!isNaN(pid)) return pid;
5542
5713
  } catch {
5543
5714
  }
5544
5715
  try {
5545
- const remote = runSync(adb("shell", "pidof", "com.microsoft.emmx.canary"));
5716
+ const remote = runSync(adb("shell", "pidof", "com.microsoft.emmx.canary"), { timeoutMs: 3e3 });
5546
5717
  const pid = parseInt(remote.stdout.toString().trim().split(/\s+/)[0], 10);
5547
5718
  if (!isNaN(pid)) return pid;
5548
5719
  } catch {
@@ -5639,6 +5810,7 @@ var init_claude_chrome_bridge = __esm({
5639
5810
  port: WS_PORT,
5640
5811
  async fetch(req, upgrade) {
5641
5812
  const url = new URL(req.url);
5813
+ if (url.pathname === "/mcp") return handleMcpHttp(req);
5642
5814
  if (url.pathname === "/health") {
5643
5815
  return new Response(
5644
5816
  JSON.stringify({
@@ -5654,6 +5826,28 @@ var init_claude_chrome_bridge = __esm({
5654
5826
  { headers: { "Content-Type": "application/json" } }
5655
5827
  );
5656
5828
  }
5829
+ if (url.pathname === "/pen-stroke" && req.method === "POST") {
5830
+ const origin = req.headers.get("origin");
5831
+ if (origin && origin !== url.origin) return new Response("Forbidden origin", { status: 403 });
5832
+ if (BRIDGE_TOKEN && req.headers.get("authorization") !== `Bearer ${BRIDGE_TOKEN}`) {
5833
+ return new Response("Unauthorized", { status: 401 });
5834
+ }
5835
+ if (!req.headers.get("content-type")?.startsWith("application/json")) {
5836
+ return new Response("Expected application/json", { status: 415 });
5837
+ }
5838
+ try {
5839
+ const raw = await req.text();
5840
+ if (Buffer.byteLength(raw) > 262144) return new Response("Stroke too large", { status: 413 });
5841
+ const params = JSON.parse(raw);
5842
+ if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error("Expected a stroke object");
5843
+ lastToolName = "pen_stroke";
5844
+ lastToolTime = (/* @__PURE__ */ new Date()).toISOString();
5845
+ const result = await cdpManager.penStroke(params);
5846
+ return Response.json({ result });
5847
+ } catch (error) {
5848
+ return Response.json({ error: error.message }, { status: 400 });
5849
+ }
5850
+ }
5657
5851
  if (url.pathname === "/shutdown" && req.method === "POST") {
5658
5852
  log("info", "Shutdown requested via HTTP");
5659
5853
  setTimeout(() => shutdown(), 200);
@@ -5810,6 +6004,40 @@ var init_claude_chrome_bridge = __esm({
5810
6004
  });
5811
6005
  lastToolName = body.method;
5812
6006
  lastToolTime = (/* @__PURE__ */ new Date()).toISOString();
6007
+ if (body.method === "computer" && (body.params?.action === "screenshot" || body.params?.action === "zoom")) {
6008
+ const action = body.params.action;
6009
+ const shotTabId = body.params.tabId;
6010
+ log("info", `HTTP /tool: intercepting computer ${action} via CDP/ADB capture (tab ${shotTabId ?? "active"})`);
6011
+ const shot = await cdpManager.captureScreenshot(shotTabId);
6012
+ if (shot.data) {
6013
+ let imgData = shot.data;
6014
+ if (action === "zoom") {
6015
+ try {
6016
+ const zoomFactor = body.params.zoom_factor ?? 2;
6017
+ const coord = body.params.coordinate ?? null;
6018
+ const { width, height, rgba } = decodePNG(shot.data);
6019
+ const cx = coord?.[0] ?? Math.round(width / 2);
6020
+ const cy = coord?.[1] ?? Math.round(height / 2);
6021
+ const cropW = Math.round(width / zoomFactor);
6022
+ const cropH = Math.round(height / zoomFactor);
6023
+ const cropX = Math.max(0, Math.min(Math.round(cx - cropW / 2), width - cropW));
6024
+ const cropY = Math.max(0, Math.min(Math.round(cy - cropH / 2), height - cropH));
6025
+ const croppedRGBA = cropPixels(rgba, width, height, cropX, cropY, cropW, cropH);
6026
+ imgData = encodePNG(croppedRGBA, cropW, cropH).toString("base64");
6027
+ } catch (cropErr) {
6028
+ log("warn", `HTTP /tool zoom crop failed, returning full screenshot: ${cropErr.message}`);
6029
+ }
6030
+ }
6031
+ return new Response(
6032
+ JSON.stringify({
6033
+ type: "tool_response",
6034
+ result: { content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: imgData } }] }
6035
+ }),
6036
+ { headers: { "Content-Type": "application/json" } }
6037
+ );
6038
+ }
6039
+ log("warn", `HTTP /tool: ADB screencap failed (${shot.error ?? "unknown"}); forwarding ${action} to extension`);
6040
+ }
5813
6041
  const MAX_PENDING_TOOLS = 50;
5814
6042
  const totalQueued = pendingToolMap.size + Array.from(busyTabs.values()).reduce((acc, arr) => acc + arr.length, 0);
5815
6043
  if (totalQueued >= MAX_PENDING_TOOLS) {
@@ -5991,11 +6219,11 @@ var init_claude_chrome_bridge = __esm({
5991
6219
  }
5992
6220
  }, 3e4);
5993
6221
  }
5994
- },
5995
- maxPayloadLength: MAX_MESSAGE_SIZE,
5996
- idleTimeout: 120
5997
- // seconds
5998
- }
6222
+ }
6223
+ },
6224
+ maxPayloadLength: MAX_MESSAGE_SIZE,
6225
+ idleTimeout: 120
6226
+ // seconds
5999
6227
  });
6000
6228
  setInterval(() => {
6001
6229
  for (const ws of wsClients) {
@@ -6133,25 +6361,13 @@ var init_claude_chrome_bridge = __esm({
6133
6361
  });
6134
6362
 
6135
6363
  // src/cli.ts
6136
- init_import_meta_shim();
6137
- var import_path2 = require("path");
6138
- var import_fs = require("fs");
6139
- var PKG_VERSION = (() => {
6140
- try {
6141
- const dir = typeof __dirname !== "undefined" ? __dirname : (0, import_path2.dirname)(new URL(import_meta_url).pathname);
6142
- const pkgPath = (0, import_path2.resolve)(dir, "../package.json");
6143
- return JSON.parse((0, import_fs.readFileSync)(pkgPath, "utf-8")).version ?? "0.0.0";
6144
- } catch {
6145
- return "0.0.0";
6146
- }
6147
- })();
6148
- var WS_PORT2 = parseInt(process.env.BRIDGE_PORT ?? "18963", 10);
6149
- var WS_HOST2 = "127.0.0.1";
6150
- var BRIDGE_URL = process.env.BRIDGE_URL ?? `http://${WS_HOST2}:${WS_PORT2}`;
6151
- var HEALTH_URL = `${BRIDGE_URL}/health`;
6152
- var SHUTDOWN_URL = `${BRIDGE_URL}/shutdown`;
6153
- var TOOL_URL = `${BRIDGE_URL}/tool`;
6154
- var TOOL_TIMEOUT_MS = 3e4;
6364
+ var cli_exports = {};
6365
+ __export(cli_exports, {
6366
+ formatToolResult: () => formatToolResult,
6367
+ handleMcpHttp: () => handleMcpHttp,
6368
+ handleMcpRequest: () => handleMcpRequest
6369
+ });
6370
+ module.exports = __toCommonJS(cli_exports);
6155
6371
  async function fetchWithTimeout(url, opts = {}) {
6156
6372
  const { timeout = 3e3, ...fetchOpts } = opts;
6157
6373
  const controller = new AbortController();
@@ -6180,14 +6396,6 @@ async function bridgeClientCount() {
6180
6396
  return null;
6181
6397
  }
6182
6398
  }
6183
- var EDGE_PACKAGES = [
6184
- "com.microsoft.emmx.canary",
6185
- "com.microsoft.emmx.dev",
6186
- "com.microsoft.emmx.beta",
6187
- "com.microsoft.emmx"
6188
- ];
6189
- var EXT_DEST = "/data/local/tmp/cfc-ext";
6190
- var FLAGS_FILE = "/data/local/tmp/chrome-command-line";
6191
6399
  function selfDir() {
6192
6400
  return typeof __dirname !== "undefined" ? __dirname : (0, import_path2.dirname)(new URL(import_meta_url).pathname);
6193
6401
  }
@@ -6225,9 +6433,9 @@ function resolveAdbSerial(sp) {
6225
6433
  if (online.length > 1) return env || online[0].serial;
6226
6434
  return "";
6227
6435
  }
6228
- function runAdb(sp, serial, args2) {
6436
+ function runAdb(sp, serial, args) {
6229
6437
  const base = serial ? ["-s", serial] : [];
6230
- return sp("adb", [...base, ...args2], { stdio: "pipe", encoding: "utf-8" });
6438
+ return sp("adb", [...base, ...args], { stdio: "pipe", encoding: "utf-8" });
6231
6439
  }
6232
6440
  function detectEdgePkg(sp, serial) {
6233
6441
  for (const pkg of EDGE_PACKAGES) {
@@ -6500,7 +6708,6 @@ Installing CFC extension v${extVersion} via --load-extension...`);
6500
6708
  console.log(" Extension will load automatically when Edge starts.");
6501
6709
  return true;
6502
6710
  }
6503
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
6504
6711
  function ask(question) {
6505
6712
  return new Promise((res) => {
6506
6713
  const rl = require("readline").createInterface({ input: process.stdin, output: process.stdout });
@@ -6510,8 +6717,6 @@ function ask(question) {
6510
6717
  });
6511
6718
  });
6512
6719
  }
6513
- var isYes = (a) => a === "" || a === "y" || a === "yes";
6514
- var EDGE_CANARY = "com.microsoft.emmx.canary";
6515
6720
  async function ensureEdgeInstalled(sp, serial, interactive) {
6516
6721
  let pkg = detectEdgePkg(sp, serial);
6517
6722
  if (pkg) return pkg;
@@ -6665,233 +6870,6 @@ async function cmdStart() {
6665
6870
  process.exit(1);
6666
6871
  }
6667
6872
  }
6668
- var MCP_TOOLS = [
6669
- {
6670
- name: "tabs_context_mcp",
6671
- 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.",
6672
- inputSchema: {
6673
- type: "object",
6674
- properties: { createIfEmpty: { type: "boolean", description: "Creates a new MCP tab group if none exists." } },
6675
- required: []
6676
- }
6677
- },
6678
- {
6679
- name: "tabs_create_mcp",
6680
- description: "Creates a new empty tab in the MCP tab group.",
6681
- inputSchema: { type: "object", properties: {}, required: [] }
6682
- },
6683
- {
6684
- name: "navigate",
6685
- description: "Navigate to a URL, or go forward/back in browser history.",
6686
- inputSchema: {
6687
- type: "object",
6688
- properties: {
6689
- url: { type: "string", description: 'URL to navigate to. Use "forward" or "back" for history.' },
6690
- tabId: { type: "number", description: "Tab ID to navigate." }
6691
- },
6692
- required: ["url", "tabId"]
6693
- }
6694
- },
6695
- {
6696
- name: "computer",
6697
- 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.",
6698
- inputSchema: {
6699
- type: "object",
6700
- properties: {
6701
- action: {
6702
- type: "string",
6703
- enum: ["left_click", "right_click", "type", "screenshot", "wait", "scroll", "key", "left_click_drag", "double_click", "triple_click", "zoom", "scroll_to", "hover"],
6704
- description: "The action to perform."
6705
- },
6706
- coordinate: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2, description: "(x, y) pixel coordinates." },
6707
- text: { type: "string", description: "Text to type or key(s) to press." },
6708
- duration: { type: "number", minimum: 0, maximum: 30, description: "Seconds to wait." },
6709
- scroll_direction: { type: "string", enum: ["up", "down", "left", "right"], description: "Scroll direction." },
6710
- scroll_amount: { type: "number", minimum: 1, maximum: 10, description: "Scroll ticks (default: 3)." },
6711
- start_coordinate: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2, description: "Start coords for drag." },
6712
- region: { type: "array", items: { type: "number" }, minItems: 4, maxItems: 4, description: "(x0,y0,x1,y1) for zoom." },
6713
- repeat: { type: "number", minimum: 1, maximum: 100, description: "Key repeat count." },
6714
- ref: { type: "string", description: "Element ref ID for scroll_to." },
6715
- modifiers: { type: "string", description: 'Modifier keys: "ctrl", "shift", "alt", "cmd".' },
6716
- tabId: { type: "number", description: "Tab ID." }
6717
- },
6718
- required: ["action", "tabId"]
6719
- }
6720
- },
6721
- {
6722
- name: "javascript_tool",
6723
- description: "Execute JavaScript in the page context. Returns the last expression result.",
6724
- inputSchema: {
6725
- type: "object",
6726
- properties: {
6727
- action: { type: "string", description: "Must be 'javascript_exec'" },
6728
- text: { type: "string", description: "JavaScript code. Don't use 'return'." },
6729
- tabId: { type: "number", description: "Tab ID." }
6730
- },
6731
- required: ["action", "text", "tabId"]
6732
- }
6733
- },
6734
- {
6735
- name: "read_page",
6736
- description: "Get accessibility tree of page elements. Filter for interactive elements or get all.",
6737
- inputSchema: {
6738
- type: "object",
6739
- properties: {
6740
- filter: { type: "string", enum: ["interactive", "all"], description: "Element filter." },
6741
- tabId: { type: "number", description: "Tab ID." },
6742
- depth: { type: "number", description: "Max tree depth (default: 15)." },
6743
- ref_id: { type: "string", description: "Parent element ref to focus on." },
6744
- max_chars: { type: "number", description: "Max output chars (default: 50000)." }
6745
- },
6746
- required: ["tabId"]
6747
- }
6748
- },
6749
- {
6750
- name: "find",
6751
- description: 'Find elements by natural language (e.g., "search bar", "login button").',
6752
- inputSchema: {
6753
- type: "object",
6754
- properties: {
6755
- query: { type: "string", description: "What to find." },
6756
- tabId: { type: "number", description: "Tab ID." }
6757
- },
6758
- required: ["query", "tabId"]
6759
- }
6760
- },
6761
- {
6762
- name: "form_input",
6763
- description: "Set form element values using ref ID from read_page.",
6764
- inputSchema: {
6765
- type: "object",
6766
- properties: {
6767
- ref: { type: "string", description: "Element ref ID." },
6768
- value: { type: ["string", "boolean", "number"], description: "Value to set." },
6769
- tabId: { type: "number", description: "Tab ID." }
6770
- },
6771
- required: ["ref", "value", "tabId"]
6772
- }
6773
- },
6774
- {
6775
- name: "get_page_text",
6776
- description: "Extract raw text content from the page.",
6777
- inputSchema: {
6778
- type: "object",
6779
- properties: { tabId: { type: "number", description: "Tab ID." } },
6780
- required: ["tabId"]
6781
- }
6782
- },
6783
- {
6784
- name: "read_console_messages",
6785
- description: "Read browser console messages. Always provide a pattern to filter.",
6786
- inputSchema: {
6787
- type: "object",
6788
- properties: {
6789
- tabId: { type: "number", description: "Tab ID." },
6790
- onlyErrors: { type: "boolean", description: "Errors only." },
6791
- clear: { type: "boolean", description: "Clear after reading." },
6792
- pattern: { type: "string", description: "Regex filter pattern." },
6793
- limit: { type: "number", description: "Max messages (default: 100)." }
6794
- },
6795
- required: ["tabId"]
6796
- }
6797
- },
6798
- {
6799
- name: "read_network_requests",
6800
- description: "Read HTTP network requests from a tab.",
6801
- inputSchema: {
6802
- type: "object",
6803
- properties: {
6804
- tabId: { type: "number", description: "Tab ID." },
6805
- urlPattern: { type: "string", description: "URL substring filter." },
6806
- clear: { type: "boolean", description: "Clear after reading." },
6807
- limit: { type: "number", description: "Max requests (default: 100)." }
6808
- },
6809
- required: ["tabId"]
6810
- }
6811
- },
6812
- {
6813
- name: "resize_window",
6814
- description: "Resize browser window.",
6815
- inputSchema: {
6816
- type: "object",
6817
- properties: {
6818
- width: { type: "number", description: "Width in pixels." },
6819
- height: { type: "number", description: "Height in pixels." },
6820
- tabId: { type: "number", description: "Tab ID." }
6821
- },
6822
- required: ["width", "height", "tabId"]
6823
- }
6824
- },
6825
- {
6826
- name: "gif_creator",
6827
- description: "Record and export browser session GIFs.",
6828
- inputSchema: {
6829
- type: "object",
6830
- properties: {
6831
- action: { type: "string", enum: ["start_recording", "stop_recording", "export", "clear"], description: "Action." },
6832
- tabId: { type: "number", description: "Tab ID." },
6833
- download: { type: "boolean", description: "Download GIF on export." },
6834
- filename: { type: "string", description: "GIF filename." },
6835
- options: { type: "object", description: "GIF options." }
6836
- },
6837
- required: ["action", "tabId"]
6838
- }
6839
- },
6840
- {
6841
- name: "upload_image",
6842
- description: "Upload a screenshot to a file input or drag & drop target.",
6843
- inputSchema: {
6844
- type: "object",
6845
- properties: {
6846
- imageId: { type: "string", description: "Screenshot ID." },
6847
- ref: { type: "string", description: "Element ref ID." },
6848
- coordinate: { type: "array", items: { type: "number" }, description: "Drop coords [x,y]." },
6849
- tabId: { type: "number", description: "Tab ID." },
6850
- filename: { type: "string", description: "Filename." }
6851
- },
6852
- required: ["imageId", "tabId"]
6853
- }
6854
- },
6855
- {
6856
- name: "update_plan",
6857
- description: "Present a plan to the user for approval.",
6858
- inputSchema: {
6859
- type: "object",
6860
- properties: {
6861
- domains: { type: "array", items: { type: "string" }, description: "Domains to visit." },
6862
- approach: { type: "array", items: { type: "string" }, description: "Steps to take." }
6863
- },
6864
- required: ["domains", "approach"]
6865
- }
6866
- },
6867
- {
6868
- name: "shortcuts_list",
6869
- description: "List available shortcuts and workflows.",
6870
- inputSchema: {
6871
- type: "object",
6872
- properties: { tabId: { type: "number", description: "Tab ID." } },
6873
- required: ["tabId"]
6874
- }
6875
- },
6876
- {
6877
- name: "shortcuts_execute",
6878
- description: "Execute a shortcut or workflow.",
6879
- inputSchema: {
6880
- type: "object",
6881
- properties: {
6882
- tabId: { type: "number", description: "Tab ID." },
6883
- shortcutId: { type: "string", description: "Shortcut ID." },
6884
- command: { type: "string", description: "Command name." }
6885
- },
6886
- required: ["tabId"]
6887
- }
6888
- },
6889
- {
6890
- name: "switch_browser",
6891
- description: "Switch which Chrome browser is used for automation.",
6892
- inputSchema: { type: "object", properties: {}, required: [] }
6893
- }
6894
- ];
6895
6873
  function mcpResult(id, result) {
6896
6874
  return { jsonrpc: "2.0", id, result };
6897
6875
  }
@@ -6903,10 +6881,10 @@ function mcpSend(response) {
6903
6881
  }
6904
6882
  async function callBridgeTool(method, params) {
6905
6883
  try {
6906
- const resp = await fetch(TOOL_URL, {
6884
+ const resp = await fetch(method === "pen_stroke" ? `${BRIDGE_URL}/pen-stroke` : TOOL_URL, {
6907
6885
  method: "POST",
6908
- headers: { "Content-Type": "application/json" },
6909
- body: JSON.stringify({ method, params }),
6886
+ headers: { "Content-Type": "application/json", ...process.env.BRIDGE_TOKEN ? { Authorization: `Bearer ${process.env.BRIDGE_TOKEN}` } : {} },
6887
+ body: JSON.stringify(method === "pen_stroke" ? params : { method, params }),
6910
6888
  signal: AbortSignal.timeout(TOOL_TIMEOUT_MS)
6911
6889
  });
6912
6890
  if (!resp.ok) {
@@ -6928,49 +6906,118 @@ async function callBridgeTool(method, params) {
6928
6906
  }
6929
6907
  function formatToolResult(result) {
6930
6908
  if (!result || typeof result !== "object") {
6931
- return [{ type: "text", text: JSON.stringify(result) }];
6909
+ return [{ type: "text", text: JSON.stringify(result) ?? "undefined" }];
6932
6910
  }
6933
6911
  const r = result;
6934
- if (Array.isArray(r.content)) return r.content;
6935
- if (r.data && typeof r.data === "string" && r.media_type) {
6936
- return [{ type: "image", source: { type: "base64", media_type: r.media_type, data: r.data } }];
6912
+ if (Array.isArray(r.content)) {
6913
+ return r.content.flatMap((item) => {
6914
+ if (!item || typeof item !== "object") return formatToolResult(item);
6915
+ const block = item;
6916
+ const source = block.source;
6917
+ if (block.type === "image" && source?.type === "base64") {
6918
+ return [{ type: "image", mimeType: source.media_type, data: source.data }];
6919
+ }
6920
+ return [block];
6921
+ });
6922
+ }
6923
+ if (typeof r.data === "string" && typeof r.media_type === "string") {
6924
+ return [{ type: "image", mimeType: r.media_type, data: r.data }];
6937
6925
  }
6938
6926
  if (r.result !== void 0) return formatToolResult(r.result);
6939
6927
  return [{ type: "text", text: JSON.stringify(result, null, 2) }];
6940
6928
  }
6941
- async function handleMcpRequest(req) {
6929
+ function toolResultFailed(result) {
6930
+ if (!result || typeof result !== "object") return false;
6931
+ const r = result;
6932
+ return Boolean(r.error || r.isError || r.result !== void 0 && toolResultFailed(r.result));
6933
+ }
6934
+ async function handleMcpRequest(req, send = mcpSend) {
6942
6935
  if (req.id === void 0 || req.id === null) return;
6943
6936
  switch (req.method) {
6944
6937
  case "initialize":
6945
- mcpSend(mcpResult(req.id, {
6946
- protocolVersion: "2024-11-05",
6938
+ send(mcpResult(req.id, {
6939
+ protocolVersion: req.params?.protocolVersion === "2024-11-05" ? "2024-11-05" : "2025-03-26",
6947
6940
  capabilities: { tools: {} },
6948
6941
  serverInfo: { name: "Claude in Chrome (Bridge)", version: PKG_VERSION }
6949
6942
  }));
6950
6943
  break;
6944
+ case "ping":
6945
+ send(mcpResult(req.id, {}));
6946
+ break;
6951
6947
  case "tools/list":
6952
- mcpSend(mcpResult(req.id, { tools: MCP_TOOLS }));
6948
+ send(mcpResult(req.id, { tools: MCP_TOOLS }));
6953
6949
  break;
6954
6950
  case "tools/call": {
6955
6951
  const toolName = req.params?.name ?? "";
6956
6952
  const toolArgs = req.params?.arguments ?? {};
6957
6953
  const tool = MCP_TOOLS.find((t) => t.name === toolName);
6958
6954
  if (!tool) {
6959
- mcpSend(mcpResult(req.id, { content: [{ type: "text", text: `Unknown tool: ${toolName}` }], isError: true }));
6955
+ send(mcpResult(req.id, { content: [{ type: "text", text: `Unknown tool: ${toolName}` }], isError: true }));
6960
6956
  break;
6961
6957
  }
6962
6958
  const { result, error } = await callBridgeTool(toolName, toolArgs);
6963
6959
  if (error) {
6964
- mcpSend(mcpResult(req.id, { content: [{ type: "text", text: error }], isError: true }));
6960
+ send(mcpResult(req.id, { content: [{ type: "text", text: error }], isError: true }));
6965
6961
  } else {
6966
- mcpSend(mcpResult(req.id, { content: formatToolResult(result) }));
6962
+ send(mcpResult(req.id, { content: formatToolResult(result), isError: toolResultFailed(result) }));
6967
6963
  }
6968
6964
  break;
6969
6965
  }
6970
6966
  default:
6971
- mcpSend(mcpError(req.id, -32601, `Method not found: ${req.method}`));
6967
+ send(mcpError(req.id, -32601, `Method not found: ${req.method}`));
6972
6968
  }
6973
6969
  }
6970
+ async function handleMcpHttp(req) {
6971
+ const url = new URL(req.url);
6972
+ const origin = req.headers.get("origin");
6973
+ const allowedHosts = /* @__PURE__ */ new Set([url.host, `localhost:${url.port}`]);
6974
+ if (!allowedHosts.has(req.headers.get("host") ?? url.host) || origin !== null && origin !== url.origin) {
6975
+ return new Response("Forbidden origin", { status: 403 });
6976
+ }
6977
+ const token = process.env.BRIDGE_TOKEN;
6978
+ if (token && req.headers.get("authorization") !== `Bearer ${token}`) {
6979
+ return new Response("Unauthorized", { status: 401 });
6980
+ }
6981
+ if (req.method !== "POST") {
6982
+ return new Response(null, { status: 405, headers: { Allow: "POST" } });
6983
+ }
6984
+ if (!req.headers.get("content-type")?.toLowerCase().startsWith("application/json")) {
6985
+ return new Response("Expected application/json", { status: 415 });
6986
+ }
6987
+ const accept = req.headers.get("accept") ?? "";
6988
+ if (!accept.includes("application/json") || !accept.includes("text/event-stream")) {
6989
+ return new Response("Expected JSON and SSE accept types", { status: 406 });
6990
+ }
6991
+ const json = (value, status = 200) => new Response(JSON.stringify(value), {
6992
+ status,
6993
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
6994
+ });
6995
+ let body;
6996
+ try {
6997
+ const raw = await req.text();
6998
+ if (Buffer.byteLength(raw) > 1048576) return new Response("Request too large", { status: 413 });
6999
+ body = JSON.parse(raw);
7000
+ } catch {
7001
+ return json(mcpError(null, -32700, "Parse error"), 400);
7002
+ }
7003
+ const messages = Array.isArray(body) ? body : [body];
7004
+ if (!messages.length) return json(mcpError(null, -32600, "Invalid Request"), 400);
7005
+ const responses = [];
7006
+ for (const value of messages) {
7007
+ if (!value || typeof value !== "object") return json(mcpError(null, -32600, "Invalid Request"), 400);
7008
+ const message = value;
7009
+ if (message.jsonrpc !== "2.0" || typeof message.method !== "string" || message.id !== void 0 && typeof message.id !== "string" && typeof message.id !== "number" || message.params !== void 0 && (!message.params || typeof message.params !== "object" || Array.isArray(message.params))) {
7010
+ return json(mcpError(null, -32600, "Invalid Request"), 400);
7011
+ }
7012
+ try {
7013
+ await handleMcpRequest(message, (response) => responses.push(response));
7014
+ } catch (error) {
7015
+ if (message.id !== void 0) responses.push(mcpError(message.id, -32603, error.message));
7016
+ }
7017
+ }
7018
+ if (!responses.length) return new Response(null, { status: 202 });
7019
+ return json(Array.isArray(body) ? responses : responses[0]);
7020
+ }
6974
7021
  async function cmdMcp() {
6975
7022
  const log2 = (msg) => process.stderr.write(`[cfc-mcp] ${msg}
6976
7023
  `);
@@ -7012,35 +7059,337 @@ async function cmdMcp() {
7012
7059
  log2("stdin closed");
7013
7060
  process.exit(0);
7014
7061
  }
7015
- var args = process.argv.slice(2);
7016
- var command = args[0] ?? "";
7017
- switch (command) {
7018
- case "--version":
7019
- case "-v":
7020
- cmdVersion();
7021
- break;
7022
- case "--help":
7023
- case "-h":
7024
- cmdHelp();
7025
- break;
7026
- case "--stop":
7027
- cmdStop();
7028
- break;
7029
- case "--setup":
7030
- cmdSetup();
7031
- break;
7032
- case "--setup-edge":
7033
- case "--doctor":
7034
- cmdSetupEdge();
7035
- break;
7036
- case "--mcp":
7037
- cmdMcp();
7038
- break;
7039
- case "":
7040
- cmdStart();
7041
- break;
7042
- default:
7043
- console.error(`Unknown option: ${command}`);
7044
- cmdHelp();
7045
- process.exit(1);
7046
- }
7062
+ var import_path2, import_fs, PKG_VERSION, WS_PORT2, WS_HOST2, BRIDGE_URL, HEALTH_URL, SHUTDOWN_URL, TOOL_URL, TOOL_TIMEOUT_MS, EDGE_PACKAGES, EXT_DEST, FLAGS_FILE, sleep, isYes, EDGE_CANARY, MCP_TOOLS;
7063
+ var init_cli = __esm({
7064
+ "src/cli.ts"() {
7065
+ init_import_meta_shim();
7066
+ import_path2 = require("path");
7067
+ import_fs = require("fs");
7068
+ PKG_VERSION = (() => {
7069
+ try {
7070
+ const dir = typeof __dirname !== "undefined" ? __dirname : (0, import_path2.dirname)(new URL(import_meta_url).pathname);
7071
+ const pkgPath = (0, import_path2.resolve)(dir, "../package.json");
7072
+ return JSON.parse((0, import_fs.readFileSync)(pkgPath, "utf-8")).version ?? "0.0.0";
7073
+ } catch {
7074
+ return "0.0.0";
7075
+ }
7076
+ })();
7077
+ WS_PORT2 = parseInt(process.env.BRIDGE_PORT ?? "18963", 10);
7078
+ WS_HOST2 = "127.0.0.1";
7079
+ BRIDGE_URL = process.env.BRIDGE_URL ?? `http://${WS_HOST2}:${WS_PORT2}`;
7080
+ HEALTH_URL = `${BRIDGE_URL}/health`;
7081
+ SHUTDOWN_URL = `${BRIDGE_URL}/shutdown`;
7082
+ TOOL_URL = `${BRIDGE_URL}/tool`;
7083
+ TOOL_TIMEOUT_MS = 35e3;
7084
+ EDGE_PACKAGES = [
7085
+ "com.microsoft.emmx.canary",
7086
+ "com.microsoft.emmx.dev",
7087
+ "com.microsoft.emmx.beta",
7088
+ "com.microsoft.emmx"
7089
+ ];
7090
+ EXT_DEST = "/data/local/tmp/cfc-ext";
7091
+ FLAGS_FILE = "/data/local/tmp/chrome-command-line";
7092
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms));
7093
+ isYes = (a) => a === "" || a === "y" || a === "yes";
7094
+ EDGE_CANARY = "com.microsoft.emmx.canary";
7095
+ MCP_TOOLS = [
7096
+ {
7097
+ name: "tabs_context_mcp",
7098
+ 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.",
7099
+ inputSchema: {
7100
+ type: "object",
7101
+ properties: { createIfEmpty: { type: "boolean", description: "Creates a new MCP tab group if none exists." } },
7102
+ required: []
7103
+ }
7104
+ },
7105
+ {
7106
+ name: "tabs_create_mcp",
7107
+ description: "Creates a new empty tab in the MCP tab group.",
7108
+ inputSchema: { type: "object", properties: {}, required: [] }
7109
+ },
7110
+ {
7111
+ name: "navigate",
7112
+ description: "Navigate to a URL, or go forward/back in browser history.",
7113
+ inputSchema: {
7114
+ type: "object",
7115
+ properties: {
7116
+ url: { type: "string", description: 'URL to navigate to. Use "forward" or "back" for history.' },
7117
+ tabId: { type: "number", description: "Tab ID to navigate." }
7118
+ },
7119
+ required: ["url", "tabId"]
7120
+ }
7121
+ },
7122
+ {
7123
+ name: "computer",
7124
+ 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.",
7125
+ inputSchema: {
7126
+ type: "object",
7127
+ properties: {
7128
+ action: {
7129
+ type: "string",
7130
+ enum: ["left_click", "right_click", "type", "screenshot", "wait", "scroll", "key", "left_click_drag", "double_click", "triple_click", "zoom", "scroll_to", "hover"],
7131
+ description: "The action to perform."
7132
+ },
7133
+ coordinate: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2, description: "(x, y) pixel coordinates." },
7134
+ text: { type: "string", description: "Text to type or key(s) to press." },
7135
+ duration: { type: "number", minimum: 0, maximum: 30, description: "Seconds to wait." },
7136
+ scroll_direction: { type: "string", enum: ["up", "down", "left", "right"], description: "Scroll direction." },
7137
+ scroll_amount: { type: "number", minimum: 1, maximum: 10, description: "Scroll ticks (default: 3)." },
7138
+ start_coordinate: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2, description: "Start coords for drag." },
7139
+ region: { type: "array", items: { type: "number" }, minItems: 4, maxItems: 4, description: "(x0,y0,x1,y1) for zoom." },
7140
+ repeat: { type: "number", minimum: 1, maximum: 100, description: "Key repeat count." },
7141
+ ref: { type: "string", description: "Element ref ID for scroll_to." },
7142
+ modifiers: { type: "string", description: 'Modifier keys: "ctrl", "shift", "alt", "cmd".' },
7143
+ tabId: { type: "number", description: "Tab ID." }
7144
+ },
7145
+ required: ["action", "tabId"]
7146
+ }
7147
+ },
7148
+ {
7149
+ name: "pen_stroke",
7150
+ description: "Draw a trusted pen stroke with per-point pressure, tilt and rotation. Coordinates are viewport CSS pixels. Requires BRIDGE_ADB_SERIAL and CDP. Specify exactly one extension tabId (refresh tabs first) or exact CDP targetId. Never falls back to mouse input. Do not replay a failed stroke without inspecting the canvas.",
7151
+ inputSchema: {
7152
+ type: "object",
7153
+ properties: {
7154
+ tabId: { type: "integer", minimum: 0, description: "Extension tab ID, resolved only when its URL uniquely matches a page." },
7155
+ targetId: { type: "string", minLength: 1, description: "Exact CDP page target ID (alternative to tabId)." },
7156
+ points: {
7157
+ type: "array",
7158
+ minItems: 1,
7159
+ maxItems: 512,
7160
+ items: {
7161
+ type: "object",
7162
+ properties: {
7163
+ x: { type: "number", minimum: 0, maximum: 1e5 },
7164
+ y: { type: "number", minimum: 0, maximum: 1e5 },
7165
+ pressure: { type: "number", minimum: 0, maximum: 1 },
7166
+ tiltX: { type: "number", minimum: -90, maximum: 90, default: 0 },
7167
+ tiltY: { type: "number", minimum: -90, maximum: 90, default: 0 },
7168
+ twist: { type: "number", minimum: 0, maximum: 359, default: 0 },
7169
+ timeMs: { type: "number", minimum: 0, maximum: 2e4, description: "Nondecreasing milliseconds from stroke start; defaults to sample index \xD7 8." }
7170
+ },
7171
+ required: ["x", "y", "pressure"]
7172
+ }
7173
+ }
7174
+ },
7175
+ required: ["points"],
7176
+ oneOf: [{ required: ["tabId"], not: { required: ["targetId"] } }, { required: ["targetId"], not: { required: ["tabId"] } }]
7177
+ }
7178
+ },
7179
+ {
7180
+ name: "javascript_tool",
7181
+ description: "Execute JavaScript in the page context. Returns the last expression result.",
7182
+ inputSchema: {
7183
+ type: "object",
7184
+ properties: {
7185
+ action: { type: "string", description: "Must be 'javascript_exec'" },
7186
+ text: { type: "string", description: "JavaScript code. Don't use 'return'." },
7187
+ tabId: { type: "number", description: "Tab ID." }
7188
+ },
7189
+ required: ["action", "text", "tabId"]
7190
+ }
7191
+ },
7192
+ {
7193
+ name: "read_page",
7194
+ description: "Get accessibility tree of page elements. Filter for interactive elements or get all.",
7195
+ inputSchema: {
7196
+ type: "object",
7197
+ properties: {
7198
+ filter: { type: "string", enum: ["interactive", "all"], description: "Element filter." },
7199
+ tabId: { type: "number", description: "Tab ID." },
7200
+ depth: { type: "number", description: "Max tree depth (default: 15)." },
7201
+ ref_id: { type: "string", description: "Parent element ref to focus on." },
7202
+ max_chars: { type: "number", description: "Max output chars (default: 50000)." }
7203
+ },
7204
+ required: ["tabId"]
7205
+ }
7206
+ },
7207
+ {
7208
+ name: "find",
7209
+ description: 'Find elements by natural language (e.g., "search bar", "login button").',
7210
+ inputSchema: {
7211
+ type: "object",
7212
+ properties: {
7213
+ query: { type: "string", description: "What to find." },
7214
+ tabId: { type: "number", description: "Tab ID." }
7215
+ },
7216
+ required: ["query", "tabId"]
7217
+ }
7218
+ },
7219
+ {
7220
+ name: "form_input",
7221
+ description: "Set form element values using ref ID from read_page.",
7222
+ inputSchema: {
7223
+ type: "object",
7224
+ properties: {
7225
+ ref: { type: "string", description: "Element ref ID." },
7226
+ value: { type: ["string", "boolean", "number"], description: "Value to set." },
7227
+ tabId: { type: "number", description: "Tab ID." }
7228
+ },
7229
+ required: ["ref", "value", "tabId"]
7230
+ }
7231
+ },
7232
+ {
7233
+ name: "get_page_text",
7234
+ description: "Extract raw text content from the page.",
7235
+ inputSchema: {
7236
+ type: "object",
7237
+ properties: { tabId: { type: "number", description: "Tab ID." } },
7238
+ required: ["tabId"]
7239
+ }
7240
+ },
7241
+ {
7242
+ name: "read_console_messages",
7243
+ description: "Read browser console messages. Always provide a pattern to filter.",
7244
+ inputSchema: {
7245
+ type: "object",
7246
+ properties: {
7247
+ tabId: { type: "number", description: "Tab ID." },
7248
+ onlyErrors: { type: "boolean", description: "Errors only." },
7249
+ clear: { type: "boolean", description: "Clear after reading." },
7250
+ pattern: { type: "string", description: "Regex filter pattern." },
7251
+ limit: { type: "number", description: "Max messages (default: 100)." }
7252
+ },
7253
+ required: ["tabId"]
7254
+ }
7255
+ },
7256
+ {
7257
+ name: "read_network_requests",
7258
+ description: "Read HTTP network requests from a tab.",
7259
+ inputSchema: {
7260
+ type: "object",
7261
+ properties: {
7262
+ tabId: { type: "number", description: "Tab ID." },
7263
+ urlPattern: { type: "string", description: "URL substring filter." },
7264
+ clear: { type: "boolean", description: "Clear after reading." },
7265
+ limit: { type: "number", description: "Max requests (default: 100)." }
7266
+ },
7267
+ required: ["tabId"]
7268
+ }
7269
+ },
7270
+ {
7271
+ name: "resize_window",
7272
+ description: "Resize browser window.",
7273
+ inputSchema: {
7274
+ type: "object",
7275
+ properties: {
7276
+ width: { type: "number", description: "Width in pixels." },
7277
+ height: { type: "number", description: "Height in pixels." },
7278
+ tabId: { type: "number", description: "Tab ID." }
7279
+ },
7280
+ required: ["width", "height", "tabId"]
7281
+ }
7282
+ },
7283
+ {
7284
+ name: "gif_creator",
7285
+ description: "Record and export browser session GIFs.",
7286
+ inputSchema: {
7287
+ type: "object",
7288
+ properties: {
7289
+ action: { type: "string", enum: ["start_recording", "stop_recording", "export", "clear"], description: "Action." },
7290
+ tabId: { type: "number", description: "Tab ID." },
7291
+ download: { type: "boolean", description: "Download GIF on export." },
7292
+ filename: { type: "string", description: "GIF filename." },
7293
+ options: { type: "object", description: "GIF options." }
7294
+ },
7295
+ required: ["action", "tabId"]
7296
+ }
7297
+ },
7298
+ {
7299
+ name: "upload_image",
7300
+ description: "Upload a screenshot to a file input or drag & drop target.",
7301
+ inputSchema: {
7302
+ type: "object",
7303
+ properties: {
7304
+ imageId: { type: "string", description: "Screenshot ID." },
7305
+ ref: { type: "string", description: "Element ref ID." },
7306
+ coordinate: { type: "array", items: { type: "number" }, description: "Drop coords [x,y]." },
7307
+ tabId: { type: "number", description: "Tab ID." },
7308
+ filename: { type: "string", description: "Filename." }
7309
+ },
7310
+ required: ["imageId", "tabId"]
7311
+ }
7312
+ },
7313
+ {
7314
+ name: "update_plan",
7315
+ description: "Present a plan to the user for approval.",
7316
+ inputSchema: {
7317
+ type: "object",
7318
+ properties: {
7319
+ domains: { type: "array", items: { type: "string" }, description: "Domains to visit." },
7320
+ approach: { type: "array", items: { type: "string" }, description: "Steps to take." }
7321
+ },
7322
+ required: ["domains", "approach"]
7323
+ }
7324
+ },
7325
+ {
7326
+ name: "shortcuts_list",
7327
+ description: "List available shortcuts and workflows.",
7328
+ inputSchema: {
7329
+ type: "object",
7330
+ properties: { tabId: { type: "number", description: "Tab ID." } },
7331
+ required: ["tabId"]
7332
+ }
7333
+ },
7334
+ {
7335
+ name: "shortcuts_execute",
7336
+ description: "Execute a shortcut or workflow.",
7337
+ inputSchema: {
7338
+ type: "object",
7339
+ properties: {
7340
+ tabId: { type: "number", description: "Tab ID." },
7341
+ shortcutId: { type: "string", description: "Shortcut ID." },
7342
+ command: { type: "string", description: "Command name." }
7343
+ },
7344
+ required: ["tabId"]
7345
+ }
7346
+ },
7347
+ {
7348
+ name: "switch_browser",
7349
+ description: "Switch which Chrome browser is used for automation.",
7350
+ inputSchema: { type: "object", properties: {}, required: [] }
7351
+ }
7352
+ ];
7353
+ if (typeof require !== "undefined" && typeof module !== "undefined" ? require.main === module : false) {
7354
+ const args = process.argv.slice(2);
7355
+ const command = args[0] ?? "";
7356
+ switch (command) {
7357
+ case "--version":
7358
+ case "-v":
7359
+ cmdVersion();
7360
+ break;
7361
+ case "--help":
7362
+ case "-h":
7363
+ cmdHelp();
7364
+ break;
7365
+ case "--stop":
7366
+ cmdStop();
7367
+ break;
7368
+ case "--setup":
7369
+ cmdSetup();
7370
+ break;
7371
+ case "--setup-edge":
7372
+ case "--doctor":
7373
+ cmdSetupEdge();
7374
+ break;
7375
+ case "--mcp":
7376
+ cmdMcp();
7377
+ break;
7378
+ case "":
7379
+ cmdStart();
7380
+ break;
7381
+ default:
7382
+ console.error(`Unknown option: ${command}`);
7383
+ cmdHelp();
7384
+ process.exit(1);
7385
+ }
7386
+ }
7387
+ }
7388
+ });
7389
+ init_cli();
7390
+ // Annotate the CommonJS export names for ESM import in node:
7391
+ 0 && (module.exports = {
7392
+ formatToolResult,
7393
+ handleMcpHttp,
7394
+ handleMcpRequest
7395
+ });