@ricsam/browser-mcp 0.3.12 → 0.3.14
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-847prxk6.js → chunk-g3yyvtve.js} +1 -1
- package/dist/{chunk-2hzkme2s.js → chunk-v483gpt7.js} +3 -2
- package/dist/{chunk-vfx8ntjb.js → chunk-y9x8c0rq.js} +433 -160
- package/dist/{chunk-xgk37h9a.js → chunk-zv1900tw.js} +10 -4
- 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
|
|
@@ -22,12 +22,13 @@ async function readCapability(path) {
|
|
|
22
22
|
}
|
|
23
23
|
const cap = JSON.parse(text);
|
|
24
24
|
const u = new URL(cap.url);
|
|
25
|
-
|
|
25
|
+
const link = cap.method === "GET" && /^\/api\/native-data\/[a-zA-Z0-9-]+\/download\/[A-Za-z0-9_-]{43}$/.test(u.pathname);
|
|
26
|
+
if (u.protocol !== "https:" || u.username || u.password || u.search || u.hash || !link && !/^\/api\/native-data\/[a-zA-Z0-9-]+$/.test(u.pathname) || !["GET", "PUT"].includes(cap.method) || !link && !/^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
27
|
throw new Error("Invalid capability");
|
|
27
28
|
return cap;
|
|
28
29
|
}
|
|
29
30
|
async function capabilityFetch(cap, body) {
|
|
30
|
-
const response = await fetch(cap.url, { method: cap.method, headers: { Authorization: cap.headers.Authorization }, body: body ? Readable.toWeb(body) : undefined, duplex: "half", redirect: "error", signal: AbortSignal.timeout(120000) });
|
|
31
|
+
const response = await fetch(cap.url, { method: cap.method, headers: cap.url.includes("/download/") ? {} : { Authorization: cap.headers.Authorization }, body: body ? Readable.toWeb(body) : undefined, duplex: "half", redirect: "error", signal: AbortSignal.timeout(120000) });
|
|
31
32
|
if (!response.ok)
|
|
32
33
|
throw new Error("Capability transfer failed; do not automatically retry");
|
|
33
34
|
return response;
|
|
@@ -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.14";
|
|
58
58
|
|
|
59
59
|
// cli/src/browser/chrome-diagnostics.ts
|
|
60
60
|
import { constants } from "node:fs";
|
|
@@ -2856,15 +2856,18 @@ class BrowserPageEvents {
|
|
|
2856
2856
|
this.pending = pending;
|
|
2857
2857
|
return await Promise.race([work, interrupted]);
|
|
2858
2858
|
}
|
|
2859
|
-
startDownload(download) {
|
|
2859
|
+
startDownload(download, downloadId) {
|
|
2860
2860
|
const event = this.record("download", {
|
|
2861
2861
|
state: "started",
|
|
2862
|
+
downloadId,
|
|
2863
|
+
resourceId: downloadId,
|
|
2864
|
+
readiness: "pending",
|
|
2862
2865
|
filename: download.suggestedFilename().slice(0, 255),
|
|
2863
2866
|
url: diagnosticUrl(download.url())
|
|
2864
2867
|
});
|
|
2865
2868
|
this.downloads.set(event.eventId, download);
|
|
2866
2869
|
return (data) => {
|
|
2867
|
-
this.record("download", { ...data, transferId: event.eventId, actionId: event.actionId, filename: event.filename });
|
|
2870
|
+
this.record("download", { ...data, downloadId, resourceId: downloadId, transferId: event.eventId, actionId: event.actionId, filename: event.filename });
|
|
2868
2871
|
this.downloads.delete(event.eventId);
|
|
2869
2872
|
};
|
|
2870
2873
|
}
|
|
@@ -3374,10 +3377,47 @@ class BrowserTabState {
|
|
|
3374
3377
|
}
|
|
3375
3378
|
}
|
|
3376
3379
|
|
|
3380
|
+
// cli/src/runtime/failures.ts
|
|
3381
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
3382
|
+
|
|
3383
|
+
class RuntimeFault extends Error {
|
|
3384
|
+
code;
|
|
3385
|
+
recovery;
|
|
3386
|
+
beforeDispatch;
|
|
3387
|
+
constructor(code2, recovery, beforeDispatch = false) {
|
|
3388
|
+
super(code2);
|
|
3389
|
+
this.code = code2;
|
|
3390
|
+
this.recovery = recovery;
|
|
3391
|
+
this.beforeDispatch = beforeDispatch;
|
|
3392
|
+
}
|
|
3393
|
+
}
|
|
3394
|
+
var OBSERVATION_OPERATIONS = new Set(["list_tabs", "list_downloads", "read_page", "screenshot", "wait_for", "capabilities", "inspect", "events", "diagnostics", "export_page", "webmcp_list", "runtime_health"]);
|
|
3395
|
+
var messages = {
|
|
3396
|
+
unsupported_target: "This target contains a privileged/internal document that browser page tools cannot inspect.",
|
|
3397
|
+
tab_closed: "The tab is closed or detached.",
|
|
3398
|
+
runtime_disconnected: "The runtime or browser connection ended.",
|
|
3399
|
+
context_destroyed: "The document execution context changed during the operation.",
|
|
3400
|
+
execution_timeout: "The browser operation exceeded its internal wait budget.",
|
|
3401
|
+
script_exception: "The script threw an exception. Page exception text and stack are suppressed.",
|
|
3402
|
+
transfer_failed: "The file transfer failed or its completion could not be confirmed.",
|
|
3403
|
+
scope_rejected: "Runtime scope or tab ownership was rejected.",
|
|
3404
|
+
runtime_operation_failed: "The browser operation failed; page-derived details are suppressed."
|
|
3405
|
+
};
|
|
3406
|
+
function failureFor(error, op, operationId, stage) {
|
|
3407
|
+
const text = error instanceof Error ? error.message : "";
|
|
3408
|
+
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";
|
|
3409
|
+
const observation = OBSERVATION_OPERATIONS.has(op);
|
|
3410
|
+
const outcome = error instanceof RuntimeFault && error.beforeDispatch ? "not_dispatched" : observation ? "failed" : "unknown";
|
|
3411
|
+
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.";
|
|
3412
|
+
const diagnosticId = randomUUID4();
|
|
3413
|
+
console.error(JSON.stringify({ event: "runtime_failure", diagnosticId, operationId, operation: op, stage, code: code2, outcome }));
|
|
3414
|
+
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 } };
|
|
3415
|
+
}
|
|
3416
|
+
|
|
3377
3417
|
// cli/src/browser/browser-runtime.ts
|
|
3378
3418
|
var MAX_DOWNLOAD_CHUNK_BYTES = 1024 * 1024;
|
|
3379
3419
|
var MAX_RUN_JS_RESULT_BYTES = 1024 * 1024;
|
|
3380
|
-
var MAX_RUN_JS_ARTIFACT_BYTES =
|
|
3420
|
+
var MAX_RUN_JS_ARTIFACT_BYTES = 20 * 1024 * 1024;
|
|
3381
3421
|
var MAX_RUN_JS_ARTIFACT_COUNT = 32;
|
|
3382
3422
|
var REF_ACTION_TIMEOUT_MS = 5000;
|
|
3383
3423
|
var NAVIGATION_TIMEOUT_MS = 20000;
|
|
@@ -3469,17 +3509,17 @@ class BrowserRuntime {
|
|
|
3469
3509
|
await this.setViewport(page, state.tabId, state.viewport);
|
|
3470
3510
|
}).catch(() => {}));
|
|
3471
3511
|
page.on("download", (download) => {
|
|
3472
|
-
const
|
|
3512
|
+
const downloadId = crypto.randomUUID();
|
|
3513
|
+
const finish = this.events.get(page).startDownload(download, downloadId);
|
|
3473
3514
|
const saving = Promise.resolve().then(async () => {
|
|
3474
3515
|
if (this.downloadHandler) {
|
|
3475
|
-
await this.downloadHandler(download, page);
|
|
3476
|
-
finish({ state: "completed" });
|
|
3516
|
+
finish(await this.downloadHandler(download, page, downloadId));
|
|
3477
3517
|
} else {
|
|
3478
3518
|
await download.cancel();
|
|
3479
|
-
finish({ state: "canceled" });
|
|
3519
|
+
finish({ state: "canceled", readiness: "unavailable", code: "capture_unavailable" });
|
|
3480
3520
|
}
|
|
3481
3521
|
}).catch((error) => {
|
|
3482
|
-
finish({ state: "failed", code: "
|
|
3522
|
+
finish({ state: "failed", readiness: "unavailable", code: "download_capture_failed", recovery: "Inspect browser_list_downloads or browser_transfer_status with resourceId equal to downloadId. Do not automatically replay the website action." });
|
|
3483
3523
|
process.stderr.write(`[r5d-browser] failed to save download
|
|
3484
3524
|
`);
|
|
3485
3525
|
}).finally(() => this.savingDownloads.delete(saving));
|
|
@@ -3714,7 +3754,7 @@ class BrowserRuntime {
|
|
|
3714
3754
|
if (action === "batch")
|
|
3715
3755
|
return await this.batch(input, execution);
|
|
3716
3756
|
const page = typeof input.tabId === "string" ? this.page(input.tabId) : undefined;
|
|
3717
|
-
if (page)
|
|
3757
|
+
if (page && action !== "close_tab")
|
|
3718
3758
|
await this.guardPage?.(page);
|
|
3719
3759
|
const events = page ? this.events.get(page) : undefined;
|
|
3720
3760
|
await events?.ready;
|
|
@@ -3807,20 +3847,23 @@ class BrowserRuntime {
|
|
|
3807
3847
|
results.push({ index, action: step.action, result });
|
|
3808
3848
|
if (result?.matched === false || result?.expected?.matched === false || result?.dispatch && result.dispatch.status !== "completed" || result?.code || result?.observation?.available === false)
|
|
3809
3849
|
return { results, stoppedAt: index, remaining: steps.length - index - 1, code: "batch_step_stopped", retrySafe: false };
|
|
3810
|
-
} catch {
|
|
3850
|
+
} catch (error) {
|
|
3851
|
+
const failure = failureFor(error, step.action, execution.operationId ?? crypto.randomUUID(), "batch_step");
|
|
3811
3852
|
return {
|
|
3812
|
-
results: [...results, { index, action: step.action, status: "unknown",
|
|
3853
|
+
results: [...results, { index, action: step.action, status: "unknown", ...failure.result, code: failure.error.code }],
|
|
3813
3854
|
stoppedAt: index,
|
|
3814
3855
|
remaining: steps.length - index - 1,
|
|
3856
|
+
status: "unknown",
|
|
3857
|
+
retrySafe: false,
|
|
3815
3858
|
code: "batch_outcome_uncertain",
|
|
3816
|
-
recovery:
|
|
3859
|
+
recovery: failure.result.recovery
|
|
3817
3860
|
};
|
|
3818
3861
|
}
|
|
3819
3862
|
}
|
|
3820
3863
|
return { results, completed: true, outcomeVerified: false };
|
|
3821
3864
|
}
|
|
3822
3865
|
async dispatch(action, input, execution) {
|
|
3823
|
-
if (typeof input.tabId === "string")
|
|
3866
|
+
if (typeof input.tabId === "string" && action !== "close_tab")
|
|
3824
3867
|
await this.guardPage?.(this.page(input.tabId));
|
|
3825
3868
|
if (action === "upload_abort") {
|
|
3826
3869
|
this.uploads.abort(input.uploadId, input.tabId);
|
|
@@ -4026,7 +4069,13 @@ class BrowserRuntime {
|
|
|
4026
4069
|
mimeType: file.mimeType
|
|
4027
4070
|
};
|
|
4028
4071
|
});
|
|
4029
|
-
return { tabId, exported: true, format: input.format, exports
|
|
4072
|
+
return { tabId, exported: true, format: input.format, exports, ...input.format === "pdf" ? {
|
|
4073
|
+
exportKind: "page_print",
|
|
4074
|
+
printMode: "css_print",
|
|
4075
|
+
contentCompleteness: "unverified",
|
|
4076
|
+
limitations: "PDF bytes were generated from the current page using Chrome print CSS, not a native document/message export. Nested scroll containers, lazy/unloaded content, collapsed sections, images, and application print styles may omit content; successful generation does not verify all source content.",
|
|
4077
|
+
guidance: "Inspect every PDF page for expected text and images. For an original message/document use the website's native download/export. If authorized, open the site's dedicated print view using its normal controls and export that tab; no print view, expansion, scrolling, or page modification is performed automatically."
|
|
4078
|
+
} : {} };
|
|
4030
4079
|
}
|
|
4031
4080
|
case "webmcp_list":
|
|
4032
4081
|
return { tabId, ...await this.webmcp.get(page).list() };
|
|
@@ -4379,32 +4428,43 @@ class BrowserRuntime {
|
|
|
4379
4428
|
evaluated = await page.evaluate(async ({ code: code2, maxBytes, maxCount }) => {
|
|
4380
4429
|
const artifacts = [];
|
|
4381
4430
|
let totalBytes = 0;
|
|
4382
|
-
const r5dCreateArtifact = (filename, content) => {
|
|
4431
|
+
const r5dCreateArtifact = (filename, content, mimeType) => {
|
|
4383
4432
|
if (typeof filename !== "string" || !filename.trim()) {
|
|
4384
4433
|
throw new TypeError("r5dCreateArtifact(filename, content): filename must be a non-empty string.");
|
|
4385
4434
|
}
|
|
4386
|
-
if (
|
|
4387
|
-
throw new TypeError(
|
|
4388
|
-
|
|
4435
|
+
if (filename.length > 255 || /[\\/\\\\\x00-\x1f]/.test(filename))
|
|
4436
|
+
throw new TypeError("Artifact filename must be a simple filename of at most 255 characters.");
|
|
4437
|
+
const text = typeof content === "string";
|
|
4438
|
+
const bytes = text ? new TextEncoder().encode(content) : content instanceof ArrayBuffer ? new Uint8Array(content) : content instanceof Uint8Array ? content : undefined;
|
|
4439
|
+
if (!bytes)
|
|
4440
|
+
throw new TypeError("Artifact content must be a string, Uint8Array or ArrayBuffer; use await response.arrayBuffer() for binary documents.");
|
|
4441
|
+
const mime = mimeType === undefined ? text ? "text/plain" : "application/octet-stream" : mimeType;
|
|
4442
|
+
if (typeof mime !== "string" || !/^[a-zA-Z0-9!#$&^_.+-]+\/[a-zA-Z0-9!#$&^_.+-]+$/.test(mime) || mime.length > 200)
|
|
4443
|
+
throw new TypeError("Artifact MIME must be a type/subtype without parameters.");
|
|
4389
4444
|
if (artifacts.length >= maxCount) {
|
|
4390
4445
|
throw new RangeError(`r5dCreateArtifact: at most ${maxCount} artifacts can be created in one browser_run_js call.`);
|
|
4391
4446
|
}
|
|
4392
|
-
totalBytes +=
|
|
4447
|
+
totalBytes += bytes.byteLength;
|
|
4393
4448
|
if (totalBytes > maxBytes) {
|
|
4394
4449
|
throw new RangeError(`r5dCreateArtifact: artifact content exceeded the ${maxBytes} byte budget for one browser_run_js call.`);
|
|
4395
4450
|
}
|
|
4396
|
-
|
|
4451
|
+
if (text)
|
|
4452
|
+
artifacts.push({ filename, content, mimeType: mime });
|
|
4453
|
+
else {
|
|
4454
|
+
let encoded = "";
|
|
4455
|
+
for (let offset = 0;offset < bytes.length; offset += 24576)
|
|
4456
|
+
encoded += btoa(String.fromCharCode(...bytes.subarray(offset, offset + 24576)));
|
|
4457
|
+
artifacts.push({ filename, base64: encoded, mimeType: mime });
|
|
4458
|
+
}
|
|
4397
4459
|
return filename;
|
|
4398
4460
|
};
|
|
4399
|
-
|
|
4461
|
+
try {
|
|
4462
|
+
const invoke = new Function("r5dCreateArtifact", `"use strict"; return (async () => {
|
|
4400
4463
|
${code2}
|
|
4401
4464
|
})()`);
|
|
4402
|
-
try {
|
|
4403
4465
|
return { result: await invoke(r5dCreateArtifact), artifacts };
|
|
4404
4466
|
} catch (error) {
|
|
4405
|
-
|
|
4406
|
-
throw error;
|
|
4407
|
-
return { artifacts, failure: error instanceof Error ? error.message : String(error) };
|
|
4467
|
+
return { artifacts, failure: "script_exception" };
|
|
4408
4468
|
}
|
|
4409
4469
|
}, { code: input.code, maxBytes: MAX_RUN_JS_ARTIFACT_BYTES, maxCount: MAX_RUN_JS_ARTIFACT_COUNT });
|
|
4410
4470
|
} catch (error) {
|
|
@@ -4414,15 +4474,19 @@ ${code2}
|
|
|
4414
4474
|
}
|
|
4415
4475
|
throw new Error(stripCallLog(message));
|
|
4416
4476
|
}
|
|
4477
|
+
if (evaluated.failure && !evaluated.artifacts.length)
|
|
4478
|
+
throw new RuntimeFault("script_exception", "Review the submitted script locally. Effects before the exception may have occurred; do not replay automatically.");
|
|
4417
4479
|
const serialized = JSON.stringify(evaluated.result);
|
|
4418
4480
|
if (serialized && Buffer.byteLength(serialized) > MAX_RUN_JS_RESULT_BYTES) {
|
|
4419
4481
|
throw new Error("Browser JavaScript result exceeded the 1 MiB limit.");
|
|
4420
4482
|
}
|
|
4483
|
+
const partialFailure = evaluated.failure ? failureFor(new Error("Script exception"), "run_js", execution.operationId ?? crypto.randomUUID(), "execute") : undefined;
|
|
4421
4484
|
return {
|
|
4422
4485
|
tabId,
|
|
4423
4486
|
result: evaluated.result,
|
|
4424
4487
|
artifacts: evaluated.artifacts,
|
|
4425
4488
|
failure: evaluated.failure,
|
|
4489
|
+
...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
4490
|
execution: "javascript_escape_hatch",
|
|
4427
4491
|
intent: input.intent,
|
|
4428
4492
|
reason: input.reason,
|
|
@@ -4481,6 +4545,7 @@ class NativeRuntime {
|
|
|
4481
4545
|
epochs = new Map;
|
|
4482
4546
|
controllers = new Map;
|
|
4483
4547
|
disconnected = false;
|
|
4548
|
+
operations = new Map;
|
|
4484
4549
|
hooks = Promise.resolve();
|
|
4485
4550
|
browserId;
|
|
4486
4551
|
constructor(context, instanceId, directory, serverOrigin) {
|
|
@@ -4488,7 +4553,7 @@ class NativeRuntime {
|
|
|
4488
4553
|
this.instanceId = instanceId;
|
|
4489
4554
|
this.serverOrigin = serverOrigin;
|
|
4490
4555
|
installCancellation(context);
|
|
4491
|
-
this.engine = new BrowserRuntime(context, directory, `${directory}.uploads`, (download, page) => this.download(download, page), (page) => this.assertPageDeep(page));
|
|
4556
|
+
this.engine = new BrowserRuntime(context, directory, `${directory}.uploads`, (download, page, downloadId) => this.download(download, page, downloadId), (page) => this.assertPageDeep(page));
|
|
4492
4557
|
context.on("page", (page) => {
|
|
4493
4558
|
this.track(page);
|
|
4494
4559
|
});
|
|
@@ -4529,19 +4594,18 @@ class NativeRuntime {
|
|
|
4529
4594
|
});
|
|
4530
4595
|
});
|
|
4531
4596
|
}
|
|
4532
|
-
async download(download, page) {
|
|
4597
|
+
async download(download, page, downloadId) {
|
|
4533
4598
|
const id = await this.engine.idFor(page), scope = this.owners.get(id);
|
|
4534
4599
|
if (!scope || this.disconnected) {
|
|
4535
4600
|
await download.cancel();
|
|
4536
|
-
return;
|
|
4601
|
+
return { state: "canceled", readiness: "unavailable", code: "download_scope_unavailable" };
|
|
4537
4602
|
}
|
|
4538
|
-
const
|
|
4539
|
-
if (!
|
|
4603
|
+
const handler = this.plugins.find((p) => p.onDownload);
|
|
4604
|
+
if (!handler) {
|
|
4540
4605
|
await download.cancel();
|
|
4541
|
-
return;
|
|
4606
|
+
return { state: "canceled", readiness: "unavailable", code: "capture_unavailable" };
|
|
4542
4607
|
}
|
|
4543
|
-
|
|
4544
|
-
await p.onDownload(download, id, scope, this.generations.get(id) ?? 0);
|
|
4608
|
+
return handler.onDownload(download, id, scope, this.generations.get(id) ?? 0, downloadId);
|
|
4545
4609
|
}
|
|
4546
4610
|
scopeEpoch(scope) {
|
|
4547
4611
|
this.validateScope(scope);
|
|
@@ -4562,8 +4626,10 @@ class NativeRuntime {
|
|
|
4562
4626
|
}
|
|
4563
4627
|
}
|
|
4564
4628
|
assertPage(page) {
|
|
4565
|
-
if (page.isClosed()
|
|
4566
|
-
throw new
|
|
4629
|
+
if (page.isClosed())
|
|
4630
|
+
throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
|
|
4631
|
+
if (page.frames().some((f) => !this.allowURL(f.url())))
|
|
4632
|
+
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
4633
|
}
|
|
4568
4634
|
async assertPageDeep(page) {
|
|
4569
4635
|
this.assertPage(page);
|
|
@@ -4580,7 +4646,7 @@ class NativeRuntime {
|
|
|
4580
4646
|
const check = (tree) => {
|
|
4581
4647
|
const origin = tree.frame.securityOrigin;
|
|
4582
4648
|
if (origin && origin !== "null" && origin !== "://" && !this.allowURL(origin))
|
|
4583
|
-
throw new
|
|
4649
|
+
throw new RuntimeFault("unsupported_target", "Use browser_capabilities and transfer the document to local document tools instead of inspecting this internal target.", true);
|
|
4584
4650
|
for (const child of tree.childFrames ?? [])
|
|
4585
4651
|
check(child);
|
|
4586
4652
|
};
|
|
@@ -4591,13 +4657,9 @@ class NativeRuntime {
|
|
|
4591
4657
|
}
|
|
4592
4658
|
async resolveTarget(tabId, scope, frames = []) {
|
|
4593
4659
|
this.validateScope(scope);
|
|
4594
|
-
const page = this.
|
|
4660
|
+
const page = this.claimPage(tabId, scope);
|
|
4595
4661
|
await this.track(page);
|
|
4596
4662
|
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
4663
|
let frame = page.mainFrame();
|
|
4602
4664
|
for (const selector of frames) {
|
|
4603
4665
|
const locator = frame.locator(selector);
|
|
@@ -4650,9 +4712,43 @@ class NativeRuntime {
|
|
|
4650
4712
|
events.diagnosticsSuppressed = false;
|
|
4651
4713
|
}
|
|
4652
4714
|
}
|
|
4715
|
+
claimPage(tabId, scope) {
|
|
4716
|
+
this.validateScope(scope);
|
|
4717
|
+
let page;
|
|
4718
|
+
try {
|
|
4719
|
+
page = this.engine.page(tabId);
|
|
4720
|
+
} catch {
|
|
4721
|
+
throw new RuntimeFault("tab_closed", "Use browser_list_tabs to choose an open tab.", true);
|
|
4722
|
+
}
|
|
4723
|
+
const owner = this.owners.get(tabId);
|
|
4724
|
+
if (owner && scopeKey(owner) !== scopeKey(scope))
|
|
4725
|
+
throw new RuntimeFault("scope_rejected", "Use a tab owned by this session.", true);
|
|
4726
|
+
this.owners.set(tabId, { ...scope });
|
|
4727
|
+
return page;
|
|
4728
|
+
}
|
|
4729
|
+
targetCapabilities(tabId, scope) {
|
|
4730
|
+
const page = this.claimPage(tabId, scope);
|
|
4731
|
+
const internal = page.frames().some((f) => !this.allowURL(f.url()));
|
|
4732
|
+
const pdf = page.frames().some((f) => f.url().startsWith("chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai")) || /\.pdf(?:[?#]|$)/i.test(page.url());
|
|
4733
|
+
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 };
|
|
4734
|
+
}
|
|
4735
|
+
async closeBlockedTab(tabId, scope, operationId) {
|
|
4736
|
+
this.validateScope(scope);
|
|
4737
|
+
const owner = this.owners.get(tabId);
|
|
4738
|
+
if (!owner || scopeKey(owner) !== scopeKey(scope))
|
|
4739
|
+
throw new RuntimeFault("scope_rejected", "Recovery is limited to the blocked operation owner.", true);
|
|
4740
|
+
const page = this.engine.page(tabId);
|
|
4741
|
+
await page.close({ runBeforeUnload: false });
|
|
4742
|
+
if (!page.isClosed())
|
|
4743
|
+
throw new Error("Tab closure unconfirmed");
|
|
4744
|
+
this.operations.get(operationId)?.abort(new Error("Blocked target closed by approved recovery"));
|
|
4745
|
+
return { closed: true };
|
|
4746
|
+
}
|
|
4653
4747
|
async execute(op, args, scope, operationId) {
|
|
4654
|
-
if (op === "session_end")
|
|
4655
|
-
|
|
4748
|
+
if (op === "session_end") {
|
|
4749
|
+
await this.endSession(scope);
|
|
4750
|
+
return { ended: true };
|
|
4751
|
+
}
|
|
4656
4752
|
const controller = new AbortController, key = scopeKey(scope);
|
|
4657
4753
|
let set = this.controllers.get(key);
|
|
4658
4754
|
if (!set) {
|
|
@@ -4660,9 +4756,11 @@ class NativeRuntime {
|
|
|
4660
4756
|
this.controllers.set(key, set);
|
|
4661
4757
|
}
|
|
4662
4758
|
set.add(controller);
|
|
4759
|
+
this.operations.set(operationId, controller);
|
|
4663
4760
|
try {
|
|
4664
4761
|
return await withCancellation(controller.signal, () => this.executeInner(op, args, scope, operationId));
|
|
4665
4762
|
} finally {
|
|
4763
|
+
this.operations.delete(operationId);
|
|
4666
4764
|
set.delete(controller);
|
|
4667
4765
|
if (!set.size)
|
|
4668
4766
|
this.controllers.delete(key);
|
|
@@ -4672,9 +4770,18 @@ class NativeRuntime {
|
|
|
4672
4770
|
await this.hooks;
|
|
4673
4771
|
this.validateScope(scope);
|
|
4674
4772
|
if (args.url !== undefined && !this.allowURL(String(args.url)))
|
|
4675
|
-
throw new
|
|
4676
|
-
if (typeof args.tabId === "string")
|
|
4677
|
-
|
|
4773
|
+
throw new RuntimeFault("unsupported_target", "Navigate only to authorized HTTP(S) pages or about:blank.", true);
|
|
4774
|
+
if (op === "capabilities" && typeof args.tabId === "string") {
|
|
4775
|
+
const target2 = this.targetCapabilities(args.tabId, scope);
|
|
4776
|
+
if (!target2.pageToolsSupported || target2.pdfDetected)
|
|
4777
|
+
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" };
|
|
4778
|
+
}
|
|
4779
|
+
if (typeof args.tabId === "string") {
|
|
4780
|
+
if (op === "close_tab")
|
|
4781
|
+
this.claimPage(args.tabId, scope);
|
|
4782
|
+
else
|
|
4783
|
+
await this.resolveTarget(args.tabId, scope);
|
|
4784
|
+
}
|
|
4678
4785
|
if (op === "batch" && Array.isArray(args.steps))
|
|
4679
4786
|
for (const step of args.steps) {
|
|
4680
4787
|
if (step.input?.url !== undefined && !this.allowURL(String(step.input.url)))
|
|
@@ -4705,14 +4812,22 @@ class NativeRuntime {
|
|
|
4705
4812
|
const tabs = await this.engine.listTabs();
|
|
4706
4813
|
return { tabs: tabs.filter((t) => this.allowURL(t.url) && (!this.owners.has(t.tabId) || scopeKey(this.owners.get(t.tabId)) === scopeKey(scope))) };
|
|
4707
4814
|
}
|
|
4708
|
-
|
|
4709
|
-
|
|
4710
|
-
|
|
4711
|
-
|
|
4712
|
-
|
|
4713
|
-
|
|
4714
|
-
|
|
4715
|
-
|
|
4815
|
+
try {
|
|
4816
|
+
const result = await this.engine.execute(op, args, { sessionId: scopeKey(scope), operationId });
|
|
4817
|
+
if (this.disconnected || (this.epochs.get(scopeKey(scope)) ?? 0) !== operationEpoch)
|
|
4818
|
+
throw new Error("Scope ended during execution; outcome uncertain");
|
|
4819
|
+
if (typeof args.tabId === "string" && op !== "close_tab")
|
|
4820
|
+
await this.assertPageDeep(this.engine.page(args.tabId));
|
|
4821
|
+
if (op === "open_tab" && typeof result?.tab?.tabId === "string")
|
|
4822
|
+
this.owners.set(result.tab.tabId, { ...scope });
|
|
4823
|
+
if (op === "capabilities" && typeof args.tabId === "string")
|
|
4824
|
+
return { ...result, ...this.targetCapabilities(args.tabId, scope) };
|
|
4825
|
+
return result;
|
|
4826
|
+
} catch (error) {
|
|
4827
|
+
if (error instanceof RuntimeFault)
|
|
4828
|
+
throw new RuntimeFault(error.code, error.recovery, false);
|
|
4829
|
+
throw error;
|
|
4830
|
+
}
|
|
4716
4831
|
}
|
|
4717
4832
|
async endSession(scope) {
|
|
4718
4833
|
const key = scopeKey(scope);
|
|
@@ -4729,9 +4844,9 @@ class NativeRuntime {
|
|
|
4729
4844
|
}
|
|
4730
4845
|
async shutdown() {
|
|
4731
4846
|
await this.disconnect();
|
|
4732
|
-
for (const
|
|
4847
|
+
for (const tabId of this.generations.keys())
|
|
4733
4848
|
for (const p of this.plugins)
|
|
4734
|
-
await p.onTabClose?.(
|
|
4849
|
+
await p.onTabClose?.(tabId);
|
|
4735
4850
|
await this.hooks;
|
|
4736
4851
|
this.engine.closeUploads();
|
|
4737
4852
|
}
|
|
@@ -4754,7 +4869,7 @@ class NativeRuntime {
|
|
|
4754
4869
|
|
|
4755
4870
|
// cli/src/runtime/relay.ts
|
|
4756
4871
|
import WebSocket2 from "ws";
|
|
4757
|
-
import { createHash as createHash5, randomUUID as
|
|
4872
|
+
import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
|
|
4758
4873
|
import fs9 from "node:fs/promises";
|
|
4759
4874
|
import path8 from "node:path";
|
|
4760
4875
|
|
|
@@ -5134,6 +5249,7 @@ class NativeLiveProducer {
|
|
|
5134
5249
|
}
|
|
5135
5250
|
|
|
5136
5251
|
// cli/src/runtime/relay.ts
|
|
5252
|
+
var sameScope3 = (a, b) => a.browserId === b.browserId && a.tokenId === b.tokenId && a.sessionKey === b.sessionKey && a.instanceId === b.instanceId;
|
|
5137
5253
|
var LIMIT = 2 * 1024 * 1024;
|
|
5138
5254
|
function wireResult(op, value) {
|
|
5139
5255
|
if (!value || typeof value !== "object")
|
|
@@ -5177,7 +5293,28 @@ class Relay {
|
|
|
5177
5293
|
stopping = false;
|
|
5178
5294
|
live;
|
|
5179
5295
|
seen = new Set;
|
|
5180
|
-
|
|
5296
|
+
active;
|
|
5297
|
+
recent = [];
|
|
5298
|
+
blocker(active, scope) {
|
|
5299
|
+
const quarantined = active.timedOut || active.interrupted;
|
|
5300
|
+
const state = { quarantined, executionState: active.settled ? active.interrupted ? "settled_after_interruption" : "settled_late" : quarantined ? "unresolved" : "in_progress" };
|
|
5301
|
+
if (scope && !sameScope3(active.scope, scope))
|
|
5302
|
+
return { ...state, ownedByAnotherScope: true };
|
|
5303
|
+
return { ...state, operationId: active.id, operation: active.op, startedAt: active.startedAt, deadlineAt: active.deadlineAt, callerDeadline: active.timedOut ? "expired" : active.interrupted ? "interrupted" : "pending", cancellationConfirmed: false, recoveryAvailable: quarantined && !!active.tabId && !active.recovering };
|
|
5304
|
+
}
|
|
5305
|
+
health(scope) {
|
|
5306
|
+
const active = this.active;
|
|
5307
|
+
return { state: this.state, paused: this.paused, queueDepth: 0, admission: active ? "blocked" : "ready", quarantined: !!active && (active.timedOut || active.interrupted), operation: active ? this.blocker(active, scope) : null, recent: this.recent.filter((r) => !scope || sameScope3(r.scope, scope)).map((r) => r.result) };
|
|
5308
|
+
}
|
|
5309
|
+
interrupt() {
|
|
5310
|
+
if (this.active)
|
|
5311
|
+
this.active.interrupted = true;
|
|
5312
|
+
}
|
|
5313
|
+
remember(active, result) {
|
|
5314
|
+
this.recent.push({ scope: active.scope, result: { operationId: active.id, ...result } });
|
|
5315
|
+
if (this.recent.length > 32)
|
|
5316
|
+
this.recent.shift();
|
|
5317
|
+
}
|
|
5181
5318
|
state = "disconnected";
|
|
5182
5319
|
paused = false;
|
|
5183
5320
|
constructor(runtime, server, token, previewDirectory, liveEnabled = false) {
|
|
@@ -5210,6 +5347,7 @@ class Relay {
|
|
|
5210
5347
|
await new Promise((resolve2, reject) => {
|
|
5211
5348
|
socket.once("error", reject);
|
|
5212
5349
|
socket.once("close", () => {
|
|
5350
|
+
this.interrupt();
|
|
5213
5351
|
clearInterval(heartbeat);
|
|
5214
5352
|
resolve2();
|
|
5215
5353
|
});
|
|
@@ -5220,7 +5358,7 @@ class Relay {
|
|
|
5220
5358
|
heartbeat.unref();
|
|
5221
5359
|
socket.once("open", () => {
|
|
5222
5360
|
this.state = "authenticating";
|
|
5223
|
-
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.
|
|
5361
|
+
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.14", 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
5362
|
});
|
|
5225
5363
|
socket.on("message", (bytes, binary) => {
|
|
5226
5364
|
if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
|
|
@@ -5240,7 +5378,7 @@ class Relay {
|
|
|
5240
5378
|
return;
|
|
5241
5379
|
}
|
|
5242
5380
|
this.state = "initializing";
|
|
5243
|
-
|
|
5381
|
+
(async () => {
|
|
5244
5382
|
await this.runtime.reconnect(message.browserId);
|
|
5245
5383
|
this.state = "connected";
|
|
5246
5384
|
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 +5401,16 @@ class Relay {
|
|
|
5263
5401
|
} });
|
|
5264
5402
|
this.live.setEnabled(this.liveEnabled);
|
|
5265
5403
|
console.error("Browser MCP connected (dedicated Chrome; local pause available)");
|
|
5266
|
-
}).catch(() => socket.close(1011));
|
|
5404
|
+
})().catch(() => socket.close(1011));
|
|
5267
5405
|
} else if (message.type === "watch") {
|
|
5268
5406
|
this.live?.onWatch(message).catch(() => {});
|
|
5269
5407
|
} else if (message.type === "ping")
|
|
5270
5408
|
socket.send(JSON.stringify({ type: "pong" }));
|
|
5271
5409
|
else if (message.type === "command") {
|
|
5272
|
-
if (
|
|
5410
|
+
if (this.state !== "connected" || this.paused) {
|
|
5411
|
+
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
5412
|
return;
|
|
5413
|
+
}
|
|
5274
5414
|
let admittedEpoch;
|
|
5275
5415
|
try {
|
|
5276
5416
|
admittedEpoch = this.runtime.scopeEpoch(message.scope);
|
|
@@ -5278,11 +5418,7 @@ class Relay {
|
|
|
5278
5418
|
socket.send(JSON.stringify({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: "invalid_scope", message: "Scope rejected at admission" } }));
|
|
5279
5419
|
return;
|
|
5280
5420
|
}
|
|
5281
|
-
|
|
5282
|
-
this.command(message, socket, admittedEpoch);
|
|
5283
|
-
return;
|
|
5284
|
-
}
|
|
5285
|
-
this.queue = this.queue.then(() => this.command(message, socket, admittedEpoch)).catch(() => {});
|
|
5421
|
+
this.command(message, socket, admittedEpoch).catch(() => socket.close(1011));
|
|
5286
5422
|
}
|
|
5287
5423
|
});
|
|
5288
5424
|
});
|
|
@@ -5315,65 +5451,137 @@ class Relay {
|
|
|
5315
5451
|
return;
|
|
5316
5452
|
}
|
|
5317
5453
|
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
|
-
|
|
5454
|
+
if (message.op === "runtime_health") {
|
|
5455
|
+
send({ type: "result", id: message.id, ok: true, result: this.health(message.scope), outcome: "completed" });
|
|
5456
|
+
return;
|
|
5457
|
+
}
|
|
5458
|
+
if (message.op === "runtime_recover") {
|
|
5459
|
+
await this.recover(message, send);
|
|
5460
|
+
return;
|
|
5461
|
+
}
|
|
5462
|
+
if (message.op === "session_end") {
|
|
5463
|
+
if (this.active && sameScope3(this.active.scope, message.scope))
|
|
5464
|
+
this.interrupt();
|
|
5465
|
+
await this.runtime.endSession(message.scope);
|
|
5466
|
+
send({ type: "result", id: message.id, ok: true, result: { ended: true }, outcome: "completed" });
|
|
5467
|
+
return;
|
|
5468
|
+
}
|
|
5469
|
+
if (this.active) {
|
|
5470
|
+
const active2 = this.active, quarantined = active2.timedOut || active2.interrupted;
|
|
5471
|
+
send({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: quarantined ? "blocked_by_prior_operation" : "runtime_busy", message: quarantined ? "A prior operation is quarantined after its deadline or an interruption. No action was queued or dispatched." : "Another operation is still in progress. No action was queued or dispatched." }, result: { operationId: message.id, blockingOperationId: sameScope3(active2.scope, message.scope) ? active2.id : undefined, category: quarantined ? "runtime_quarantined" : "runtime_busy", blocker: this.blocker(active2, message.scope), quarantined, retrySafe: true, executionState: "not_started", ...!quarantined ? { retryAfterMs: 250 } : {}, recovery: quarantined ? "Call browser_runtime_health. The prior outcome remains unknown; never replay the prior mutation. Wait for late settlement or request explicit user-approved recovery if available." : "Wait for the in-progress call to finish, or wait 250 ms and check browser_runtime_health before retrying only this never-dispatched request with a new request ID. Avoid tight retry loops; no tab closure or recovery is needed for ordinary contention." } });
|
|
5472
|
+
return;
|
|
5473
|
+
}
|
|
5474
|
+
let finish;
|
|
5475
|
+
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) => {
|
|
5476
|
+
finish = resolve2;
|
|
5477
|
+
}) };
|
|
5478
|
+
this.active = active;
|
|
5479
|
+
let stage = "execute", timer;
|
|
5480
|
+
const expired = new Promise((resolve2) => {
|
|
5481
|
+
timer = setTimeout(() => {
|
|
5482
|
+
active.timedOut = true;
|
|
5483
|
+
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." } });
|
|
5484
|
+
console.error(JSON.stringify({ event: "runtime_deadline", diagnosticId: active.id, operation: active.op, stage, executionState: "unresolved" }));
|
|
5485
|
+
resolve2();
|
|
5486
|
+
}, Math.max(1, active.deadlineAt - Date.now()));
|
|
5487
|
+
});
|
|
5488
|
+
const task = (async () => {
|
|
5489
|
+
let response;
|
|
5490
|
+
try {
|
|
5491
|
+
const result = await this.runtime.execute(message.op, message.args, message.scope, message.id);
|
|
5492
|
+
if (active.timedOut || active.interrupted || this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
|
|
5493
|
+
return;
|
|
5494
|
+
this.runtime.validateScope(message.scope);
|
|
5495
|
+
if (typeof message.args.tabId === "string") {
|
|
5496
|
+
this.live?.followTab(message.args.tabId);
|
|
5497
|
+
this.live?.emitCursor({ type: "action", phase: "end", ok: true, at: Date.now(), runtimeTabId: message.args.tabId, tool: message.op });
|
|
5351
5498
|
}
|
|
5352
|
-
|
|
5353
|
-
|
|
5354
|
-
|
|
5355
|
-
|
|
5499
|
+
stage = "transfer";
|
|
5500
|
+
const blobs = [];
|
|
5501
|
+
if (result?.base64 && message.op === "screenshot") {
|
|
5502
|
+
const bytes = Buffer.from(result.base64, "base64");
|
|
5503
|
+
delete result.base64;
|
|
5504
|
+
blobs.push(await this.upload(bytes, "screenshot", "screenshot.png", "image/png"));
|
|
5505
|
+
}
|
|
5506
|
+
if (message.op === "export_page" && Array.isArray(result?.exports))
|
|
5507
|
+
for (const item of result.exports) {
|
|
5508
|
+
const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
|
|
5509
|
+
if (path8.basename(filename) !== filename)
|
|
5510
|
+
throw new Error("Invalid export file");
|
|
5511
|
+
const filenamePath = path8.join(this.previewDirectory, filename);
|
|
5512
|
+
const stat = await fs9.lstat(filenamePath);
|
|
5513
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
|
|
5514
|
+
throw new Error("Invalid export file");
|
|
5515
|
+
blobs.push(await this.upload(await fs9.readFile(filenamePath), "export", item.filename, item.mimeType));
|
|
5516
|
+
await fs9.unlink(filenamePath);
|
|
5517
|
+
delete item.downloadId;
|
|
5518
|
+
}
|
|
5519
|
+
if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
|
|
5520
|
+
for (const artifact2 of result.artifacts)
|
|
5521
|
+
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"));
|
|
5522
|
+
result.artifacts = result.artifacts.map((a) => ({ filename: path8.basename(a.filename) }));
|
|
5523
|
+
}
|
|
5524
|
+
if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
|
|
5525
|
+
throw new Error("Result budget exceeded");
|
|
5526
|
+
response = { type: "result", id: message.id, ok: true, result: wireResult(message.op, result), blobs, outcome: result?.status === "unknown" ? "unknown" : "completed" };
|
|
5527
|
+
} catch (error) {
|
|
5528
|
+
const failure = failureFor(error, message.op, message.id, stage);
|
|
5529
|
+
response = { type: "result", id: message.id, ok: false, ...failure };
|
|
5530
|
+
} finally {
|
|
5531
|
+
clearTimeout(timer);
|
|
5532
|
+
active.settled = true;
|
|
5533
|
+
finish();
|
|
5534
|
+
if (active.timedOut || active.interrupted)
|
|
5535
|
+
this.remember(active, { callerDeadline: active.timedOut ? "expired" : "interrupted", executionState: active.interrupted ? "settled_after_interruption" : "settled_late", outcome: "unknown", retrySafe: false, cancellationConfirmed: false });
|
|
5536
|
+
if (this.active === active && !active.interrupted && !active.recovering)
|
|
5537
|
+
this.active = undefined;
|
|
5356
5538
|
}
|
|
5357
|
-
if (
|
|
5358
|
-
|
|
5359
|
-
|
|
5539
|
+
if (response && !active.timedOut && !active.interrupted)
|
|
5540
|
+
send(response);
|
|
5541
|
+
})();
|
|
5542
|
+
await Promise.race([task, expired]);
|
|
5543
|
+
}
|
|
5544
|
+
async recover(message, send) {
|
|
5545
|
+
const active = this.active;
|
|
5546
|
+
const reject = (code2, messageText) => send({ type: "result", id: message.id, ok: false, outcome: "not_dispatched", error: { code: code2, message: messageText } });
|
|
5547
|
+
if (!active || active.id !== message.args.operationId || !sameScope3(active.scope, message.scope))
|
|
5548
|
+
return reject("recovery_unavailable", "No matching blocked operation belongs to this session.");
|
|
5549
|
+
if (!(active.timedOut || active.interrupted) || !active.tabId || active.recovering)
|
|
5550
|
+
return reject("recovery_unavailable", "Recovery requires a quarantined tab operation, with no recovery already running.");
|
|
5551
|
+
if (message.args.method !== "close_tab" || typeof message.args.approval !== "string" || !message.args.approval.trim())
|
|
5552
|
+
return reject("approval_required", "Explicit user approval to close the blocked tab is required. This may discard unsaved page state; profile data is retained.");
|
|
5553
|
+
active.recovering = true;
|
|
5554
|
+
const work = (async () => {
|
|
5555
|
+
await this.runtime.closeBlockedTab(active.tabId, message.scope, active.id);
|
|
5556
|
+
await active.done;
|
|
5557
|
+
this.remember(active, { executionState: "target_closed", terminationConfirmed: true, outcome: "unknown", retrySafe: false, replayed: false });
|
|
5558
|
+
if (this.active === active)
|
|
5559
|
+
this.active = undefined;
|
|
5560
|
+
return { recovered: true, operationId: active.id, executionState: "target_closed", terminationConfirmed: true, originalOutcome: "unknown", retrySafe: false, replayed: false, profilePreserved: true };
|
|
5561
|
+
})();
|
|
5562
|
+
let timer;
|
|
5563
|
+
try {
|
|
5564
|
+
const result = await Promise.race([work, new Promise((_, reject2) => {
|
|
5565
|
+
timer = setTimeout(() => reject2(new Error("Recovery timeout")), 5000);
|
|
5566
|
+
})]);
|
|
5567
|
+
send({ type: "result", id: message.id, ok: true, result, outcome: "completed" });
|
|
5360
5568
|
} 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." } });
|
|
5569
|
+
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
5570
|
} finally {
|
|
5364
|
-
clearTimeout(
|
|
5571
|
+
clearTimeout(timer);
|
|
5365
5572
|
}
|
|
5366
5573
|
}
|
|
5367
5574
|
async upload(bytes, role, name, mimeType) {
|
|
5368
5575
|
if (bytes.length > 20 * 1024 * 1024)
|
|
5369
5576
|
throw new Error("Preview exceeds 20 MiB");
|
|
5370
|
-
const blobId =
|
|
5577
|
+
const blobId = randomUUID5(), sha256 = createHash5("sha256").update(bytes).digest("hex");
|
|
5371
5578
|
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
5579
|
if (!response.ok)
|
|
5373
5580
|
throw new Error("Preview upload failed");
|
|
5374
5581
|
return { blobId, role, name, mimeType, size: bytes.length, sha256 };
|
|
5375
5582
|
}
|
|
5376
5583
|
async pause() {
|
|
5584
|
+
this.interrupt();
|
|
5377
5585
|
this.paused = true;
|
|
5378
5586
|
this.state = "paused";
|
|
5379
5587
|
this.socket?.close();
|
|
@@ -5384,6 +5592,7 @@ class Relay {
|
|
|
5384
5592
|
this.paused = false;
|
|
5385
5593
|
}
|
|
5386
5594
|
async stop() {
|
|
5595
|
+
this.interrupt();
|
|
5387
5596
|
this.stopping = true;
|
|
5388
5597
|
this.socket?.close();
|
|
5389
5598
|
await this.live?.stop();
|
|
@@ -5394,13 +5603,13 @@ class Relay {
|
|
|
5394
5603
|
// cli/src/data/index.ts
|
|
5395
5604
|
import { mkdir as mkdir2, open as open2, rename, unlink as unlink2, rmdir as rmdir2, chmod, lstat as lstat2 } from "node:fs/promises";
|
|
5396
5605
|
import { createReadStream, createWriteStream } from "node:fs";
|
|
5397
|
-
import { randomUUID as
|
|
5606
|
+
import { randomUUID as randomUUID7, createHash as createHash6 } from "node:crypto";
|
|
5398
5607
|
import { join as join2, basename } from "node:path";
|
|
5399
5608
|
import { Readable, Transform } from "node:stream";
|
|
5400
5609
|
import { pipeline } from "node:stream/promises";
|
|
5401
5610
|
|
|
5402
5611
|
// cli/src/data/vault.ts
|
|
5403
|
-
import { randomUUID as
|
|
5612
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
5404
5613
|
class SecretVault {
|
|
5405
5614
|
access;
|
|
5406
5615
|
entries = new Map;
|
|
@@ -5467,7 +5676,7 @@ class SecretVault {
|
|
|
5467
5676
|
}
|
|
5468
5677
|
if (!Object.keys(clean).length || Object.keys(clean).length > LIMITS.count || total + 1024 > LIMITS.secret)
|
|
5469
5678
|
throw new Error("Vault quota exceeded");
|
|
5470
|
-
const entry = { id:
|
|
5679
|
+
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
5680
|
this.entries.set(entry.id, entry);
|
|
5472
5681
|
return this.metadata(entry);
|
|
5473
5682
|
} catch {
|
|
@@ -5529,8 +5738,22 @@ async function createDataPlugin(access, options) {
|
|
|
5529
5738
|
await mkdir2(options.directory, { mode: 448 });
|
|
5530
5739
|
const resources = new Map, owned = new Set, ownedDirs = new Set, vault = new SecretVault(access);
|
|
5531
5740
|
let stopped = false;
|
|
5741
|
+
const terminal = new Map;
|
|
5742
|
+
function remember(r) {
|
|
5743
|
+
if (r.purpose !== "download")
|
|
5744
|
+
return;
|
|
5745
|
+
terminal.set(r.id, { scope: r.scope, meta: { ...meta(r), state: r.terminalCode?.startsWith("download_capture") || r.terminalCode === "download_quota_exceeded" ? "failed" : r.terminalCode === "download_expired" ? "expired" : "cancelled", size: r.hash ? r.size : undefined, maxBytes: undefined, retrieval: undefined, readiness: "unavailable", code: r.terminalCode ?? "download_revoked", recovery: "Retained bytes are unavailable. Do not automatically replay the source action; ask before recreating the download." }, until: Date.now() + LIMITS.ttl });
|
|
5746
|
+
while (terminal.size > 128)
|
|
5747
|
+
terminal.delete(terminal.keys().next().value);
|
|
5748
|
+
}
|
|
5749
|
+
function status(scope, id) {
|
|
5750
|
+
const t = terminal.get(String(id));
|
|
5751
|
+
if (t && t.until >= Date.now() && sameScope(t.scope, scope))
|
|
5752
|
+
return t.meta;
|
|
5753
|
+
return meta(get(scope, id));
|
|
5754
|
+
}
|
|
5532
5755
|
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 };
|
|
5756
|
+
return { resourceId: r.id, fileId: r.id, maxBytes: r.size, size: r.purpose === "download" && !r.hash ? undefined : 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
5757
|
}
|
|
5535
5758
|
function get(scope, id) {
|
|
5536
5759
|
const r = resources.get(String(id));
|
|
@@ -5545,13 +5768,15 @@ async function createDataPlugin(access, options) {
|
|
|
5545
5768
|
}
|
|
5546
5769
|
function create(scope, purpose, size, name) {
|
|
5547
5770
|
reserve(scope, size);
|
|
5548
|
-
const r = { id:
|
|
5771
|
+
const r = { id: randomUUID7(), scope: { ...scope }, purpose, size, name: safeName(name), state: "prepared", abort: new AbortController, expiresAt: Date.now() + LIMITS.ttl };
|
|
5549
5772
|
resources.set(r.id, r);
|
|
5550
5773
|
return r;
|
|
5551
5774
|
}
|
|
5552
5775
|
async function remove(r) {
|
|
5776
|
+
r.terminalCode ??= "download_revoked";
|
|
5553
5777
|
r.abort.abort();
|
|
5554
5778
|
r.state = "cancelled";
|
|
5779
|
+
remember(r);
|
|
5555
5780
|
await r.task?.catch(() => {});
|
|
5556
5781
|
r.bytes?.fill(0);
|
|
5557
5782
|
r.bytes = undefined;
|
|
@@ -5624,7 +5849,8 @@ async function createDataPlugin(access, options) {
|
|
|
5624
5849
|
r.state = "ready";
|
|
5625
5850
|
}
|
|
5626
5851
|
} catch {
|
|
5627
|
-
r.state
|
|
5852
|
+
if (r.state !== "cancelled")
|
|
5853
|
+
r.state = "failed";
|
|
5628
5854
|
if (r.path && owned.has(r.path) && r.purpose === "upload") {
|
|
5629
5855
|
await unlink2(r.path).catch(() => {});
|
|
5630
5856
|
owned.delete(r.path);
|
|
@@ -5635,10 +5861,27 @@ async function createDataPlugin(access, options) {
|
|
|
5635
5861
|
r.bytes?.fill(0);
|
|
5636
5862
|
r.bytes = undefined;
|
|
5637
5863
|
}
|
|
5864
|
+
if (r.purpose === "download" && r.state !== "cancelled" && !stopped && resources.get(r.id) === r) {
|
|
5865
|
+
r.authorized = false;
|
|
5866
|
+
r.abort = new AbortController;
|
|
5867
|
+
r.state = "ready";
|
|
5868
|
+
}
|
|
5638
5869
|
}
|
|
5639
5870
|
}
|
|
5871
|
+
async function sweepExpired() {
|
|
5872
|
+
await revoke((r) => {
|
|
5873
|
+
if (r.expiresAt < Date.now() && r.state !== "attached") {
|
|
5874
|
+
r.terminalCode = "download_expired";
|
|
5875
|
+
return true;
|
|
5876
|
+
}
|
|
5877
|
+
return false;
|
|
5878
|
+
});
|
|
5879
|
+
for (const [id, t] of terminal)
|
|
5880
|
+
if (t.until < Date.now())
|
|
5881
|
+
terminal.delete(id);
|
|
5882
|
+
}
|
|
5640
5883
|
let sweep = setInterval(() => {
|
|
5641
|
-
|
|
5884
|
+
sweepExpired();
|
|
5642
5885
|
}, 1e4);
|
|
5643
5886
|
sweep.unref?.();
|
|
5644
5887
|
return {
|
|
@@ -5658,17 +5901,20 @@ async function createDataPlugin(access, options) {
|
|
|
5658
5901
|
return meta(r);
|
|
5659
5902
|
}
|
|
5660
5903
|
if (op === "create_download") {
|
|
5661
|
-
const r = get(scope, args.fileId ?? args.resourceId);
|
|
5904
|
+
const r = get(scope, args.downloadId ?? args.fileId ?? args.resourceId);
|
|
5662
5905
|
if (r.purpose !== "download" || r.state !== "ready")
|
|
5663
5906
|
throw new Error("Download unavailable");
|
|
5664
5907
|
return meta(r);
|
|
5665
5908
|
}
|
|
5666
|
-
if (op === "transfer_status")
|
|
5667
|
-
|
|
5909
|
+
if (op === "transfer_status") {
|
|
5910
|
+
await sweepExpired();
|
|
5911
|
+
return status(scope, args.resourceId ?? args.transferId);
|
|
5912
|
+
}
|
|
5668
5913
|
if (op === "cancel_transfer") {
|
|
5669
5914
|
const r = get(scope, args.resourceId ?? args.transferId);
|
|
5670
5915
|
if (r.state === "attached")
|
|
5671
5916
|
throw new Error("Attached files retained until document ends");
|
|
5917
|
+
r.terminalCode = "download_cancelled";
|
|
5672
5918
|
await remove(r);
|
|
5673
5919
|
return { cancelled: true };
|
|
5674
5920
|
}
|
|
@@ -5682,8 +5928,10 @@ async function createDataPlugin(access, options) {
|
|
|
5682
5928
|
r.task = transfer(r, grant);
|
|
5683
5929
|
return { resourceId: r.id, state: "transferring" };
|
|
5684
5930
|
}
|
|
5685
|
-
if (op === "list_downloads")
|
|
5686
|
-
|
|
5931
|
+
if (op === "list_downloads") {
|
|
5932
|
+
await sweepExpired();
|
|
5933
|
+
return { files: [...resources.values()].filter((r) => sameScope(r.scope, scope) && r.purpose === "download").map(meta), terminal: [...terminal.values()].filter((t) => sameScope(t.scope, scope)).map((t) => t.meta) };
|
|
5934
|
+
}
|
|
5687
5935
|
if (op === "upload_files") {
|
|
5688
5936
|
const ids = args.fileIds;
|
|
5689
5937
|
if (!Array.isArray(ids) || !ids.length || ids.length > 100 || new Set(ids).size !== ids.length)
|
|
@@ -5737,54 +5985,79 @@ async function createDataPlugin(access, options) {
|
|
|
5737
5985
|
}
|
|
5738
5986
|
throw new Error("Unsupported data operation");
|
|
5739
5987
|
},
|
|
5740
|
-
async onDownload(download, tabId, scope, generation) {
|
|
5988
|
+
async onDownload(download, tabId, scope, generation, downloadId = randomUUID7()) {
|
|
5741
5989
|
let r;
|
|
5990
|
+
let timeout2;
|
|
5742
5991
|
try {
|
|
5743
5992
|
r = create(scope, "download", LIMITS.file, download.suggestedFilename());
|
|
5993
|
+
resources.delete(r.id);
|
|
5994
|
+
r.id = downloadId;
|
|
5995
|
+
resources.set(r.id, r);
|
|
5744
5996
|
r.tabId = tabId;
|
|
5745
5997
|
r.generation = generation;
|
|
5746
|
-
|
|
5747
|
-
|
|
5748
|
-
|
|
5749
|
-
|
|
5750
|
-
|
|
5751
|
-
|
|
5752
|
-
|
|
5753
|
-
|
|
5754
|
-
received += chunk.length;
|
|
5755
|
-
if (received > LIMITS.file)
|
|
5756
|
-
return callback(new Error("Download quota exceeded"));
|
|
5757
|
-
callback(null, chunk);
|
|
5758
|
-
} });
|
|
5759
|
-
const timeout2 = setTimeout(() => r.abort.abort(), LIMITS.duration);
|
|
5998
|
+
r.abort.signal.addEventListener("abort", () => {
|
|
5999
|
+
download.cancel().catch(() => {});
|
|
6000
|
+
}, { once: true });
|
|
6001
|
+
timeout2 = setTimeout(() => {
|
|
6002
|
+
r.terminalCode = "download_capture_timeout";
|
|
6003
|
+
r.abort.abort();
|
|
6004
|
+
download.cancel().catch(() => {});
|
|
6005
|
+
}, LIMITS.duration);
|
|
5760
6006
|
timeout2.unref?.();
|
|
5761
|
-
|
|
5762
|
-
|
|
5763
|
-
|
|
5764
|
-
|
|
5765
|
-
|
|
5766
|
-
|
|
5767
|
-
|
|
5768
|
-
|
|
5769
|
-
|
|
5770
|
-
|
|
5771
|
-
|
|
5772
|
-
|
|
5773
|
-
|
|
5774
|
-
|
|
5775
|
-
|
|
6007
|
+
const captured = r;
|
|
6008
|
+
r.task = (async () => {
|
|
6009
|
+
const path9 = join2(options.directory, captured.id);
|
|
6010
|
+
captured.path = path9;
|
|
6011
|
+
owned.add(path9);
|
|
6012
|
+
const source = await download.createReadStream();
|
|
6013
|
+
if (!source)
|
|
6014
|
+
throw new Error("Download unavailable");
|
|
6015
|
+
let received = 0;
|
|
6016
|
+
const hash = createHash6("sha256");
|
|
6017
|
+
const bound = new Transform({ transform(chunk, _encoding, callback) {
|
|
6018
|
+
received += chunk.length;
|
|
6019
|
+
if (received > LIMITS.file) {
|
|
6020
|
+
captured.terminalCode = "download_quota_exceeded";
|
|
6021
|
+
return callback(new Error("Download quota exceeded"));
|
|
6022
|
+
}
|
|
6023
|
+
hash.update(chunk);
|
|
6024
|
+
callback(null, chunk);
|
|
6025
|
+
} });
|
|
6026
|
+
await pipeline(source, bound, createWriteStream(path9, { flags: "wx", mode: 384 }), { signal: captured.abort.signal });
|
|
6027
|
+
await chmod(path9, 384);
|
|
6028
|
+
const stat = await lstat2(path9);
|
|
6029
|
+
if (!stat.isFile() || stat.size !== received || captured.abort.signal.aborted || stopped || resources.get(captured.id) !== captured)
|
|
6030
|
+
throw new Error("Download revoked");
|
|
6031
|
+
captured.size = stat.size;
|
|
6032
|
+
captured.hash = hash.digest("hex");
|
|
6033
|
+
captured.state = "ready";
|
|
6034
|
+
})();
|
|
6035
|
+
await r.task;
|
|
6036
|
+
await download.delete().catch(() => {});
|
|
6037
|
+
if (r.abort.signal.aborted || stopped || resources.get(r.id) !== r)
|
|
5776
6038
|
throw new Error("Download revoked");
|
|
5777
|
-
r
|
|
6039
|
+
return { ...meta(r), state: "completed", readiness: "ready" };
|
|
5778
6040
|
} catch {
|
|
5779
6041
|
await download.cancel().catch(() => {});
|
|
5780
|
-
if (r)
|
|
6042
|
+
if (r) {
|
|
6043
|
+
r.terminalCode ??= "download_capture_failed";
|
|
5781
6044
|
await remove(r);
|
|
6045
|
+
return { ...status(scope, downloadId), state: "failed" };
|
|
6046
|
+
}
|
|
6047
|
+
const failed = { downloadId, resourceId: downloadId, state: "failed", readiness: "unavailable", code: "download_capture_rejected", recovery: "Capture could not be reserved. Do not automatically repeat the website action." };
|
|
6048
|
+
terminal.set(downloadId, { scope: { ...scope }, meta: failed, until: Date.now() + LIMITS.ttl });
|
|
6049
|
+
while (terminal.size > 128)
|
|
6050
|
+
terminal.delete(terminal.keys().next().value);
|
|
6051
|
+
return failed;
|
|
5782
6052
|
} finally {
|
|
5783
|
-
|
|
6053
|
+
if (timeout2)
|
|
6054
|
+
clearTimeout(timeout2);
|
|
6055
|
+
if (r?.state !== "ready")
|
|
6056
|
+
await download.delete().catch(() => {});
|
|
5784
6057
|
}
|
|
5785
6058
|
},
|
|
5786
6059
|
async onNavigation(tabId, generation) {
|
|
5787
|
-
await revoke((r) => r.tabId === tabId && r.generation !== generation);
|
|
6060
|
+
await revoke((r) => r.purpose !== "download" && r.tabId === tabId && r.generation !== generation);
|
|
5788
6061
|
},
|
|
5789
6062
|
async onTabClose(tabId) {
|
|
5790
6063
|
await revoke((r) => r.tabId === tabId);
|
|
@@ -5812,7 +6085,7 @@ async function createDataPlugin(access, options) {
|
|
|
5812
6085
|
await mkdir2(options.directory, { mode: 448 });
|
|
5813
6086
|
stopped = false;
|
|
5814
6087
|
sweep = setInterval(() => {
|
|
5815
|
-
|
|
6088
|
+
sweepExpired();
|
|
5816
6089
|
}, 1e4);
|
|
5817
6090
|
sweep.unref?.();
|
|
5818
6091
|
}
|
|
@@ -6084,7 +6357,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
6084
6357
|
return;
|
|
6085
6358
|
} else if (cmd !== "status")
|
|
6086
6359
|
throw new Error("Invalid command");
|
|
6087
|
-
socket.end(JSON.stringify({
|
|
6360
|
+
socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.14", protocol: 3 }) + `
|
|
6088
6361
|
`);
|
|
6089
6362
|
})().catch(() => socket.destroy());
|
|
6090
6363
|
});
|
|
@@ -2,12 +2,13 @@ import {
|
|
|
2
2
|
capabilityFetch,
|
|
3
3
|
exclusiveOutput,
|
|
4
4
|
readCapability
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-v483gpt7.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)
|
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.14
|
|
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.14");
|
|
22
22
|
return;
|
|
23
23
|
}
|
|
24
24
|
if (command === "browser")
|
|
25
|
-
return (await import("./chunk-
|
|
25
|
+
return (await import("./chunk-y9x8c0rq.js")).runBrowser(args);
|
|
26
26
|
if (command === "files")
|
|
27
|
-
return (await import("./chunk-
|
|
27
|
+
return (await import("./chunk-zv1900tw.js")).runFilesCommand(args);
|
|
28
28
|
if (command === "secrets")
|
|
29
|
-
return (await import("./chunk-
|
|
29
|
+
return (await import("./chunk-g3yyvtve.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.");
|