claude-chrome-android 1.5.1 → 1.7.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
  });
@@ -65,6 +72,7 @@ var require_buffer_util = __commonJS({
65
72
  "node_modules/ws/lib/buffer-util.js"(exports2, module2) {
66
73
  "use strict";
67
74
  init_import_meta_shim();
75
+ var { websocketMask, websocketUnmask } = require("http");
68
76
  var { EMPTY_BUFFER } = require_constants();
69
77
  var FastBuffer = Buffer[Symbol.species];
70
78
  function concat(list, totalLength) {
@@ -119,7 +127,16 @@ var require_buffer_util = __commonJS({
119
127
  toBuffer,
120
128
  unmask: _unmask
121
129
  };
122
- if (!process.env.WS_NO_BUFFER_UTIL) {
130
+ if (websocketMask) {
131
+ module2.exports.mask = function(source, mask, output, offset, length) {
132
+ if (length < 24) _mask(source, mask, output, offset, length);
133
+ else websocketMask(source, mask, output, offset, length);
134
+ };
135
+ module2.exports.unmask = function(buffer, mask) {
136
+ if (buffer.length < 24) _unmask(buffer, mask);
137
+ else websocketUnmask(buffer, mask);
138
+ };
139
+ } else if (!process.env.WS_NO_BUFFER_UTIL) {
123
140
  try {
124
141
  const bufferUtil = require("bufferutil");
125
142
  module2.exports.mask = function(source, mask, output, offset, length) {
@@ -317,7 +334,7 @@ var require_permessage_deflate = __commonJS({
317
334
  acceptAsServer(offers) {
318
335
  const opts = this._options;
319
336
  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) {
337
+ 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
338
  return false;
322
339
  }
323
340
  return true;
@@ -839,6 +856,7 @@ var require_receiver = __commonJS({
839
856
  this._opcode = 0;
840
857
  this._totalPayloadLength = 0;
841
858
  this._messageLength = 0;
859
+ this._numFragments = 0;
842
860
  this._fragments = [];
843
861
  this._errored = false;
844
862
  this._loop = false;
@@ -1185,27 +1203,28 @@ var require_receiver = __commonJS({
1185
1203
  unmask(data, this._mask);
1186
1204
  }
1187
1205
  }
1206
+ this._mask = void 0;
1188
1207
  if (this._opcode > 7) {
1189
1208
  this.controlMessage(data, cb);
1190
1209
  return;
1191
1210
  }
1211
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
1212
+ const error = this.createError(
1213
+ RangeError,
1214
+ "Too many message fragments",
1215
+ false,
1216
+ 1008,
1217
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1218
+ );
1219
+ cb(error);
1220
+ return;
1221
+ }
1192
1222
  if (this._compressed) {
1193
1223
  this._state = INFLATING;
1194
1224
  this.decompress(data, cb);
1195
1225
  return;
1196
1226
  }
1197
1227
  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
1228
  this._messageLength = this._totalPayloadLength;
1210
1229
  this._fragments.push(data);
1211
1230
  }
@@ -1235,17 +1254,6 @@ var require_receiver = __commonJS({
1235
1254
  cb(error);
1236
1255
  return;
1237
1256
  }
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
1257
  this._fragments.push(buf);
1250
1258
  }
1251
1259
  this.dataMessage(cb);
@@ -1268,6 +1276,7 @@ var require_receiver = __commonJS({
1268
1276
  this._totalPayloadLength = 0;
1269
1277
  this._messageLength = 0;
1270
1278
  this._fragmented = 0;
1279
+ this._numFragments = 0;
1271
1280
  this._fragments = [];
1272
1281
  if (this._opcode === 2) {
1273
1282
  let data;
@@ -1528,12 +1537,15 @@ var require_sender = __commonJS({
1528
1537
  target[2] = target[3] = 0;
1529
1538
  target.writeUIntBE(dataLength, 4, 6);
1530
1539
  }
1531
- if (!options.mask) return [target, data];
1540
+ if (!options.mask) {
1541
+ return dataLength ? [target, data] : [target];
1542
+ }
1532
1543
  target[1] |= 128;
1533
1544
  target[offset - 4] = mask[0];
1534
1545
  target[offset - 3] = mask[1];
1535
1546
  target[offset - 2] = mask[2];
1536
1547
  target[offset - 1] = mask[3];
1548
+ if (!dataLength) return [target];
1537
1549
  if (skipMasking) return [target, data];
1538
1550
  if (merge) {
1539
1551
  applyMask(data, mask, target, offset, dataLength);
@@ -2293,6 +2305,7 @@ var require_websocket = __commonJS({
2293
2305
  var https = require("https");
2294
2306
  var http2 = require("http");
2295
2307
  var net = require("net");
2308
+ var querystring = require("querystring");
2296
2309
  var tls = require("tls");
2297
2310
  var { randomBytes, createHash } = require("crypto");
2298
2311
  var { Duplex, Readable: Readable2 } = require("stream");
@@ -2350,21 +2363,38 @@ var require_websocket = __commonJS({
2350
2363
  this._isServer = false;
2351
2364
  this._redirects = 0;
2352
2365
  if (protocols === void 0) {
2353
- protocols = [];
2366
+ if (!options || options.protocols === void 0) {
2367
+ protocols = [];
2368
+ } else if (Array.isArray(options.protocols)) {
2369
+ protocols = options.protocols;
2370
+ } else {
2371
+ protocols = [options.protocols];
2372
+ }
2354
2373
  } else if (!Array.isArray(protocols)) {
2355
2374
  if (typeof protocols === "object" && protocols !== null) {
2356
2375
  options = protocols;
2357
- protocols = [];
2376
+ if (options.protocols === void 0) {
2377
+ protocols = [];
2378
+ } else if (Array.isArray(options.protocols)) {
2379
+ protocols = options.protocols;
2380
+ } else {
2381
+ protocols = [options.protocols];
2382
+ }
2358
2383
  } else {
2359
2384
  protocols = [protocols];
2360
2385
  }
2361
2386
  }
2362
- initAsClient(this, address, protocols, options);
2387
+ options = initAsClient(this, address, protocols, options);
2363
2388
  } else {
2364
- this._autoPong = options.autoPong;
2365
- this._closeTimeout = options.closeTimeout;
2366
2389
  this._isServer = true;
2367
2390
  }
2391
+ if (options.autoPong) {
2392
+ this._autoPong = true;
2393
+ this._autoPongComplete = () => autoPongComplete(this);
2394
+ this._pendingAutoPongs = 0;
2395
+ this._maxPendingAutoPongs = options.maxPendingAutoPongs | 0;
2396
+ }
2397
+ this._closeTimeout = options.closeTimeout;
2368
2398
  }
2369
2399
  /**
2370
2400
  * For historical reasons, the custom "nodebuffer" type is used by the default
@@ -2551,7 +2581,6 @@ var require_websocket = __commonJS({
2551
2581
  }
2552
2582
  return;
2553
2583
  }
2554
- this._readyState = _WebSocket.CLOSING;
2555
2584
  this._sender.close(code, data, !this._isServer, (err) => {
2556
2585
  if (err) return;
2557
2586
  this._closeFrameSent = true;
@@ -2559,6 +2588,7 @@ var require_websocket = __commonJS({
2559
2588
  this._socket.end();
2560
2589
  }
2561
2590
  });
2591
+ this._readyState = _WebSocket.CLOSING;
2562
2592
  setCloseTimer(this);
2563
2593
  }
2564
2594
  /**
@@ -2772,9 +2802,10 @@ var require_websocket = __commonJS({
2772
2802
  autoPong: true,
2773
2803
  closeTimeout: CLOSE_TIMEOUT,
2774
2804
  protocolVersion: protocolVersions[1],
2775
- maxBufferedChunks: 1024 * 1024,
2776
- maxFragments: 128 * 1024,
2805
+ maxBufferedChunks: 256 * 1024,
2806
+ maxFragments: 16 * 1024,
2777
2807
  maxPayload: 100 * 1024 * 1024,
2808
+ maxPendingAutoPongs: 60,
2778
2809
  skipUTF8Validation: false,
2779
2810
  perMessageDeflate: true,
2780
2811
  followRedirects: false,
@@ -2783,14 +2814,13 @@ var require_websocket = __commonJS({
2783
2814
  socketPath: void 0,
2784
2815
  hostname: void 0,
2785
2816
  protocol: void 0,
2817
+ protocols: void 0,
2786
2818
  timeout: void 0,
2787
2819
  method: "GET",
2788
2820
  host: void 0,
2789
2821
  path: void 0,
2790
2822
  port: void 0
2791
2823
  };
2792
- websocket._autoPong = opts.autoPong;
2793
- websocket._closeTimeout = opts.closeTimeout;
2794
2824
  if (!protocolVersions.includes(opts.protocolVersion)) {
2795
2825
  throw new RangeError(
2796
2826
  `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
@@ -2806,10 +2836,9 @@ var require_websocket = __commonJS({
2806
2836
  throw new SyntaxError(`Invalid URL: ${address}`);
2807
2837
  }
2808
2838
  }
2809
- if (parsedUrl.protocol === "http:") {
2810
- parsedUrl.protocol = "ws:";
2811
- } else if (parsedUrl.protocol === "https:") {
2812
- parsedUrl.protocol = "wss:";
2839
+ if (parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:") {
2840
+ parsedUrl = new URL2(parsedUrl);
2841
+ parsedUrl.protocol = parsedUrl.protocol === "http:" ? "ws:" : "wss:";
2813
2842
  }
2814
2843
  websocket._url = parsedUrl.href;
2815
2844
  const isSecure = parsedUrl.protocol === "wss:";
@@ -2878,12 +2907,19 @@ var require_websocket = __commonJS({
2878
2907
  }
2879
2908
  }
2880
2909
  if (parsedUrl.username || parsedUrl.password) {
2881
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2910
+ const username = querystring.unescape(parsedUrl.username);
2911
+ const password = querystring.unescape(parsedUrl.password);
2912
+ opts.auth = `${username}:${password}`;
2882
2913
  }
2883
2914
  if (isIpcUrl) {
2884
- const parts = opts.path.split(":");
2885
- opts.socketPath = parts[0];
2886
- opts.path = parts[1];
2915
+ const i = opts.path.indexOf(":");
2916
+ if (i === -1) {
2917
+ opts.socketPath = opts.path;
2918
+ opts.path = "";
2919
+ } else {
2920
+ opts.socketPath = opts.path.slice(0, i);
2921
+ opts.path = opts.path.slice(i + 1);
2922
+ }
2887
2923
  }
2888
2924
  let req;
2889
2925
  if (opts.followRedirects) {
@@ -3027,6 +3063,7 @@ var require_websocket = __commonJS({
3027
3063
  } else {
3028
3064
  req.end();
3029
3065
  }
3066
+ return opts;
3030
3067
  }
3031
3068
  function emitErrorAndClose(websocket, err) {
3032
3069
  websocket._readyState = WebSocket3.CLOSING;
@@ -3078,8 +3115,13 @@ var require_websocket = __commonJS({
3078
3115
  function receiverOnConclude(code, reason) {
3079
3116
  const websocket = this[kWebSocket];
3080
3117
  websocket._closeFrameReceived = true;
3081
- websocket._closeMessage = reason;
3082
3118
  websocket._closeCode = code;
3119
+ if (reason.length === 0) {
3120
+ websocket._closeMessage = EMPTY_BUFFER;
3121
+ } else {
3122
+ websocket._closeMessage = Buffer.allocUnsafeSlow(reason.length);
3123
+ websocket._closeMessage.set(reason);
3124
+ }
3083
3125
  if (websocket._socket[kWebSocket] === void 0) return;
3084
3126
  websocket._socket.removeListener("data", socketOnData);
3085
3127
  process.nextTick(resume, websocket._socket);
@@ -3110,9 +3152,19 @@ var require_websocket = __commonJS({
3110
3152
  }
3111
3153
  function receiverOnPing(data) {
3112
3154
  const websocket = this[kWebSocket];
3113
- if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3155
+ if (websocket._autoPong && websocket.readyState === WebSocket3.OPEN) {
3156
+ if (websocket._maxPendingAutoPongs > 0 && websocket._pendingAutoPongs >= websocket._maxPendingAutoPongs) {
3157
+ websocket.terminate();
3158
+ } else {
3159
+ websocket._pendingAutoPongs++;
3160
+ websocket.pong(data, !this._isServer, websocket._autoPongComplete);
3161
+ }
3162
+ }
3114
3163
  websocket.emit("ping", data);
3115
3164
  }
3165
+ function autoPongComplete(websocket) {
3166
+ websocket._pendingAutoPongs--;
3167
+ }
3116
3168
  function receiverOnPong(data) {
3117
3169
  this[kWebSocket].emit("pong", data);
3118
3170
  }
@@ -3363,12 +3415,14 @@ var require_websocket_server = __commonJS({
3363
3415
  * called
3364
3416
  * @param {Function} [options.handleProtocols] A hook to handle protocols
3365
3417
  * @param {String} [options.host] The hostname where to bind the server
3366
- * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of
3418
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
3367
3419
  * buffered data chunks
3368
- * @param {Number} [options.maxFragments=131072] The maximum number of message
3420
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
3369
3421
  * fragments
3370
3422
  * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3371
3423
  * size
3424
+ * @param {Number} [options.maxPendingAutoPongs=60] The maximum number of
3425
+ * pending automatic pongs
3372
3426
  * @param {Boolean} [options.noServer=false] Enable no server mode
3373
3427
  * @param {String} [options.path] Accept only connections matching this path
3374
3428
  * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
@@ -3388,9 +3442,10 @@ var require_websocket_server = __commonJS({
3388
3442
  options = {
3389
3443
  allowSynchronousEvents: true,
3390
3444
  autoPong: true,
3391
- maxBufferedChunks: 1024 * 1024,
3392
- maxFragments: 128 * 1024,
3445
+ maxBufferedChunks: 256 * 1024,
3446
+ maxFragments: 16 * 1024,
3393
3447
  maxPayload: 100 * 1024 * 1024,
3448
+ maxPendingAutoPongs: 60,
3394
3449
  skipUTF8Validation: false,
3395
3450
  perMessageDeflate: false,
3396
3451
  handleProtocols: null,
@@ -3895,7 +3950,8 @@ function createBunServer(config) {
3895
3950
  });
3896
3951
  return {
3897
3952
  stop: () => server2.stop(),
3898
- port: server2.port
3953
+ // Bun types `server.port` as optional; a bound server always has one.
3954
+ port: server2.port ?? config.port
3899
3955
  };
3900
3956
  }
3901
3957
  function createNodeServer(config) {
@@ -4016,7 +4072,12 @@ var init_compat = __esm({
4016
4072
 
4017
4073
  // ../claude-chrome-bridge.ts
4018
4074
  var claude_chrome_bridge_exports = {};
4075
+ __export(claude_chrome_bridge_exports, {
4076
+ sendPenPoints: () => sendPenPoints,
4077
+ validatePenPoints: () => validatePenPoints
4078
+ });
4019
4079
  function getAdbSerial() {
4080
+ if (process.env.BRIDGE_ADB_SERIAL) return process.env.BRIDGE_ADB_SERIAL;
4020
4081
  const now = Date.now();
4021
4082
  if (now - _adbSerialTs < ADB_SERIAL_TTL_MS) return _adbSerial;
4022
4083
  _adbSerialTs = now;
@@ -4025,9 +4086,20 @@ function getAdbSerial() {
4025
4086
  const result = runSync([ADB_PATH, "devices"], { timeoutMs: ADB_CALL_TIMEOUT_MS });
4026
4087
  const lines = result.stdout.toString().trim().split("\n").filter((l) => l.endsWith(" device"));
4027
4088
  if (lines.length <= 1) {
4028
- _adbSerial = "";
4089
+ _adbSerial = lines[0]?.split(" ")[0] ?? "";
4029
4090
  return _adbSerial;
4030
4091
  }
4092
+ const localBootId = readLocalBootId();
4093
+ if (localBootId) {
4094
+ for (const line of lines) {
4095
+ const serial = line.split(" ")[0];
4096
+ const check = runSync([ADB_PATH, "-s", serial, "shell", "cat", "/proc/sys/kernel/random/boot_id"], { timeoutMs: ADB_CALL_TIMEOUT_MS });
4097
+ if (check.exitCode === 0 && check.stdout.toString().trim() === localBootId) {
4098
+ _adbSerial = serial;
4099
+ return _adbSerial;
4100
+ }
4101
+ }
4102
+ }
4031
4103
  for (const line of lines) {
4032
4104
  const serial = line.split(" ")[0];
4033
4105
  const check = runSync([ADB_PATH, "-s", serial, "shell", "pidof", "com.microsoft.emmx.canary"], { timeoutMs: ADB_CALL_TIMEOUT_MS });
@@ -4043,9 +4115,17 @@ function getAdbSerial() {
4043
4115
  return _adbSerial;
4044
4116
  }
4045
4117
  }
4046
- function adb(...args2) {
4118
+ function readLocalBootId() {
4119
+ try {
4120
+ const { readFileSync: readFileSync2 } = require("fs");
4121
+ return readFileSync2("/proc/sys/kernel/random/boot_id", "utf-8").trim();
4122
+ } catch {
4123
+ return "";
4124
+ }
4125
+ }
4126
+ function adb(...args) {
4047
4127
  const serial = getAdbSerial();
4048
- return serial ? [ADB_PATH, "-s", serial, ...args2] : [ADB_PATH, ...args2];
4128
+ return serial ? [ADB_PATH, "-s", serial, ...args] : [ADB_PATH, ...args];
4049
4129
  }
4050
4130
  function adbNotify(tag, title, text) {
4051
4131
  try {
@@ -4068,12 +4148,12 @@ function findRuntime() {
4068
4148
  }
4069
4149
  return process.execPath;
4070
4150
  }
4071
- function log(level, msg, ...args2) {
4151
+ function log(level, msg, ...args) {
4072
4152
  if (LOG_PRIORITY[level] < LOG_PRIORITY[LOG_LEVEL]) return;
4073
4153
  const ts = (/* @__PURE__ */ new Date()).toISOString();
4074
4154
  const prefix = `[${ts}] [bridge:${level}]`;
4075
- if (level === "error") console.error(prefix, msg, ...args2);
4076
- else console.log(prefix, msg, ...args2);
4155
+ if (level === "error") console.error(prefix, msg, ...args);
4156
+ else console.log(prefix, msg, ...args);
4077
4157
  }
4078
4158
  function encodeNativeMessage(json) {
4079
4159
  const body = Buffer.from(json, "utf-8");
@@ -4084,6 +4164,89 @@ function encodeNativeMessage(json) {
4084
4164
  header.writeUInt32LE(body.length, 0);
4085
4165
  return Buffer.concat([header, body]);
4086
4166
  }
4167
+ function validatePenPoints(value) {
4168
+ if (!Array.isArray(value) || value.length < 1 || value.length > 512) {
4169
+ throw new Error("points must contain 1\u2013512 pen samples");
4170
+ }
4171
+ let previousTime = 0;
4172
+ return value.map((item, index) => {
4173
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
4174
+ throw new Error(`points[${index}] must be an object`);
4175
+ }
4176
+ const p = item;
4177
+ const number = (key, min, max, fallback) => {
4178
+ const v = p[key] === void 0 ? fallback : p[key];
4179
+ if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max) {
4180
+ throw new Error(`points[${index}].${key} must be finite and within ${min}\u2026${max}`);
4181
+ }
4182
+ return v;
4183
+ };
4184
+ const point = {
4185
+ x: number("x", 0, 1e5),
4186
+ y: number("y", 0, 1e5),
4187
+ pressure: number("pressure", 0, 1),
4188
+ tiltX: number("tiltX", -90, 90, 0),
4189
+ tiltY: number("tiltY", -90, 90, 0),
4190
+ twist: number("twist", 0, 359, 0),
4191
+ timeMs: number("timeMs", 0, 2e4, index * 8)
4192
+ };
4193
+ if (point.timeMs < previousTime) throw new Error("Sample times must be nondecreasing");
4194
+ previousTime = point.timeMs;
4195
+ return point;
4196
+ });
4197
+ }
4198
+ async function sendPenPoints(points, send) {
4199
+ const start = performance.now();
4200
+ let last = points[0];
4201
+ let pressed = false;
4202
+ let failure;
4203
+ try {
4204
+ for (let index = 0; index < points.length; index++) {
4205
+ const point = points[index];
4206
+ const delay = point.timeMs - (performance.now() - start);
4207
+ if (delay > 0) await new Promise((resolve3) => setTimeout(resolve3, delay));
4208
+ if (performance.now() - start > 25e3) throw new Error("Pen stroke exceeded 25 seconds; remaining samples cancelled");
4209
+ last = point;
4210
+ pressed = true;
4211
+ await send({
4212
+ type: index === 0 ? "mousePressed" : "mouseMoved",
4213
+ x: point.x,
4214
+ y: point.y,
4215
+ force: point.pressure,
4216
+ tiltX: point.tiltX,
4217
+ tiltY: point.tiltY,
4218
+ twist: point.twist,
4219
+ pointerType: "pen",
4220
+ button: "left",
4221
+ buttons: 1,
4222
+ clickCount: 1
4223
+ });
4224
+ }
4225
+ } catch (error) {
4226
+ failure = error;
4227
+ } finally {
4228
+ if (pressed) {
4229
+ try {
4230
+ await send({
4231
+ type: "mouseReleased",
4232
+ x: last.x,
4233
+ y: last.y,
4234
+ force: 0,
4235
+ tiltX: last.tiltX,
4236
+ tiltY: last.tiltY,
4237
+ twist: last.twist,
4238
+ pointerType: "pen",
4239
+ button: "left",
4240
+ buttons: 0,
4241
+ clickCount: 1
4242
+ });
4243
+ } catch (error) {
4244
+ failure = new Error(`${failure ? String(failure) + "; " : ""}Pen release failed: ${String(error)}`);
4245
+ }
4246
+ }
4247
+ }
4248
+ if (failure) throw failure;
4249
+ }
4087
4250
  function crc32(data) {
4088
4251
  let crc = 4294967295;
4089
4252
  for (let i = 0; i < data.length; i++) crc = crc32Table[(crc ^ data[i]) & 255] ^ crc >>> 8;
@@ -4194,6 +4357,22 @@ function encodePNG(rgba, width, height) {
4194
4357
  const sig = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
4195
4358
  return Buffer.concat([sig, writeChunk("IHDR", ihdr), idat, iend]);
4196
4359
  }
4360
+ function normalizeScreenshot(data) {
4361
+ let png = Buffer.from(data, "base64");
4362
+ let width = png.readUInt32BE(16);
4363
+ let height = png.readUInt32BE(20);
4364
+ if (width < 2e3 && height < 2e3 && png.length < 4e6) return data;
4365
+ let decoded = decodePNG(data);
4366
+ do {
4367
+ const factor = Math.min(0.9, 1999 / width, 1999 / height);
4368
+ decoded = scalePixels(decoded.rgba, width, height, Math.max(1, Math.floor(width * factor)));
4369
+ width = decoded.width;
4370
+ height = decoded.height;
4371
+ png = encodePNG(decoded.rgba, width, height);
4372
+ } while ((width >= 2e3 || height >= 2e3 || png.length >= 4e6) && width > 1 && height > 1);
4373
+ if (png.length >= 4e6 || width >= 2e3 || height >= 2e3) throw new Error("Screenshot exceeds output limits");
4374
+ return png.toString("base64");
4375
+ }
4197
4376
  function scalePixels(rgba, srcW, srcH, maxW) {
4198
4377
  if (srcW <= maxW) return { rgba, width: srcW, height: srcH };
4199
4378
  const scale = maxW / srcW;
@@ -4391,15 +4570,17 @@ function encodeGIF(frames, delayMs) {
4391
4570
  return result;
4392
4571
  }
4393
4572
  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;
4573
+ if (wsClients.size === 0 && !cdpManager.isAvailable()) return false;
4574
+ handleNativeMessage(requestJson, (json) => {
4575
+ const entry = pendingToolMap.get(requestId);
4576
+ if (!entry) return true;
4577
+ pendingToolMap.delete(requestId);
4578
+ clearTimeout(entry.timeout);
4579
+ entry.resolve({ ...JSON.parse(json), requestId });
4580
+ drainTabQueue(entry.tabId);
4581
+ return true;
4582
+ });
4583
+ return true;
4403
4584
  }
4404
4585
  function rejectAllPendingTools(reason) {
4405
4586
  for (const [requestId, entry] of pendingToolMap) {
@@ -4435,6 +4616,24 @@ function drainTabQueue(tabId) {
4435
4616
  next.resolve({ type: "tool_response", error: "All bridge clients disconnected before dispatch" });
4436
4617
  }
4437
4618
  }
4619
+ function refreshTabUrlsFromExtension() {
4620
+ if (wsClients.size === 0) return Promise.resolve();
4621
+ const requestId = `req_${++toolRequestCounter}_${Date.now()}_tabs`;
4622
+ return new Promise((resolve3) => {
4623
+ const timeout = setTimeout(() => {
4624
+ pendingToolMap.delete(requestId);
4625
+ resolve3();
4626
+ }, TAB_URL_REFRESH_TIMEOUT_MS);
4627
+ pendingToolMap.set(requestId, { resolve: () => resolve3(), timeout, tabId: -1 });
4628
+ const request = JSON.stringify({ type: "tool_request", method: "tabs_context_mcp", params: {}, requestId });
4629
+ for (const client of wsClients) {
4630
+ try {
4631
+ client.send(request);
4632
+ } catch {
4633
+ }
4634
+ }
4635
+ });
4636
+ }
4438
4637
  function spawnNativeHost() {
4439
4638
  if (nativeHost) {
4440
4639
  log("warn", "Native host already running, killing first");
@@ -4498,7 +4697,7 @@ function spawnNativeHost() {
4498
4697
  }
4499
4698
  });
4500
4699
  }
4501
- function handleNativeMessage(json) {
4700
+ function handleNativeMessage(json, reply = sendToNativeHost) {
4502
4701
  log("debug", `native\u2192ws: ${json.slice(0, 200)}`);
4503
4702
  let outJson = json;
4504
4703
  try {
@@ -4509,15 +4708,16 @@ function handleNativeMessage(json) {
4509
4708
  outJson = JSON.stringify(parsed);
4510
4709
  log("debug", `Unwrapped execute_tool \u2192 ${parsed.method}`);
4511
4710
  }
4711
+ if (parsed.type === "tool_request") void cdpManager.thawRenderers();
4512
4712
  if (parsed.type === "tool_request" && parsed.method === "javascript_tool" && cdpManager.isAvailable()) {
4513
4713
  const code = parsed.params?.text ?? "";
4514
4714
  const tabId = parsed.params?.tabId;
4515
4715
  log("info", `CDP: intercepting javascript_tool (${code.slice(0, 80)})`);
4516
- cdpManager.evaluateJS(code, tabId).then((cdpResult) => {
4716
+ cdpManager.ensurePageAwake(tabId).then(() => cdpManager.evaluateJS(code, tabId)).then((cdpResult) => {
4517
4717
  const response = JSON.stringify({ type: "tool_response", result: cdpResult });
4518
4718
  log("debug", `CDP\u2192native: ${response.slice(0, 200)}`);
4519
4719
  try {
4520
- sendToNativeHost(response);
4720
+ reply(response);
4521
4721
  } catch (e) {
4522
4722
  log("warn", `sendToNativeHost failed after CDP eval: ${e.message}`);
4523
4723
  for (const client of wsClients) {
@@ -4544,7 +4744,7 @@ function handleNativeMessage(json) {
4544
4744
  cdpManager.captureScreenshot(tabId).then((cdpResult) => {
4545
4745
  if (cdpResult.data) {
4546
4746
  try {
4547
- sendToNativeHost(JSON.stringify({
4747
+ reply(JSON.stringify({
4548
4748
  type: "tool_response",
4549
4749
  result: {
4550
4750
  content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: cdpResult.data } }]
@@ -4559,6 +4759,12 @@ function handleNativeMessage(json) {
4559
4759
  }
4560
4760
  }
4561
4761
  }
4762
+ } else if (cdpResult.final) {
4763
+ log("warn", `CDP screenshot failed: ${cdpResult.error}`);
4764
+ try {
4765
+ reply(JSON.stringify({ type: "tool_response", error: cdpResult.error }));
4766
+ } catch {
4767
+ }
4562
4768
  } else {
4563
4769
  log("warn", `CDP screenshot failed: ${cdpResult.error}`);
4564
4770
  for (const client of wsClients) {
@@ -4587,6 +4793,13 @@ function handleNativeMessage(json) {
4587
4793
  cdpManager.captureScreenshot(tabId).then((cdpResult) => {
4588
4794
  if (!cdpResult.data) {
4589
4795
  log("warn", `CDP zoom screenshot failed: ${cdpResult.error}`);
4796
+ if (cdpResult.final) {
4797
+ try {
4798
+ reply(JSON.stringify({ type: "tool_response", error: cdpResult.error }));
4799
+ } catch {
4800
+ }
4801
+ return;
4802
+ }
4590
4803
  for (const client of wsClients) {
4591
4804
  try {
4592
4805
  client.send(outJson);
@@ -4607,7 +4820,7 @@ function handleNativeMessage(json) {
4607
4820
  const pngBuf = encodePNG(croppedRGBA, cropW, cropH);
4608
4821
  const b64 = pngBuf.toString("base64");
4609
4822
  try {
4610
- sendToNativeHost(JSON.stringify({
4823
+ reply(JSON.stringify({
4611
4824
  type: "tool_response",
4612
4825
  result: {
4613
4826
  content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: b64 } }]
@@ -4657,12 +4870,13 @@ function handleNativeMessage(json) {
4657
4870
  const action = parsed.params.action;
4658
4871
  const tabId = parsed.params?.tabId;
4659
4872
  log("info", `CDP: intercepting computer ${action} (tab ${tabId ?? "active"})`);
4660
- cdpManager.dispatchComputerAction(action, parsed.params ?? {}, tabId).then((cdpResult) => {
4873
+ cdpManager.ensurePageAwake(tabId).then(() => cdpManager.dispatchComputerAction(action, parsed.params ?? {}, tabId)).then(async (cdpResult) => {
4661
4874
  if (cdpResult.result) {
4875
+ const note = await cdpManager.hiddenTabNote(tabId);
4662
4876
  try {
4663
- sendToNativeHost(JSON.stringify({
4877
+ reply(JSON.stringify({
4664
4878
  type: "tool_response",
4665
- result: { result: cdpResult.result }
4879
+ result: { result: cdpResult.result + note }
4666
4880
  }));
4667
4881
  } catch (e) {
4668
4882
  log("warn", `sendToNativeHost failed after CDP ${action}: ${e.message}`);
@@ -4699,7 +4913,7 @@ function handleNativeMessage(json) {
4699
4913
  log("info", `CDP: intercepting resize_window (${width}\xD7${height})`);
4700
4914
  cdpManager.setDeviceMetrics(width, height, parsed.params?.tabId).then((r) => {
4701
4915
  try {
4702
- sendToNativeHost(JSON.stringify({ type: "tool_response", result: r }));
4916
+ reply(JSON.stringify({ type: "tool_response", result: r }));
4703
4917
  } catch (e) {
4704
4918
  log("warn", `sendToNativeHost failed after CDP resize: ${e.message}`);
4705
4919
  for (const client of wsClients) {
@@ -4728,7 +4942,7 @@ function handleNativeMessage(json) {
4728
4942
  if (cdpRequests.length > 0) {
4729
4943
  log("info", `CDP: returning ${cdpRequests.length} network requests`);
4730
4944
  try {
4731
- sendToNativeHost(JSON.stringify({
4945
+ reply(JSON.stringify({
4732
4946
  type: "tool_response",
4733
4947
  result: { result: cdpRequests, count: cdpRequests.length, source: "cdp" }
4734
4948
  }));
@@ -4738,6 +4952,30 @@ function handleNativeMessage(json) {
4738
4952
  return;
4739
4953
  }
4740
4954
  }
4955
+ if (parsed.type === "tool_request" && EXTENSION_PAGE_TOOLS.has(parsed.method) && typeof parsed.params?.tabId === "number" && cdpManager.isAvailable()) {
4956
+ const tabId = parsed.params.tabId;
4957
+ void (async () => {
4958
+ const awake = await cdpManager.ensurePageAwake(tabId);
4959
+ if (!awake.ok) {
4960
+ log("warn", `${parsed.method}: tab ${tabId} is frozen by Edge and was not woken: ${awake.reason}`);
4961
+ try {
4962
+ reply(JSON.stringify({
4963
+ type: "tool_response",
4964
+ error: `Tab ${tabId} is frozen by Edge (hidden while Edge is not the foreground app), so its page cannot run ${parsed.method}, and it was not woken because ${awake.reason}. Select the tab in Edge or bring Edge to the front and retry; synchronous javascript_tool code and computer input still reach it.`
4965
+ }));
4966
+ } catch {
4967
+ }
4968
+ return;
4969
+ }
4970
+ for (const client of wsClients) {
4971
+ try {
4972
+ client.send(outJson);
4973
+ } catch {
4974
+ }
4975
+ }
4976
+ })();
4977
+ return;
4978
+ }
4741
4979
  } catch {
4742
4980
  }
4743
4981
  for (const ws of wsClients) {
@@ -4783,12 +5021,13 @@ function shutdown() {
4783
5021
  log("info", "Bridge stopped");
4784
5022
  process.exit(0);
4785
5023
  }
4786
- var import_path, import_node_zlib, SCRIPT_DIR, MANIFEST_PATH, BRIDGE_VERSION, WS_PORT, WS_HOST, BRIDGE_TOKEN, MAX_MESSAGE_SIZE, RECONNECT_DELAY_MS, HEARTBEAT_INTERVAL_MS, TERMUX_PREFIX, TERMUX_BIN, ADB_PATH, _adbSerial, _adbSerialTs, ADB_SERIAL_TTL_MS, NATIVE_HOST_WRAPPER, BUN_GLOBAL_CLI, NPM_GLOBAL_CLI, CLI_PATH, RUNTIME_PATH, LOG_LEVEL, LOG_PRIORITY, NativeMessageDecoder, CDP_PORT, CDP_PID_CHECK_INTERVAL_MS, CDP_MAX_BACKOFF_ATTEMPTS, CDP_TARGET_CACHE_TTL_MS, CDP_TIMEOUT_MS, CdpManager, cdpManager, crc32Table, toolRequestCounter, pendingToolMap, busyTabs, HTTP_TOOL_TIMEOUT_MS, lastToolName, lastToolTime, nativeHost, nativeHostKillTimer, stdoutDecoder, wsClients, server, TEST_PAGE_HTML;
5024
+ var import_path, import_node_zlib, SCRIPT_DIR, MANIFEST_PATH, BRIDGE_VERSION, WS_PORT, WS_HOST, BRIDGE_TOKEN, MAX_MESSAGE_SIZE, RECONNECT_DELAY_MS, HEARTBEAT_INTERVAL_MS, TERMUX_PREFIX, TERMUX_BIN, ADB_PATH, _adbSerial, _adbSerialTs, ADB_SERIAL_TTL_MS, NATIVE_HOST_WRAPPER, BUN_GLOBAL_CLI, NPM_GLOBAL_CLI, CLI_PATH, RUNTIME_PATH, LOG_LEVEL, LOG_PRIORITY, NativeMessageDecoder, CDP_PORT, CDP_PID_CHECK_INTERVAL_MS, CDP_MAX_BACKOFF_ATTEMPTS, CDP_TARGET_CACHE_TTL_MS, CDP_TIMEOUT_MS, EDGE_RENDERER_PREFIX, RENDERER_THAW_INTERVAL_MS, RENDERER_THAW_TIMEOUT_MS, PAGE_PROBE_TIMEOUT_MS, WAKE_FROZEN_TABS, WAKE_MIN_INTERVAL_MS, MESSAGE_CHANNEL_PROBE, EXTENSION_PAGE_TOOLS, CdpManager, cdpManager, crc32Table, toolRequestCounter, pendingToolMap, busyTabs, HTTP_TOOL_TIMEOUT_MS, lastToolName, lastToolTime, nativeHost, nativeHostKillTimer, stdoutDecoder, wsClients, TAB_URL_REFRESH_TIMEOUT_MS, server, TEST_PAGE_HTML;
4787
5025
  var init_claude_chrome_bridge = __esm({
4788
5026
  "../claude-chrome-bridge.ts"() {
4789
5027
  init_import_meta_shim();
4790
5028
  import_path = require("path");
4791
5029
  import_node_zlib = require("node:zlib");
5030
+ init_cli();
4792
5031
  init_compat();
4793
5032
  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
5033
  MANIFEST_PATH = (0, import_path.resolve)(SCRIPT_DIR, "edge-claude-ext/manifest.json");
@@ -4877,7 +5116,16 @@ var init_claude_chrome_bridge = __esm({
4877
5116
  CDP_MAX_BACKOFF_ATTEMPTS = 10;
4878
5117
  CDP_TARGET_CACHE_TTL_MS = 1e4;
4879
5118
  CDP_TIMEOUT_MS = 15e3;
5119
+ EDGE_RENDERER_PREFIX = "com.microsoft.emmx.canary:sandboxed_process";
5120
+ RENDERER_THAW_INTERVAL_MS = 1e4;
5121
+ RENDERER_THAW_TIMEOUT_MS = 5e3;
5122
+ PAGE_PROBE_TIMEOUT_MS = 1500;
5123
+ WAKE_FROZEN_TABS = process.env.BRIDGE_WAKE_FROZEN_TABS !== "0";
5124
+ WAKE_MIN_INTERVAL_MS = 5e3;
5125
+ MESSAGE_CHANNEL_PROBE = "new Promise((r) => { const c = new MessageChannel(); c.port1.onmessage = () => r(1); c.port2.postMessage(0); })";
5126
+ EXTENSION_PAGE_TOOLS = /* @__PURE__ */ new Set(["get_page_text", "read_page", "find", "form_input"]);
4880
5127
  CdpManager = class {
5128
+ penBusy = false;
4881
5129
  ws = null;
4882
5130
  edgePid = null;
4883
5131
  state = "disconnected";
@@ -4928,7 +5176,7 @@ var init_claude_chrome_bridge = __esm({
4928
5176
  let versionData = null;
4929
5177
  if (existingForward) {
4930
5178
  try {
4931
- const resp = await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`);
5179
+ const resp = await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`, { signal: AbortSignal.timeout(3e3) });
4932
5180
  versionData = await resp.json();
4933
5181
  log("debug", `CDP: reusing existing ADB forward on port ${CDP_PORT}`);
4934
5182
  } catch {
@@ -4942,7 +5190,7 @@ var init_claude_chrome_bridge = __esm({
4942
5190
  );
4943
5191
  if (fwdResult.exitCode !== 0) continue;
4944
5192
  try {
4945
- const resp = await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`);
5193
+ const resp = await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`, { signal: AbortSignal.timeout(3e3) });
4946
5194
  versionData = await resp.json();
4947
5195
  log("info", `CDP: Edge version \u2014 ${versionData["Browser"] ?? "unknown"}, pkg: ${versionData["Android-Package"] ?? "unknown"} (socket: ${socketName})`);
4948
5196
  break;
@@ -5116,7 +5364,9 @@ var init_claude_chrome_bridge = __esm({
5116
5364
  if (r.description) return { result: r.description };
5117
5365
  return { result: String(r) };
5118
5366
  } catch (err) {
5119
- return { error: `CDP eval failed: ${err.message}` };
5367
+ const message = err.message;
5368
+ const hint = message.startsWith("CDP timeout") ? " (if the code awaited setTimeout, requestAnimationFrame or a MessageChannel-based library: a hidden tab \u2014 Edge not in the foreground \u2014 defers those; its side effects may still happen later)" : "";
5369
+ return { error: `CDP eval failed: ${message}${hint}` };
5120
5370
  }
5121
5371
  }
5122
5372
  /** Resolve an extension tabId to a CDP targetId by URL matching */
@@ -5129,32 +5379,53 @@ var init_claude_chrome_bridge = __esm({
5129
5379
  return this.tabTargetMap.get(tabId);
5130
5380
  }
5131
5381
  if (tabId !== void 0) {
5132
- const tabUrl = this.tabUrlCache.get(tabId);
5133
- if (tabUrl) {
5134
- const target = this.cachedTargets.find((t) => t.url === tabUrl && t.type === "page");
5135
- if (target) {
5136
- this.tabTargetMap.set(tabId, target.targetId);
5137
- log("debug", `CDP: resolveTarget(${tabId}) \u2192 URL match ${target.targetId.slice(0, 16)}... (${tabUrl})`);
5138
- return target.targetId;
5139
- }
5140
- log("debug", `CDP: resolveTarget(${tabId}) \u2014 URL ${tabUrl} not found in ${this.cachedTargets.length} targets`);
5141
- } else {
5142
- log("debug", `CDP: resolveTarget(${tabId}) \u2014 no cached URL (cache size: ${this.tabUrlCache.size})`);
5382
+ let target = this.matchTabByUrl(tabId);
5383
+ if (!target && this.tabUrlRefresher) {
5384
+ await this.tabUrlRefresher();
5385
+ await this.refreshTargets();
5386
+ target = this.matchTabByUrl(tabId);
5387
+ }
5388
+ if (target) {
5389
+ this.tabTargetMap.set(tabId, target);
5390
+ return target;
5143
5391
  }
5392
+ log("warn", `CDP: no target found for tab ${tabId} (url ${this.tabUrlCache.get(tabId) ?? "unknown"})`);
5393
+ return null;
5144
5394
  }
5145
5395
  const firstPage = this.cachedTargets.find((t) => t.type === "page");
5146
5396
  log("debug", `CDP: resolveTarget(${tabId ?? "none"}) \u2192 fallback to first page: ${firstPage?.url ?? "none"}`);
5147
5397
  return firstPage?.targetId ?? null;
5148
5398
  }
5399
+ /** Asks the extension for current tab URLs (fills tabUrlCache); set by the server */
5400
+ tabUrlRefresher = null;
5401
+ setTabUrlRefresher(refresher) {
5402
+ this.tabUrlRefresher = refresher;
5403
+ }
5404
+ /**
5405
+ * Target for an extension tab by its cached URL. When several page targets
5406
+ * share the URL (the same page open twice), prefer one not already mapped to
5407
+ * a different tab.
5408
+ */
5409
+ matchTabByUrl(tabId) {
5410
+ const tabUrl = this.tabUrlCache.get(tabId);
5411
+ if (!tabUrl) return null;
5412
+ const candidates = this.cachedTargets.filter((t) => t.url === tabUrl && t.type === "page");
5413
+ if (candidates.length === 0) return null;
5414
+ const claimed = new Set(
5415
+ [...this.tabTargetMap].filter(([otherTab]) => otherTab !== tabId).map(([, targetId]) => targetId)
5416
+ );
5417
+ return (candidates.find((t) => !claimed.has(t.targetId)) ?? candidates[0]).targetId;
5418
+ }
5149
5419
  /** Fetch CDP targets via Target.getTargets (not /json/list — those IDs differ) */
5150
5420
  async refreshTargets() {
5151
5421
  try {
5152
5422
  const result = await this.sendCommand("Target.getTargets");
5153
5423
  this.cachedTargets = result.targetInfos;
5154
5424
  this.targetsLastFetched = Date.now();
5155
- for (const [tabId, url] of this.tabUrlCache) {
5156
- const target = this.cachedTargets.find((t) => t.url === url && t.type === "page");
5157
- if (target) this.tabTargetMap.set(tabId, target.targetId);
5425
+ for (const tabId of this.tabUrlCache.keys()) {
5426
+ const target = this.matchTabByUrl(tabId);
5427
+ if (target) this.tabTargetMap.set(tabId, target);
5428
+ else this.tabTargetMap.delete(tabId);
5158
5429
  }
5159
5430
  } catch (err) {
5160
5431
  log("debug", `CDP: refreshTargets failed \u2014 ${err.message}`);
@@ -5203,42 +5474,109 @@ var init_claude_chrome_bridge = __esm({
5203
5474
  }
5204
5475
  }
5205
5476
  /**
5206
- * Capture a PNG screenshot. Tries CDP Page.captureScreenshot first, then
5207
- * falls back to ADB screencap (Edge Android doesn't support CDP screenshots).
5477
+ * Capture a PNG screenshot.
5478
+ *
5479
+ * Preferred path — CDP `Page.captureScreenshot`: captures the tab's own
5480
+ * renderer surface (the actual page content), so it works even when the Edge
5481
+ * app is backgrounded. `Page.bringToFront` is REQUIRED first: a backgrounded
5482
+ * renderer has no compositor surface and `captureScreenshot` fails with
5483
+ * "Internal error" until the tab is the active one. bringToFront DOES bring
5484
+ * the Edge app to the foreground on Edge 154 Android (measured 2026-11-25:
5485
+ * focus moved from RustDesk and from Termux to ChromeTabbedActivity), so a
5486
+ * screenshot taken while the user is in another app briefly takes over the
5487
+ * screen; the previously focused activity is started again after capture
5488
+ * (not possible for the lock screen or notification shade).
5489
+ *
5490
+ * Fallback — ADB `screencap`: grabs the whole device screen (so Edge must be
5491
+ * foregrounded to show the page). Used only when CDP is unavailable or the
5492
+ * renderer can't produce a frame.
5208
5493
  */
5209
5494
  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 {
5495
+ if (this.isAvailable()) {
5496
+ let targetId = null;
5497
+ try {
5498
+ targetId = await this.resolveTarget(tabId);
5499
+ if (targetId) {
5500
+ let sessionId = this.sessionMap.get(targetId);
5501
+ if (!sessionId) {
5502
+ const attach = await this.sendCommand("Target.attachToTarget", { targetId, flatten: true });
5503
+ sessionId = attach.sessionId;
5504
+ this.sessionMap.set(targetId, sessionId);
5505
+ }
5506
+ const before = this.readDeviceState();
5507
+ let shot;
5508
+ try {
5509
+ try {
5510
+ await this.sendCommand("Page.bringToFront", {}, sessionId);
5511
+ } catch {
5512
+ }
5513
+ shot = await this.sendCommand("Page.captureScreenshot", { format: "png" }, sessionId);
5514
+ } finally {
5515
+ this.refocus(before.focus, "captured screenshot");
5516
+ }
5517
+ if (shot?.data) {
5518
+ log("info", `CDP: Page.captureScreenshot captured ~${Math.round(shot.data.length * 3 / 4)} bytes`);
5519
+ return { data: normalizeScreenshot(shot.data) };
5520
+ }
5223
5521
  }
5522
+ } catch (err) {
5523
+ if (targetId) this.sessionMap.delete(targetId);
5524
+ log("debug", `CDP: Page.captureScreenshot failed, falling back to ADB screencap \u2014 ${err.message}`);
5525
+ }
5526
+ }
5527
+ try {
5528
+ const focus = runSync(adb("shell", "dumpsys", "window"), { timeoutMs: 3e3 });
5529
+ const focusLine = focus.stdout.toString().split("\n").find((l) => l.includes("mCurrentFocus")) ?? "";
5530
+ if (focus.exitCode === 0 && !focusLine.includes("com.microsoft.emmx.canary")) {
5531
+ return {
5532
+ error: "Screenshot not available: CDP capture failed and Edge is not the foreground app, so ADB screencap would capture a different app",
5533
+ final: true
5534
+ };
5224
5535
  }
5225
5536
  } catch {
5226
5537
  }
5227
5538
  try {
5228
5539
  const tmpPath = "/data/data/com.termux/files/usr/tmp/cdp-screencap.png";
5229
- const cap = runSync(adb("shell", "screencap", "-p", "/sdcard/cdp-screencap.png"));
5540
+ const cap = runSync(adb("shell", "screencap", "-p", "/sdcard/cdp-screencap.png"), { timeoutMs: 1e4 });
5230
5541
  if (cap.exitCode === 0) {
5231
- const pull = runSync(adb("pull", "/sdcard/cdp-screencap.png", tmpPath));
5542
+ const pull = runSync(adb("pull", "/sdcard/cdp-screencap.png", tmpPath), { timeoutMs: 1e4 });
5232
5543
  if (pull.exitCode === 0 && await fileExists(tmpPath)) {
5233
5544
  const { readFile: rf } = await import("node:fs/promises");
5234
5545
  const buf = await rf(tmpPath);
5235
5546
  log("info", `CDP: ADB screencap captured ${buf.length} bytes`);
5236
- return { data: buf.toString("base64") };
5547
+ return { data: normalizeScreenshot(buf.toString("base64")) };
5237
5548
  }
5238
5549
  }
5239
5550
  } catch {
5240
5551
  }
5241
- return { error: "Screenshot not available (CDP Page.captureScreenshot unsupported on Android, ADB screencap failed)" };
5552
+ return { error: "Screenshot not available (CDP Page.captureScreenshot failed and ADB screencap failed)" };
5553
+ }
5554
+ /** Draw on an exact target; never guess the active page or downgrade to mouse. */
5555
+ async penStroke(params) {
5556
+ const points = validatePenPoints(params.points);
5557
+ const hasTarget = typeof params.targetId === "string" && params.targetId.length > 0;
5558
+ const hasTab = typeof params.tabId === "number" && Number.isSafeInteger(params.tabId) && params.tabId >= 0;
5559
+ if (hasTarget === hasTab) throw new Error("Specify exactly one targetId or tabId");
5560
+ if (!process.env.BRIDGE_ADB_SERIAL) throw new Error("Set BRIDGE_ADB_SERIAL to the intended device before using pen_stroke");
5561
+ if (!this.isAvailable()) throw new Error("CDP unavailable; pen strokes require a connected browser");
5562
+ if (this.penBusy) throw new Error("Another pen stroke is in progress; retry after it finishes");
5563
+ this.penBusy = true;
5564
+ try {
5565
+ await this.refreshTargets();
5566
+ const candidates = this.cachedTargets.filter((t) => t.type === "page" && (hasTarget ? t.targetId === params.targetId : t.url === this.tabUrlCache.get(params.tabId)));
5567
+ if (candidates.length !== 1) throw new Error("Pen target missing or ambiguous; refresh tabs or supply an exact CDP targetId");
5568
+ const targetId = candidates[0].targetId;
5569
+ let sessionId = this.sessionMap.get(targetId);
5570
+ if (!sessionId) {
5571
+ const attached = await this.sendCommand("Target.attachToTarget", { targetId, flatten: true });
5572
+ sessionId = attached.sessionId;
5573
+ this.sessionMap.set(targetId, sessionId);
5574
+ }
5575
+ await sendPenPoints(points, (event) => this.sendCommand("Input.dispatchMouseEvent", event, sessionId));
5576
+ return { samples: points.length, targetId };
5577
+ } finally {
5578
+ this.penBusy = false;
5579
+ }
5242
5580
  }
5243
5581
  /** Dispatch a computer tool action via CDP Input domain */
5244
5582
  async dispatchComputerAction(action, params, tabId) {
@@ -5351,6 +5689,165 @@ var init_claude_chrome_bridge = __esm({
5351
5689
  return { error: `CDP input failed: ${err.message}` };
5352
5690
  }
5353
5691
  }
5692
+ /** Attached CDP session for an extension tab (or the active one), or null when it has no target */
5693
+ async sessionForTab(tabId) {
5694
+ const targetId = await this.resolveTarget(tabId);
5695
+ if (!targetId) return null;
5696
+ let sessionId = this.sessionMap.get(targetId);
5697
+ if (!sessionId) {
5698
+ const attach = await this.sendCommand("Target.attachToTarget", { targetId, flatten: true });
5699
+ sessionId = attach.sessionId;
5700
+ this.sessionMap.set(targetId, sessionId);
5701
+ }
5702
+ return sessionId;
5703
+ }
5704
+ /** Runtime.evaluate that gives up after `ms`; null means no answer in time */
5705
+ async evaluateWithin(sessionId, expression, awaitPromise, ms) {
5706
+ const call = this.sendCommand("Runtime.evaluate", { expression, returnByValue: true, awaitPromise }, sessionId).then((r) => r.result?.value ?? "undefined");
5707
+ const timeout = new Promise((resolve3) => setTimeout(() => resolve3(null), ms));
5708
+ return Promise.race([call, timeout]).catch(() => null);
5709
+ }
5710
+ /**
5711
+ * True when Edge has frozen the tab's page (Page Lifecycle "frozen"): it
5712
+ * still answers synchronous CDP evaluation, but its task queues are
5713
+ * suspended, so timers, MessageChannel and every extension content-script
5714
+ * request wait until the tab becomes visible. Observed on hidden tabs
5715
+ * within ~45 s to hours of Edge leaving the foreground, not on every tab;
5716
+ * neither Page.setWebLifecycleState nor the Chromium background-throttling
5717
+ * switches undo it (2026-11-27). False when the page answers, and also when
5718
+ * it does not even answer synchronously (an OS-frozen or dead renderer is a
5719
+ * different problem, handled by thawRenderers).
5720
+ */
5721
+ async pageIsFrozen(tabId) {
5722
+ try {
5723
+ const sessionId = await this.sessionForTab(tabId);
5724
+ if (!sessionId) return false;
5725
+ if (await this.evaluateWithin(sessionId, "1", false, PAGE_PROBE_TIMEOUT_MS) === null) return false;
5726
+ return await this.evaluateWithin(sessionId, MESSAGE_CHANNEL_PROBE, true, PAGE_PROBE_TIMEOUT_MS) === null;
5727
+ } catch {
5728
+ return false;
5729
+ }
5730
+ }
5731
+ /** Counters for /health: how often each background layer was hit */
5732
+ backgroundStats = {
5733
+ renderersExempted: 0,
5734
+ sweepFailures: 0,
5735
+ frozenPagesDetected: 0,
5736
+ wakes: 0,
5737
+ wakesSkipped: 0,
5738
+ lastWakeSkipReason: null
5739
+ };
5740
+ lastWakeAt = 0;
5741
+ wakeInFlight = null;
5742
+ /**
5743
+ * One adb call for everything a wake decision needs: whether the screen is
5744
+ * on, whether the keyguard (lock screen) is showing, whether a phone call is
5745
+ * active, and the focused activity ("pkg/cls", or null for system windows
5746
+ * such as the notification shade).
5747
+ */
5748
+ readDeviceState() {
5749
+ const out = runSync(adb(
5750
+ "shell",
5751
+ "dumpsys power | grep -m1 mWakefulness=; dumpsys window | grep -E -m2 'mCurrentFocus|isKeyguardShowing'; dumpsys telephony.registry | grep -m1 mCallState"
5752
+ ), { timeoutMs: 4e3 }).stdout.toString();
5753
+ const focusLine = out.split("\n").find((l) => l.includes("mCurrentFocus")) ?? "";
5754
+ return {
5755
+ awake: /mWakefulness=Awake/.test(out),
5756
+ keyguard: /isKeyguardShowing=true/.test(out),
5757
+ inCall: /mCallState=[12]\b/.test(out),
5758
+ focus: /\s(\S+\/\S+)\}/.exec(focusLine)?.[1] ?? null
5759
+ };
5760
+ }
5761
+ /** Start the previously focused activity again after Edge was brought forward. */
5762
+ refocus(previous, why) {
5763
+ if (!previous || previous.startsWith("com.microsoft.emmx.canary/")) return;
5764
+ runSync(adb("shell", "am", "start", "-n", previous), { timeoutMs: 5e3 });
5765
+ log("info", `CDP: ${why}; refocused ${previous}`);
5766
+ }
5767
+ /**
5768
+ * Wake a frozen tab: Page.bringToFront makes it visible (Chromium resumes
5769
+ * it), which also brings the Edge app to the foreground, so afterwards the
5770
+ * previously focused activity is started again. Refuses (returns a reason)
5771
+ * when the screen is off, the lock screen is up or a call is active: the
5772
+ * restore could not return there, and taking over the screen mid-call is
5773
+ * worse than a failed tool. Concurrent requests share one wake, and wakes
5774
+ * are at least WAKE_MIN_INTERVAL_MS apart.
5775
+ */
5776
+ async wakeFrozenTab(tabId) {
5777
+ if (this.wakeInFlight) return { ok: await this.wakeInFlight, reason: "shared wake" };
5778
+ if (Date.now() - this.lastWakeAt < WAKE_MIN_INTERVAL_MS) return this.skipWake("another wake ran under 5 s ago");
5779
+ const state = this.readDeviceState();
5780
+ if (!state.awake) return this.skipWake("the screen is off");
5781
+ if (state.keyguard) return this.skipWake("the phone is locked");
5782
+ if (state.inCall) return this.skipWake("a phone call is active");
5783
+ const sessionId = await this.sessionForTab(tabId);
5784
+ if (!sessionId) return this.skipWake("the tab has no CDP target");
5785
+ this.lastWakeAt = Date.now();
5786
+ this.wakeInFlight = (async () => {
5787
+ try {
5788
+ await this.sendCommand("Page.bringToFront", {}, sessionId);
5789
+ for (let i = 0; i < 6; i++) {
5790
+ if (await this.evaluateWithin(sessionId, MESSAGE_CHANNEL_PROBE, true, 500) !== null) return true;
5791
+ }
5792
+ return false;
5793
+ } catch {
5794
+ return false;
5795
+ } finally {
5796
+ this.refocus(state.focus, `woke frozen tab ${tabId ?? "active"}`);
5797
+ }
5798
+ })();
5799
+ try {
5800
+ const ok = await this.wakeInFlight;
5801
+ if (ok) this.backgroundStats.wakes++;
5802
+ return ok ? { ok } : { ok, reason: "the page did not resume after bringToFront" };
5803
+ } finally {
5804
+ this.wakeInFlight = null;
5805
+ }
5806
+ }
5807
+ skipWake(reason) {
5808
+ this.backgroundStats.wakesSkipped++;
5809
+ this.backgroundStats.lastWakeSkipReason = reason;
5810
+ return { ok: false, reason };
5811
+ }
5812
+ /**
5813
+ * Make sure a tab can run page work before a tool touches it: thaw Edge's
5814
+ * renderers (Android freezer), then, if Edge has frozen the page itself,
5815
+ * wake it (unless disabled or unsafe). `ok: false` carries why; callers that
5816
+ * only need synchronous CDP may proceed anyway.
5817
+ */
5818
+ async ensurePageAwake(tabId) {
5819
+ await this.thawRenderers();
5820
+ if (!await this.pageIsFrozen(tabId)) return { ok: true, frozen: false };
5821
+ this.backgroundStats.frozenPagesDetected++;
5822
+ if (!WAKE_FROZEN_TABS) return { ok: false, frozen: true, reason: "waking is disabled (BRIDGE_WAKE_FROZEN_TABS=0)" };
5823
+ const woke = await this.wakeFrozenTab(tabId);
5824
+ return { ok: woke.ok, frozen: true, reason: woke.reason };
5825
+ }
5826
+ /**
5827
+ * A note to append to an input result when the tab is hidden (Edge is not
5828
+ * the foreground app). The input itself is delivered, but the page's timers
5829
+ * run about once a minute and requestAnimationFrame / MessageChannel tasks
5830
+ * stall, so handlers that continue through them (e.g. React's scheduler)
5831
+ * may not have updated the page yet. Returns "" for a visible tab or when
5832
+ * the check does not answer within 1.5 s.
5833
+ */
5834
+ async hiddenTabNote(tabId) {
5835
+ try {
5836
+ const targetId = await this.resolveTarget(tabId);
5837
+ const sessionId = targetId ? this.sessionMap.get(targetId) : void 0;
5838
+ if (!sessionId) return "";
5839
+ const check = this.sendCommand("Runtime.evaluate", {
5840
+ expression: "document.visibilityState",
5841
+ returnByValue: true
5842
+ }, sessionId);
5843
+ const timeout = new Promise((resolve3) => setTimeout(() => resolve3(null), 1500));
5844
+ const r = await Promise.race([check, timeout]);
5845
+ if (r?.result?.value !== "hidden") return "";
5846
+ return " (tab hidden: Edge is not the foreground app, so page timers run about once a minute and animation frames do not run; the page may not have reacted yet, re-read it before relying on the result)";
5847
+ } catch {
5848
+ return "";
5849
+ }
5850
+ }
5354
5851
  /** Parse modifier string like "ctrl+shift" into CDP modifier flags */
5355
5852
  parseModifiers(mods) {
5356
5853
  if (!mods) return {};
@@ -5447,12 +5944,79 @@ var init_claude_chrome_bridge = __esm({
5447
5944
  isAvailable() {
5448
5945
  return this.state === "connected" && this.ws?.readyState === WebSocket.OPEN;
5449
5946
  }
5947
+ /** Renderers already given a sticky unfreeze (it lasts their lifetime),
5948
+ * keyed "pid:starttime" so a reused pid is never mistaken for a handled one */
5949
+ thawedRenderers = /* @__PURE__ */ new Set();
5950
+ lastThawSweep = 0;
5951
+ thawInFlight = null;
5952
+ /**
5953
+ * Exempt Edge's tab renderers from Android's cached-apps freezer.
5954
+ *
5955
+ * When the Edge app is not in the foreground, Chromium drops its renderer
5956
+ * processes to cached priority and Android freezes them at the cgroup level
5957
+ * (cgroup.freeze=1) after ~40-60 s. A frozen renderer answers nothing: every
5958
+ * CDP Runtime/Input command and every extension content-script call for its
5959
+ * tabs waits until the 15 s / 30 s timeouts. `Page.setWebLifecycleState`
5960
+ * cannot reach it, and `Page.bringToFront` only works by foregrounding the
5961
+ * Edge app. `cmd activity unfreeze --sticky` (shell uid, via adb) thaws a
5962
+ * process and keeps it thawed for its lifetime, so each renderer needs it
5963
+ * once; later sweeps only pick up renderers spawned since.
5964
+ *
5965
+ * Callers do not need to await this: a command queued to a frozen renderer
5966
+ * runs as soon as the sweep thaws it (a healthy sweep takes ~70-200 ms).
5967
+ * Hidden-tab throttling still applies to a thawed tab: timers are batched to
5968
+ * about once a minute, and requestAnimationFrame / MessageChannel tasks did
5969
+ * not run within 8 s in measurements.
5970
+ */
5971
+ thawRenderers() {
5972
+ if (this.thawInFlight) return this.thawInFlight;
5973
+ if (Date.now() - this.lastThawSweep < RENDERER_THAW_INTERVAL_MS) return Promise.resolve();
5974
+ this.lastThawSweep = Date.now();
5975
+ const skip = [...this.thawedRenderers].join(" ");
5976
+ const script = `for p in $(ps -A -o PID,NAME | awk '$2 ~ /^${EDGE_RENDERER_PREFIX.replace(/\./g, "\\.")}/ {print $1}'); do k="$p:$(cut -d' ' -f22 /proc/$p/stat 2>/dev/null)"; echo "live $k"; case " ${skip} " in *" $k "*) continue;; esac; cmd activity unfreeze --sticky "$p" >/dev/null 2>&1 && echo "thawed $k"; done; echo "sweep-done"`;
5977
+ this.thawInFlight = (async () => {
5978
+ try {
5979
+ const proc = spawnProcess(adb("shell", script));
5980
+ const timer = setTimeout(() => proc.kill(9), RENDERER_THAW_TIMEOUT_MS);
5981
+ const out = proc.stdout ? await new Response(proc.stdout).text() : "";
5982
+ const exitCode = await proc.exited;
5983
+ clearTimeout(timer);
5984
+ if (exitCode !== 0 || !out.includes("sweep-done")) {
5985
+ throw new Error(`adb shell exited ${exitCode}${out.includes("sweep-done") ? "" : ", sweep incomplete"}`);
5986
+ }
5987
+ const live = /* @__PURE__ */ new Set();
5988
+ const newlyThawed = [];
5989
+ for (const line of out.split("\n")) {
5990
+ const [kind, key] = line.trim().split(" ");
5991
+ if (!key || !/^\d+:\d+$/.test(key)) continue;
5992
+ if (kind === "live") live.add(key);
5993
+ else if (kind === "thawed") newlyThawed.push(key);
5994
+ }
5995
+ for (const key of this.thawedRenderers) if (!live.has(key)) this.thawedRenderers.delete(key);
5996
+ for (const key of newlyThawed) this.thawedRenderers.add(key);
5997
+ this.backgroundStats.renderersExempted += newlyThawed.length;
5998
+ if (newlyThawed.length) {
5999
+ log("info", `CDP: exempted Edge renderer(s) ${newlyThawed.map((k) => k.split(":")[0]).join(", ")} from the Android freezer`);
6000
+ }
6001
+ } catch (err) {
6002
+ this.lastThawSweep = 0;
6003
+ this.backgroundStats.sweepFailures++;
6004
+ log("warn", `CDP: renderer freezer sweep failed \u2014 ${err.message}; frozen tabs will time out until a sweep succeeds`);
6005
+ } finally {
6006
+ this.thawInFlight = null;
6007
+ }
6008
+ })();
6009
+ return this.thawInFlight;
6010
+ }
5450
6011
  /** Get status info for /health endpoint */
5451
6012
  getStatus() {
5452
6013
  return {
6014
+ background: { ...this.backgroundStats, wakeFrozenTabs: WAKE_FROZEN_TABS, renderersTracked: this.thawedRenderers.size },
5453
6015
  state: this.state,
5454
6016
  edgePid: this.edgePid,
5455
6017
  port: CDP_PORT,
6018
+ deviceSerial: process.env.BRIDGE_ADB_SERIAL ?? null,
6019
+ penBusy: this.penBusy,
5456
6020
  targets: this.cachedTargets.filter((t) => t.type === "page").length
5457
6021
  };
5458
6022
  }
@@ -5522,9 +6086,12 @@ var init_claude_chrome_bridge = __esm({
5522
6086
  /** Check if an ADB forward for our CDP port already exists */
5523
6087
  checkExistingForward() {
5524
6088
  try {
5525
- const result = runSync(adb("forward", "--list"));
6089
+ const result = runSync(adb("forward", "--list"), { timeoutMs: 3e3 });
5526
6090
  const lines = result.stdout.toString().trim().split("\n");
5527
- return lines.some((l) => l.includes(`tcp:${CDP_PORT}`));
6091
+ return lines.some((line) => {
6092
+ const [serial, local] = line.trim().split(/\s+/);
6093
+ return serial === getAdbSerial() && local === `tcp:${CDP_PORT}`;
6094
+ });
5528
6095
  } catch {
5529
6096
  return false;
5530
6097
  }
@@ -5535,14 +6102,14 @@ var init_claude_chrome_bridge = __esm({
5535
6102
  * Returns NaN if Edge is not running or both methods fail.
5536
6103
  */
5537
6104
  getEdgePid() {
5538
- try {
6105
+ if (!process.env.BRIDGE_ADB_SERIAL) try {
5539
6106
  const local = runSync(["pidof", "com.microsoft.emmx.canary"]);
5540
6107
  const pid = parseInt(local.stdout.toString().trim().split(/\s+/)[0], 10);
5541
6108
  if (!isNaN(pid)) return pid;
5542
6109
  } catch {
5543
6110
  }
5544
6111
  try {
5545
- const remote = runSync(adb("shell", "pidof", "com.microsoft.emmx.canary"));
6112
+ const remote = runSync(adb("shell", "pidof", "com.microsoft.emmx.canary"), { timeoutMs: 3e3 });
5546
6113
  const pid = parseInt(remote.stdout.toString().trim().split(/\s+/)[0], 10);
5547
6114
  if (!isNaN(pid)) return pid;
5548
6115
  } catch {
@@ -5634,11 +6201,14 @@ var init_claude_chrome_bridge = __esm({
5634
6201
  nativeHostKillTimer = null;
5635
6202
  stdoutDecoder = new NativeMessageDecoder();
5636
6203
  wsClients = /* @__PURE__ */ new Set();
6204
+ TAB_URL_REFRESH_TIMEOUT_MS = 5e3;
6205
+ cdpManager.setTabUrlRefresher(refreshTabUrlsFromExtension);
5637
6206
  server = createBridgeServer({
5638
6207
  hostname: WS_HOST,
5639
6208
  port: WS_PORT,
5640
6209
  async fetch(req, upgrade) {
5641
6210
  const url = new URL(req.url);
6211
+ if (url.pathname === "/mcp") return handleMcpHttp(req);
5642
6212
  if (url.pathname === "/health") {
5643
6213
  return new Response(
5644
6214
  JSON.stringify({
@@ -5654,6 +6224,29 @@ var init_claude_chrome_bridge = __esm({
5654
6224
  { headers: { "Content-Type": "application/json" } }
5655
6225
  );
5656
6226
  }
6227
+ if (url.pathname === "/pen-stroke" && req.method === "POST") {
6228
+ const origin = req.headers.get("origin");
6229
+ if (origin && origin !== url.origin) return new Response("Forbidden origin", { status: 403 });
6230
+ if (BRIDGE_TOKEN && req.headers.get("authorization") !== `Bearer ${BRIDGE_TOKEN}`) {
6231
+ return new Response("Unauthorized", { status: 401 });
6232
+ }
6233
+ if (!req.headers.get("content-type")?.startsWith("application/json")) {
6234
+ return new Response("Expected application/json", { status: 415 });
6235
+ }
6236
+ try {
6237
+ const raw = await req.text();
6238
+ if (Buffer.byteLength(raw) > 262144) return new Response("Stroke too large", { status: 413 });
6239
+ const params = JSON.parse(raw);
6240
+ if (!params || typeof params !== "object" || Array.isArray(params)) throw new Error("Expected a stroke object");
6241
+ lastToolName = "pen_stroke";
6242
+ lastToolTime = (/* @__PURE__ */ new Date()).toISOString();
6243
+ await cdpManager.thawRenderers();
6244
+ const result = await cdpManager.penStroke(params);
6245
+ return Response.json({ result });
6246
+ } catch (error) {
6247
+ return Response.json({ error: error.message }, { status: 400 });
6248
+ }
6249
+ }
5657
6250
  if (url.pathname === "/shutdown" && req.method === "POST") {
5658
6251
  log("info", "Shutdown requested via HTTP");
5659
6252
  setTimeout(() => shutdown(), 200);
@@ -5800,7 +6393,8 @@ var init_claude_chrome_bridge = __esm({
5800
6393
  }
5801
6394
  try {
5802
6395
  const body = await req.json();
5803
- const requestId = `req_${++toolRequestCounter}_${Date.now()}`;
6396
+ const toolStart = Date.now();
6397
+ const requestId = `req_${++toolRequestCounter}_${toolStart}`;
5804
6398
  const tabId = body.params?.tabId || 0;
5805
6399
  const toolRequest = JSON.stringify({
5806
6400
  type: "tool_request",
@@ -5810,6 +6404,47 @@ var init_claude_chrome_bridge = __esm({
5810
6404
  });
5811
6405
  lastToolName = body.method;
5812
6406
  lastToolTime = (/* @__PURE__ */ new Date()).toISOString();
6407
+ void cdpManager.thawRenderers();
6408
+ if (body.method === "computer" && (body.params?.action === "screenshot" || body.params?.action === "zoom")) {
6409
+ const action = body.params.action;
6410
+ const shotTabId = body.params.tabId;
6411
+ log("info", `HTTP /tool: intercepting computer ${action} via CDP/ADB capture (tab ${shotTabId ?? "active"})`);
6412
+ const shot = await cdpManager.captureScreenshot(shotTabId);
6413
+ if (shot.data) {
6414
+ let imgData = shot.data;
6415
+ if (action === "zoom") {
6416
+ try {
6417
+ const zoomFactor = body.params.zoom_factor ?? 2;
6418
+ const coord = body.params.coordinate ?? null;
6419
+ const { width, height, rgba } = decodePNG(shot.data);
6420
+ const cx = coord?.[0] ?? Math.round(width / 2);
6421
+ const cy = coord?.[1] ?? Math.round(height / 2);
6422
+ const cropW = Math.round(width / zoomFactor);
6423
+ const cropH = Math.round(height / zoomFactor);
6424
+ const cropX = Math.max(0, Math.min(Math.round(cx - cropW / 2), width - cropW));
6425
+ const cropY = Math.max(0, Math.min(Math.round(cy - cropH / 2), height - cropH));
6426
+ const croppedRGBA = cropPixels(rgba, width, height, cropX, cropY, cropW, cropH);
6427
+ imgData = encodePNG(croppedRGBA, cropW, cropH).toString("base64");
6428
+ } catch (cropErr) {
6429
+ log("warn", `HTTP /tool zoom crop failed, returning full screenshot: ${cropErr.message}`);
6430
+ }
6431
+ }
6432
+ return new Response(
6433
+ JSON.stringify({
6434
+ type: "tool_response",
6435
+ result: { content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: imgData } }] }
6436
+ }),
6437
+ { headers: { "Content-Type": "application/json" } }
6438
+ );
6439
+ }
6440
+ if (shot.final) {
6441
+ return new Response(
6442
+ JSON.stringify({ type: "tool_response", error: shot.error }),
6443
+ { headers: { "Content-Type": "application/json" } }
6444
+ );
6445
+ }
6446
+ log("warn", `HTTP /tool: ADB screencap failed (${shot.error ?? "unknown"}); forwarding ${action} to extension`);
6447
+ }
5813
6448
  const MAX_PENDING_TOOLS = 50;
5814
6449
  const totalQueued = pendingToolMap.size + Array.from(busyTabs.values()).reduce((acc, arr) => acc + arr.length, 0);
5815
6450
  if (totalQueued >= MAX_PENDING_TOOLS) {
@@ -5854,6 +6489,12 @@ var init_claude_chrome_bridge = __esm({
5854
6489
  }
5855
6490
  }
5856
6491
  });
6492
+ const toolError = result;
6493
+ const errText = toolError?.error ?? toolError?.result?.error;
6494
+ log(
6495
+ errText ? "warn" : "info",
6496
+ `HTTP /tool: ${body.method} [${requestId}] ${errText ? `failed: ${String(errText).slice(0, 160)}` : "ok"} in ${Date.now() - toolStart} ms`
6497
+ );
5857
6498
  return new Response(
5858
6499
  JSON.stringify(result),
5859
6500
  { headers: { "Content-Type": "application/json" } }
@@ -5991,11 +6632,11 @@ var init_claude_chrome_bridge = __esm({
5991
6632
  }
5992
6633
  }, 3e4);
5993
6634
  }
5994
- },
5995
- maxPayloadLength: MAX_MESSAGE_SIZE,
5996
- idleTimeout: 120
5997
- // seconds
5998
- }
6635
+ }
6636
+ },
6637
+ maxPayloadLength: MAX_MESSAGE_SIZE,
6638
+ idleTimeout: 120
6639
+ // seconds
5999
6640
  });
6000
6641
  setInterval(() => {
6001
6642
  for (const ws of wsClients) {
@@ -6133,25 +6774,13 @@ var init_claude_chrome_bridge = __esm({
6133
6774
  });
6134
6775
 
6135
6776
  // 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;
6777
+ var cli_exports = {};
6778
+ __export(cli_exports, {
6779
+ formatToolResult: () => formatToolResult,
6780
+ handleMcpHttp: () => handleMcpHttp,
6781
+ handleMcpRequest: () => handleMcpRequest
6782
+ });
6783
+ module.exports = __toCommonJS(cli_exports);
6155
6784
  async function fetchWithTimeout(url, opts = {}) {
6156
6785
  const { timeout = 3e3, ...fetchOpts } = opts;
6157
6786
  const controller = new AbortController();
@@ -6180,14 +6809,6 @@ async function bridgeClientCount() {
6180
6809
  return null;
6181
6810
  }
6182
6811
  }
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
6812
  function selfDir() {
6192
6813
  return typeof __dirname !== "undefined" ? __dirname : (0, import_path2.dirname)(new URL(import_meta_url).pathname);
6193
6814
  }
@@ -6225,9 +6846,9 @@ function resolveAdbSerial(sp) {
6225
6846
  if (online.length > 1) return env || online[0].serial;
6226
6847
  return "";
6227
6848
  }
6228
- function runAdb(sp, serial, args2) {
6849
+ function runAdb(sp, serial, args) {
6229
6850
  const base = serial ? ["-s", serial] : [];
6230
- return sp("adb", [...base, ...args2], { stdio: "pipe", encoding: "utf-8" });
6851
+ return sp("adb", [...base, ...args], { stdio: "pipe", encoding: "utf-8" });
6231
6852
  }
6232
6853
  function detectEdgePkg(sp, serial) {
6233
6854
  for (const pkg of EDGE_PACKAGES) {
@@ -6500,7 +7121,6 @@ Installing CFC extension v${extVersion} via --load-extension...`);
6500
7121
  console.log(" Extension will load automatically when Edge starts.");
6501
7122
  return true;
6502
7123
  }
6503
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
6504
7124
  function ask(question) {
6505
7125
  return new Promise((res) => {
6506
7126
  const rl = require("readline").createInterface({ input: process.stdin, output: process.stdout });
@@ -6510,8 +7130,6 @@ function ask(question) {
6510
7130
  });
6511
7131
  });
6512
7132
  }
6513
- var isYes = (a) => a === "" || a === "y" || a === "yes";
6514
- var EDGE_CANARY = "com.microsoft.emmx.canary";
6515
7133
  async function ensureEdgeInstalled(sp, serial, interactive) {
6516
7134
  let pkg = detectEdgePkg(sp, serial);
6517
7135
  if (pkg) return pkg;
@@ -6665,233 +7283,6 @@ async function cmdStart() {
6665
7283
  process.exit(1);
6666
7284
  }
6667
7285
  }
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
7286
  function mcpResult(id, result) {
6896
7287
  return { jsonrpc: "2.0", id, result };
6897
7288
  }
@@ -6903,10 +7294,10 @@ function mcpSend(response) {
6903
7294
  }
6904
7295
  async function callBridgeTool(method, params) {
6905
7296
  try {
6906
- const resp = await fetch(TOOL_URL, {
7297
+ const resp = await fetch(method === "pen_stroke" ? `${BRIDGE_URL}/pen-stroke` : TOOL_URL, {
6907
7298
  method: "POST",
6908
- headers: { "Content-Type": "application/json" },
6909
- body: JSON.stringify({ method, params }),
7299
+ headers: { "Content-Type": "application/json", ...process.env.BRIDGE_TOKEN ? { Authorization: `Bearer ${process.env.BRIDGE_TOKEN}` } : {} },
7300
+ body: JSON.stringify(method === "pen_stroke" ? params : { method, params }),
6910
7301
  signal: AbortSignal.timeout(TOOL_TIMEOUT_MS)
6911
7302
  });
6912
7303
  if (!resp.ok) {
@@ -6928,48 +7319,117 @@ async function callBridgeTool(method, params) {
6928
7319
  }
6929
7320
  function formatToolResult(result) {
6930
7321
  if (!result || typeof result !== "object") {
6931
- return [{ type: "text", text: JSON.stringify(result) }];
7322
+ return [{ type: "text", text: JSON.stringify(result) ?? "undefined" }];
6932
7323
  }
6933
7324
  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 } }];
7325
+ if (Array.isArray(r.content)) {
7326
+ return r.content.flatMap((item) => {
7327
+ if (!item || typeof item !== "object") return formatToolResult(item);
7328
+ const block = item;
7329
+ const source = block.source;
7330
+ if (block.type === "image" && source?.type === "base64") {
7331
+ return [{ type: "image", mimeType: source.media_type, data: source.data }];
7332
+ }
7333
+ return [block];
7334
+ });
7335
+ }
7336
+ if (typeof r.data === "string" && typeof r.media_type === "string") {
7337
+ return [{ type: "image", mimeType: r.media_type, data: r.data }];
6937
7338
  }
6938
7339
  if (r.result !== void 0) return formatToolResult(r.result);
6939
7340
  return [{ type: "text", text: JSON.stringify(result, null, 2) }];
6940
7341
  }
6941
- async function handleMcpRequest(req) {
7342
+ function toolResultFailed(result) {
7343
+ if (!result || typeof result !== "object") return false;
7344
+ const r = result;
7345
+ return Boolean(r.error || r.isError || r.result !== void 0 && toolResultFailed(r.result));
7346
+ }
7347
+ async function handleMcpRequest(req, send = mcpSend) {
6942
7348
  if (req.id === void 0 || req.id === null) return;
6943
7349
  switch (req.method) {
6944
7350
  case "initialize":
6945
- mcpSend(mcpResult(req.id, {
6946
- protocolVersion: "2024-11-05",
7351
+ send(mcpResult(req.id, {
7352
+ protocolVersion: req.params?.protocolVersion === "2024-11-05" ? "2024-11-05" : "2025-03-26",
6947
7353
  capabilities: { tools: {} },
6948
7354
  serverInfo: { name: "Claude in Chrome (Bridge)", version: PKG_VERSION }
6949
7355
  }));
6950
7356
  break;
7357
+ case "ping":
7358
+ send(mcpResult(req.id, {}));
7359
+ break;
6951
7360
  case "tools/list":
6952
- mcpSend(mcpResult(req.id, { tools: MCP_TOOLS }));
7361
+ send(mcpResult(req.id, { tools: MCP_TOOLS }));
6953
7362
  break;
6954
7363
  case "tools/call": {
6955
7364
  const toolName = req.params?.name ?? "";
6956
7365
  const toolArgs = req.params?.arguments ?? {};
6957
7366
  const tool = MCP_TOOLS.find((t) => t.name === toolName);
6958
7367
  if (!tool) {
6959
- mcpSend(mcpResult(req.id, { content: [{ type: "text", text: `Unknown tool: ${toolName}` }], isError: true }));
7368
+ send(mcpResult(req.id, { content: [{ type: "text", text: `Unknown tool: ${toolName}` }], isError: true }));
6960
7369
  break;
6961
7370
  }
6962
7371
  const { result, error } = await callBridgeTool(toolName, toolArgs);
6963
7372
  if (error) {
6964
- mcpSend(mcpResult(req.id, { content: [{ type: "text", text: error }], isError: true }));
7373
+ send(mcpResult(req.id, { content: [{ type: "text", text: error }], isError: true }));
6965
7374
  } else {
6966
- mcpSend(mcpResult(req.id, { content: formatToolResult(result) }));
7375
+ send(mcpResult(req.id, { content: formatToolResult(result), isError: toolResultFailed(result) }));
6967
7376
  }
6968
7377
  break;
6969
7378
  }
6970
7379
  default:
6971
- mcpSend(mcpError(req.id, -32601, `Method not found: ${req.method}`));
7380
+ send(mcpError(req.id, -32601, `Method not found: ${req.method}`));
7381
+ }
7382
+ }
7383
+ async function handleMcpHttp(req) {
7384
+ const url = new URL(req.url);
7385
+ const origin = req.headers.get("origin");
7386
+ const allowedHosts = /* @__PURE__ */ new Set([url.host, `localhost:${url.port}`]);
7387
+ if (!allowedHosts.has(req.headers.get("host") ?? url.host) || origin !== null && origin !== url.origin) {
7388
+ return new Response("Forbidden origin", { status: 403 });
7389
+ }
7390
+ const token = process.env.BRIDGE_TOKEN;
7391
+ if (token && req.headers.get("authorization") !== `Bearer ${token}`) {
7392
+ return new Response("Unauthorized", { status: 401 });
7393
+ }
7394
+ if (req.method !== "POST") {
7395
+ return new Response(null, { status: 405, headers: { Allow: "POST" } });
7396
+ }
7397
+ if (!req.headers.get("content-type")?.toLowerCase().startsWith("application/json")) {
7398
+ return new Response("Expected application/json", { status: 415 });
7399
+ }
7400
+ const accept = req.headers.get("accept") ?? "";
7401
+ if (!accept.includes("application/json") || !accept.includes("text/event-stream")) {
7402
+ return new Response("Expected JSON and SSE accept types", { status: 406 });
7403
+ }
7404
+ const json = (value, status = 200) => new Response(JSON.stringify(value), {
7405
+ status,
7406
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
7407
+ });
7408
+ let body;
7409
+ try {
7410
+ const raw = await req.text();
7411
+ if (Buffer.byteLength(raw) > 1048576) return new Response("Request too large", { status: 413 });
7412
+ body = JSON.parse(raw);
7413
+ } catch {
7414
+ return json(mcpError(null, -32700, "Parse error"), 400);
7415
+ }
7416
+ const messages = Array.isArray(body) ? body : [body];
7417
+ if (!messages.length) return json(mcpError(null, -32600, "Invalid Request"), 400);
7418
+ const responses = [];
7419
+ for (const value of messages) {
7420
+ if (!value || typeof value !== "object") return json(mcpError(null, -32600, "Invalid Request"), 400);
7421
+ const message = value;
7422
+ 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))) {
7423
+ return json(mcpError(null, -32600, "Invalid Request"), 400);
7424
+ }
7425
+ try {
7426
+ await handleMcpRequest(message, (response) => responses.push(response));
7427
+ } catch (error) {
7428
+ if (message.id !== void 0) responses.push(mcpError(message.id, -32603, error.message));
7429
+ }
6972
7430
  }
7431
+ if (!responses.length) return new Response(null, { status: 202 });
7432
+ return json(Array.isArray(body) ? responses : responses[0]);
6973
7433
  }
6974
7434
  async function cmdMcp() {
6975
7435
  const log2 = (msg) => process.stderr.write(`[cfc-mcp] ${msg}
@@ -7012,35 +7472,337 @@ async function cmdMcp() {
7012
7472
  log2("stdin closed");
7013
7473
  process.exit(0);
7014
7474
  }
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
- }
7475
+ 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;
7476
+ var init_cli = __esm({
7477
+ "src/cli.ts"() {
7478
+ init_import_meta_shim();
7479
+ import_path2 = require("path");
7480
+ import_fs = require("fs");
7481
+ PKG_VERSION = (() => {
7482
+ try {
7483
+ const dir = typeof __dirname !== "undefined" ? __dirname : (0, import_path2.dirname)(new URL(import_meta_url).pathname);
7484
+ const pkgPath = (0, import_path2.resolve)(dir, "../package.json");
7485
+ return JSON.parse((0, import_fs.readFileSync)(pkgPath, "utf-8")).version ?? "0.0.0";
7486
+ } catch {
7487
+ return "0.0.0";
7488
+ }
7489
+ })();
7490
+ WS_PORT2 = parseInt(process.env.BRIDGE_PORT ?? "18963", 10);
7491
+ WS_HOST2 = "127.0.0.1";
7492
+ BRIDGE_URL = process.env.BRIDGE_URL ?? `http://${WS_HOST2}:${WS_PORT2}`;
7493
+ HEALTH_URL = `${BRIDGE_URL}/health`;
7494
+ SHUTDOWN_URL = `${BRIDGE_URL}/shutdown`;
7495
+ TOOL_URL = `${BRIDGE_URL}/tool`;
7496
+ TOOL_TIMEOUT_MS = 35e3;
7497
+ EDGE_PACKAGES = [
7498
+ "com.microsoft.emmx.canary",
7499
+ "com.microsoft.emmx.dev",
7500
+ "com.microsoft.emmx.beta",
7501
+ "com.microsoft.emmx"
7502
+ ];
7503
+ EXT_DEST = "/data/local/tmp/cfc-ext";
7504
+ FLAGS_FILE = "/data/local/tmp/chrome-command-line";
7505
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms));
7506
+ isYes = (a) => a === "" || a === "y" || a === "yes";
7507
+ EDGE_CANARY = "com.microsoft.emmx.canary";
7508
+ MCP_TOOLS = [
7509
+ {
7510
+ name: "tabs_context_mcp",
7511
+ 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.",
7512
+ inputSchema: {
7513
+ type: "object",
7514
+ properties: { createIfEmpty: { type: "boolean", description: "Creates a new MCP tab group if none exists." } },
7515
+ required: []
7516
+ }
7517
+ },
7518
+ {
7519
+ name: "tabs_create_mcp",
7520
+ description: "Creates a new empty tab in the MCP tab group.",
7521
+ inputSchema: { type: "object", properties: {}, required: [] }
7522
+ },
7523
+ {
7524
+ name: "navigate",
7525
+ description: "Navigate to a URL, or go forward/back in browser history.",
7526
+ inputSchema: {
7527
+ type: "object",
7528
+ properties: {
7529
+ url: { type: "string", description: 'URL to navigate to. Use "forward" or "back" for history.' },
7530
+ tabId: { type: "number", description: "Tab ID to navigate." }
7531
+ },
7532
+ required: ["url", "tabId"]
7533
+ }
7534
+ },
7535
+ {
7536
+ name: "computer",
7537
+ 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.",
7538
+ inputSchema: {
7539
+ type: "object",
7540
+ properties: {
7541
+ action: {
7542
+ type: "string",
7543
+ enum: ["left_click", "right_click", "type", "screenshot", "wait", "scroll", "key", "left_click_drag", "double_click", "triple_click", "zoom", "scroll_to", "hover"],
7544
+ description: "The action to perform."
7545
+ },
7546
+ coordinate: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2, description: "(x, y) pixel coordinates." },
7547
+ text: { type: "string", description: "Text to type or key(s) to press." },
7548
+ duration: { type: "number", minimum: 0, maximum: 30, description: "Seconds to wait." },
7549
+ scroll_direction: { type: "string", enum: ["up", "down", "left", "right"], description: "Scroll direction." },
7550
+ scroll_amount: { type: "number", minimum: 1, maximum: 10, description: "Scroll ticks (default: 3)." },
7551
+ start_coordinate: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2, description: "Start coords for drag." },
7552
+ region: { type: "array", items: { type: "number" }, minItems: 4, maxItems: 4, description: "(x0,y0,x1,y1) for zoom." },
7553
+ repeat: { type: "number", minimum: 1, maximum: 100, description: "Key repeat count." },
7554
+ ref: { type: "string", description: "Element ref ID for scroll_to." },
7555
+ modifiers: { type: "string", description: 'Modifier keys: "ctrl", "shift", "alt", "cmd".' },
7556
+ tabId: { type: "number", description: "Tab ID." }
7557
+ },
7558
+ required: ["action", "tabId"]
7559
+ }
7560
+ },
7561
+ {
7562
+ name: "pen_stroke",
7563
+ 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.",
7564
+ inputSchema: {
7565
+ type: "object",
7566
+ properties: {
7567
+ tabId: { type: "integer", minimum: 0, description: "Extension tab ID, resolved only when its URL uniquely matches a page." },
7568
+ targetId: { type: "string", minLength: 1, description: "Exact CDP page target ID (alternative to tabId)." },
7569
+ points: {
7570
+ type: "array",
7571
+ minItems: 1,
7572
+ maxItems: 512,
7573
+ items: {
7574
+ type: "object",
7575
+ properties: {
7576
+ x: { type: "number", minimum: 0, maximum: 1e5 },
7577
+ y: { type: "number", minimum: 0, maximum: 1e5 },
7578
+ pressure: { type: "number", minimum: 0, maximum: 1 },
7579
+ tiltX: { type: "number", minimum: -90, maximum: 90, default: 0 },
7580
+ tiltY: { type: "number", minimum: -90, maximum: 90, default: 0 },
7581
+ twist: { type: "number", minimum: 0, maximum: 359, default: 0 },
7582
+ timeMs: { type: "number", minimum: 0, maximum: 2e4, description: "Nondecreasing milliseconds from stroke start; defaults to sample index \xD7 8." }
7583
+ },
7584
+ required: ["x", "y", "pressure"]
7585
+ }
7586
+ }
7587
+ },
7588
+ required: ["points"],
7589
+ oneOf: [{ required: ["tabId"], not: { required: ["targetId"] } }, { required: ["targetId"], not: { required: ["tabId"] } }]
7590
+ }
7591
+ },
7592
+ {
7593
+ name: "javascript_tool",
7594
+ description: "Execute JavaScript in the page context. Returns the last expression result.",
7595
+ inputSchema: {
7596
+ type: "object",
7597
+ properties: {
7598
+ action: { type: "string", description: "Must be 'javascript_exec'" },
7599
+ text: { type: "string", description: "JavaScript code. Don't use 'return'." },
7600
+ tabId: { type: "number", description: "Tab ID." }
7601
+ },
7602
+ required: ["action", "text", "tabId"]
7603
+ }
7604
+ },
7605
+ {
7606
+ name: "read_page",
7607
+ description: "Get accessibility tree of page elements. Filter for interactive elements or get all.",
7608
+ inputSchema: {
7609
+ type: "object",
7610
+ properties: {
7611
+ filter: { type: "string", enum: ["interactive", "all"], description: "Element filter." },
7612
+ tabId: { type: "number", description: "Tab ID." },
7613
+ depth: { type: "number", description: "Max tree depth (default: 15)." },
7614
+ ref_id: { type: "string", description: "Parent element ref to focus on." },
7615
+ max_chars: { type: "number", description: "Max output chars (default: 50000)." }
7616
+ },
7617
+ required: ["tabId"]
7618
+ }
7619
+ },
7620
+ {
7621
+ name: "find",
7622
+ description: 'Find elements by natural language (e.g., "search bar", "login button").',
7623
+ inputSchema: {
7624
+ type: "object",
7625
+ properties: {
7626
+ query: { type: "string", description: "What to find." },
7627
+ tabId: { type: "number", description: "Tab ID." }
7628
+ },
7629
+ required: ["query", "tabId"]
7630
+ }
7631
+ },
7632
+ {
7633
+ name: "form_input",
7634
+ description: "Set form element values using ref ID from read_page.",
7635
+ inputSchema: {
7636
+ type: "object",
7637
+ properties: {
7638
+ ref: { type: "string", description: "Element ref ID." },
7639
+ value: { type: ["string", "boolean", "number"], description: "Value to set." },
7640
+ tabId: { type: "number", description: "Tab ID." }
7641
+ },
7642
+ required: ["ref", "value", "tabId"]
7643
+ }
7644
+ },
7645
+ {
7646
+ name: "get_page_text",
7647
+ description: "Extract raw text content from the page.",
7648
+ inputSchema: {
7649
+ type: "object",
7650
+ properties: { tabId: { type: "number", description: "Tab ID." } },
7651
+ required: ["tabId"]
7652
+ }
7653
+ },
7654
+ {
7655
+ name: "read_console_messages",
7656
+ description: "Read browser console messages. Always provide a pattern to filter.",
7657
+ inputSchema: {
7658
+ type: "object",
7659
+ properties: {
7660
+ tabId: { type: "number", description: "Tab ID." },
7661
+ onlyErrors: { type: "boolean", description: "Errors only." },
7662
+ clear: { type: "boolean", description: "Clear after reading." },
7663
+ pattern: { type: "string", description: "Regex filter pattern." },
7664
+ limit: { type: "number", description: "Max messages (default: 100)." }
7665
+ },
7666
+ required: ["tabId"]
7667
+ }
7668
+ },
7669
+ {
7670
+ name: "read_network_requests",
7671
+ description: "Read HTTP network requests from a tab.",
7672
+ inputSchema: {
7673
+ type: "object",
7674
+ properties: {
7675
+ tabId: { type: "number", description: "Tab ID." },
7676
+ urlPattern: { type: "string", description: "URL substring filter." },
7677
+ clear: { type: "boolean", description: "Clear after reading." },
7678
+ limit: { type: "number", description: "Max requests (default: 100)." }
7679
+ },
7680
+ required: ["tabId"]
7681
+ }
7682
+ },
7683
+ {
7684
+ name: "resize_window",
7685
+ description: "Resize browser window.",
7686
+ inputSchema: {
7687
+ type: "object",
7688
+ properties: {
7689
+ width: { type: "number", description: "Width in pixels." },
7690
+ height: { type: "number", description: "Height in pixels." },
7691
+ tabId: { type: "number", description: "Tab ID." }
7692
+ },
7693
+ required: ["width", "height", "tabId"]
7694
+ }
7695
+ },
7696
+ {
7697
+ name: "gif_creator",
7698
+ description: "Record and export browser session GIFs.",
7699
+ inputSchema: {
7700
+ type: "object",
7701
+ properties: {
7702
+ action: { type: "string", enum: ["start_recording", "stop_recording", "export", "clear"], description: "Action." },
7703
+ tabId: { type: "number", description: "Tab ID." },
7704
+ download: { type: "boolean", description: "Download GIF on export." },
7705
+ filename: { type: "string", description: "GIF filename." },
7706
+ options: { type: "object", description: "GIF options." }
7707
+ },
7708
+ required: ["action", "tabId"]
7709
+ }
7710
+ },
7711
+ {
7712
+ name: "upload_image",
7713
+ description: "Upload a screenshot to a file input or drag & drop target.",
7714
+ inputSchema: {
7715
+ type: "object",
7716
+ properties: {
7717
+ imageId: { type: "string", description: "Screenshot ID." },
7718
+ ref: { type: "string", description: "Element ref ID." },
7719
+ coordinate: { type: "array", items: { type: "number" }, description: "Drop coords [x,y]." },
7720
+ tabId: { type: "number", description: "Tab ID." },
7721
+ filename: { type: "string", description: "Filename." }
7722
+ },
7723
+ required: ["imageId", "tabId"]
7724
+ }
7725
+ },
7726
+ {
7727
+ name: "update_plan",
7728
+ description: "Present a plan to the user for approval.",
7729
+ inputSchema: {
7730
+ type: "object",
7731
+ properties: {
7732
+ domains: { type: "array", items: { type: "string" }, description: "Domains to visit." },
7733
+ approach: { type: "array", items: { type: "string" }, description: "Steps to take." }
7734
+ },
7735
+ required: ["domains", "approach"]
7736
+ }
7737
+ },
7738
+ {
7739
+ name: "shortcuts_list",
7740
+ description: "List available shortcuts and workflows.",
7741
+ inputSchema: {
7742
+ type: "object",
7743
+ properties: { tabId: { type: "number", description: "Tab ID." } },
7744
+ required: ["tabId"]
7745
+ }
7746
+ },
7747
+ {
7748
+ name: "shortcuts_execute",
7749
+ description: "Execute a shortcut or workflow.",
7750
+ inputSchema: {
7751
+ type: "object",
7752
+ properties: {
7753
+ tabId: { type: "number", description: "Tab ID." },
7754
+ shortcutId: { type: "string", description: "Shortcut ID." },
7755
+ command: { type: "string", description: "Command name." }
7756
+ },
7757
+ required: ["tabId"]
7758
+ }
7759
+ },
7760
+ {
7761
+ name: "switch_browser",
7762
+ description: "Switch which Chrome browser is used for automation.",
7763
+ inputSchema: { type: "object", properties: {}, required: [] }
7764
+ }
7765
+ ];
7766
+ if (typeof require !== "undefined" && typeof module !== "undefined" ? require.main === module : false) {
7767
+ const args = process.argv.slice(2);
7768
+ const command = args[0] ?? "";
7769
+ switch (command) {
7770
+ case "--version":
7771
+ case "-v":
7772
+ cmdVersion();
7773
+ break;
7774
+ case "--help":
7775
+ case "-h":
7776
+ cmdHelp();
7777
+ break;
7778
+ case "--stop":
7779
+ cmdStop();
7780
+ break;
7781
+ case "--setup":
7782
+ cmdSetup();
7783
+ break;
7784
+ case "--setup-edge":
7785
+ case "--doctor":
7786
+ cmdSetupEdge();
7787
+ break;
7788
+ case "--mcp":
7789
+ cmdMcp();
7790
+ break;
7791
+ case "":
7792
+ cmdStart();
7793
+ break;
7794
+ default:
7795
+ console.error(`Unknown option: ${command}`);
7796
+ cmdHelp();
7797
+ process.exit(1);
7798
+ }
7799
+ }
7800
+ }
7801
+ });
7802
+ init_cli();
7803
+ // Annotate the CommonJS export names for ESM import in node:
7804
+ 0 && (module.exports = {
7805
+ formatToolResult,
7806
+ handleMcpHttp,
7807
+ handleMcpRequest
7808
+ });