@ricsam/browser-mcp 0.3.20 → 0.3.21

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 CHANGED
@@ -3,10 +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.20 uses one cross-platform Node package with matching server/chart 0.3.20, native protocol 3 and no database schema change. Screenshots are returned as soon as Chrome captures them, with nothing running in the page after the capture, and screenshots, page reads, `browser_run_js`, waits and inspections carry `pageState` timing (`capturedAt`, document state, pending requests and the tab's last action). Upload and secret-export capabilities in tool text with up-front transfer grant limits (0.3.19), private download routing (0.3.18), background screenshots and capture-only download retry remain. Verified readiness is still required before retrieving bytes. Keep administrative sign-ins outside automated profiles unless deliberately delegated: internal pages, local files and the Browser MCP dashboard are no longer blanket-blocked, subject to Chrome's interface limits. 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.
6
+ Release 0.3.21 uses one cross-platform Node package with matching server/chart 0.3.21, native protocol 3 and no database schema change. With `--live-view`, the owner can take control of the streamed tab from the dashboard or an MCP App, agents can hand it over with `browser_takeover`, and agent tool calls on a tab the user controls are refused with `user_in_control`. Tab results no longer contain internal session identifiers. Screenshots returned as soon as Chrome captures them with `pageState` timing (0.3.20), upload and secret-export capabilities in tool text with up-front transfer grant limits (0.3.19), private download routing (0.3.18), background screenshots and capture-only download retry remain. Verified readiness is still required before retrieving bytes. Keep administrative sign-ins outside automated profiles unless deliberately delegated: internal pages, local files and the Browser MCP dashboard are no longer blanket-blocked, subject to Chrome's interface limits. 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
7
 
8
8
  ```sh
9
- npm install -g @ricsam/browser-mcp@0.3.20
9
+ npm install -g @ricsam/browser-mcp@0.3.21
10
10
  browser-mcp browser start --server https://browser-mcp.click --profile work
11
11
  browser-mcp browser status --profile work
12
12
  browser-mcp browser pause --profile work
@@ -20,7 +20,9 @@ Profiles are dedicated and persistent by default. `--ephemeral` is explicit.
20
20
  `--chrome-path /absolute/path/to/chrome` selects an installed binary, never a
21
21
  profile. Profile names cannot contain paths. Your daily-driver profile is never
22
22
  opened, copied or attached. `--live-view` enables screenshot-based live view
23
- locally (off by default); remote viewers cannot enable it.
23
+ locally (off by default); remote viewers cannot enable it. With it, the signed-in
24
+ owner can also take control of the streamed tab (takeover) from the dashboard or
25
+ an MCP App; the agent cannot use that tab until control returns.
24
26
 
25
27
  Foreground lifecycle: keep the CLI running. Ctrl-C, stop, or normal CLI exit
26
28
  closes its Chrome. There is no detach or automatic CDP reattachment. Each launch
@@ -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.20";
57
+ var version = "0.3.21";
58
58
 
59
59
  // cli/src/browser/chrome-diagnostics.ts
60
60
  import { constants } from "node:fs";
@@ -2895,6 +2895,7 @@ class BrowserPageEvents {
2895
2895
  entries = [];
2896
2896
  listeners = new Set;
2897
2897
  changes = new Set;
2898
+ dialogListeners = new Set;
2898
2899
  requests = new WeakMap;
2899
2900
  inflight = new Map;
2900
2901
  lastNetworkActivity;
@@ -2943,6 +2944,7 @@ class BrowserPageEvents {
2943
2944
  actionId: current.event.actionId
2944
2945
  });
2945
2946
  this.dialog = undefined;
2947
+ this.dialogChanged();
2946
2948
  });
2947
2949
  cdp.send("Page.enable").catch(() => {
2948
2950
  return;
@@ -2995,6 +2997,7 @@ class BrowserPageEvents {
2995
2997
  this.dialog = { value, event };
2996
2998
  for (const listener of this.listeners)
2997
2999
  listener();
3000
+ this.dialogChanged();
2998
3001
  });
2999
3002
  page.on("filechooser", (chooser) => {
3000
3003
  const event = this.record("chooser", { multiple: chooser.isMultiple(), state: "open", document: this.document });
@@ -3022,8 +3025,25 @@ class BrowserPageEvents {
3022
3025
  this.downloads.clear();
3023
3026
  this.inflight.clear();
3024
3027
  this.dialog = undefined;
3028
+ this.dialogListeners.clear();
3025
3029
  });
3026
3030
  }
3031
+ onDialog(listener) {
3032
+ this.dialogListeners.add(listener);
3033
+ return () => this.dialogListeners.delete(listener);
3034
+ }
3035
+ dialogDetails() {
3036
+ const value = this.dialog?.value;
3037
+ return value ? { type: value.type(), message: value.message(), defaultValue: value.defaultValue() } : null;
3038
+ }
3039
+ dialogChanged() {
3040
+ const details = this.dialogDetails();
3041
+ for (const listener of [...this.dialogListeners]) {
3042
+ try {
3043
+ listener(details);
3044
+ } catch {}
3045
+ }
3046
+ }
3027
3047
  isMainFrameNavigation(request) {
3028
3048
  try {
3029
3049
  return request.isNavigationRequest() && request.frame() === this.page.mainFrame();
@@ -3176,17 +3196,19 @@ class BrowserPageEvents {
3176
3196
  pendingAction() {
3177
3197
  return this.pending ? { actionId: this.pending.actionId, status: "pending" } : null;
3178
3198
  }
3179
- async handleDialog(input) {
3199
+ async handleDialog(input, handledBy = "agent") {
3180
3200
  const current = this.dialog;
3181
3201
  if (!current || current.event.eventId !== input.dialogId)
3182
3202
  return { handled: false, code: "stale_dialog", dialog: this.activeDialog() };
3183
3203
  if (input.promptText !== undefined && (current.value.type() !== "prompt" || input.decision !== "accept"))
3184
3204
  return { handled: false, code: "prompt_text_requires_accept_prompt" };
3185
- current.event.handledBy = "agent";
3205
+ current.event.handledBy = handledBy;
3186
3206
  await (input.decision === "accept" ? current.value.accept(input.promptText) : current.value.dismiss());
3187
3207
  current.event.state = input.decision === "accept" ? "accepted" : "dismissed";
3188
- if (this.dialog === current)
3208
+ if (this.dialog === current) {
3189
3209
  this.dialog = undefined;
3210
+ this.dialogChanged();
3211
+ }
3190
3212
  const pending = this.pending;
3191
3213
  const outcome = pending ? await this.racePending(pending, 1000) : undefined;
3192
3214
  return {
@@ -3922,7 +3944,10 @@ class RuntimeFault extends Error {
3922
3944
  }
3923
3945
  }
3924
3946
  var OBSERVATION_OPERATIONS = new Set(["list_tabs", "list_downloads", "read_page", "screenshot", "wait_for", "capabilities", "inspect", "events", "diagnostics", "export_page", "webmcp_list", "runtime_health"]);
3947
+ var USER_IN_CONTROL_MESSAGE = "The user controls this tab in live view (takeover), so the agent cannot use it now. No action was dispatched.";
3948
+ var USER_IN_CONTROL_RECOVERY = "Wait for the user to give control back with browser_takeover_status {tabId, waitMs}, or ask for it with browser_takeover_reclaim and respect a declined request. Other tabs keep working. Once you have control, observe this tab again before acting; retry only with a fresh idempotency key.";
3925
3949
  var messages = {
3950
+ user_in_control: USER_IN_CONTROL_MESSAGE,
3926
3951
  unsupported_target: "Chrome does not expose the interface required by this operation on this target.",
3927
3952
  browser_operation_unsupported: "Chrome reported that this operation or protocol method is not supported on this target.",
3928
3953
  tab_closed: "The tab is closed or detached.",
@@ -3998,6 +4023,12 @@ function refActionError(error, ref, verb) {
3998
4023
  return new Error(`${message}
3999
4024
  Ref ${ref} comes from the most recent browser_read_page snapshot of this tab. ` + `The ${verb} outcome may be uncertain. ` + BROWSER_RECOVERY, { cause: error });
4000
4025
  }
4026
+ function tabStateView(state) {
4027
+ return {
4028
+ retention: state.retention,
4029
+ ...state.viewport ? { viewport: { width: state.viewport.width, height: state.viewport.height } } : {}
4030
+ };
4031
+ }
4001
4032
 
4002
4033
  class BrowserRuntime {
4003
4034
  context;
@@ -4237,8 +4268,9 @@ class BrowserRuntime {
4237
4268
  await this.initialization.get(page);
4238
4269
  const tabId = this.ids.get(page);
4239
4270
  const state = (await this.tabState.resolve(page)).state;
4271
+ const info = ({ windowId: windowId2, title: title2 }) => ({ tabId, windowId: windowId2, title: title2, url: page.url(), ...tabStateView(state) });
4240
4272
  if (this.events.get(page)?.activeDialog()) {
4241
- return { ...state, tabId, ...this.tabPresentation.get(page) ?? { windowId: "unknown", title: "" }, url: page.url() };
4273
+ return info(this.tabPresentation.get(page) ?? { windowId: "unknown", title: "" });
4242
4274
  }
4243
4275
  let windowId = "unknown";
4244
4276
  let title = "";
@@ -4254,7 +4286,7 @@ class BrowserRuntime {
4254
4286
  });
4255
4287
  }
4256
4288
  this.tabPresentation.set(page, { windowId, title });
4257
- return { ...state, tabId, windowId, title, url: page.url() };
4289
+ return info({ windowId, title });
4258
4290
  }
4259
4291
  async listTabs() {
4260
4292
  await Promise.all(this.initialization.values());
@@ -4485,6 +4517,19 @@ class BrowserRuntime {
4485
4517
  if (result?.matched === false || result?.expected?.matched === false || result?.dispatch && result.dispatch.status !== "completed" || result?.code || result?.observation?.available === false)
4486
4518
  return { results, stoppedAt: index, remaining: steps.length - index - 1, code: "batch_step_stopped", retrySafe: false };
4487
4519
  } catch (error) {
4520
+ if (error instanceof RuntimeFault && error.beforeDispatch) {
4521
+ if (index === 0)
4522
+ throw error;
4523
+ const refused = failureFor(error, step.action, execution.operationId ?? crypto.randomUUID(), "batch_step");
4524
+ return {
4525
+ results: [...results, { index, action: step.action, status: "not_dispatched", ...refused.result, code: refused.error.code }],
4526
+ stoppedAt: index,
4527
+ remaining: steps.length - index,
4528
+ code: "batch_step_stopped",
4529
+ retrySafe: false,
4530
+ recovery: refused.result.recovery
4531
+ };
4532
+ }
4488
4533
  const failure = failureFor(error, step.action, execution.operationId ?? crypto.randomUUID(), "batch_step");
4489
4534
  return {
4490
4535
  results: [...results, { index, action: step.action, status: "unknown", ...failure.result, code: failure.error.code }],
@@ -4675,7 +4720,7 @@ class BrowserRuntime {
4675
4720
  retention: input.mode === "handoff" ? "user" : input.mode === "temporary" ? "temporary" : "retained",
4676
4721
  ...input.mode === "handoff" ? { ownerSessionId: undefined, ...input.preserveViewport === true ? {} : { viewport: undefined } } : {}
4677
4722
  });
4678
- return { changed: true, ...next };
4723
+ return { changed: true, tabId, ...tabStateView(next) };
4679
4724
  }
4680
4725
  case "clipboard":
4681
4726
  return { tabId, ...await clipboard(page, input), scope: "system" };
@@ -5231,6 +5276,7 @@ class NativeRuntime {
5231
5276
  operations = new Map;
5232
5277
  hooks = Promise.resolve();
5233
5278
  browserId;
5279
+ userControlledTabs = new Set;
5234
5280
  constructor(context, instanceId, directory, serverOrigin) {
5235
5281
  this.context = context;
5236
5282
  this.instanceId = instanceId;
@@ -5470,7 +5516,11 @@ class NativeRuntime {
5470
5516
  this.operations.get(operationId)?.abort(new Error("Blocked target closed by approved recovery"));
5471
5517
  return { closed: true };
5472
5518
  }
5473
- admissionGuard(args, scope) {
5519
+ assertAgentControl(tabId, op) {
5520
+ if (typeof tabId === "string" && this.userControlledTabs.has(tabId) && op !== "release_tab" && op !== "session_end")
5521
+ throw new RuntimeFault("user_in_control", USER_IN_CONTROL_RECOVERY, true);
5522
+ }
5523
+ admissionGuard(args, scope, op) {
5474
5524
  const epoch = this.scopeEpoch(scope), connectionEpoch = this.connectionEpoch;
5475
5525
  const tabId = typeof args.tabId === "string" ? args.tabId : undefined;
5476
5526
  const page = tabId ? this.engine.page(tabId) : undefined;
@@ -5478,6 +5528,7 @@ class NativeRuntime {
5478
5528
  return (checkDocument = true) => {
5479
5529
  if (this.scopeEpoch(scope) !== epoch || this.connectionEpoch !== connectionEpoch)
5480
5530
  throw new RuntimeFault("scope_rejected", "Scope or connection changed while waiting; submit a fresh authorized request.", true);
5531
+ this.assertAgentControl(tabId, op);
5481
5532
  if (tabId) {
5482
5533
  let current2;
5483
5534
  try {
@@ -5528,6 +5579,7 @@ class NativeRuntime {
5528
5579
  await this.hooks;
5529
5580
  this.validateScope(scope);
5530
5581
  if (typeof args.tabId === "string") {
5582
+ this.assertAgentControl(args.tabId, op);
5531
5583
  const page = await this.claimPage(args.tabId, scope);
5532
5584
  await this.track(page);
5533
5585
  this.assertPageAvailable(page);
@@ -5669,6 +5721,53 @@ function sanitizeLiveEvent(value) {
5669
5721
  return null;
5670
5722
  }
5671
5723
  }
5724
+ var LIVE_MODIFIERS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
5725
+ var MAX_LIVE_INPUT_TEXT = 200;
5726
+ var isLiveRelease = (event) => event.kind === "release" || (event.kind === "mouse" || event.kind === "key") && event.type === "up";
5727
+ var MAX_LIVE_DIALOG_TEXT = 500;
5728
+ var MAX_CONTROL_TABS = 8;
5729
+ var modifierMask = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 15;
5730
+ var NAMED_KEY = /^[A-Za-z][A-Za-z0-9]{1,31}$/;
5731
+ var KEY_CODE = /^[A-Za-z0-9]{0,32}$/;
5732
+ var CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/;
5733
+ var LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
5734
+ var cleanText = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max && !CONTROL.test(value) && !LONE_SURROGATE.test(value);
5735
+ var keyValue = (value) => typeof value === "string" && (NAMED_KEY.test(value) || value.length <= 4 && cleanText(value, 4) && !/[\t\n\r]/.test(value));
5736
+ var button = (value) => value === "left" || value === "middle" || value === "right";
5737
+ function sanitizeLiveInput(value) {
5738
+ if (!value || typeof value !== "object" || Array.isArray(value))
5739
+ return null;
5740
+ const e = value;
5741
+ const mac = e.mac === true;
5742
+ switch (e.kind) {
5743
+ case "mouse":
5744
+ if (e.type !== "move" && e.type !== "down" && e.type !== "up" || !coordinate(e.x) || !coordinate(e.y) || !button(e.button) || !modifierMask(e.modifiers) || typeof e.clickCount !== "number" || !Number.isInteger(e.clickCount) || e.clickCount < 0 || e.clickCount > 3)
5745
+ return null;
5746
+ return { kind: "mouse", type: e.type, x: e.x, y: e.y, button: e.button, clickCount: e.type === "move" ? 0 : Math.max(1, e.clickCount), modifiers: e.modifiers, mac };
5747
+ case "wheel":
5748
+ if (!coordinate(e.x) || !coordinate(e.y) || !coordinate(e.deltaX) || !coordinate(e.deltaY) || !modifierMask(e.modifiers))
5749
+ return null;
5750
+ return { kind: "wheel", x: e.x, y: e.y, deltaX: e.deltaX, deltaY: e.deltaY, modifiers: e.modifiers, mac };
5751
+ case "key":
5752
+ if (e.type !== "down" && e.type !== "up" || !keyValue(e.key) || typeof e.code !== "string" || !KEY_CODE.test(e.code) || !modifierMask(e.modifiers))
5753
+ return null;
5754
+ return { kind: "key", type: e.type, key: e.key, code: e.code, modifiers: e.modifiers, repeat: e.repeat === true, mac };
5755
+ case "text":
5756
+ return cleanText(e.text, MAX_LIVE_INPUT_TEXT) ? { kind: "text", text: e.text } : null;
5757
+ case "release":
5758
+ return { kind: "release" };
5759
+ case "dialog":
5760
+ if (typeof e.accept !== "boolean")
5761
+ return null;
5762
+ if (e.text === undefined)
5763
+ return { kind: "dialog", accept: e.accept };
5764
+ return typeof e.text === "string" && e.text.length <= MAX_LIVE_DIALOG_TEXT && !CONTROL.test(e.text) && !LONE_SURROGATE.test(e.text) ? { kind: "dialog", accept: e.accept, text: e.text } : null;
5765
+ default:
5766
+ return null;
5767
+ }
5768
+ }
5769
+ var DIALOG_TYPES = new Set(["alert", "confirm", "prompt", "beforeunload"]);
5770
+ var MAX_LIVE_DIALOG_MESSAGE = 500;
5672
5771
 
5673
5772
  // cli/src/live/wire.ts
5674
5773
  function mediaURL(server) {
@@ -5722,6 +5821,7 @@ function eventMessage(value, navSeq) {
5722
5821
 
5723
5822
  // cli/src/live/producer.ts
5724
5823
  var STAGE_TIMEOUT_MS = 5000;
5824
+ var MAX_ATTACH_RETRIES = 4;
5725
5825
 
5726
5826
  class CaptureTimeout extends Error {
5727
5827
  stage;
@@ -5747,6 +5847,7 @@ class NativeLiveProducer {
5747
5847
  active = false;
5748
5848
  closed = false;
5749
5849
  tab;
5850
+ controlTab;
5750
5851
  generation = 0;
5751
5852
  serial = Promise.resolve();
5752
5853
  socket;
@@ -5755,8 +5856,9 @@ class NativeLiveProducer {
5755
5856
  unlisten;
5756
5857
  frameSeq = 0;
5757
5858
  navSeq = 0;
5758
- lastFrame = 0;
5759
5859
  eventWindow = { start: 0, count: 0 };
5860
+ retries = 0;
5861
+ retryTab;
5760
5862
  constructor(options) {
5761
5863
  this.options = options;
5762
5864
  const url = new URL(options.mediaUrl);
@@ -5776,17 +5878,27 @@ class NativeLiveProducer {
5776
5878
  if (this.closed)
5777
5879
  return this.serial;
5778
5880
  this.active = frame.active === true;
5779
- if (isRuntimeTabId(frame.followTabId))
5881
+ if (isRuntimeTabId(frame.followTabId) && (!this.controlTab || frame.followTabId === this.controlTab))
5780
5882
  this.tab = frame.followTabId;
5781
5883
  return this.schedule();
5782
5884
  }
5783
5885
  followTab(runtimeTabId) {
5784
- if (this.closed || !isRuntimeTabId(runtimeTabId) || runtimeTabId === this.tab)
5886
+ if (this.closed || !isRuntimeTabId(runtimeTabId) || runtimeTabId === this.tab || this.controlTab && runtimeTabId !== this.controlTab)
5785
5887
  return this.serial;
5786
5888
  this.tab = runtimeTabId;
5787
5889
  this.navSeq++;
5788
5890
  return this.schedule();
5789
5891
  }
5892
+ setControl(runtimeTabId) {
5893
+ if (this.closed)
5894
+ return this.serial;
5895
+ this.controlTab = isRuntimeTabId(runtimeTabId) ? runtimeTabId : undefined;
5896
+ if (!this.controlTab || this.controlTab === this.tab)
5897
+ return this.serial;
5898
+ this.tab = this.controlTab;
5899
+ this.navSeq++;
5900
+ return this.schedule();
5901
+ }
5790
5902
  emitCursor(event) {
5791
5903
  const ws = this.socket;
5792
5904
  if (!this.enabled || !this.active || this.closed || !ws || ws.readyState !== WebSocket.OPEN || ws.bufferedAmount > 512 * 1024)
@@ -5824,6 +5936,23 @@ class NativeLiveProducer {
5824
5936
  });
5825
5937
  return this.serial;
5826
5938
  }
5939
+ retry(generation, detail) {
5940
+ if (generation !== this.generation)
5941
+ return;
5942
+ if (this.retryTab !== this.tab) {
5943
+ this.retryTab = this.tab;
5944
+ this.retries = 0;
5945
+ }
5946
+ if (this.retries >= MAX_ATTACH_RETRIES) {
5947
+ this.state("blocked", detail);
5948
+ return;
5949
+ }
5950
+ const timer2 = setTimeout(() => {
5951
+ if (generation === this.generation)
5952
+ this.schedule();
5953
+ }, 250 * ++this.retries);
5954
+ timer2.unref?.();
5955
+ }
5827
5956
  async teardown() {
5828
5957
  clearInterval(this.heartbeat);
5829
5958
  this.heartbeat = undefined;
@@ -5873,8 +6002,13 @@ class NativeLiveProducer {
5873
6002
  this.state("blocked", error instanceof CaptureTimeout ? `${error.stage}_timeout` : "page_unavailable");
5874
6003
  return;
5875
6004
  }
5876
- if (generation !== this.generation || initialNav !== this.navSeq) {
6005
+ if (generation !== this.generation) {
6006
+ await this.teardown();
6007
+ return;
6008
+ }
6009
+ if (initialNav !== this.navSeq) {
5877
6010
  await this.teardown();
6011
+ this.retry(generation, "page_unavailable");
5878
6012
  return;
5879
6013
  }
5880
6014
  if (!authorized) {
@@ -5915,7 +6049,7 @@ class NativeLiveProducer {
5915
6049
  }
5916
6050
  ws.on("error", () => {});
5917
6051
  ws.once("close", () => {
5918
- if (generation === this.generation && !this.closed) {
6052
+ if (generation === this.generation && !this.closed && this.socket === ws) {
5919
6053
  this.active = false;
5920
6054
  this.schedule();
5921
6055
  }
@@ -5945,33 +6079,29 @@ class NativeLiveProducer {
5945
6079
  return;
5946
6080
  }
5947
6081
  let checkingFrame = false;
5948
- cdp.on("Page.screencastFrame", (event) => {
5949
- cdp.send("Page.screencastFrameAck", { sessionId: event.sessionId }).catch(() => {});
5950
- if (generation !== this.generation || !this.enabled || !this.active || ws.readyState !== WebSocket.OPEN)
6082
+ let lastFrame = 0;
6083
+ let deferred;
6084
+ const forward = (event, nav) => {
6085
+ if (generation !== this.generation || nav !== this.navSeq || !this.enabled || !this.active || ws.readyState !== WebSocket.OPEN)
5951
6086
  return;
5952
- let allowed = false;
5953
- try {
5954
- allowed = this.options.getPage(tab) === page;
5955
- } catch {}
5956
- if (!allowed) {
5957
- this.active = false;
5958
- this.schedule();
6087
+ const wait = Math.max(lastFrame + 100 - Date.now(), checkingFrame || ws.bufferedAmount > 512 * 1024 ? 100 : 0);
6088
+ if (wait > 0) {
6089
+ clearTimeout(deferred);
6090
+ deferred = setTimeout(() => {
6091
+ deferred = undefined;
6092
+ forward(event, nav);
6093
+ }, wait);
6094
+ deferred.unref?.();
5959
6095
  return;
5960
6096
  }
5961
- const now = Date.now();
5962
- if (now - this.lastFrame < 100 || ws.bufferedAmount > 512 * 1024 || event.data.length > Math.ceil(MAX_LIVE_FRAME_BYTES / 3) * 4)
5963
- return;
5964
- if (checkingFrame)
5965
- return;
5966
- this.lastFrame = now;
6097
+ lastFrame = Date.now();
5967
6098
  checkingFrame = true;
5968
- const nav = this.navSeq;
5969
6099
  (async () => {
5970
6100
  try {
5971
- const allowed2 = await bounded2("frame_authorize", this.options.authorizePage(page));
6101
+ const allowed = await bounded2("frame_authorize", this.options.authorizePage(page));
5972
6102
  if (generation !== this.generation || nav !== this.navSeq || this.closed || !this.enabled || !this.active || this.socket !== ws || ws.readyState !== WebSocket.OPEN)
5973
6103
  return;
5974
- if (!allowed2 || this.options.getPage(tab) !== page) {
6104
+ if (!allowed || this.options.getPage(tab) !== page) {
5975
6105
  this.active = false;
5976
6106
  this.schedule();
5977
6107
  return;
@@ -5982,12 +6112,40 @@ class NativeLiveProducer {
5982
6112
  checkingFrame = false;
5983
6113
  }
5984
6114
  })();
6115
+ };
6116
+ cdp.on("Page.screencastFrame", (event) => {
6117
+ cdp.send("Page.screencastFrameAck", { sessionId: event.sessionId }).catch(() => {});
6118
+ if (generation !== this.generation || !this.enabled || !this.active || ws.readyState !== WebSocket.OPEN)
6119
+ return;
6120
+ let allowed = false;
6121
+ try {
6122
+ allowed = this.options.getPage(tab) === page;
6123
+ } catch {}
6124
+ if (!allowed) {
6125
+ this.active = false;
6126
+ this.schedule();
6127
+ return;
6128
+ }
6129
+ if (event.data.length > Math.ceil(MAX_LIVE_FRAME_BYTES / 3) * 4)
6130
+ return;
6131
+ forward(event, this.navSeq);
5985
6132
  });
5986
6133
  const startNav = this.navSeq;
5987
- if (!await bounded2("authorize", this.options.authorizePage(page)) || generation !== this.generation || startNav !== this.navSeq) {
6134
+ const stillAllowed = await bounded2("authorize", this.options.authorizePage(page));
6135
+ if (generation !== this.generation) {
5988
6136
  await this.teardown();
5989
6137
  return;
5990
6138
  }
6139
+ if (startNav !== this.navSeq) {
6140
+ await this.teardown();
6141
+ this.retry(generation, "capture_unavailable");
6142
+ return;
6143
+ }
6144
+ if (!stillAllowed) {
6145
+ await this.teardown();
6146
+ this.state("blocked", "page_unavailable");
6147
+ return;
6148
+ }
5991
6149
  await bounded2("start_screencast", cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 1600, maxHeight: 1000, everyNthFrame: 1 }));
5992
6150
  if (generation !== this.generation) {
5993
6151
  await this.teardown();
@@ -5998,18 +6156,360 @@ class NativeLiveProducer {
5998
6156
  ws.send('{"type":"ping"}');
5999
6157
  }, 20000);
6000
6158
  this.heartbeat.unref?.();
6159
+ this.retries = 0;
6001
6160
  this.state("streaming");
6002
6161
  } catch (error) {
6003
6162
  await this.teardown();
6004
- if (generation === this.generation)
6005
- this.state("blocked", error instanceof CaptureTimeout ? `${error.stage}_timeout` : "capture_unavailable");
6163
+ if (generation !== this.generation)
6164
+ return;
6165
+ const detail = error instanceof CaptureTimeout ? `${error.stage}_timeout` : "capture_unavailable";
6166
+ if (!page.isClosed())
6167
+ this.retry(generation, detail);
6168
+ else
6169
+ this.state("blocked", detail);
6006
6170
  }
6007
6171
  }
6008
6172
  }
6009
6173
 
6174
+ // cli/src/live/takeover.ts
6175
+ var MAX_QUEUE = 128;
6176
+ var STEP_TIMEOUT_MS = 3000;
6177
+ var DIALOG_TYPES2 = new Set(["alert", "confirm", "prompt", "beforeunload"]);
6178
+ var MODIFIERS = Object.entries(LIVE_MODIFIERS);
6179
+ async function bounded3(work, ms) {
6180
+ let timer2;
6181
+ await Promise.race([work.catch(() => {}), new Promise((resolve2) => {
6182
+ timer2 = setTimeout(resolve2, ms);
6183
+ })]);
6184
+ clearTimeout(timer2);
6185
+ }
6186
+
6187
+ class TakeoverInput {
6188
+ options;
6189
+ group;
6190
+ queue = [];
6191
+ pumping;
6192
+ releases = new Map;
6193
+ constructor(options) {
6194
+ this.options = options;
6195
+ }
6196
+ get currentTab() {
6197
+ return this.group?.session?.tabId;
6198
+ }
6199
+ activate(root) {
6200
+ if (!isRuntimeTabId(root) || this.group?.root === root)
6201
+ return;
6202
+ this.deactivate();
6203
+ const page = this.options.getPage(root);
6204
+ if (!page || page.isClosed()) {
6205
+ this.lost(root);
6206
+ return;
6207
+ }
6208
+ const group = { root, tabs: [root], ended: false, cleanup: [] };
6209
+ this.group = group;
6210
+ this.join(group, root, page);
6211
+ this.focus(group, root, page);
6212
+ }
6213
+ deactivate() {
6214
+ const group = this.group;
6215
+ if (group)
6216
+ this.end(group);
6217
+ }
6218
+ input(frame) {
6219
+ const session = this.group?.session;
6220
+ if (!session || frame.runtimeTabId !== session.tabId)
6221
+ return;
6222
+ const event = sanitizeLiveInput(frame.event);
6223
+ if (!event)
6224
+ return;
6225
+ if (event.kind === "dialog") {
6226
+ this.answerDialog(this.options.events(session.page), event).catch(() => {});
6227
+ return;
6228
+ }
6229
+ const last = this.queue[this.queue.length - 1];
6230
+ if (event.kind === "mouse" && event.type === "move" && last?.session === session && last.event.kind === "mouse" && last.event.type === "move") {
6231
+ last.event = event;
6232
+ return;
6233
+ }
6234
+ const essential = isLiveRelease(event);
6235
+ if (this.queue.length >= (essential ? MAX_QUEUE * 2 : MAX_QUEUE))
6236
+ return;
6237
+ this.push({ session, event });
6238
+ }
6239
+ async settled(tabId) {
6240
+ const release = this.releases.get(tabId);
6241
+ if (release)
6242
+ await bounded3(release, STEP_TIMEOUT_MS);
6243
+ }
6244
+ async stop() {
6245
+ this.deactivate();
6246
+ const pumping = this.pumping;
6247
+ if (pumping)
6248
+ await bounded3(pumping, STEP_TIMEOUT_MS);
6249
+ }
6250
+ join(group, tabId, page) {
6251
+ const onClose = () => this.left(group, tabId);
6252
+ const onPopup = (popup) => {
6253
+ this.opened(group, popup);
6254
+ };
6255
+ page.on("close", onClose);
6256
+ page.on("popup", onPopup);
6257
+ group.cleanup.push(() => {
6258
+ page.off("close", onClose);
6259
+ page.off("popup", onPopup);
6260
+ });
6261
+ }
6262
+ async opened(group, popup) {
6263
+ let id;
6264
+ try {
6265
+ id = await this.options.idFor(popup);
6266
+ } catch {
6267
+ return;
6268
+ }
6269
+ if (group.ended || this.group !== group || !isRuntimeTabId(id) || popup.isClosed() || group.tabs.includes(id) || group.tabs.length >= MAX_CONTROL_TABS)
6270
+ return;
6271
+ group.tabs.push(id);
6272
+ this.join(group, id, popup);
6273
+ this.focus(group, id, popup);
6274
+ }
6275
+ left(group, tabId) {
6276
+ if (group.ended || this.group !== group)
6277
+ return;
6278
+ if (tabId === group.root) {
6279
+ this.end(group);
6280
+ this.lost(tabId);
6281
+ return;
6282
+ }
6283
+ group.tabs = group.tabs.filter((id) => id !== tabId);
6284
+ if (group.session?.tabId !== tabId) {
6285
+ this.report(group);
6286
+ return;
6287
+ }
6288
+ for (const id of [...group.tabs].reverse()) {
6289
+ const page = this.options.getPage(id);
6290
+ if (page && !page.isClosed()) {
6291
+ this.focus(group, id, page);
6292
+ return;
6293
+ }
6294
+ }
6295
+ this.end(group);
6296
+ this.lost(group.root);
6297
+ }
6298
+ focus(group, tabId, page) {
6299
+ if (group.session)
6300
+ this.close(group.session);
6301
+ const session = { tabId, page, keys: new Map, buttons: new Set, pointer: { x: Number.NaN, y: Number.NaN }, ended: false, cleanup: [] };
6302
+ group.session = session;
6303
+ const gate = this.options.agentActivity(tabId);
6304
+ if (gate) {
6305
+ session.gate = gate;
6306
+ gate.then(() => {
6307
+ if (session.gate !== gate)
6308
+ return;
6309
+ session.gate = undefined;
6310
+ if (group.session === session && !session.ended)
6311
+ this.report(group);
6312
+ });
6313
+ }
6314
+ const events = this.options.events(page);
6315
+ if (events)
6316
+ session.cleanup.push(events.onDialog((dialog) => {
6317
+ if (group.session === session && !session.ended)
6318
+ this.reportDialog(tabId, dialog);
6319
+ }));
6320
+ this.report(group);
6321
+ const open2 = events?.dialogDetails();
6322
+ if (open2)
6323
+ this.reportDialog(tabId, open2);
6324
+ }
6325
+ close(session) {
6326
+ session.ended = true;
6327
+ for (const done of session.cleanup.splice(0)) {
6328
+ try {
6329
+ done();
6330
+ } catch {}
6331
+ }
6332
+ this.queue = this.queue.filter((item) => item.session !== session);
6333
+ let finish;
6334
+ const released = new Promise((resolve2) => {
6335
+ finish = resolve2;
6336
+ });
6337
+ this.releases.set(session.tabId, released);
6338
+ released.then(() => {
6339
+ if (this.releases.get(session.tabId) === released)
6340
+ this.releases.delete(session.tabId);
6341
+ });
6342
+ this.push({ session, event: { kind: "release_all" }, done: finish });
6343
+ }
6344
+ end(group) {
6345
+ group.ended = true;
6346
+ if (this.group === group)
6347
+ this.group = undefined;
6348
+ for (const done of group.cleanup.splice(0)) {
6349
+ try {
6350
+ done();
6351
+ } catch {}
6352
+ }
6353
+ if (group.session && !group.session.ended)
6354
+ this.close(group.session);
6355
+ }
6356
+ report(group) {
6357
+ const session = group.session;
6358
+ if (group.ended || this.group !== group || !session)
6359
+ return;
6360
+ this.options.onTabs([...group.tabs], session.tabId);
6361
+ this.options.sendEvent({ type: "event", event: "live_control_state", runtimeTabId: group.root, tabs: [...group.tabs], current: session.tabId, busy: !!session.gate });
6362
+ }
6363
+ lost(tabId) {
6364
+ this.options.sendEvent({ type: "event", event: "live_control_lost", runtimeTabId: tabId, reason: "tab_closed" });
6365
+ }
6366
+ reportDialog(tabId, dialog) {
6367
+ const type = dialog?.type;
6368
+ this.options.sendEvent({
6369
+ type: "event",
6370
+ event: "live_dialog",
6371
+ runtimeTabId: tabId,
6372
+ dialog: dialog && type && DIALOG_TYPES2.has(type) ? { type, message: dialog.message.slice(0, MAX_LIVE_DIALOG_MESSAGE), ...type === "prompt" ? { defaultValue: dialog.defaultValue.slice(0, MAX_LIVE_DIALOG_TEXT) } : {} } : null
6373
+ });
6374
+ }
6375
+ push(item) {
6376
+ this.queue.push(item);
6377
+ if (this.pumping)
6378
+ return;
6379
+ this.pumping = (async () => {
6380
+ while (this.queue.length) {
6381
+ const item2 = this.queue.shift();
6382
+ const { session, event } = item2;
6383
+ try {
6384
+ if (event.kind !== "release_all") {
6385
+ if (session.ended)
6386
+ continue;
6387
+ if (session.gate)
6388
+ await session.gate;
6389
+ if (session.ended)
6390
+ continue;
6391
+ }
6392
+ await bounded3(this.dispatch(session, event), STEP_TIMEOUT_MS);
6393
+ } finally {
6394
+ item2.done?.();
6395
+ }
6396
+ }
6397
+ })().finally(() => {
6398
+ this.pumping = undefined;
6399
+ });
6400
+ }
6401
+ keyName(key2, mac) {
6402
+ if (mac === this.options.hostMac)
6403
+ return key2;
6404
+ return key2 === "Meta" ? "Control" : key2 === "Control" ? "Meta" : key2;
6405
+ }
6406
+ modifierMask(mask, mac) {
6407
+ if (mac === this.options.hostMac)
6408
+ return mask;
6409
+ const { Control, Meta } = LIVE_MODIFIERS;
6410
+ return mask & ~(Control | Meta) | (mask & Control ? Meta : 0) | (mask & Meta ? Control : 0);
6411
+ }
6412
+ async dispatch(session, event) {
6413
+ const { page } = session;
6414
+ if (page.isClosed())
6415
+ return;
6416
+ if (event.kind === "release_all" || event.kind === "release") {
6417
+ await this.releaseAll(session);
6418
+ return;
6419
+ }
6420
+ const events = this.options.events(page);
6421
+ if (event.kind === "dialog") {
6422
+ await this.answerDialog(events, event);
6423
+ return;
6424
+ }
6425
+ if (events?.dialogDetails())
6426
+ return;
6427
+ switch (event.kind) {
6428
+ case "mouse": {
6429
+ await this.syncModifiers(session, this.modifierMask(event.modifiers, event.mac));
6430
+ if (event.type === "move" || session.pointer.x !== event.x || session.pointer.y !== event.y) {
6431
+ session.pointer = { x: event.x, y: event.y };
6432
+ await page.mouse.move(event.x, event.y);
6433
+ }
6434
+ if (event.type === "down") {
6435
+ session.buttons.add(event.button);
6436
+ await page.mouse.down({ button: event.button, clickCount: event.clickCount });
6437
+ } else if (event.type === "up" && session.buttons.delete(event.button)) {
6438
+ await page.mouse.up({ button: event.button, clickCount: event.clickCount });
6439
+ }
6440
+ return;
6441
+ }
6442
+ case "wheel":
6443
+ await this.syncModifiers(session, this.modifierMask(event.modifiers, event.mac));
6444
+ if (session.pointer.x !== event.x || session.pointer.y !== event.y) {
6445
+ session.pointer = { x: event.x, y: event.y };
6446
+ await page.mouse.move(event.x, event.y);
6447
+ }
6448
+ await page.mouse.wheel(event.deltaX, event.deltaY);
6449
+ return;
6450
+ case "key": {
6451
+ const key2 = this.keyName(event.key, event.mac);
6452
+ const id = event.code || key2;
6453
+ if (event.type === "up") {
6454
+ const pressed = session.keys.get(id);
6455
+ if (pressed === undefined)
6456
+ return;
6457
+ session.keys.delete(id);
6458
+ await page.keyboard.up(pressed);
6459
+ return;
6460
+ }
6461
+ session.keys.set(id, key2);
6462
+ try {
6463
+ await page.keyboard.down(key2);
6464
+ } catch (error) {
6465
+ session.keys.delete(id);
6466
+ if (error instanceof Error && /Unknown key/.test(error.message) && [...key2].length === 1)
6467
+ await page.keyboard.insertText(key2);
6468
+ }
6469
+ return;
6470
+ }
6471
+ case "text":
6472
+ await page.keyboard.insertText(event.text);
6473
+ return;
6474
+ }
6475
+ }
6476
+ async syncModifiers(session, mask) {
6477
+ for (const [name, bit] of MODIFIERS) {
6478
+ const held = [...session.keys].filter(([, key2]) => key2 === name);
6479
+ if (mask & bit) {
6480
+ if (held.length)
6481
+ continue;
6482
+ session.keys.set(`modifier:${name}`, name);
6483
+ await session.page.keyboard.down(name);
6484
+ } else if (held.length) {
6485
+ for (const [id] of held)
6486
+ session.keys.delete(id);
6487
+ await session.page.keyboard.up(name);
6488
+ }
6489
+ }
6490
+ }
6491
+ async releaseAll(session) {
6492
+ const buttons = [...session.buttons], keys = new Set(session.keys.values());
6493
+ session.buttons.clear();
6494
+ session.keys.clear();
6495
+ for (const button2 of buttons)
6496
+ await session.page.mouse.up({ button: button2 }).catch(() => {});
6497
+ for (const key2 of keys)
6498
+ await session.page.keyboard.up(key2).catch(() => {});
6499
+ }
6500
+ async answerDialog(events, event) {
6501
+ const dialog = events?.activeDialog(), details = events?.dialogDetails();
6502
+ if (!events || !dialog || !details)
6503
+ return;
6504
+ const prompt = details.type === "prompt" && event.accept && event.text !== undefined;
6505
+ await events.handleDialog({ dialogId: dialog.dialogId, decision: event.accept ? "accept" : "dismiss", ...prompt ? { promptText: event.text } : {} }, "viewer");
6506
+ }
6507
+ }
6508
+
6010
6509
  // cli/src/runtime/relay.ts
6011
6510
  var sameScope3 = (a, b) => a.browserId === b.browserId && a.tokenId === b.tokenId && a.sessionKey === b.sessionKey && a.instanceId === b.instanceId;
6012
6511
  var QUEUE_LIMITS = Object.freeze({ maxWaiting: 16, maxWaitingPerScope: 8, maxWaitMs: 5000 });
6512
+ var INPUT_OPERATIONS = new Set(["mouse_click", "move_mouse", "hover", "drag", "scroll", "keyboard", "keyboard_type", "form_input", "select_text", "edit_text", "batch"]);
6013
6513
  var LIMIT = 2 * 1024 * 1024;
6014
6514
  function wireResult(op, value) {
6015
6515
  if (!value || typeof value !== "object")
@@ -6072,13 +6572,13 @@ class Relay {
6072
6572
  this.active?.interrupt();
6073
6573
  this.flushWaiting(code2, "The runtime was interrupted. Waiting work was never dispatched; reconnect and re-observe before submitting a fresh request.");
6074
6574
  }
6075
- rejectWaiting(entry, code2, message) {
6575
+ rejectWaiting(entry, code2, message, recovery) {
6076
6576
  const index = this.waiting.indexOf(entry);
6077
6577
  if (index < 0)
6078
6578
  return;
6079
6579
  this.waiting.splice(index, 1);
6080
6580
  clearTimeout(entry.timer);
6081
- const result = { operationId: entry.message.id, category: code2, executionState: "not_started", rejectedBeforeAdmission: true, retrySafe: true, cancellationConfirmed: true, quarantined: !!this.active && (this.active.timedOut || this.active.interrupted), recovery: "This request was never dispatched. Check browser_runtime_health and current target/authority before submitting a fresh request ID; never replay the blocking operation." };
6581
+ const result = { operationId: entry.message.id, category: code2, executionState: "not_started", rejectedBeforeAdmission: true, retrySafe: true, cancellationConfirmed: true, quarantined: !!this.active && (this.active.timedOut || this.active.interrupted), recovery: recovery ?? "This request was never dispatched. Check browser_runtime_health and current target/authority before submitting a fresh request ID; never replay the blocking operation." };
6082
6582
  entry.send({ type: "result", id: entry.message.id, ok: false, outcome: "not_dispatched", error: { code: code2, message }, result });
6083
6583
  this.recent.push({ scope: entry.message.scope, result });
6084
6584
  if (this.recent.length > 32)
@@ -6135,8 +6635,11 @@ class Relay {
6135
6635
  }
6136
6636
  try {
6137
6637
  entry.guard();
6138
- } catch {
6139
- this.rejectWaiting(entry, "stale_queued_request", "Scope, target identity or document changed while waiting. No action was dispatched.");
6638
+ } catch (error) {
6639
+ if (error instanceof RuntimeFault && error.code === "user_in_control")
6640
+ this.rejectWaiting(entry, "user_in_control", USER_IN_CONTROL_MESSAGE, error.recovery);
6641
+ else
6642
+ this.rejectWaiting(entry, "stale_queued_request", "Scope, target identity or document changed while waiting. No action was dispatched.");
6140
6643
  this.drain();
6141
6644
  return;
6142
6645
  }
@@ -6158,12 +6661,67 @@ class Relay {
6158
6661
  }
6159
6662
  state = "disconnected";
6160
6663
  paused = false;
6664
+ control;
6665
+ watch;
6666
+ takeover;
6161
6667
  constructor(runtime, server, token, previewDirectory, liveEnabled = false) {
6162
6668
  this.runtime = runtime;
6163
6669
  this.server = server;
6164
6670
  this.token = token;
6165
6671
  this.previewDirectory = previewDirectory;
6166
6672
  this.liveEnabled = liveEnabled;
6673
+ this.takeover = new TakeoverInput({
6674
+ getPage: (id) => {
6675
+ try {
6676
+ return this.runtime.engine.page(id);
6677
+ } catch {
6678
+ return;
6679
+ }
6680
+ },
6681
+ idFor: (page) => this.runtime.engine.idFor(page),
6682
+ events: (page) => this.runtime.engine.pageEvents(page),
6683
+ agentActivity: (tab) => {
6684
+ const active = this.active;
6685
+ if (!active || active.settled || active.tabId !== tab || !INPUT_OPERATIONS.has(active.op))
6686
+ return;
6687
+ let timer2;
6688
+ return Promise.race([active.done, new Promise((resolve2) => {
6689
+ timer2 = setTimeout(resolve2, Math.max(0, active.deadlineAt - Date.now()));
6690
+ })]).finally(() => clearTimeout(timer2));
6691
+ },
6692
+ onTabs: (tabs, current2) => {
6693
+ if (this.control)
6694
+ this.controlled(tabs, current2);
6695
+ },
6696
+ sendEvent: (event) => {
6697
+ const socket = this.socket;
6698
+ if (socket?.readyState === WebSocket2.OPEN)
6699
+ socket.send(JSON.stringify(event));
6700
+ },
6701
+ hostMac: process.platform === "darwin"
6702
+ });
6703
+ }
6704
+ setControl(tab) {
6705
+ if (tab !== undefined && (!this.liveEnabled || !isRuntimeTabId(tab)))
6706
+ tab = undefined;
6707
+ if (tab === this.control)
6708
+ return;
6709
+ this.control = tab;
6710
+ if (tab) {
6711
+ this.controlled([tab], tab);
6712
+ this.takeover.activate(tab);
6713
+ } else {
6714
+ this.takeover.deactivate();
6715
+ this.controlled([], undefined);
6716
+ }
6717
+ this.drain();
6718
+ }
6719
+ controlled(tabs, current2) {
6720
+ this.runtime.userControlledTabs = new Set(tabs);
6721
+ for (const entry of [...this.waiting])
6722
+ if (typeof entry.message.args?.tabId === "string" && this.runtime.userControlledTabs.has(entry.message.args.tabId) && entry.message.op !== "release_tab")
6723
+ this.rejectWaiting(entry, "user_in_control", USER_IN_CONTROL_MESSAGE, USER_IN_CONTROL_RECOVERY);
6724
+ this.live?.setControl(current2).catch(() => {});
6167
6725
  }
6168
6726
  async start() {
6169
6727
  while (!this.stopping) {
@@ -6172,6 +6730,8 @@ class Relay {
6172
6730
  continue;
6173
6731
  }
6174
6732
  await this.connect().catch(() => {});
6733
+ this.setControl(undefined);
6734
+ this.watch = undefined;
6175
6735
  await this.live?.stop();
6176
6736
  this.live = undefined;
6177
6737
  await this.runtime.disconnect();
@@ -6201,7 +6761,7 @@ class Relay {
6201
6761
  if (this.paused || this.stopping || socket !== this.socket || socket.readyState !== WebSocket2.OPEN)
6202
6762
  return;
6203
6763
  this.state = "authenticating";
6204
- socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.20", instanceId: this.runtime.instanceId, operations: [...BROWSER_OPERATIONS, ...this.runtime.plugins.flatMap((p) => p.operations), "session_end", "release_tab", "runtime_health", "runtime_recover"], capabilities: ["runtime-queue.v1", "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 } } }));
6764
+ socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.21", instanceId: this.runtime.instanceId, operations: [...BROWSER_OPERATIONS, ...this.runtime.plugins.flatMap((p) => p.operations), "session_end", "release_tab", "runtime_health", "runtime_recover"], capabilities: ["runtime-queue.v1", "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", "live-control.v1"], liveView: { enabled: this.liveEnabled } } }));
6205
6765
  });
6206
6766
  socket.on("message", (bytes, binary) => {
6207
6767
  if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
@@ -6245,11 +6805,24 @@ class Relay {
6245
6805
  if (socket.readyState === WebSocket2.OPEN)
6246
6806
  socket.send(JSON.stringify(event));
6247
6807
  } });
6808
+ if (this.control)
6809
+ this.live.setControl(this.takeover.currentTab ?? this.control).catch(() => {});
6810
+ if (this.watch)
6811
+ this.live.onWatch(this.watch).catch(() => {});
6248
6812
  this.live.setEnabled(this.liveEnabled);
6249
6813
  console.error("Browser MCP connected (dedicated Chrome; local pause available)");
6250
6814
  })().catch(() => socket.close(1011));
6251
6815
  } else if (message.type === "watch") {
6252
- this.live?.onWatch(message).catch(() => {});
6816
+ if (socket === this.socket) {
6817
+ this.watch = message;
6818
+ this.live?.onWatch(message).catch(() => {});
6819
+ }
6820
+ } else if (message.type === "control") {
6821
+ if (socket === this.socket)
6822
+ this.setControl(message.active === true ? message.runtimeTabId : undefined);
6823
+ } else if (message.type === "input") {
6824
+ if (socket === this.socket && this.control)
6825
+ this.takeover.input(message);
6253
6826
  } else if (message.type === "ping")
6254
6827
  socket.send(JSON.stringify({ type: "pong" }));
6255
6828
  else if (message.type === "cancel" && typeof message.id === "string")
@@ -6339,9 +6912,13 @@ class Relay {
6339
6912
  }
6340
6913
  let guard;
6341
6914
  try {
6342
- guard = this.runtime.admissionGuard(message.args, message.scope);
6915
+ guard = this.runtime.admissionGuard(message.args, message.scope, message.op);
6343
6916
  guard();
6344
- } catch {
6917
+ } catch (error) {
6918
+ if (error instanceof RuntimeFault && error.code === "user_in_control") {
6919
+ reject("user_in_control", USER_IN_CONTROL_MESSAGE, { recovery: error.recovery });
6920
+ return;
6921
+ }
6345
6922
  reject("stale_queued_request", "Scope or target is unavailable. No action was dispatched.");
6346
6923
  return;
6347
6924
  }
@@ -6404,6 +6981,8 @@ class Relay {
6404
6981
  const task = (async () => {
6405
6982
  let response;
6406
6983
  try {
6984
+ if (typeof message.args.tabId === "string")
6985
+ await this.takeover.settled(message.args.tabId);
6407
6986
  const beforeDispatch = () => {
6408
6987
  if (active.timedOut || active.interrupted || this.stopping || this.paused || socket !== this.socket || socket.readyState !== WebSocket2.OPEN || Date.now() >= active.deadlineAt)
6409
6988
  throw new RuntimeFault("queue_wait_expired", "Request expired or was interrupted before browser dispatch.", true);
@@ -6526,7 +7105,9 @@ class Relay {
6526
7105
  this.interrupt("queue_paused");
6527
7106
  this.state = "paused";
6528
7107
  this.socket?.close();
7108
+ this.setControl(undefined);
6529
7109
  await this.live?.stop();
7110
+ await this.takeover.stop();
6530
7111
  await this.runtime.disconnect();
6531
7112
  }
6532
7113
  resume() {
@@ -6539,7 +7120,9 @@ class Relay {
6539
7120
  this.stopping = true;
6540
7121
  this.interrupt("queue_shutdown");
6541
7122
  this.socket?.close();
7123
+ this.setControl(undefined);
6542
7124
  await this.live?.stop();
7125
+ await this.takeover.stop();
6543
7126
  await this.runtime.disconnect();
6544
7127
  }
6545
7128
  }
@@ -7697,7 +8280,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
7697
8280
  return;
7698
8281
  } else if (cmd !== "status")
7699
8282
  throw new Error("Invalid command");
7700
- socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.20", protocol: 3 }) + `
8283
+ socket.end(JSON.stringify({ ...relay.health(), instanceId: session.instanceId, profile, version: "0.3.21", protocol: 3 }) + `
7701
8284
  `);
7702
8285
  })().catch(() => socket.destroy());
7703
8286
  });
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.20
11
+ console.log(`@ricsam/browser-mcp 0.3.21
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,11 +18,11 @@ 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.20");
21
+ console.log("0.3.21");
22
22
  return;
23
23
  }
24
24
  if (command === "browser")
25
- return (await import("./chunk-99qqnbnf.js")).runBrowser(args);
25
+ return (await import("./chunk-pj7a03s7.js")).runBrowser(args);
26
26
  if (command === "files")
27
27
  return (await import("./chunk-zv1900tw.js")).runFilesCommand(args);
28
28
  if (command === "secrets")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ricsam/browser-mcp",
3
- "version": "0.3.20",
3
+ "version": "0.3.21",
4
4
  "description": "Dedicated native Chrome companion for Browser MCP",
5
5
  "type": "module",
6
6
  "bin": { "browser-mcp": "dist/main.js" },