claude-chrome-android 1.2.0 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/claude-code-bridge.crx +0 -0
- package/dist/cli.js +335 -83
- package/package.json +1 -1
|
Binary file
|
package/dist/cli.js
CHANGED
|
@@ -3947,8 +3947,35 @@ var init_compat = __esm({
|
|
|
3947
3947
|
|
|
3948
3948
|
// ../claude-chrome-bridge.ts
|
|
3949
3949
|
var claude_chrome_bridge_exports = {};
|
|
3950
|
+
function getAdbSerial() {
|
|
3951
|
+
const now = Date.now();
|
|
3952
|
+
if (now - _adbSerialTs < ADB_SERIAL_TTL_MS) return _adbSerial;
|
|
3953
|
+
_adbSerialTs = now;
|
|
3954
|
+
try {
|
|
3955
|
+
const result = runSync([ADB_PATH, "devices"]);
|
|
3956
|
+
const lines = result.stdout.toString().trim().split("\n").filter((l) => l.endsWith(" device"));
|
|
3957
|
+
if (lines.length <= 1) {
|
|
3958
|
+
_adbSerial = "";
|
|
3959
|
+
return _adbSerial;
|
|
3960
|
+
}
|
|
3961
|
+
for (const line of lines) {
|
|
3962
|
+
const serial = line.split(" ")[0];
|
|
3963
|
+
const check = runSync([ADB_PATH, "-s", serial, "shell", "pidof", "com.microsoft.emmx.canary"]);
|
|
3964
|
+
if (check.exitCode === 0 && check.stdout.toString().trim()) {
|
|
3965
|
+
_adbSerial = serial;
|
|
3966
|
+
return _adbSerial;
|
|
3967
|
+
}
|
|
3968
|
+
}
|
|
3969
|
+
_adbSerial = lines[0]?.split(" ")[0] ?? "";
|
|
3970
|
+
return _adbSerial;
|
|
3971
|
+
} catch {
|
|
3972
|
+
_adbSerial = "";
|
|
3973
|
+
return _adbSerial;
|
|
3974
|
+
}
|
|
3975
|
+
}
|
|
3950
3976
|
function adb(...args2) {
|
|
3951
|
-
|
|
3977
|
+
const serial = getAdbSerial();
|
|
3978
|
+
return serial ? [ADB_PATH, "-s", serial, ...args2] : [ADB_PATH, ...args2];
|
|
3952
3979
|
}
|
|
3953
3980
|
function adbNotify(tag, title, text) {
|
|
3954
3981
|
try {
|
|
@@ -4293,15 +4320,36 @@ function encodeGIF(frames, delayMs) {
|
|
|
4293
4320
|
}
|
|
4294
4321
|
return result;
|
|
4295
4322
|
}
|
|
4296
|
-
function
|
|
4297
|
-
|
|
4298
|
-
const next = pendingToolQueue[0];
|
|
4323
|
+
function sendToolRequest(requestId, requestJson) {
|
|
4324
|
+
let sent = false;
|
|
4299
4325
|
for (const client of wsClients) {
|
|
4300
4326
|
try {
|
|
4301
|
-
client.send(
|
|
4327
|
+
client.send(requestJson);
|
|
4328
|
+
sent = true;
|
|
4302
4329
|
} catch {
|
|
4303
4330
|
}
|
|
4304
4331
|
}
|
|
4332
|
+
return sent;
|
|
4333
|
+
}
|
|
4334
|
+
function drainTabQueue(tabId) {
|
|
4335
|
+
const queue = busyTabs.get(tabId);
|
|
4336
|
+
if (!queue || queue.length === 0) {
|
|
4337
|
+
busyTabs.delete(tabId);
|
|
4338
|
+
return;
|
|
4339
|
+
}
|
|
4340
|
+
const next = queue.shift();
|
|
4341
|
+
if (queue.length === 0) busyTabs.delete(tabId);
|
|
4342
|
+
pendingToolMap.set(next.requestId, {
|
|
4343
|
+
resolve: next.resolve,
|
|
4344
|
+
timeout: next.timeout,
|
|
4345
|
+
tabId: next.tabId
|
|
4346
|
+
});
|
|
4347
|
+
const sent = sendToolRequest(next.requestId, next.requestJson);
|
|
4348
|
+
if (!sent) {
|
|
4349
|
+
pendingToolMap.delete(next.requestId);
|
|
4350
|
+
clearTimeout(next.timeout);
|
|
4351
|
+
next.resolve({ type: "tool_response", error: "All bridge clients disconnected before dispatch" });
|
|
4352
|
+
}
|
|
4305
4353
|
}
|
|
4306
4354
|
function spawnNativeHost() {
|
|
4307
4355
|
if (nativeHost) {
|
|
@@ -4355,8 +4403,8 @@ function spawnNativeHost() {
|
|
|
4355
4403
|
log("error", "stderr read error:", err);
|
|
4356
4404
|
}
|
|
4357
4405
|
};
|
|
4358
|
-
readStdout();
|
|
4359
|
-
readStderr();
|
|
4406
|
+
readStdout().catch((err) => log("error", "readStdout unhandled:", err));
|
|
4407
|
+
readStderr().catch((err) => log("error", "readStderr unhandled:", err));
|
|
4360
4408
|
nativeHost.exited.then((code) => {
|
|
4361
4409
|
log("warn", `Native host exited with code ${code}`);
|
|
4362
4410
|
nativeHost = null;
|
|
@@ -4384,7 +4432,17 @@ function handleNativeMessage(json) {
|
|
|
4384
4432
|
cdpManager.evaluateJS(code, tabId).then((cdpResult) => {
|
|
4385
4433
|
const response = JSON.stringify({ type: "tool_response", result: cdpResult });
|
|
4386
4434
|
log("debug", `CDP\u2192native: ${response.slice(0, 200)}`);
|
|
4387
|
-
|
|
4435
|
+
try {
|
|
4436
|
+
sendToNativeHost(response);
|
|
4437
|
+
} catch (e) {
|
|
4438
|
+
log("warn", `sendToNativeHost failed after CDP eval: ${e.message}`);
|
|
4439
|
+
for (const client of wsClients) {
|
|
4440
|
+
try {
|
|
4441
|
+
client.send(outJson);
|
|
4442
|
+
} catch {
|
|
4443
|
+
}
|
|
4444
|
+
}
|
|
4445
|
+
}
|
|
4388
4446
|
}).catch((err) => {
|
|
4389
4447
|
log("warn", `CDP eval failed, forwarding to extension: ${err.message}`);
|
|
4390
4448
|
for (const client of wsClients) {
|
|
@@ -4401,12 +4459,22 @@ function handleNativeMessage(json) {
|
|
|
4401
4459
|
log("info", `CDP: intercepting computer screenshot (tab ${tabId ?? "active"})`);
|
|
4402
4460
|
cdpManager.captureScreenshot(tabId).then((cdpResult) => {
|
|
4403
4461
|
if (cdpResult.data) {
|
|
4404
|
-
|
|
4405
|
-
|
|
4406
|
-
|
|
4407
|
-
|
|
4462
|
+
try {
|
|
4463
|
+
sendToNativeHost(JSON.stringify({
|
|
4464
|
+
type: "tool_response",
|
|
4465
|
+
result: {
|
|
4466
|
+
content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: cdpResult.data } }]
|
|
4467
|
+
}
|
|
4468
|
+
}));
|
|
4469
|
+
} catch (e) {
|
|
4470
|
+
log("warn", `sendToNativeHost failed after CDP screenshot: ${e.message}`);
|
|
4471
|
+
for (const client of wsClients) {
|
|
4472
|
+
try {
|
|
4473
|
+
client.send(outJson);
|
|
4474
|
+
} catch {
|
|
4475
|
+
}
|
|
4408
4476
|
}
|
|
4409
|
-
}
|
|
4477
|
+
}
|
|
4410
4478
|
} else {
|
|
4411
4479
|
log("warn", `CDP screenshot failed: ${cdpResult.error}`);
|
|
4412
4480
|
for (const client of wsClients) {
|
|
@@ -4454,12 +4522,22 @@ function handleNativeMessage(json) {
|
|
|
4454
4522
|
const croppedRGBA = cropPixels(rgba, width, height, cropX, cropY, cropW, cropH);
|
|
4455
4523
|
const pngBuf = encodePNG(croppedRGBA, cropW, cropH);
|
|
4456
4524
|
const b64 = pngBuf.toString("base64");
|
|
4457
|
-
|
|
4458
|
-
|
|
4459
|
-
|
|
4460
|
-
|
|
4525
|
+
try {
|
|
4526
|
+
sendToNativeHost(JSON.stringify({
|
|
4527
|
+
type: "tool_response",
|
|
4528
|
+
result: {
|
|
4529
|
+
content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: b64 } }]
|
|
4530
|
+
}
|
|
4531
|
+
}));
|
|
4532
|
+
} catch (e) {
|
|
4533
|
+
log("warn", `sendToNativeHost failed after CDP zoom: ${e.message}`);
|
|
4534
|
+
for (const client of wsClients) {
|
|
4535
|
+
try {
|
|
4536
|
+
client.send(outJson);
|
|
4537
|
+
} catch {
|
|
4538
|
+
}
|
|
4461
4539
|
}
|
|
4462
|
-
}
|
|
4540
|
+
}
|
|
4463
4541
|
} catch (cropErr) {
|
|
4464
4542
|
log("warn", `CDP zoom crop failed: ${cropErr.message}`);
|
|
4465
4543
|
for (const client of wsClients) {
|
|
@@ -4497,10 +4575,20 @@ function handleNativeMessage(json) {
|
|
|
4497
4575
|
log("info", `CDP: intercepting computer ${action} (tab ${tabId ?? "active"})`);
|
|
4498
4576
|
cdpManager.dispatchComputerAction(action, parsed.params ?? {}, tabId).then((cdpResult) => {
|
|
4499
4577
|
if (cdpResult.result) {
|
|
4500
|
-
|
|
4501
|
-
|
|
4502
|
-
|
|
4503
|
-
|
|
4578
|
+
try {
|
|
4579
|
+
sendToNativeHost(JSON.stringify({
|
|
4580
|
+
type: "tool_response",
|
|
4581
|
+
result: { result: cdpResult.result }
|
|
4582
|
+
}));
|
|
4583
|
+
} catch (e) {
|
|
4584
|
+
log("warn", `sendToNativeHost failed after CDP ${action}: ${e.message}`);
|
|
4585
|
+
for (const client of wsClients) {
|
|
4586
|
+
try {
|
|
4587
|
+
client.send(outJson);
|
|
4588
|
+
} catch {
|
|
4589
|
+
}
|
|
4590
|
+
}
|
|
4591
|
+
}
|
|
4504
4592
|
} else {
|
|
4505
4593
|
log("warn", `CDP ${action} failed: ${cdpResult.error}`);
|
|
4506
4594
|
for (const client of wsClients) {
|
|
@@ -4526,7 +4614,17 @@ function handleNativeMessage(json) {
|
|
|
4526
4614
|
if (width && height) {
|
|
4527
4615
|
log("info", `CDP: intercepting resize_window (${width}\xD7${height})`);
|
|
4528
4616
|
cdpManager.setDeviceMetrics(width, height, parsed.params?.tabId).then((r) => {
|
|
4529
|
-
|
|
4617
|
+
try {
|
|
4618
|
+
sendToNativeHost(JSON.stringify({ type: "tool_response", result: r }));
|
|
4619
|
+
} catch (e) {
|
|
4620
|
+
log("warn", `sendToNativeHost failed after CDP resize: ${e.message}`);
|
|
4621
|
+
for (const client of wsClients) {
|
|
4622
|
+
try {
|
|
4623
|
+
client.send(outJson);
|
|
4624
|
+
} catch {
|
|
4625
|
+
}
|
|
4626
|
+
}
|
|
4627
|
+
}
|
|
4530
4628
|
}).catch(() => {
|
|
4531
4629
|
for (const client of wsClients) {
|
|
4532
4630
|
try {
|
|
@@ -4545,10 +4643,14 @@ function handleNativeMessage(json) {
|
|
|
4545
4643
|
const cdpRequests = cdpManager.getNetworkRequests(tabId, since, typeFilter);
|
|
4546
4644
|
if (cdpRequests.length > 0) {
|
|
4547
4645
|
log("info", `CDP: returning ${cdpRequests.length} network requests`);
|
|
4548
|
-
|
|
4549
|
-
|
|
4550
|
-
|
|
4551
|
-
|
|
4646
|
+
try {
|
|
4647
|
+
sendToNativeHost(JSON.stringify({
|
|
4648
|
+
type: "tool_response",
|
|
4649
|
+
result: { result: cdpRequests, count: cdpRequests.length, source: "cdp" }
|
|
4650
|
+
}));
|
|
4651
|
+
} catch (e) {
|
|
4652
|
+
log("warn", `sendToNativeHost failed for network requests: ${e.message}`);
|
|
4653
|
+
}
|
|
4552
4654
|
return;
|
|
4553
4655
|
}
|
|
4554
4656
|
}
|
|
@@ -4597,7 +4699,7 @@ function shutdown() {
|
|
|
4597
4699
|
log("info", "Bridge stopped");
|
|
4598
4700
|
process.exit(0);
|
|
4599
4701
|
}
|
|
4600
|
-
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,
|
|
4702
|
+
var import_path, import_node_zlib, SCRIPT_DIR, MANIFEST_PATH, BRIDGE_VERSION, WS_PORT, WS_HOST, BRIDGE_TOKEN, MAX_MESSAGE_SIZE, RECONNECT_DELAY_MS, HEARTBEAT_INTERVAL_MS, TERMUX_PREFIX, TERMUX_BIN, ADB_PATH, _adbSerial, _adbSerialTs, ADB_SERIAL_TTL_MS, REPO_CLI, BUN_GLOBAL_CLI, NPM_GLOBAL_CLI, CLI_PATH, RUNTIME_PATH, LOG_LEVEL, LOG_PRIORITY, NativeMessageDecoder, CDP_PORT, CDP_PID_CHECK_INTERVAL_MS, CDP_MAX_BACKOFF_ATTEMPTS, CDP_TARGET_CACHE_TTL_MS, CDP_TIMEOUT_MS, CdpManager, cdpManager, crc32Table, toolRequestCounter, pendingToolMap, busyTabs, HTTP_TOOL_TIMEOUT_MS, lastToolName, lastToolTime, nativeHost, stdoutDecoder, wsClients, server, TEST_PAGE_HTML;
|
|
4601
4703
|
var init_claude_chrome_bridge = __esm({
|
|
4602
4704
|
"../claude-chrome-bridge.ts"() {
|
|
4603
4705
|
init_import_meta_shim();
|
|
@@ -4624,21 +4726,9 @@ var init_claude_chrome_bridge = __esm({
|
|
|
4624
4726
|
TERMUX_PREFIX = "/data/data/com.termux/files/usr";
|
|
4625
4727
|
TERMUX_BIN = `${TERMUX_PREFIX}/bin`;
|
|
4626
4728
|
ADB_PATH = `${TERMUX_BIN}/adb`;
|
|
4627
|
-
|
|
4628
|
-
|
|
4629
|
-
|
|
4630
|
-
const lines = result.stdout.toString().trim().split("\n").filter((l) => l.endsWith(" device"));
|
|
4631
|
-
if (lines.length <= 1) return "";
|
|
4632
|
-
for (const line of lines) {
|
|
4633
|
-
const serial = line.split(" ")[0];
|
|
4634
|
-
const check = runSync([ADB_PATH, "-s", serial, "shell", "pidof", "com.microsoft.emmx.canary"]);
|
|
4635
|
-
if (check.exitCode === 0 && check.stdout.toString().trim()) return serial;
|
|
4636
|
-
}
|
|
4637
|
-
return lines[0]?.split(" ")[0] ?? "";
|
|
4638
|
-
} catch {
|
|
4639
|
-
return "";
|
|
4640
|
-
}
|
|
4641
|
-
})();
|
|
4729
|
+
_adbSerial = "";
|
|
4730
|
+
_adbSerialTs = 0;
|
|
4731
|
+
ADB_SERIAL_TTL_MS = 3e4;
|
|
4642
4732
|
REPO_CLI = (0, import_path.resolve)(SCRIPT_DIR, "cli.js");
|
|
4643
4733
|
BUN_GLOBAL_CLI = (0, import_path.resolve)(
|
|
4644
4734
|
process.env.HOME ?? "~",
|
|
@@ -4688,7 +4778,8 @@ var init_claude_chrome_bridge = __esm({
|
|
|
4688
4778
|
}
|
|
4689
4779
|
};
|
|
4690
4780
|
CDP_PORT = parseInt(process.env.CDP_PORT ?? "9223", 10);
|
|
4691
|
-
CDP_PID_CHECK_INTERVAL_MS =
|
|
4781
|
+
CDP_PID_CHECK_INTERVAL_MS = 3e4;
|
|
4782
|
+
CDP_MAX_BACKOFF_ATTEMPTS = 10;
|
|
4692
4783
|
CDP_TARGET_CACHE_TTL_MS = 1e4;
|
|
4693
4784
|
CDP_TIMEOUT_MS = 15e3;
|
|
4694
4785
|
CdpManager = class {
|
|
@@ -4712,6 +4803,10 @@ var init_claude_chrome_bridge = __esm({
|
|
|
4712
4803
|
pidCheckTimer = null;
|
|
4713
4804
|
/** Reconnect interval handle (active when disconnected) */
|
|
4714
4805
|
reconnectTimer = null;
|
|
4806
|
+
/** Exponential backoff reconnect attempts counter */
|
|
4807
|
+
reconnectBackoffAttempts = 0;
|
|
4808
|
+
/** Exponential backoff timer handle */
|
|
4809
|
+
backoffTimer = null;
|
|
4715
4810
|
/** Sessions where Network domain has been enabled */
|
|
4716
4811
|
networkEnabledSessions = /* @__PURE__ */ new Set();
|
|
4717
4812
|
/** Network request events per sessionId */
|
|
@@ -4728,6 +4823,7 @@ var init_claude_chrome_bridge = __esm({
|
|
|
4728
4823
|
this.state = "disconnected";
|
|
4729
4824
|
return false;
|
|
4730
4825
|
}
|
|
4826
|
+
const existingForward = this.checkExistingForward();
|
|
4731
4827
|
const socketCandidates = [
|
|
4732
4828
|
`chrome_devtools_remote_${this.edgePid}`,
|
|
4733
4829
|
// Chrome convention (PID-suffixed)
|
|
@@ -4735,20 +4831,31 @@ var init_claude_chrome_bridge = __esm({
|
|
|
4735
4831
|
// Edge Android convention (plain)
|
|
4736
4832
|
];
|
|
4737
4833
|
let versionData = null;
|
|
4738
|
-
|
|
4739
|
-
const fwdResult = runSync(
|
|
4740
|
-
adb("forward", `tcp:${CDP_PORT}`, `localabstract:${socketName}`)
|
|
4741
|
-
);
|
|
4742
|
-
if (fwdResult.exitCode !== 0) continue;
|
|
4834
|
+
if (existingForward) {
|
|
4743
4835
|
try {
|
|
4744
4836
|
const resp = await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`);
|
|
4745
4837
|
versionData = await resp.json();
|
|
4746
|
-
log("
|
|
4747
|
-
break;
|
|
4838
|
+
log("debug", `CDP: reusing existing ADB forward on port ${CDP_PORT}`);
|
|
4748
4839
|
} catch {
|
|
4749
4840
|
runSync(adb("forward", "--remove", `tcp:${CDP_PORT}`));
|
|
4750
4841
|
}
|
|
4751
4842
|
}
|
|
4843
|
+
if (!versionData) {
|
|
4844
|
+
for (const socketName of socketCandidates) {
|
|
4845
|
+
const fwdResult = runSync(
|
|
4846
|
+
adb("forward", `tcp:${CDP_PORT}`, `localabstract:${socketName}`)
|
|
4847
|
+
);
|
|
4848
|
+
if (fwdResult.exitCode !== 0) continue;
|
|
4849
|
+
try {
|
|
4850
|
+
const resp = await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`);
|
|
4851
|
+
versionData = await resp.json();
|
|
4852
|
+
log("info", `CDP: Edge version \u2014 ${versionData["Browser"] ?? "unknown"}, pkg: ${versionData["Android-Package"] ?? "unknown"} (socket: ${socketName})`);
|
|
4853
|
+
break;
|
|
4854
|
+
} catch {
|
|
4855
|
+
runSync(adb("forward", "--remove", `tcp:${CDP_PORT}`));
|
|
4856
|
+
}
|
|
4857
|
+
}
|
|
4858
|
+
}
|
|
4752
4859
|
if (!versionData) {
|
|
4753
4860
|
log("warn", "CDP: no working DevTools socket found");
|
|
4754
4861
|
this.state = "disconnected";
|
|
@@ -4756,6 +4863,8 @@ var init_claude_chrome_bridge = __esm({
|
|
|
4756
4863
|
}
|
|
4757
4864
|
const wsUrl = versionData.webSocketDebuggerUrl?.replace(/^ws:\/\/[^/]+/, `ws://127.0.0.1:${CDP_PORT}`) ?? `ws://127.0.0.1:${CDP_PORT}/devtools/browser`;
|
|
4758
4865
|
await this.connectWebSocket(wsUrl);
|
|
4866
|
+
this.reconnectBackoffAttempts = 0;
|
|
4867
|
+
this.cancelBackoff();
|
|
4759
4868
|
this.stopReconnectTimer();
|
|
4760
4869
|
if (!this.pidCheckTimer) {
|
|
4761
4870
|
this.pidCheckTimer = setInterval(() => this.recheckPid(), CDP_PID_CHECK_INTERVAL_MS);
|
|
@@ -4792,11 +4901,20 @@ var init_claude_chrome_bridge = __esm({
|
|
|
4792
4901
|
this.ws = null;
|
|
4793
4902
|
this.sessionMap.clear();
|
|
4794
4903
|
this.tabTargetMap.clear();
|
|
4904
|
+
if (this.pending.size > 0) {
|
|
4905
|
+
log("warn", `CDP: rejecting ${this.pending.size} pending commands on WS close`);
|
|
4906
|
+
this.pending.forEach((p) => {
|
|
4907
|
+
clearTimeout(p.timer);
|
|
4908
|
+
p.reject(new Error("CDP WebSocket closed"));
|
|
4909
|
+
});
|
|
4910
|
+
this.pending.clear();
|
|
4911
|
+
}
|
|
4912
|
+
this.scheduleExpBackoff();
|
|
4795
4913
|
});
|
|
4796
4914
|
this.ws.addEventListener("message", (ev) => {
|
|
4797
4915
|
try {
|
|
4798
4916
|
const data = JSON.parse(String(ev.data));
|
|
4799
|
-
if (data.id
|
|
4917
|
+
if (typeof data.id === "number") {
|
|
4800
4918
|
const p = this.pending.get(data.id);
|
|
4801
4919
|
if (p) {
|
|
4802
4920
|
clearTimeout(p.timer);
|
|
@@ -4810,7 +4928,13 @@ var init_claude_chrome_bridge = __esm({
|
|
|
4810
4928
|
if (sessionId) {
|
|
4811
4929
|
const p = data.params;
|
|
4812
4930
|
const resp = p.response;
|
|
4813
|
-
if (!this.networkEvents.has(sessionId))
|
|
4931
|
+
if (!this.networkEvents.has(sessionId)) {
|
|
4932
|
+
if (this.networkEvents.size >= 20) {
|
|
4933
|
+
const oldestKey = this.networkEvents.keys().next().value;
|
|
4934
|
+
if (oldestKey) this.networkEvents.delete(oldestKey);
|
|
4935
|
+
}
|
|
4936
|
+
this.networkEvents.set(sessionId, []);
|
|
4937
|
+
}
|
|
4814
4938
|
const buf = this.networkEvents.get(sessionId);
|
|
4815
4939
|
buf.push({
|
|
4816
4940
|
url: resp?.url ?? "",
|
|
@@ -4819,7 +4943,7 @@ var init_claude_chrome_bridge = __esm({
|
|
|
4819
4943
|
type: p.type ?? "other",
|
|
4820
4944
|
timestamp: Date.now()
|
|
4821
4945
|
});
|
|
4822
|
-
if (buf.length >
|
|
4946
|
+
if (buf.length > 200) buf.shift();
|
|
4823
4947
|
}
|
|
4824
4948
|
}
|
|
4825
4949
|
} catch {
|
|
@@ -4828,8 +4952,13 @@ var init_claude_chrome_bridge = __esm({
|
|
|
4828
4952
|
});
|
|
4829
4953
|
});
|
|
4830
4954
|
}
|
|
4831
|
-
/** Send a CDP command and await its response */
|
|
4832
|
-
sendCommand(method, params = {}, sessionId) {
|
|
4955
|
+
/** Send a CDP command and await its response. Tries one reconnect if disconnected. */
|
|
4956
|
+
async sendCommand(method, params = {}, sessionId) {
|
|
4957
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
4958
|
+
log("debug", `CDP: sendCommand(${method}) \u2014 not connected, attempting reconnect`);
|
|
4959
|
+
const ok = await this.connect();
|
|
4960
|
+
if (!ok) throw new Error("CDP not connected");
|
|
4961
|
+
}
|
|
4833
4962
|
return new Promise((resolve3, reject) => {
|
|
4834
4963
|
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
4835
4964
|
reject(new Error("CDP not connected"));
|
|
@@ -5232,6 +5361,43 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5232
5361
|
targets: this.cachedTargets.filter((t) => t.type === "page").length
|
|
5233
5362
|
};
|
|
5234
5363
|
}
|
|
5364
|
+
/** Schedule exponential backoff reconnect: 2s, 4s, 8s, 16s, max 30s */
|
|
5365
|
+
scheduleExpBackoff() {
|
|
5366
|
+
if (this.backoffTimer) return;
|
|
5367
|
+
if (this.reconnectBackoffAttempts >= CDP_MAX_BACKOFF_ATTEMPTS) {
|
|
5368
|
+
log("info", `CDP: backoff exhausted (${CDP_MAX_BACKOFF_ATTEMPTS} attempts), falling back to PID timer`);
|
|
5369
|
+
this.reconnectBackoffAttempts = 0;
|
|
5370
|
+
this.startReconnectTimer();
|
|
5371
|
+
return;
|
|
5372
|
+
}
|
|
5373
|
+
const delay = Math.min(2e3 * Math.pow(2, this.reconnectBackoffAttempts), 3e4);
|
|
5374
|
+
this.reconnectBackoffAttempts++;
|
|
5375
|
+
log("debug", `CDP: backoff reconnect in ${delay}ms (attempt ${this.reconnectBackoffAttempts}/${CDP_MAX_BACKOFF_ATTEMPTS})`);
|
|
5376
|
+
this.backoffTimer = setTimeout(async () => {
|
|
5377
|
+
this.backoffTimer = null;
|
|
5378
|
+
const ok = await this.connect();
|
|
5379
|
+
if (!ok && this.state === "disconnected") {
|
|
5380
|
+
this.scheduleExpBackoff();
|
|
5381
|
+
}
|
|
5382
|
+
}, delay);
|
|
5383
|
+
}
|
|
5384
|
+
/** Cancel pending backoff timer */
|
|
5385
|
+
cancelBackoff() {
|
|
5386
|
+
if (this.backoffTimer) {
|
|
5387
|
+
clearTimeout(this.backoffTimer);
|
|
5388
|
+
this.backoffTimer = null;
|
|
5389
|
+
}
|
|
5390
|
+
}
|
|
5391
|
+
/** Check if an ADB forward for our CDP port already exists */
|
|
5392
|
+
checkExistingForward() {
|
|
5393
|
+
try {
|
|
5394
|
+
const result = runSync(adb("forward", "--list"));
|
|
5395
|
+
const lines = result.stdout.toString().trim().split("\n");
|
|
5396
|
+
return lines.some((l) => l.includes(`tcp:${CDP_PORT}`));
|
|
5397
|
+
} catch {
|
|
5398
|
+
return false;
|
|
5399
|
+
}
|
|
5400
|
+
}
|
|
5235
5401
|
/**
|
|
5236
5402
|
* Get Edge PID — tries local `pidof` first (works on-device without ADB),
|
|
5237
5403
|
* falls back to `adb shell pidof` if local fails.
|
|
@@ -5286,12 +5452,14 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5286
5452
|
this.reconnectTimer = null;
|
|
5287
5453
|
}
|
|
5288
5454
|
}
|
|
5289
|
-
/** Stop reconnect timer
|
|
5455
|
+
/** Stop reconnect timer and cancel backoff for final shutdown */
|
|
5290
5456
|
stopReconnectForShutdown() {
|
|
5291
5457
|
this.stopReconnectTimer();
|
|
5458
|
+
this.cancelBackoff();
|
|
5292
5459
|
}
|
|
5293
5460
|
/** Clean up CDP connection and ADB forward, restart reconnect timer */
|
|
5294
5461
|
cleanup() {
|
|
5462
|
+
this.cancelBackoff();
|
|
5295
5463
|
if (this.pidCheckTimer) {
|
|
5296
5464
|
clearInterval(this.pidCheckTimer);
|
|
5297
5465
|
this.pidCheckTimer = null;
|
|
@@ -5325,8 +5493,12 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5325
5493
|
for (let j = 0; j < 8; j++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
5326
5494
|
crc32Table[i] = c;
|
|
5327
5495
|
}
|
|
5328
|
-
|
|
5496
|
+
toolRequestCounter = 0;
|
|
5497
|
+
pendingToolMap = /* @__PURE__ */ new Map();
|
|
5498
|
+
busyTabs = /* @__PURE__ */ new Map();
|
|
5329
5499
|
HTTP_TOOL_TIMEOUT_MS = 3e4;
|
|
5500
|
+
lastToolName = null;
|
|
5501
|
+
lastToolTime = null;
|
|
5330
5502
|
nativeHost = null;
|
|
5331
5503
|
stdoutDecoder = new NativeMessageDecoder();
|
|
5332
5504
|
wsClients = /* @__PURE__ */ new Set();
|
|
@@ -5343,7 +5515,9 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5343
5515
|
nativeHost: nativeHost !== null,
|
|
5344
5516
|
clients: wsClients.size,
|
|
5345
5517
|
uptime: process.uptime(),
|
|
5346
|
-
cdp: cdpManager.getStatus()
|
|
5518
|
+
cdp: cdpManager.getStatus(),
|
|
5519
|
+
lastTool: lastToolName,
|
|
5520
|
+
lastToolTime
|
|
5347
5521
|
}),
|
|
5348
5522
|
{ headers: { "Content-Type": "application/json" } }
|
|
5349
5523
|
);
|
|
@@ -5487,23 +5661,54 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5487
5661
|
}
|
|
5488
5662
|
try {
|
|
5489
5663
|
const body = await req.json();
|
|
5664
|
+
const requestId = `req_${++toolRequestCounter}_${Date.now()}`;
|
|
5665
|
+
const tabId = body.params?.tabId || 0;
|
|
5490
5666
|
const toolRequest = JSON.stringify({
|
|
5491
5667
|
type: "tool_request",
|
|
5492
5668
|
method: body.method,
|
|
5493
|
-
params: body.params ?? {}
|
|
5669
|
+
params: body.params ?? {},
|
|
5670
|
+
requestId
|
|
5494
5671
|
});
|
|
5495
|
-
|
|
5496
|
-
|
|
5672
|
+
lastToolName = body.method;
|
|
5673
|
+
lastToolTime = (/* @__PURE__ */ new Date()).toISOString();
|
|
5674
|
+
const MAX_PENDING_TOOLS = 50;
|
|
5675
|
+
const totalQueued = pendingToolMap.size + Array.from(busyTabs.values()).reduce((acc, arr) => acc + arr.length, 0);
|
|
5676
|
+
if (totalQueued >= MAX_PENDING_TOOLS) {
|
|
5677
|
+
return new Response(
|
|
5678
|
+
JSON.stringify({ error: "Too many pending tool requests" }),
|
|
5679
|
+
{ status: 429, headers: { "Content-Type": "application/json" } }
|
|
5680
|
+
);
|
|
5681
|
+
}
|
|
5682
|
+
const tabBusy = [...pendingToolMap.values()].some((e) => e.tabId === tabId);
|
|
5683
|
+
log("info", `HTTP /tool: ${body.method} [${requestId}] tab=${tabId} busy=${tabBusy} pending=${pendingToolMap.size}`);
|
|
5497
5684
|
const result = await new Promise((resolve3) => {
|
|
5685
|
+
let settled = false;
|
|
5686
|
+
const safeResolve = (val) => {
|
|
5687
|
+
if (settled) return;
|
|
5688
|
+
settled = true;
|
|
5689
|
+
resolve3(val);
|
|
5690
|
+
};
|
|
5498
5691
|
const timeout = setTimeout(() => {
|
|
5499
|
-
|
|
5500
|
-
|
|
5501
|
-
|
|
5502
|
-
|
|
5503
|
-
|
|
5692
|
+
if (pendingToolMap.has(requestId)) {
|
|
5693
|
+
pendingToolMap.delete(requestId);
|
|
5694
|
+
drainTabQueue(tabId);
|
|
5695
|
+
} else {
|
|
5696
|
+
const queue = busyTabs.get(tabId);
|
|
5697
|
+
if (queue) {
|
|
5698
|
+
const idx = queue.findIndex((e) => e.requestId === requestId);
|
|
5699
|
+
if (idx !== -1) queue.splice(idx, 1);
|
|
5700
|
+
if (queue.length === 0) busyTabs.delete(tabId);
|
|
5701
|
+
}
|
|
5702
|
+
}
|
|
5703
|
+
safeResolve({ type: "tool_response", error: "Tool call timed out (30s)" });
|
|
5504
5704
|
}, HTTP_TOOL_TIMEOUT_MS);
|
|
5505
|
-
|
|
5506
|
-
|
|
5705
|
+
if (tabBusy) {
|
|
5706
|
+
if (!busyTabs.has(tabId)) busyTabs.set(tabId, []);
|
|
5707
|
+
busyTabs.get(tabId).push({ requestJson: toolRequest, resolve: safeResolve, timeout, requestId, tabId });
|
|
5708
|
+
} else {
|
|
5709
|
+
pendingToolMap.set(requestId, { resolve: safeResolve, timeout, tabId });
|
|
5710
|
+
sendToolRequest(requestId, toolRequest);
|
|
5711
|
+
}
|
|
5507
5712
|
});
|
|
5508
5713
|
return new Response(
|
|
5509
5714
|
JSON.stringify(result),
|
|
@@ -5549,6 +5754,10 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5549
5754
|
try {
|
|
5550
5755
|
const parsed = JSON.parse(json);
|
|
5551
5756
|
log("debug", `WS message type: ${parsed.type}`);
|
|
5757
|
+
if (parsed.type === "ping") {
|
|
5758
|
+
ws.send(JSON.stringify({ type: "pong" }));
|
|
5759
|
+
return;
|
|
5760
|
+
}
|
|
5552
5761
|
if (parsed.type === "tool_response" && parsed.result?.result?.tabs) {
|
|
5553
5762
|
const tabs = parsed.result.result.tabs;
|
|
5554
5763
|
log("debug", `CDP: caching ${tabs.length} tab URLs from tabs_context_mcp`);
|
|
@@ -5558,14 +5767,31 @@ var init_claude_chrome_bridge = __esm({
|
|
|
5558
5767
|
}
|
|
5559
5768
|
}
|
|
5560
5769
|
}
|
|
5561
|
-
if (parsed.type === "tool_response" &&
|
|
5562
|
-
|
|
5563
|
-
|
|
5564
|
-
|
|
5565
|
-
|
|
5566
|
-
|
|
5567
|
-
|
|
5568
|
-
|
|
5770
|
+
if (parsed.type === "tool_response" && pendingToolMap.size > 0) {
|
|
5771
|
+
let matched = false;
|
|
5772
|
+
if (parsed.requestId && pendingToolMap.has(parsed.requestId)) {
|
|
5773
|
+
const entry = pendingToolMap.get(parsed.requestId);
|
|
5774
|
+
pendingToolMap.delete(parsed.requestId);
|
|
5775
|
+
clearTimeout(entry.timeout);
|
|
5776
|
+
if ("method" in parsed) delete parsed.method;
|
|
5777
|
+
log("debug", `HTTP /tool response [${parsed.requestId}] (${pendingToolMap.size} pending): ${json.slice(0, 200)}`);
|
|
5778
|
+
entry.resolve(parsed);
|
|
5779
|
+
drainTabQueue(entry.tabId);
|
|
5780
|
+
matched = true;
|
|
5781
|
+
} else if (!parsed.requestId) {
|
|
5782
|
+
const firstKey = pendingToolMap.keys().next().value;
|
|
5783
|
+
if (firstKey) {
|
|
5784
|
+
const entry = pendingToolMap.get(firstKey);
|
|
5785
|
+
pendingToolMap.delete(firstKey);
|
|
5786
|
+
clearTimeout(entry.timeout);
|
|
5787
|
+
if ("method" in parsed) delete parsed.method;
|
|
5788
|
+
log("debug", `HTTP /tool response (FIFO fallback, ${pendingToolMap.size} pending): ${json.slice(0, 200)}`);
|
|
5789
|
+
entry.resolve(parsed);
|
|
5790
|
+
drainTabQueue(entry.tabId);
|
|
5791
|
+
matched = true;
|
|
5792
|
+
}
|
|
5793
|
+
}
|
|
5794
|
+
if (matched) return;
|
|
5569
5795
|
}
|
|
5570
5796
|
if (parsed.type === "tool_response" && "method" in parsed) {
|
|
5571
5797
|
delete parsed.method;
|
|
@@ -5898,16 +6124,29 @@ echo "[$(date +%H:%M:%S)] termux-url-opener: $url" >> "$PREFIX/tmp/url-opener.lo
|
|
|
5898
6124
|
case "$url" in
|
|
5899
6125
|
*cfcbridge*/start*)
|
|
5900
6126
|
BRIDGE_LOG="$PREFIX/tmp/bridge.log"
|
|
5901
|
-
|
|
6127
|
+
# Health-check the bridge directly \u2014 avoids pgrep self-match
|
|
6128
|
+
if curl -sf --connect-timeout 2 http://127.0.0.1:18963/health > /dev/null 2>&1; then
|
|
5902
6129
|
echo "[$(date +%H:%M:%S)] bridge already running" >> "$PREFIX/tmp/url-opener.log"
|
|
5903
6130
|
exit 0
|
|
5904
6131
|
fi
|
|
6132
|
+
# Find a JS runtime that can actually execute code.
|
|
6133
|
+
# bun on Termux uses a C wrapper (bun-termux) that may fail if its
|
|
6134
|
+
# shim library is missing \u2014 test with a real eval, not just --version.
|
|
6135
|
+
_try_runtime() {
|
|
6136
|
+
"$1" -e "process.exit(0)" > /dev/null 2>&1
|
|
6137
|
+
}
|
|
5905
6138
|
RUNTIME=""
|
|
5906
|
-
if [[ -x "$HOME/.bun/bin/bun" ]]
|
|
5907
|
-
|
|
5908
|
-
elif command -v
|
|
6139
|
+
if [[ -x "$HOME/.bun/bin/bun" ]] && _try_runtime "$HOME/.bun/bin/bun"; then
|
|
6140
|
+
RUNTIME="$HOME/.bun/bin/bun"
|
|
6141
|
+
elif command -v bun > /dev/null 2>&1 && _try_runtime bun; then
|
|
6142
|
+
RUNTIME="$(command -v bun)"
|
|
6143
|
+
elif command -v node > /dev/null 2>&1 && _try_runtime node; then
|
|
6144
|
+
RUNTIME="$(command -v node)"
|
|
6145
|
+
fi
|
|
6146
|
+
if [[ -z "$RUNTIME" ]]; then
|
|
6147
|
+
echo "[$(date +%H:%M:%S)] no working JS runtime found" >> "$PREFIX/tmp/url-opener.log"
|
|
6148
|
+
exit 1
|
|
5909
6149
|
fi
|
|
5910
|
-
if [[ -z "$RUNTIME" ]]; then exit 1; fi
|
|
5911
6150
|
BRIDGE_SCRIPT=""
|
|
5912
6151
|
if [[ -f "$HOME/git/termux-tools/claude-chrome-bridge.ts" ]]; then
|
|
5913
6152
|
BRIDGE_SCRIPT="$HOME/git/termux-tools/claude-chrome-bridge.ts"
|
|
@@ -6320,7 +6559,13 @@ async function callBridgeTool(method, params) {
|
|
|
6320
6559
|
const body = await resp.text();
|
|
6321
6560
|
return { error: `Bridge HTTP ${resp.status}: ${body}` };
|
|
6322
6561
|
}
|
|
6323
|
-
const
|
|
6562
|
+
const text = await resp.text();
|
|
6563
|
+
let data;
|
|
6564
|
+
try {
|
|
6565
|
+
data = JSON.parse(text);
|
|
6566
|
+
} catch {
|
|
6567
|
+
return { error: `Bridge returned non-JSON: ${text.slice(0, 200)}` };
|
|
6568
|
+
}
|
|
6324
6569
|
if (data.error) return { error: String(data.error) };
|
|
6325
6570
|
return { result: data.result ?? data };
|
|
6326
6571
|
} catch (err) {
|
|
@@ -6385,8 +6630,15 @@ async function cmdMcp() {
|
|
|
6385
6630
|
}
|
|
6386
6631
|
const decoder = new TextDecoder();
|
|
6387
6632
|
let buffer = "";
|
|
6633
|
+
const MAX_BUFFER_SIZE = 10 * 1024 * 1024;
|
|
6388
6634
|
for await (const chunk of process.stdin) {
|
|
6389
6635
|
buffer += typeof chunk === "string" ? chunk : decoder.decode(chunk);
|
|
6636
|
+
if (buffer.length > MAX_BUFFER_SIZE) {
|
|
6637
|
+
log2(`WARN: MCP buffer exceeded ${MAX_BUFFER_SIZE} bytes, discarding`);
|
|
6638
|
+
buffer = "";
|
|
6639
|
+
mcpSend(mcpError(0, -32600, "Request too large"));
|
|
6640
|
+
continue;
|
|
6641
|
+
}
|
|
6390
6642
|
let idx;
|
|
6391
6643
|
while ((idx = buffer.indexOf("\n")) !== -1) {
|
|
6392
6644
|
const line = buffer.slice(0, idx).trim();
|
package/package.json
CHANGED