@ricsam/browser-mcp 0.3.12 → 0.3.13
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/README.md +3 -1
- package/dist/{chunk-xgk37h9a.js → chunk-6dypb4ga.js} +10 -4
- package/dist/{chunk-847prxk6.js → chunk-6kc5yfp5.js} +1 -1
- package/dist/{chunk-2hzkme2s.js → chunk-k9cpr8vk.js} +1 -1
- package/dist/{chunk-vfx8ntjb.js → chunk-vw3wanmm.js} +302 -104
- package/dist/main.js +5 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
Native Chrome companion. Requires Node >=22.14.0 and an installed
|
|
4
4
|
Google Chrome. No browser download or startup occurs during npm installation.
|
|
5
5
|
|
|
6
|
+
Release 0.3.13 uses one cross-platform Node package with matching server/chart 0.3.13, native protocol 3 and no database schema change. It adds independent health and deadline quarantine, explicitly approved blocked-tab recovery, sanitized failure diagnostics, and verified binary download/export/script transfers. Older runtimes require an update for new capabilities. Stop the old CLI before upgrading, then restart the same named profile to preserve sign-ins and pairing; never replay uncertain actions automatically.
|
|
7
|
+
|
|
6
8
|
```sh
|
|
7
|
-
npm install -g @ricsam/browser-mcp@0.3.
|
|
9
|
+
npm install -g @ricsam/browser-mcp@0.3.13
|
|
8
10
|
browser-mcp browser start --server https://browser-mcp.click --profile work
|
|
9
11
|
browser-mcp browser status --profile work
|
|
10
12
|
browser-mcp browser pause --profile work
|
|
@@ -2,12 +2,13 @@ import {
|
|
|
2
2
|
capabilityFetch,
|
|
3
3
|
exclusiveOutput,
|
|
4
4
|
readCapability
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-k9cpr8vk.js";
|
|
6
6
|
import"./chunk-1sjcwr28.js";
|
|
7
7
|
|
|
8
8
|
// cli/src/agent/files.ts
|
|
9
9
|
import { open, constants, unlink } from "node:fs/promises";
|
|
10
10
|
import { Readable, Transform } from "node:stream";
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
11
12
|
import { pipeline } from "node:stream/promises";
|
|
12
13
|
async function uploadFile(capabilityPath, inputPath) {
|
|
13
14
|
const cap = await readCapability(capabilityPath);
|
|
@@ -26,8 +27,8 @@ async function uploadFile(capabilityPath, inputPath) {
|
|
|
26
27
|
}
|
|
27
28
|
async function downloadFile(capabilityPath, outputPath) {
|
|
28
29
|
const cap = await readCapability(capabilityPath);
|
|
29
|
-
if (cap.method !== "GET")
|
|
30
|
-
throw new Error("Download capability required");
|
|
30
|
+
if (cap.method !== "GET" || cap.size === undefined || cap.sha256 === undefined)
|
|
31
|
+
throw new Error("Download capability with exact size and SHA-256 required");
|
|
31
32
|
const file = await exclusiveOutput(outputPath);
|
|
32
33
|
let success = false;
|
|
33
34
|
try {
|
|
@@ -35,16 +36,21 @@ async function downloadFile(capabilityPath, outputPath) {
|
|
|
35
36
|
if (!response.body)
|
|
36
37
|
throw new Error("Missing transfer body");
|
|
37
38
|
let bytes = 0;
|
|
39
|
+
const hash = createHash("sha256");
|
|
38
40
|
const limiter = new Transform({ transform(chunk, _encoding, callback) {
|
|
39
41
|
bytes += chunk.length;
|
|
40
42
|
if (bytes > cap.limits.maxBytes)
|
|
41
43
|
return callback(new Error("Size exceeded"));
|
|
44
|
+
hash.update(chunk);
|
|
42
45
|
callback(null, chunk);
|
|
43
46
|
} });
|
|
44
47
|
await pipeline(Readable.fromWeb(response.body), limiter, file.createWriteStream({ autoClose: false }));
|
|
48
|
+
const sha256 = hash.digest("hex");
|
|
49
|
+
if (bytes !== cap.size || sha256 !== cap.sha256)
|
|
50
|
+
throw new Error("Download integrity verification failed; request a new capability, never retry this one");
|
|
45
51
|
await file.sync();
|
|
46
52
|
success = true;
|
|
47
|
-
return { downloaded: true, bytes };
|
|
53
|
+
return { downloaded: true, bytes, sha256 };
|
|
48
54
|
} finally {
|
|
49
55
|
await file.close();
|
|
50
56
|
if (!success)
|
|
@@ -22,7 +22,7 @@ async function readCapability(path) {
|
|
|
22
22
|
}
|
|
23
23
|
const cap = JSON.parse(text);
|
|
24
24
|
const u = new URL(cap.url);
|
|
25
|
-
if (u.protocol !== "https:" || u.username || u.password || u.search || u.hash || !/^\/api\/native-data\/[a-zA-Z0-9-]+$/.test(u.pathname) || !["GET", "PUT"].includes(cap.method) || !/^Bearer [A-Za-z0-9_-]{43}$/.test(cap.headers.Authorization) || cap.expiresAt <= Date.now() || !Number.isSafeInteger(cap.limits.maxBytes) || cap.limits.maxBytes < 0 || cap.limits.maxBytes > 256 * 1024 * 1024)
|
|
25
|
+
if (u.protocol !== "https:" || u.username || u.password || u.search || u.hash || !/^\/api\/native-data\/[a-zA-Z0-9-]+$/.test(u.pathname) || !["GET", "PUT"].includes(cap.method) || !/^Bearer [A-Za-z0-9_-]{43}$/.test(cap.headers.Authorization) || !Number.isFinite(cap.expiresAt) || cap.expiresAt <= Date.now() || cap.limits.maxAttempts !== 1 || cap.limits.resumable !== false || cap.size !== undefined && (!Number.isSafeInteger(cap.size) || cap.size !== cap.limits.maxBytes) || cap.sha256 !== undefined && !/^[a-f0-9]{64}$/.test(cap.sha256) || !Number.isSafeInteger(cap.limits.maxBytes) || cap.limits.maxBytes < 0 || cap.limits.maxBytes > 256 * 1024 * 1024)
|
|
26
26
|
throw new Error("Invalid capability");
|
|
27
27
|
return cap;
|
|
28
28
|
}
|
|
@@ -54,7 +54,7 @@ function onceAsync(action) {
|
|
|
54
54
|
// cli/src/browser/owned-chrome.ts
|
|
55
55
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
56
56
|
// cli/package.json
|
|
57
|
-
var version = "0.3.
|
|
57
|
+
var version = "0.3.13";
|
|
58
58
|
|
|
59
59
|
// cli/src/browser/chrome-diagnostics.ts
|
|
60
60
|
import { constants } from "node:fs";
|
|
@@ -3374,10 +3374,47 @@ class BrowserTabState {
|
|
|
3374
3374
|
}
|
|
3375
3375
|
}
|
|
3376
3376
|
|
|
3377
|
+
// cli/src/runtime/failures.ts
|
|
3378
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
3379
|
+
|
|
3380
|
+
class RuntimeFault extends Error {
|
|
3381
|
+
code;
|
|
3382
|
+
recovery;
|
|
3383
|
+
beforeDispatch;
|
|
3384
|
+
constructor(code2, recovery, beforeDispatch = false) {
|
|
3385
|
+
super(code2);
|
|
3386
|
+
this.code = code2;
|
|
3387
|
+
this.recovery = recovery;
|
|
3388
|
+
this.beforeDispatch = beforeDispatch;
|
|
3389
|
+
}
|
|
3390
|
+
}
|
|
3391
|
+
var OBSERVATION_OPERATIONS = new Set(["list_tabs", "list_downloads", "read_page", "screenshot", "wait_for", "capabilities", "inspect", "events", "diagnostics", "export_page", "webmcp_list", "runtime_health"]);
|
|
3392
|
+
var messages = {
|
|
3393
|
+
unsupported_target: "This target contains a privileged/internal document that browser page tools cannot inspect.",
|
|
3394
|
+
tab_closed: "The tab is closed or detached.",
|
|
3395
|
+
runtime_disconnected: "The runtime or browser connection ended.",
|
|
3396
|
+
context_destroyed: "The document execution context changed during the operation.",
|
|
3397
|
+
execution_timeout: "The browser operation exceeded its internal wait budget.",
|
|
3398
|
+
script_exception: "The script threw an exception. Page exception text and stack are suppressed.",
|
|
3399
|
+
transfer_failed: "The file transfer failed or its completion could not be confirmed.",
|
|
3400
|
+
scope_rejected: "Runtime scope or tab ownership was rejected.",
|
|
3401
|
+
runtime_operation_failed: "The browser operation failed; page-derived details are suppressed."
|
|
3402
|
+
};
|
|
3403
|
+
function failureFor(error, op, operationId, stage) {
|
|
3404
|
+
const text = error instanceof Error ? error.message : "";
|
|
3405
|
+
let code2 = error instanceof RuntimeFault ? error.code : /no longer open|Target page, context or browser has been closed|Target closed|Frame was detached/i.test(text) ? "tab_closed" : /Runtime disconnected|Browser closed|browser has been closed|Connection closed/i.test(text) ? "runtime_disconnected" : /Execution context was destroyed|destroying its JavaScript context|Cannot find context with specified id/i.test(text) ? "context_destroyed" : /Timeout|timed out|time out/i.test(text) ? "execution_timeout" : stage === "transfer" ? "transfer_failed" : op === "run_js" ? "script_exception" : /download|upload|transfer|resource|grant/i.test(op) ? "transfer_failed" : "runtime_operation_failed";
|
|
3406
|
+
const observation = OBSERVATION_OPERATIONS.has(op);
|
|
3407
|
+
const outcome = error instanceof RuntimeFault && error.beforeDispatch ? "not_dispatched" : observation ? "failed" : "unknown";
|
|
3408
|
+
const recovery = error instanceof RuntimeFault ? error.recovery : code2 === "runtime_disconnected" ? "Reconnect the runtime, then call browser_runtime_health. Do not repeat an uncertain mutation." : code2 === "tab_closed" ? "Use browser_list_tabs to select an existing tab. Do not replay the prior mutation." : code2 === "execution_timeout" ? "Call browser_runtime_health to distinguish a settled wait from quarantined execution. A timeout does not cancel page effects." : code2 === "transfer_failed" ? "Inspect browser_transfer_status and browser_list_downloads. Reissue a grant only for retained bytes; do not repeat a website action." : code2 === "script_exception" ? "Review the submitted script locally. Effects before the exception may have occurred; do not replay automatically." : "Call browser_runtime_health, then browser_capabilities for a supported target. Do not repeat an uncertain mutation.";
|
|
3409
|
+
const diagnosticId = randomUUID4();
|
|
3410
|
+
console.error(JSON.stringify({ event: "runtime_failure", diagnosticId, operationId, operation: op, stage, code: code2, outcome }));
|
|
3411
|
+
return { error: { code: code2, message: messages[code2] ?? "Runtime operation rejected." }, outcome, result: { diagnosticId, operationId, category: code2, stage, recovery, retrySafe: outcome !== "unknown", executionState: "settled", cancellationConfirmed: false } };
|
|
3412
|
+
}
|
|
3413
|
+
|
|
3377
3414
|
// cli/src/browser/browser-runtime.ts
|
|
3378
3415
|
var MAX_DOWNLOAD_CHUNK_BYTES = 1024 * 1024;
|
|
3379
3416
|
var MAX_RUN_JS_RESULT_BYTES = 1024 * 1024;
|
|
3380
|
-
var MAX_RUN_JS_ARTIFACT_BYTES =
|
|
3417
|
+
var MAX_RUN_JS_ARTIFACT_BYTES = 20 * 1024 * 1024;
|
|
3381
3418
|
var MAX_RUN_JS_ARTIFACT_COUNT = 32;
|
|
3382
3419
|
var REF_ACTION_TIMEOUT_MS = 5000;
|
|
3383
3420
|
var NAVIGATION_TIMEOUT_MS = 20000;
|
|
@@ -3714,7 +3751,7 @@ class BrowserRuntime {
|
|
|
3714
3751
|
if (action === "batch")
|
|
3715
3752
|
return await this.batch(input, execution);
|
|
3716
3753
|
const page = typeof input.tabId === "string" ? this.page(input.tabId) : undefined;
|
|
3717
|
-
if (page)
|
|
3754
|
+
if (page && action !== "close_tab")
|
|
3718
3755
|
await this.guardPage?.(page);
|
|
3719
3756
|
const events = page ? this.events.get(page) : undefined;
|
|
3720
3757
|
await events?.ready;
|
|
@@ -3807,20 +3844,23 @@ class BrowserRuntime {
|
|
|
3807
3844
|
results.push({ index, action: step.action, result });
|
|
3808
3845
|
if (result?.matched === false || result?.expected?.matched === false || result?.dispatch && result.dispatch.status !== "completed" || result?.code || result?.observation?.available === false)
|
|
3809
3846
|
return { results, stoppedAt: index, remaining: steps.length - index - 1, code: "batch_step_stopped", retrySafe: false };
|
|
3810
|
-
} catch {
|
|
3847
|
+
} catch (error) {
|
|
3848
|
+
const failure = failureFor(error, step.action, execution.operationId ?? crypto.randomUUID(), "batch_step");
|
|
3811
3849
|
return {
|
|
3812
|
-
results: [...results, { index, action: step.action, status: "unknown",
|
|
3850
|
+
results: [...results, { index, action: step.action, status: "unknown", ...failure.result, code: failure.error.code }],
|
|
3813
3851
|
stoppedAt: index,
|
|
3814
3852
|
remaining: steps.length - index - 1,
|
|
3853
|
+
status: "unknown",
|
|
3854
|
+
retrySafe: false,
|
|
3815
3855
|
code: "batch_outcome_uncertain",
|
|
3816
|
-
recovery:
|
|
3856
|
+
recovery: failure.result.recovery
|
|
3817
3857
|
};
|
|
3818
3858
|
}
|
|
3819
3859
|
}
|
|
3820
3860
|
return { results, completed: true, outcomeVerified: false };
|
|
3821
3861
|
}
|
|
3822
3862
|
async dispatch(action, input, execution) {
|
|
3823
|
-
if (typeof input.tabId === "string")
|
|
3863
|
+
if (typeof input.tabId === "string" && action !== "close_tab")
|
|
3824
3864
|
await this.guardPage?.(this.page(input.tabId));
|
|
3825
3865
|
if (action === "upload_abort") {
|
|
3826
3866
|
this.uploads.abort(input.uploadId, input.tabId);
|
|
@@ -4379,32 +4419,43 @@ class BrowserRuntime {
|
|
|
4379
4419
|
evaluated = await page.evaluate(async ({ code: code2, maxBytes, maxCount }) => {
|
|
4380
4420
|
const artifacts = [];
|
|
4381
4421
|
let totalBytes = 0;
|
|
4382
|
-
const r5dCreateArtifact = (filename, content) => {
|
|
4422
|
+
const r5dCreateArtifact = (filename, content, mimeType) => {
|
|
4383
4423
|
if (typeof filename !== "string" || !filename.trim()) {
|
|
4384
4424
|
throw new TypeError("r5dCreateArtifact(filename, content): filename must be a non-empty string.");
|
|
4385
4425
|
}
|
|
4386
|
-
if (
|
|
4387
|
-
throw new TypeError(
|
|
4388
|
-
|
|
4426
|
+
if (filename.length > 255 || /[\\/\\\\\x00-\x1f]/.test(filename))
|
|
4427
|
+
throw new TypeError("Artifact filename must be a simple filename of at most 255 characters.");
|
|
4428
|
+
const text = typeof content === "string";
|
|
4429
|
+
const bytes = text ? new TextEncoder().encode(content) : content instanceof ArrayBuffer ? new Uint8Array(content) : content instanceof Uint8Array ? content : undefined;
|
|
4430
|
+
if (!bytes)
|
|
4431
|
+
throw new TypeError("Artifact content must be a string, Uint8Array or ArrayBuffer; use await response.arrayBuffer() for binary documents.");
|
|
4432
|
+
const mime = mimeType === undefined ? text ? "text/plain" : "application/octet-stream" : mimeType;
|
|
4433
|
+
if (typeof mime !== "string" || !/^[a-zA-Z0-9!#$&^_.+-]+\/[a-zA-Z0-9!#$&^_.+-]+$/.test(mime) || mime.length > 200)
|
|
4434
|
+
throw new TypeError("Artifact MIME must be a type/subtype without parameters.");
|
|
4389
4435
|
if (artifacts.length >= maxCount) {
|
|
4390
4436
|
throw new RangeError(`r5dCreateArtifact: at most ${maxCount} artifacts can be created in one browser_run_js call.`);
|
|
4391
4437
|
}
|
|
4392
|
-
totalBytes +=
|
|
4438
|
+
totalBytes += bytes.byteLength;
|
|
4393
4439
|
if (totalBytes > maxBytes) {
|
|
4394
4440
|
throw new RangeError(`r5dCreateArtifact: artifact content exceeded the ${maxBytes} byte budget for one browser_run_js call.`);
|
|
4395
4441
|
}
|
|
4396
|
-
|
|
4442
|
+
if (text)
|
|
4443
|
+
artifacts.push({ filename, content, mimeType: mime });
|
|
4444
|
+
else {
|
|
4445
|
+
let encoded = "";
|
|
4446
|
+
for (let offset = 0;offset < bytes.length; offset += 24576)
|
|
4447
|
+
encoded += btoa(String.fromCharCode(...bytes.subarray(offset, offset + 24576)));
|
|
4448
|
+
artifacts.push({ filename, base64: encoded, mimeType: mime });
|
|
4449
|
+
}
|
|
4397
4450
|
return filename;
|
|
4398
4451
|
};
|
|
4399
|
-
|
|
4452
|
+
try {
|
|
4453
|
+
const invoke = new Function("r5dCreateArtifact", `"use strict"; return (async () => {
|
|
4400
4454
|
${code2}
|
|
4401
4455
|
})()`);
|
|
4402
|
-
try {
|
|
4403
4456
|
return { result: await invoke(r5dCreateArtifact), artifacts };
|
|
4404
4457
|
} catch (error) {
|
|
4405
|
-
|
|
4406
|
-
throw error;
|
|
4407
|
-
return { artifacts, failure: error instanceof Error ? error.message : String(error) };
|
|
4458
|
+
return { artifacts, failure: "script_exception" };
|
|
4408
4459
|
}
|
|
4409
4460
|
}, { code: input.code, maxBytes: MAX_RUN_JS_ARTIFACT_BYTES, maxCount: MAX_RUN_JS_ARTIFACT_COUNT });
|
|
4410
4461
|
} catch (error) {
|
|
@@ -4414,15 +4465,19 @@ ${code2}
|
|
|
4414
4465
|
}
|
|
4415
4466
|
throw new Error(stripCallLog(message));
|
|
4416
4467
|
}
|
|
4468
|
+
if (evaluated.failure && !evaluated.artifacts.length)
|
|
4469
|
+
throw new RuntimeFault("script_exception", "Review the submitted script locally. Effects before the exception may have occurred; do not replay automatically.");
|
|
4417
4470
|
const serialized = JSON.stringify(evaluated.result);
|
|
4418
4471
|
if (serialized && Buffer.byteLength(serialized) > MAX_RUN_JS_RESULT_BYTES) {
|
|
4419
4472
|
throw new Error("Browser JavaScript result exceeded the 1 MiB limit.");
|
|
4420
4473
|
}
|
|
4474
|
+
const partialFailure = evaluated.failure ? failureFor(new Error("Script exception"), "run_js", execution.operationId ?? crypto.randomUUID(), "execute") : undefined;
|
|
4421
4475
|
return {
|
|
4422
4476
|
tabId,
|
|
4423
4477
|
result: evaluated.result,
|
|
4424
4478
|
artifacts: evaluated.artifacts,
|
|
4425
4479
|
failure: evaluated.failure,
|
|
4480
|
+
...partialFailure ? { ...partialFailure.result, status: "unknown", retrySafe: false, recovery: "The script failed after producing these artifacts. Prior effects may have occurred; do not replay automatically." } : {},
|
|
4426
4481
|
execution: "javascript_escape_hatch",
|
|
4427
4482
|
intent: input.intent,
|
|
4428
4483
|
reason: input.reason,
|
|
@@ -4481,6 +4536,7 @@ class NativeRuntime {
|
|
|
4481
4536
|
epochs = new Map;
|
|
4482
4537
|
controllers = new Map;
|
|
4483
4538
|
disconnected = false;
|
|
4539
|
+
operations = new Map;
|
|
4484
4540
|
hooks = Promise.resolve();
|
|
4485
4541
|
browserId;
|
|
4486
4542
|
constructor(context, instanceId, directory, serverOrigin) {
|
|
@@ -4562,8 +4618,10 @@ class NativeRuntime {
|
|
|
4562
4618
|
}
|
|
4563
4619
|
}
|
|
4564
4620
|
assertPage(page) {
|
|
4565
|
-
if (page.isClosed()
|
|
4566
|
-
throw new
|
|
4621
|
+
if (page.isClosed())
|
|
4622
|
+
throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
|
|
4623
|
+
if (page.frames().some((f) => !this.allowURL(f.url())))
|
|
4624
|
+
throw new RuntimeFault("unsupported_target", "Call browser_capabilities. For documents use the website download, browser_list_downloads, then browser_create_download; do not screenshot or evaluate an internal viewer.", true);
|
|
4567
4625
|
}
|
|
4568
4626
|
async assertPageDeep(page) {
|
|
4569
4627
|
this.assertPage(page);
|
|
@@ -4580,7 +4638,7 @@ class NativeRuntime {
|
|
|
4580
4638
|
const check = (tree) => {
|
|
4581
4639
|
const origin = tree.frame.securityOrigin;
|
|
4582
4640
|
if (origin && origin !== "null" && origin !== "://" && !this.allowURL(origin))
|
|
4583
|
-
throw new
|
|
4641
|
+
throw new RuntimeFault("unsupported_target", "Use browser_capabilities and transfer the document to local document tools instead of inspecting this internal target.", true);
|
|
4584
4642
|
for (const child of tree.childFrames ?? [])
|
|
4585
4643
|
check(child);
|
|
4586
4644
|
};
|
|
@@ -4591,13 +4649,9 @@ class NativeRuntime {
|
|
|
4591
4649
|
}
|
|
4592
4650
|
async resolveTarget(tabId, scope, frames = []) {
|
|
4593
4651
|
this.validateScope(scope);
|
|
4594
|
-
const page = this.
|
|
4652
|
+
const page = this.claimPage(tabId, scope);
|
|
4595
4653
|
await this.track(page);
|
|
4596
4654
|
await this.assertPageDeep(page);
|
|
4597
|
-
const owner = this.owners.get(tabId);
|
|
4598
|
-
if (owner && scopeKey(owner) !== scopeKey(scope))
|
|
4599
|
-
throw new Error("Tab belongs to another runtime scope");
|
|
4600
|
-
this.owners.set(tabId, { ...scope });
|
|
4601
4655
|
let frame = page.mainFrame();
|
|
4602
4656
|
for (const selector of frames) {
|
|
4603
4657
|
const locator = frame.locator(selector);
|
|
@@ -4650,9 +4704,43 @@ class NativeRuntime {
|
|
|
4650
4704
|
events.diagnosticsSuppressed = false;
|
|
4651
4705
|
}
|
|
4652
4706
|
}
|
|
4707
|
+
claimPage(tabId, scope) {
|
|
4708
|
+
this.validateScope(scope);
|
|
4709
|
+
let page;
|
|
4710
|
+
try {
|
|
4711
|
+
page = this.engine.page(tabId);
|
|
4712
|
+
} catch {
|
|
4713
|
+
throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
|
|
4714
|
+
}
|
|
4715
|
+
const owner = this.owners.get(tabId);
|
|
4716
|
+
if (owner && scopeKey(owner) !== scopeKey(scope))
|
|
4717
|
+
throw new RuntimeFault("scope_rejected", "Use a tab owned by this session.", true);
|
|
4718
|
+
this.owners.set(tabId, { ...scope });
|
|
4719
|
+
return page;
|
|
4720
|
+
}
|
|
4721
|
+
targetCapabilities(tabId, scope) {
|
|
4722
|
+
const page = this.claimPage(tabId, scope);
|
|
4723
|
+
const internal = page.frames().some((f) => !this.allowURL(f.url()));
|
|
4724
|
+
const pdf = page.frames().some((f) => f.url().startsWith("chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai")) || /\.pdf(?:[?#]|$)/i.test(page.url());
|
|
4725
|
+
return { targetKind: internal ? pdf ? "pdf_viewer" : "internal" : pdf ? "possible_pdf" : "web", pageToolsSupported: !internal, pdfDetected: pdf, requiresDocumentTools: internal || pdf, retrieval: { tool: "browser_create_download", source: "browser_list_downloads" }, recovery: internal || pdf ? "Download the original document using the website UI, then browser_list_downloads and browser_create_download. Alternatively fetch an authorized document from a supported same-origin web page into r5dCreateArtifact; do not forward cookies or decode PDF in page scripts." : null };
|
|
4726
|
+
}
|
|
4727
|
+
async closeBlockedTab(tabId, scope, operationId) {
|
|
4728
|
+
this.validateScope(scope);
|
|
4729
|
+
const owner = this.owners.get(tabId);
|
|
4730
|
+
if (!owner || scopeKey(owner) !== scopeKey(scope))
|
|
4731
|
+
throw new RuntimeFault("scope_rejected", "Recovery is limited to the blocked operation owner.", true);
|
|
4732
|
+
const page = this.engine.page(tabId);
|
|
4733
|
+
await page.close({ runBeforeUnload: false });
|
|
4734
|
+
if (!page.isClosed())
|
|
4735
|
+
throw new Error("Tab closure unconfirmed");
|
|
4736
|
+
this.operations.get(operationId)?.abort(new Error("Blocked target closed by approved recovery"));
|
|
4737
|
+
return { closed: true };
|
|
4738
|
+
}
|
|
4653
4739
|
async execute(op, args, scope, operationId) {
|
|
4654
|
-
if (op === "session_end")
|
|
4655
|
-
|
|
4740
|
+
if (op === "session_end") {
|
|
4741
|
+
await this.endSession(scope);
|
|
4742
|
+
return { ended: true };
|
|
4743
|
+
}
|
|
4656
4744
|
const controller = new AbortController, key = scopeKey(scope);
|
|
4657
4745
|
let set = this.controllers.get(key);
|
|
4658
4746
|
if (!set) {
|
|
@@ -4660,9 +4748,11 @@ class NativeRuntime {
|
|
|
4660
4748
|
this.controllers.set(key, set);
|
|
4661
4749
|
}
|
|
4662
4750
|
set.add(controller);
|
|
4751
|
+
this.operations.set(operationId, controller);
|
|
4663
4752
|
try {
|
|
4664
4753
|
return await withCancellation(controller.signal, () => this.executeInner(op, args, scope, operationId));
|
|
4665
4754
|
} finally {
|
|
4755
|
+
this.operations.delete(operationId);
|
|
4666
4756
|
set.delete(controller);
|
|
4667
4757
|
if (!set.size)
|
|
4668
4758
|
this.controllers.delete(key);
|
|
@@ -4672,9 +4762,18 @@ class NativeRuntime {
|
|
|
4672
4762
|
await this.hooks;
|
|
4673
4763
|
this.validateScope(scope);
|
|
4674
4764
|
if (args.url !== undefined && !this.allowURL(String(args.url)))
|
|
4675
|
-
throw new
|
|
4676
|
-
if (typeof args.tabId === "string")
|
|
4677
|
-
|
|
4765
|
+
throw new RuntimeFault("unsupported_target", "Navigate only to authorized HTTP(S) pages or about:blank.", true);
|
|
4766
|
+
if (op === "capabilities" && typeof args.tabId === "string") {
|
|
4767
|
+
const target2 = this.targetCapabilities(args.tabId, scope);
|
|
4768
|
+
if (!target2.pageToolsSupported || target2.pdfDetected)
|
|
4769
|
+
return { tabId: args.tabId, ...target2, observation: target2.pageToolsSupported ? null : false, screenshot: { supported: target2.pageToolsSupported ? null : false }, runJs: { supported: target2.pageToolsSupported ? null : false }, export: { supported: target2.pageToolsSupported ? null : false }, capabilityProbe: "metadata_only" };
|
|
4770
|
+
}
|
|
4771
|
+
if (typeof args.tabId === "string") {
|
|
4772
|
+
if (op === "close_tab")
|
|
4773
|
+
this.claimPage(args.tabId, scope);
|
|
4774
|
+
else
|
|
4775
|
+
await this.resolveTarget(args.tabId, scope);
|
|
4776
|
+
}
|
|
4678
4777
|
if (op === "batch" && Array.isArray(args.steps))
|
|
4679
4778
|
for (const step of args.steps) {
|
|
4680
4779
|
if (step.input?.url !== undefined && !this.allowURL(String(step.input.url)))
|
|
@@ -4705,14 +4804,22 @@ class NativeRuntime {
|
|
|
4705
4804
|
const tabs = await this.engine.listTabs();
|
|
4706
4805
|
return { tabs: tabs.filter((t) => this.allowURL(t.url) && (!this.owners.has(t.tabId) || scopeKey(this.owners.get(t.tabId)) === scopeKey(scope))) };
|
|
4707
4806
|
}
|
|
4708
|
-
|
|
4709
|
-
|
|
4710
|
-
|
|
4711
|
-
|
|
4712
|
-
|
|
4713
|
-
|
|
4714
|
-
|
|
4715
|
-
|
|
4807
|
+
try {
|
|
4808
|
+
const result = await this.engine.execute(op, args, { sessionId: scopeKey(scope), operationId });
|
|
4809
|
+
if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
|
|
4810
|
+
throw new Error("Scope ended during execution; outcome uncertain");
|
|
4811
|
+
if (typeof args.tabId === "string" && op !== "close_tab")
|
|
4812
|
+
await this.assertPageDeep(this.engine.page(args.tabId));
|
|
4813
|
+
if (op === "open_tab" && typeof result?.tab?.tabId === "string")
|
|
4814
|
+
this.owners.set(result.tab.tabId, { ...scope });
|
|
4815
|
+
if (op === "capabilities" && typeof args.tabId === "string")
|
|
4816
|
+
return { ...result, ...this.targetCapabilities(args.tabId, scope) };
|
|
4817
|
+
return result;
|
|
4818
|
+
} catch (error) {
|
|
4819
|
+
if (error instanceof RuntimeFault)
|
|
4820
|
+
throw new RuntimeFault(error.code, error.recovery, false);
|
|
4821
|
+
throw error;
|
|
4822
|
+
}
|
|
4716
4823
|
}
|
|
4717
4824
|
async endSession(scope) {
|
|
4718
4825
|
const key = scopeKey(scope);
|
|
@@ -4729,9 +4836,9 @@ class NativeRuntime {
|
|
|
4729
4836
|
}
|
|
4730
4837
|
async shutdown() {
|
|
4731
4838
|
await this.disconnect();
|
|
4732
|
-
for (const
|
|
4839
|
+
for (const tabId of this.generations.keys())
|
|
4733
4840
|
for (const p of this.plugins)
|
|
4734
|
-
await p.onTabClose?.(
|
|
4841
|
+
await p.onTabClose?.(tabId);
|
|
4735
4842
|
await this.hooks;
|
|
4736
4843
|
this.engine.closeUploads();
|
|
4737
4844
|
}
|
|
@@ -4754,7 +4861,7 @@ class NativeRuntime {
|
|
|
4754
4861
|
|
|
4755
4862
|
// cli/src/runtime/relay.ts
|
|
4756
4863
|
import WebSocket2 from "ws";
|
|
4757
|
-
import { createHash as createHash5, randomUUID as
|
|
4864
|
+
import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
|
|
4758
4865
|
import fs9 from "node:fs/promises";
|
|
4759
4866
|
import path8 from "node:path";
|
|
4760
4867
|
|
|
@@ -5134,6 +5241,7 @@ class NativeLiveProducer {
|
|
|
5134
5241
|
}
|
|
5135
5242
|
|
|
5136
5243
|
// cli/src/runtime/relay.ts
|
|
5244
|
+
var sameScope3 = (a, b) => a.browserId === b.browserId && a.tokenId === b.tokenId && a.sessionKey === b.sessionKey && a.instanceId === b.instanceId;
|
|
5137
5245
|
var LIMIT = 2 * 1024 * 1024;
|
|
5138
5246
|
function wireResult(op, value) {
|
|
5139
5247
|
if (!value || typeof value !== "object")
|
|
@@ -5177,7 +5285,21 @@ class Relay {
|
|
|
5177
5285
|
stopping = false;
|
|
5178
5286
|
live;
|
|
5179
5287
|
seen = new Set;
|
|
5180
|
-
|
|
5288
|
+
active;
|
|
5289
|
+
recent = [];
|
|
5290
|
+
health(scope) {
|
|
5291
|
+
const active = this.active, own = active && (!scope || sameScope3(active.scope, scope));
|
|
5292
|
+
return { state: this.state, paused: this.paused, queueDepth: 0, admission: active ? "blocked" : "ready", quarantined: !!active && (active.timedOut || active.interrupted), operation: own ? { operationId: active.id, operation: active.op, startedAt: active.startedAt, deadlineAt: active.deadlineAt, callerDeadline: active.timedOut ? "expired" : "pending", executionState: active.settled ? "settled_after_interruption" : "unresolved", cancellationConfirmed: false, recoveryAvailable: !!active.tabId && !active.recovering } : active ? { ownedByAnotherScope: true } : null, recent: this.recent.filter((r) => !scope || sameScope3(r.scope, scope)).map((r) => r.result) };
|
|
5293
|
+
}
|
|
5294
|
+
interrupt() {
|
|
5295
|
+
if (this.active)
|
|
5296
|
+
this.active.interrupted = true;
|
|
5297
|
+
}
|
|
5298
|
+
remember(active, result) {
|
|
5299
|
+
this.recent.push({ scope: active.scope, result: { operationId: active.id, ...result } });
|
|
5300
|
+
if (this.recent.length > 32)
|
|
5301
|
+
this.recent.shift();
|
|
5302
|
+
}
|
|
5181
5303
|
state = "disconnected";
|
|
5182
5304
|
paused = false;
|
|
5183
5305
|
constructor(runtime, server, token, previewDirectory, liveEnabled = false) {
|
|
@@ -5210,6 +5332,7 @@ class Relay {
|
|
|
5210
5332
|
await new Promise((resolve2, reject) => {
|
|
5211
5333
|
socket.once("error", reject);
|
|
5212
5334
|
socket.once("close", () => {
|
|
5335
|
+
this.interrupt();
|
|
5213
5336
|
clearInterval(heartbeat);
|
|
5214
5337
|
resolve2();
|
|
5215
5338
|
});
|
|
@@ -5220,7 +5343,7 @@ class Relay {
|
|
|
5220
5343
|
heartbeat.unref();
|
|
5221
5344
|
socket.once("open", () => {
|
|
5222
5345
|
this.state = "authenticating";
|
|
5223
|
-
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.
|
|
5346
|
+
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.13", instanceId: this.runtime.instanceId, operations: [...BROWSER_OPERATIONS, ...this.runtime.plugins.flatMap((p) => p.operations), "session_end", "release_tab", "runtime_health", "runtime_recover"], capabilities: ["runtime-quarantine.v1", "binary-artifacts.v1", "browser-controls.v1", "screenshot-ids.v1", "webmcp.page-context.v1", "clipboard.native.v1", "native-transfers.v1", "secrets.v1", "forwarding.v1", "live-view.v1"], liveView: { enabled: this.liveEnabled } } }));
|
|
5224
5347
|
});
|
|
5225
5348
|
socket.on("message", (bytes, binary) => {
|
|
5226
5349
|
if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
|
|
@@ -5240,7 +5363,7 @@ class Relay {
|
|
|
5240
5363
|
return;
|
|
5241
5364
|
}
|
|
5242
5365
|
this.state = "initializing";
|
|
5243
|
-
|
|
5366
|
+
(async () => {
|
|
5244
5367
|
await this.runtime.reconnect(message.browserId);
|
|
5245
5368
|
this.state = "connected";
|
|
5246
5369
|
this.live = new NativeLiveProducer({ mediaUrl: mediaURL(this.server), token: this.token, instanceId: this.runtime.instanceId, credentialEpoch: message.credentialEpoch, context: this.runtime.context, authorizePage: async (page) => {
|
|
@@ -5263,14 +5386,16 @@ class Relay {
|
|
|
5263
5386
|
} });
|
|
5264
5387
|
this.live.setEnabled(this.liveEnabled);
|
|
5265
5388
|
console.error("Browser MCP connected (dedicated Chrome; local pause available)");
|
|
5266
|
-
}).catch(() => socket.close(1011));
|
|
5389
|
+
})().catch(() => socket.close(1011));
|
|
5267
5390
|
} else if (message.type === "watch") {
|
|
5268
5391
|
this.live?.onWatch(message).catch(() => {});
|
|
5269
5392
|
} else if (message.type === "ping")
|
|
5270
5393
|
socket.send(JSON.stringify({ type: "pong" }));
|
|
5271
5394
|
else if (message.type === "command") {
|
|
5272
|
-
if (
|
|
5395
|
+
if (this.state !== "connected" || this.paused) {
|
|
5396
|
+
socket.send(JSON.stringify({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: this.paused ? "runtime_paused" : "runtime_initializing", message: "Runtime is paused or initializing; no action was dispatched." }, result: { executionState: "not_started", retrySafe: true, recovery: "Use local browser-mcp browser status for independent health. Resume locally if paused; retry health after the runtime connects." } }));
|
|
5273
5397
|
return;
|
|
5398
|
+
}
|
|
5274
5399
|
let admittedEpoch;
|
|
5275
5400
|
try {
|
|
5276
5401
|
admittedEpoch = this.runtime.scopeEpoch(message.scope);
|
|
@@ -5278,11 +5403,7 @@ class Relay {
|
|
|
5278
5403
|
socket.send(JSON.stringify({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: "invalid_scope", message: "Scope rejected at admission" } }));
|
|
5279
5404
|
return;
|
|
5280
5405
|
}
|
|
5281
|
-
|
|
5282
|
-
this.command(message, socket, admittedEpoch);
|
|
5283
|
-
return;
|
|
5284
|
-
}
|
|
5285
|
-
this.queue = this.queue.then(() => this.command(message, socket, admittedEpoch)).catch(() => {});
|
|
5406
|
+
this.command(message, socket, admittedEpoch).catch(() => socket.close(1011));
|
|
5286
5407
|
}
|
|
5287
5408
|
});
|
|
5288
5409
|
});
|
|
@@ -5315,65 +5436,135 @@ class Relay {
|
|
|
5315
5436
|
return;
|
|
5316
5437
|
}
|
|
5317
5438
|
this.seen.add(message.id);
|
|
5318
|
-
|
|
5319
|
-
|
|
5320
|
-
|
|
5321
|
-
|
|
5322
|
-
|
|
5323
|
-
|
|
5324
|
-
|
|
5325
|
-
|
|
5326
|
-
|
|
5327
|
-
|
|
5328
|
-
|
|
5329
|
-
|
|
5330
|
-
|
|
5331
|
-
|
|
5332
|
-
|
|
5333
|
-
|
|
5334
|
-
|
|
5335
|
-
|
|
5336
|
-
|
|
5337
|
-
|
|
5338
|
-
|
|
5339
|
-
|
|
5340
|
-
|
|
5341
|
-
|
|
5342
|
-
|
|
5343
|
-
|
|
5344
|
-
|
|
5345
|
-
|
|
5346
|
-
|
|
5347
|
-
|
|
5348
|
-
|
|
5349
|
-
|
|
5350
|
-
|
|
5439
|
+
if (message.op === "runtime_health") {
|
|
5440
|
+
send({ type: "result", id: message.id, ok: true, result: this.health(message.scope), outcome: "completed" });
|
|
5441
|
+
return;
|
|
5442
|
+
}
|
|
5443
|
+
if (message.op === "runtime_recover") {
|
|
5444
|
+
await this.recover(message, send);
|
|
5445
|
+
return;
|
|
5446
|
+
}
|
|
5447
|
+
if (message.op === "session_end") {
|
|
5448
|
+
if (this.active && sameScope3(this.active.scope, message.scope))
|
|
5449
|
+
this.interrupt();
|
|
5450
|
+
await this.runtime.endSession(message.scope);
|
|
5451
|
+
send({ type: "result", id: message.id, ok: true, result: { ended: true }, outcome: "completed" });
|
|
5452
|
+
return;
|
|
5453
|
+
}
|
|
5454
|
+
if (this.active) {
|
|
5455
|
+
send({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: "blocked_by_prior_operation", message: "A prior operation is unresolved or quarantined. No action was queued or dispatched." }, result: { operationId: message.id, blockingOperationId: sameScope3(this.active.scope, message.scope) ? this.active.id : undefined, retrySafe: true, executionState: "not_started", recovery: "Call browser_runtime_health. Wait for confirmed settlement or request explicit user-approved recovery; never replay the prior mutation." } });
|
|
5456
|
+
return;
|
|
5457
|
+
}
|
|
5458
|
+
let finish;
|
|
5459
|
+
const active = { id: message.id, scope: { ...message.scope }, tabId: typeof message.args.tabId === "string" ? message.args.tabId : undefined, op: message.op, startedAt: Date.now(), deadlineAt: Date.now() + Math.max(500, Math.min(120000, Number(message.timeoutMs) || 30000)), timedOut: false, interrupted: false, settled: false, recovering: false, done: new Promise((resolve2) => {
|
|
5460
|
+
finish = resolve2;
|
|
5461
|
+
}) };
|
|
5462
|
+
this.active = active;
|
|
5463
|
+
let stage = "execute", timer;
|
|
5464
|
+
const expired = new Promise((resolve2) => {
|
|
5465
|
+
timer = setTimeout(() => {
|
|
5466
|
+
active.timedOut = true;
|
|
5467
|
+
send({ type: "result", id: message.id, ok: false, outcome: OBSERVATION_OPERATIONS.has(message.op) ? "failed" : "unknown", error: { code: "runtime_timeout", message: "Caller deadline expired. Execution is not confirmed cancelled; do not replay a mutation." }, result: { operationId: active.id, diagnosticId: active.id, category: "execution_timeout", stage, callerDeadline: "expired", executionState: "unresolved", quarantined: true, cancellationConfirmed: false, retrySafe: false, recovery: "Use browser_runtime_health independently. Wait for late settlement or, with explicit user approval, browser_runtime_recover to close this blocked tab." } });
|
|
5468
|
+
console.error(JSON.stringify({ event: "runtime_deadline", diagnosticId: active.id, operation: active.op, stage, executionState: "unresolved" }));
|
|
5469
|
+
resolve2();
|
|
5470
|
+
}, Math.max(1, active.deadlineAt - Date.now()));
|
|
5471
|
+
});
|
|
5472
|
+
const task = (async () => {
|
|
5473
|
+
try {
|
|
5474
|
+
const result = await this.runtime.execute(message.op, message.args, message.scope, message.id);
|
|
5475
|
+
if (active.timedOut || active.interrupted || this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
|
|
5476
|
+
return;
|
|
5477
|
+
this.runtime.validateScope(message.scope);
|
|
5478
|
+
if (typeof message.args.tabId === "string") {
|
|
5479
|
+
this.live?.followTab(message.args.tabId);
|
|
5480
|
+
this.live?.emitCursor({ type: "action", phase: "end", ok: true, at: Date.now(), runtimeTabId: message.args.tabId, tool: message.op });
|
|
5481
|
+
}
|
|
5482
|
+
stage = "transfer";
|
|
5483
|
+
const blobs = [];
|
|
5484
|
+
if (result?.base64 && message.op === "screenshot") {
|
|
5485
|
+
const bytes = Buffer.from(result.base64, "base64");
|
|
5486
|
+
delete result.base64;
|
|
5487
|
+
blobs.push(await this.upload(bytes, "screenshot", "screenshot.png", "image/png"));
|
|
5351
5488
|
}
|
|
5352
|
-
|
|
5353
|
-
|
|
5354
|
-
|
|
5355
|
-
|
|
5489
|
+
if (message.op === "export_page" && Array.isArray(result?.exports))
|
|
5490
|
+
for (const item of result.exports) {
|
|
5491
|
+
const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
|
|
5492
|
+
if (path8.basename(filename) !== filename)
|
|
5493
|
+
throw new Error("Invalid export file");
|
|
5494
|
+
const filenamePath = path8.join(this.previewDirectory, filename);
|
|
5495
|
+
const stat = await fs9.lstat(filenamePath);
|
|
5496
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
|
|
5497
|
+
throw new Error("Invalid export file");
|
|
5498
|
+
blobs.push(await this.upload(await fs9.readFile(filenamePath), "export", item.filename, item.mimeType));
|
|
5499
|
+
await fs9.unlink(filenamePath);
|
|
5500
|
+
delete item.downloadId;
|
|
5501
|
+
}
|
|
5502
|
+
if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
|
|
5503
|
+
for (const artifact2 of result.artifacts)
|
|
5504
|
+
blobs.push(await this.upload(artifact2.base64 !== undefined ? Buffer.from(artifact2.base64, "base64") : Buffer.from(artifact2.content), "artifact", path8.basename(artifact2.filename), artifact2.mimeType ?? "text/plain"));
|
|
5505
|
+
result.artifacts = result.artifacts.map((a) => ({ filename: path8.basename(a.filename) }));
|
|
5506
|
+
}
|
|
5507
|
+
if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
|
|
5508
|
+
throw new Error("Result budget exceeded");
|
|
5509
|
+
if (!active.timedOut && !active.interrupted)
|
|
5510
|
+
send({ type: "result", id: message.id, ok: true, result: wireResult(message.op, result), blobs, outcome: result?.status === "unknown" ? "unknown" : "completed" });
|
|
5511
|
+
} catch (error) {
|
|
5512
|
+
const failure = failureFor(error, message.op, message.id, stage);
|
|
5513
|
+
if (!active.timedOut && !active.interrupted)
|
|
5514
|
+
send({ type: "result", id: message.id, ok: false, ...failure });
|
|
5515
|
+
} finally {
|
|
5516
|
+
clearTimeout(timer);
|
|
5517
|
+
active.settled = true;
|
|
5518
|
+
finish();
|
|
5519
|
+
if (active.timedOut || active.interrupted)
|
|
5520
|
+
this.remember(active, { callerDeadline: active.timedOut ? "expired" : "interrupted", executionState: active.interrupted ? "settled_after_interruption" : "settled_late", outcome: "unknown", retrySafe: false, cancellationConfirmed: false });
|
|
5521
|
+
if (this.active === active && !active.interrupted && !active.recovering)
|
|
5522
|
+
this.active = undefined;
|
|
5356
5523
|
}
|
|
5357
|
-
|
|
5358
|
-
|
|
5359
|
-
|
|
5524
|
+
})();
|
|
5525
|
+
await Promise.race([task, expired]);
|
|
5526
|
+
}
|
|
5527
|
+
async recover(message, send) {
|
|
5528
|
+
const active = this.active;
|
|
5529
|
+
const reject = (code2, messageText) => send({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: code2, message: messageText } });
|
|
5530
|
+
if (!active || active.id !== message.args.operationId || !sameScope3(active.scope, message.scope))
|
|
5531
|
+
return reject("recovery_unavailable", "No matching blocked operation belongs to this session.");
|
|
5532
|
+
if (!(active.timedOut || active.interrupted) || !active.tabId || active.recovering)
|
|
5533
|
+
return reject("recovery_unavailable", "Recovery requires a quarantined tab operation, with no recovery already running.");
|
|
5534
|
+
if (message.args.method !== "close_tab" || typeof message.args.approval !== "string" || !message.args.approval.trim())
|
|
5535
|
+
return reject("approval_required", "Explicit user approval to close the blocked tab is required. This may discard unsaved page state; profile data is retained.");
|
|
5536
|
+
active.recovering = true;
|
|
5537
|
+
const work = (async () => {
|
|
5538
|
+
await this.runtime.closeBlockedTab(active.tabId, message.scope, active.id);
|
|
5539
|
+
await active.done;
|
|
5540
|
+
this.remember(active, { executionState: "target_closed", terminationConfirmed: true, outcome: "unknown", retrySafe: false, replayed: false });
|
|
5541
|
+
if (this.active === active)
|
|
5542
|
+
this.active = undefined;
|
|
5543
|
+
return { recovered: true, operationId: active.id, executionState: "target_closed", terminationConfirmed: true, originalOutcome: "unknown", retrySafe: false, replayed: false, profilePreserved: true };
|
|
5544
|
+
})();
|
|
5545
|
+
let timer;
|
|
5546
|
+
try {
|
|
5547
|
+
const result = await Promise.race([work, new Promise((_, reject2) => {
|
|
5548
|
+
timer = setTimeout(() => reject2(new Error("Recovery timeout")), 5000);
|
|
5549
|
+
})]);
|
|
5550
|
+
send({ type: "result", id: message.id, ok: true, result, outcome: "completed" });
|
|
5360
5551
|
} catch {
|
|
5361
|
-
|
|
5362
|
-
send({ type: "result", id: message.id, ok: false, outcome: "unknown", error: { code: "runtime_operation_failed", message: "Operation failed or became uncertain. Observe the page before retrying. Page exception details are suppressed." } });
|
|
5552
|
+
send({ type: "result", id: message.id, ok: false, outcome: "unknown", error: { code: "recovery_uncertain", message: "Recovery completion is unconfirmed. Do not repeat it; query browser_runtime_health or ask the user to stop and restart this dedicated runtime." }, result: { operationId: active.id, retrySafe: false, cancellationConfirmed: false } });
|
|
5363
5553
|
} finally {
|
|
5364
|
-
clearTimeout(
|
|
5554
|
+
clearTimeout(timer);
|
|
5365
5555
|
}
|
|
5366
5556
|
}
|
|
5367
5557
|
async upload(bytes, role, name, mimeType) {
|
|
5368
5558
|
if (bytes.length > 20 * 1024 * 1024)
|
|
5369
5559
|
throw new Error("Preview exceeds 20 MiB");
|
|
5370
|
-
const blobId =
|
|
5560
|
+
const blobId = randomUUID5(), sha256 = createHash5("sha256").update(bytes).digest("hex");
|
|
5371
5561
|
const response = await fetch(new URL(`/api/runtime/blobs/${blobId}`, this.server), { method: "PUT", headers: { Authorization: `Bearer ${this.token}`, "Content-Type": "application/octet-stream", "X-Runtime-Instance": this.runtime.instanceId, "X-Content-SHA256": sha256 }, body: bytes, redirect: "error", signal: AbortSignal.timeout(30000) });
|
|
5372
5562
|
if (!response.ok)
|
|
5373
5563
|
throw new Error("Preview upload failed");
|
|
5374
5564
|
return { blobId, role, name, mimeType, size: bytes.length, sha256 };
|
|
5375
5565
|
}
|
|
5376
5566
|
async pause() {
|
|
5567
|
+
this.interrupt();
|
|
5377
5568
|
this.paused = true;
|
|
5378
5569
|
this.state = "paused";
|
|
5379
5570
|
this.socket?.close();
|
|
@@ -5384,6 +5575,7 @@ class Relay {
|
|
|
5384
5575
|
this.paused = false;
|
|
5385
5576
|
}
|
|
5386
5577
|
async stop() {
|
|
5578
|
+
this.interrupt();
|
|
5387
5579
|
this.stopping = true;
|
|
5388
5580
|
this.socket?.close();
|
|
5389
5581
|
await this.live?.stop();
|
|
@@ -5394,13 +5586,13 @@ class Relay {
|
|
|
5394
5586
|
// cli/src/data/index.ts
|
|
5395
5587
|
import { mkdir as mkdir2, open as open2, rename, unlink as unlink2, rmdir as rmdir2, chmod, lstat as lstat2 } from "node:fs/promises";
|
|
5396
5588
|
import { createReadStream, createWriteStream } from "node:fs";
|
|
5397
|
-
import { randomUUID as
|
|
5589
|
+
import { randomUUID as randomUUID7, createHash as createHash6 } from "node:crypto";
|
|
5398
5590
|
import { join as join2, basename } from "node:path";
|
|
5399
5591
|
import { Readable, Transform } from "node:stream";
|
|
5400
5592
|
import { pipeline } from "node:stream/promises";
|
|
5401
5593
|
|
|
5402
5594
|
// cli/src/data/vault.ts
|
|
5403
|
-
import { randomUUID as
|
|
5595
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
5404
5596
|
class SecretVault {
|
|
5405
5597
|
access;
|
|
5406
5598
|
entries = new Map;
|
|
@@ -5467,7 +5659,7 @@ class SecretVault {
|
|
|
5467
5659
|
}
|
|
5468
5660
|
if (!Object.keys(clean).length || Object.keys(clean).length > LIMITS.count || total + 1024 > LIMITS.secret)
|
|
5469
5661
|
throw new Error("Vault quota exceeded");
|
|
5470
|
-
const entry = { id:
|
|
5662
|
+
const entry = { id: randomUUID6(), scope: { ...scope }, tabId, generation: target2.generation, origin: new URL(target2.frame.url()).origin, expiresAt: Date.now() + LIMITS.ttl, values: clean };
|
|
5471
5663
|
this.entries.set(entry.id, entry);
|
|
5472
5664
|
return this.metadata(entry);
|
|
5473
5665
|
} catch {
|
|
@@ -5530,7 +5722,7 @@ async function createDataPlugin(access, options) {
|
|
|
5530
5722
|
const resources = new Map, owned = new Set, ownedDirs = new Set, vault = new SecretVault(access);
|
|
5531
5723
|
let stopped = false;
|
|
5532
5724
|
function meta(r) {
|
|
5533
|
-
return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: r.size, name: r.name, state: r.state, sha256: r.hash, expiresAt: r.expiresAt };
|
|
5725
|
+
return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: r.size, name: r.name, state: r.state, sha256: r.hash, expiresAt: r.expiresAt, ...r.purpose === "download" ? { downloadId: r.id, mimeType: "application/octet-stream", sourceKind: "download", readiness: r.state === "ready" ? "ready" : "pending", retrieval: { tool: "browser_create_download", arguments: { downloadId: r.id } } } : {} };
|
|
5534
5726
|
}
|
|
5535
5727
|
function get(scope, id) {
|
|
5536
5728
|
const r = resources.get(String(id));
|
|
@@ -5545,7 +5737,7 @@ async function createDataPlugin(access, options) {
|
|
|
5545
5737
|
}
|
|
5546
5738
|
function create(scope, purpose, size, name) {
|
|
5547
5739
|
reserve(scope, size);
|
|
5548
|
-
const r = { id:
|
|
5740
|
+
const r = { id: randomUUID7(), scope: { ...scope }, purpose, size, name: safeName(name), state: "prepared", abort: new AbortController, expiresAt: Date.now() + LIMITS.ttl };
|
|
5549
5741
|
resources.set(r.id, r);
|
|
5550
5742
|
return r;
|
|
5551
5743
|
}
|
|
@@ -5624,7 +5816,8 @@ async function createDataPlugin(access, options) {
|
|
|
5624
5816
|
r.state = "ready";
|
|
5625
5817
|
}
|
|
5626
5818
|
} catch {
|
|
5627
|
-
r.state
|
|
5819
|
+
if (r.state !== "cancelled")
|
|
5820
|
+
r.state = "failed";
|
|
5628
5821
|
if (r.path && owned.has(r.path) && r.purpose === "upload") {
|
|
5629
5822
|
await unlink2(r.path).catch(() => {});
|
|
5630
5823
|
owned.delete(r.path);
|
|
@@ -5635,6 +5828,11 @@ async function createDataPlugin(access, options) {
|
|
|
5635
5828
|
r.bytes?.fill(0);
|
|
5636
5829
|
r.bytes = undefined;
|
|
5637
5830
|
}
|
|
5831
|
+
if (r.purpose === "download" && r.state !== "cancelled" && !stopped && resources.get(r.id) === r) {
|
|
5832
|
+
r.authorized = false;
|
|
5833
|
+
r.abort = new AbortController;
|
|
5834
|
+
r.state = "ready";
|
|
5835
|
+
}
|
|
5638
5836
|
}
|
|
5639
5837
|
}
|
|
5640
5838
|
let sweep = setInterval(() => {
|
|
@@ -5658,7 +5856,7 @@ async function createDataPlugin(access, options) {
|
|
|
5658
5856
|
return meta(r);
|
|
5659
5857
|
}
|
|
5660
5858
|
if (op === "create_download") {
|
|
5661
|
-
const r = get(scope, args.fileId ?? args.resourceId);
|
|
5859
|
+
const r = get(scope, args.downloadId ?? args.fileId ?? args.resourceId);
|
|
5662
5860
|
if (r.purpose !== "download" || r.state !== "ready")
|
|
5663
5861
|
throw new Error("Download unavailable");
|
|
5664
5862
|
return meta(r);
|
|
@@ -6084,7 +6282,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6084
6282
|
return;
|
|
6085
6283
|
} else if (cmd !== "status")
|
|
6086
6284
|
throw new Error("Invalid command");
|
|
6087
|
-
socket.end(JSON.stringify({
|
|
6285
|
+
socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.13", protocol: 3 }) + `
|
|
6088
6286
|
`);
|
|
6089
6287
|
})().catch(() => socket.destroy());
|
|
6090
6288
|
});
|
package/dist/main.js
CHANGED
|
@@ -8,7 +8,7 @@ var args = process.argv.slice(2);
|
|
|
8
8
|
var command = args.shift();
|
|
9
9
|
async function main() {
|
|
10
10
|
if (!command || command === "--help" || command === "help") {
|
|
11
|
-
console.log(`@ricsam/browser-mcp 0.3.
|
|
11
|
+
console.log(`@ricsam/browser-mcp 0.3.13
|
|
12
12
|
Usage: browser-mcp browser start|status|pause|resume|stop|recover [options]
|
|
13
13
|
browser-mcp files upload|download [options]
|
|
14
14
|
browser-mcp secrets export|exec [options]
|
|
@@ -18,15 +18,15 @@ Browser dependencies load only for browser commands. No automatic Chrome downloa
|
|
|
18
18
|
return;
|
|
19
19
|
}
|
|
20
20
|
if (command === "--version") {
|
|
21
|
-
console.log("0.3.
|
|
21
|
+
console.log("0.3.13");
|
|
22
22
|
return;
|
|
23
23
|
}
|
|
24
24
|
if (command === "browser")
|
|
25
|
-
return (await import("./chunk-
|
|
25
|
+
return (await import("./chunk-vw3wanmm.js")).runBrowser(args);
|
|
26
26
|
if (command === "files")
|
|
27
|
-
return (await import("./chunk-
|
|
27
|
+
return (await import("./chunk-6dypb4ga.js")).runFilesCommand(args);
|
|
28
28
|
if (command === "secrets")
|
|
29
|
-
return (await import("./chunk-
|
|
29
|
+
return (await import("./chunk-6kc5yfp5.js")).runSecretsCommand(args);
|
|
30
30
|
if (command === "forward")
|
|
31
31
|
return (await import("./chunk-swy0qtx0.js")).runForward(args);
|
|
32
32
|
throw new Error("Unknown command. Use --help.");
|