@mearl/client 3.3.0 → 3.3.2-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -25,7 +25,9 @@ Run `mearl guide` for the core workflow in this version. Use `mearl guide --list
25
25
 
26
26
  This package maintains its bundled guides in `guides/`, copies them to `dist/guides/` at build time, and checks them with `pnpm check:skills`. CLI output converts local document links into guide commands. `skills/mearl/` distributes a compact `SKILL.md`. MCP-only clients use the current tool descriptions and schemas.
27
27
 
28
- A unified browser SDK and CLI discovering browsers on this machine and all connectors under configured cloud-server instances. Global `browserId` from `browser_list` selects local Socket or cloud WebSocket routing automatically.
28
+ A unified browser SDK and CLI for browsers on this machine and configured cloud connectors. `browser_list` and launch or attach results from `browser_manage` return a `b_…` browser ID. Pass that ID to `--browser` for subsequent commands, including detach. The client routes each operation to the correct local or remote host.
29
+
30
+ Use a client and Native Host that support short IDs. Remote operations also require compatible Cloud Server and Cloud Connector versions.
29
31
 
30
32
  Use type-safe named methods such as `getRequests` and `sendRequest`, or the flexible low-level `invoke(action, payload)`.
31
33
 
package/README.md CHANGED
@@ -25,7 +25,9 @@
25
25
 
26
26
  本包随附的指南维护在 `guides/`,构建时复制到 `dist/guides/`,由 `pnpm check:skills` 校验一致性。CLI 输出将本地文档链接转换为指南命令。`skills/mearl/` 分发精简的 `SKILL.md`。仅使用 MCP 时,直接使用当前工具说明与 schema。
27
27
 
28
- 统一浏览器 SDK 与 CLI。它会发现当前机器及已配置 cloud-server 下所有 connector 的浏览器,并根据 `browser_list` 返回的全局 `browserId` 自动选择本地 Socket 或云端 WebSocket 链路。
28
+ 统一浏览器 SDK 与 CLI。它会发现当前机器和已配置云端连接器上的浏览器。`browser_list` 和 `browser_manage` 的接入或启动结果返回 `b_…` 格式的 `browserId`。把这个 ID 直接传给后续命令的 `--browser`,包括断开接入,客户端会选择对应的本地或远端链路。
29
+
30
+ 本机使用支持短 ID 的客户端和 Native Host,远端操作同时需要支持短 ID 的 Cloud Server 和 Cloud Connector。
29
31
 
30
32
  提供两种用法:类型安全的具名方法(`getRequests`、`sendRequest` 等),以及灵活的底层 `invoke(action, payload)`。
31
33
 
@@ -11,6 +11,7 @@
11
11
  import fs from 'node:fs';
12
12
  import os from 'node:os';
13
13
  import path from 'node:path';
14
+ import { decodeBrowserTarget } from './browserTarget.js';
14
15
  import { isDiscoverableBrowser, } from '@mearl/browser-core';
15
16
  /** Must match @mearl/daemon-core's DAEMON_HOME + the native-host 'browsers' subdir. */
16
17
  const BROWSERS_DIR = path.join(os.homedir(), '.mearl', 'browsers');
@@ -67,6 +68,12 @@ export function listLiveBrowsers() {
67
68
  * exact (case-insensitive) name, then a substring of id/name.
68
69
  */
69
70
  export function findBrowser(browsers, selector, exactOnly = false) {
71
+ const target = decodeBrowserTarget(selector);
72
+ if (target) {
73
+ return target.connector
74
+ ? null
75
+ : (browsers.find(browser => browser.browserId === target.browser) ?? null);
76
+ }
70
77
  const sel = selector.trim().toLowerCase();
71
78
  if (!sel)
72
79
  return null;
@@ -0,0 +1,11 @@
1
+ import type { BrowserTarget } from './browserTarget.js';
2
+ export declare function isShortBrowserId(id: string | undefined): id is `b_${string}`;
3
+ /** The index stores routing coordinates only. Browser liveness is checked by the target host. */
4
+ export declare class BrowserRoutes {
5
+ private readonly localScope;
6
+ private readonly remoteScope;
7
+ private readonly targets;
8
+ constructor(serverUrl?: string);
9
+ get(id: string): BrowserTarget | undefined;
10
+ remember(target: BrowserTarget): string;
11
+ }
@@ -0,0 +1,61 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { hostname } from 'node:os';
3
+ import { claimRecord, keyedConfigFile, readRecord } from '@mearl/daemon-core';
4
+ function hash(value) {
5
+ return createHash('sha256').update(JSON.stringify(value)).digest('hex');
6
+ }
7
+ export function isShortBrowserId(id) {
8
+ return typeof id === 'string' && /^b_[0-9a-f]{15}$/.test(id);
9
+ }
10
+ function routeId(scope, { browser, connector }) {
11
+ return `b_${hash([scope, connector ?? null, browser]).slice(0, 15)}`;
12
+ }
13
+ /** The index stores routing coordinates only. Browser liveness is checked by the target host. */
14
+ export class BrowserRoutes {
15
+ localScope = hash(['local', hostname(), process.env.MEARL_SOCKET_PATH ?? '']);
16
+ remoteScope;
17
+ targets = new Map();
18
+ constructor(serverUrl) {
19
+ this.remoteScope = serverUrl ? hash(['remote', serverUrl]) : undefined;
20
+ }
21
+ get(id) {
22
+ const cached = this.targets.get(id);
23
+ if (cached)
24
+ return cached;
25
+ const record = readRecord(keyedConfigFile('browser-routes', id));
26
+ const target = record?.target;
27
+ if (!target ||
28
+ typeof target.browser !== 'string' ||
29
+ !target.browser ||
30
+ (target.connector !== undefined &&
31
+ (typeof target.connector !== 'string' || !target.connector)) ||
32
+ record.scope !== (target.connector ? this.remoteScope : this.localScope) ||
33
+ routeId(record.scope, target) !== id) {
34
+ return undefined;
35
+ }
36
+ this.targets.set(id, target);
37
+ return target;
38
+ }
39
+ remember(target) {
40
+ const scope = target.connector ? this.remoteScope : this.localScope;
41
+ if (!scope)
42
+ throw new Error('A remote browser route requires a cloud server');
43
+ const id = routeId(scope, target);
44
+ let existing = this.get(id);
45
+ if (!existing) {
46
+ try {
47
+ const file = keyedConfigFile('browser-routes', id);
48
+ if (!claimRecord(file, { pid: process.pid, scope, target }))
49
+ existing = this.get(id);
50
+ }
51
+ catch {
52
+ // Discovery can still resolve the target when the index cannot be written.
53
+ }
54
+ }
55
+ if (existing &&
56
+ (existing.browser !== target.browser || existing.connector !== target.connector))
57
+ throw new Error(`Browser ID collision: ${id}`);
58
+ this.targets.set(id, target);
59
+ return id;
60
+ }
61
+ }
@@ -0,0 +1,7 @@
1
+ export interface BrowserTarget {
2
+ browser: string;
3
+ connector?: string;
4
+ }
5
+ export declare const GLOBAL_BROWSER_PREFIX = "mearl:";
6
+ export declare function encodeBrowserTarget(target: BrowserTarget): string;
7
+ export declare function decodeBrowserTarget(selector: string | undefined): BrowserTarget | undefined;
@@ -0,0 +1,31 @@
1
+ export const GLOBAL_BROWSER_PREFIX = 'mearl:';
2
+ export function encodeBrowserTarget(target) {
3
+ const browser = encodeURIComponent(target.browser).replace(/%3A/g, ':');
4
+ return target.connector
5
+ ? `${GLOBAL_BROWSER_PREFIX}remote:${encodeURIComponent(target.connector)}:${browser}`
6
+ : `${GLOBAL_BROWSER_PREFIX}local:${browser}`;
7
+ }
8
+ export function decodeBrowserTarget(selector) {
9
+ if (!selector?.startsWith(GLOBAL_BROWSER_PREFIX))
10
+ return undefined;
11
+ try {
12
+ const target = selector.slice(GLOBAL_BROWSER_PREFIX.length);
13
+ if (target.startsWith('local:')) {
14
+ const browser = decodeURIComponent(target.slice('local:'.length));
15
+ return browser ? { browser } : undefined;
16
+ }
17
+ if (target.startsWith('remote:')) {
18
+ const remoteTarget = target.slice('remote:'.length);
19
+ const separator = remoteTarget.indexOf(':');
20
+ if (separator < 0)
21
+ return undefined;
22
+ const connector = decodeURIComponent(remoteTarget.slice(0, separator));
23
+ const browser = decodeURIComponent(remoteTarget.slice(separator + 1));
24
+ return connector && browser ? { connector, browser } : undefined;
25
+ }
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ return undefined;
31
+ }
package/dist/check.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { CloudConnectorInfo } from '@mearl/cloud-types';
2
2
  import { type NativeHostDiagnostic } from './nativeHost.js';
3
- import type { BrowserCapabilities, BrowserProviderIdentity, BrowserProviderOperation } from '@mearl/browser-core';
3
+ import type { BrowserCapabilities, BrowserProviderIdentity, BrowserProviderOperation, BrowserSource } from '@mearl/browser-core';
4
4
  import { type UnifiedClientOptions, type UnifiedInvokeOptions } from './unified.js';
5
5
  export interface UnifiedCheckVersions {
6
6
  nativeHost?: string;
@@ -32,6 +32,7 @@ interface BrowserInfo {
32
32
  originalBrowserId?: string;
33
33
  originalName?: string;
34
34
  status: string;
35
+ source?: BrowserSource;
35
36
  type?: string;
36
37
  provider?: BrowserProviderIdentity;
37
38
  ownership?: 'owned' | 'attached';
package/dist/check.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { inspectNativeHostInstallation } from './nativeHost.js';
2
- import { UnifiedClient, normalizeBrowserSelector, } from './unified.js';
2
+ import { isShortBrowserId } from './browserRoutes.js';
3
+ import { GLOBAL_BROWSER_PREFIX } from './browserTarget.js';
4
+ import { UnifiedClient, decodeBrowserTarget, normalizeBrowserSelector, } from './unified.js';
3
5
  const UPDATE_SOURCES = {
4
6
  client: 'https://registry.npmjs.org/@mearl%2Fclient/latest',
5
7
  'native-host': 'https://registry.npmjs.org/@mearl%2Fnative-host/latest',
@@ -74,6 +76,15 @@ function redactServerUrl(serverUrl) {
74
76
  }
75
77
  function browserMatches(browser, selector) {
76
78
  const normalized = normalizeBrowserSelector(selector);
79
+ if (isShortBrowserId(normalized))
80
+ return browser.browserId === normalized;
81
+ if (normalized.startsWith(GLOBAL_BROWSER_PREFIX)) {
82
+ const target = decodeBrowserTarget(selector.trim());
83
+ const route = decodeBrowserTarget(browser.browserId);
84
+ return (target !== undefined &&
85
+ target.browser === (browser.originalBrowserId ?? route?.browser) &&
86
+ target.connector === (browser.source?.connectorId ?? route?.connector));
87
+ }
77
88
  return (browser.browserId.toLowerCase() === normalized ||
78
89
  browser.originalBrowserId?.toLowerCase() === normalized ||
79
90
  browser.name.toLowerCase() === normalized ||
@@ -81,15 +92,19 @@ function browserMatches(browser, selector) {
81
92
  }
82
93
  function findBrowsers(browsers, selector) {
83
94
  const exact = browsers.filter(browser => browserMatches(browser, selector));
84
- if (exact.length > 0)
85
- return exact;
86
95
  const normalized = normalizeBrowserSelector(selector);
96
+ if (exact.length > 0 ||
97
+ isShortBrowserId(normalized) ||
98
+ normalized.startsWith(GLOBAL_BROWSER_PREFIX))
99
+ return exact;
87
100
  return browsers.filter(browser => browser.browserId.toLowerCase().includes(normalized) ||
88
101
  browser.originalBrowserId?.toLowerCase().includes(normalized) ||
89
102
  browser.name.toLowerCase().includes(normalized) ||
90
103
  browser.originalName?.toLowerCase().includes(normalized));
91
104
  }
92
105
  function shortBrowserId(browserId) {
106
+ if (isShortBrowserId(browserId))
107
+ return browserId;
93
108
  const parts = browserId.split(':');
94
109
  const raw = decodeURIComponent(parts.at(-1) ?? browserId);
95
110
  return raw.length > 12 ? `${raw.slice(0, 8)}…` : raw;
package/dist/cli.js CHANGED
@@ -11,7 +11,8 @@ import { COMMANDS, COMMAND_MAP } from './commands.js';
11
11
  import { formatCommandHelp } from './commandHelp.js';
12
12
  import { CLIENT_VERSION } from './socket.js';
13
13
  import { UnifiedClient } from './unified.js';
14
- import { findPluginEntry, findPluginRegistration, findOfficialPlugin, listPluginNames, listOfficialPluginNames, loadRegisteredPlugin, PluginError, } from './plugins/sdk/plugin.js';
14
+ import { findOfficialPlugin, listOfficialPluginNames } from './plugins/officialPluginCatalog.js';
15
+ import { findPluginEntry, findPluginRegistration, listPluginNames, PluginError, } from './plugins/pluginRegistry.js';
15
16
  import { resolveServer } from './unifiedConfig.js';
16
17
  const TOP_LEVEL_COMMAND_NAME_WIDTH = 22;
17
18
  const CATEGORIES = [
@@ -272,6 +273,7 @@ async function sameNamePluginHelp(commandName, name) {
272
273
  try {
273
274
  if (!findPluginEntry(name))
274
275
  return undefined;
276
+ const { loadRegisteredPlugin } = await import('./plugins/sdk/plugin.js');
275
277
  const plugin = await loadRegisteredPlugin(name, {
276
278
  async invoke() {
277
279
  throw new Error('生成插件帮助时不能调用宿主能力');
@@ -506,6 +508,7 @@ async function runPluginCli(args, commandName) {
506
508
  }
507
509
  let client;
508
510
  try {
511
+ const { loadRegisteredPlugin } = await import('./plugins/sdk/plugin.js');
509
512
  const invokeOptions = {
510
513
  ...(parsed.timeoutOption ? { timeoutSec: parsed.timeoutSec } : {}),
511
514
  ...(parsed.browser ? { browser: parsed.browser } : {}),
@@ -26,7 +26,7 @@
26
26
  mearl browser_manage --payload '{"operation":"launch","provider":"<providerId>","providerOptions":{}}'
27
27
  ```
28
28
 
29
- 本机与远端 connector 同时存在时,用 `--local`、`--connector <id|name>`,或用 `--browser <global-id>` 同时指定宿主和 Cookie/UA 的来源浏览器。启动响应中的全局 `browserId` 用于首次操作和交付;建立控制会话后,后续操作由 `--session` 固定目标,无会话时继续传选定的 `--browser`。
29
+ 本机与远端 connector 同时存在时,用 `--local`、`--connector <id|name>`,或用 `--browser <browserId>` 同时指定宿主和 Cookie/UA 的来源浏览器。启动或接入返回 `b_…` 格式的 `browserId`,可直接用于页面操作和断开接入。建立控制会话后,后续页面操作由 `--session` 固定目标。
30
30
 
31
31
  `browser_manage close` 关闭托管实例;`deleteProfile: true` 表示同时删除 Provider 持久化数据。是否支持关闭、删除、启动、同步 Cookie、detach 或访问入口,以实例的 `operations` 和 Provider 命令帮助为准。
32
32
 
@@ -2,7 +2,8 @@ import { PluginHostConnection } from './pluginHostConnection.js';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { isProcessOwnerAlive, readRecord } from '@mearl/daemon-core';
4
4
  import { pluginHostPaths } from '../runtime/pluginHostPaths.js';
5
- import { UnifiedClient, decodeBrowserTarget } from '../../unified.js';
5
+ import { UnifiedClient } from '../../unified.js';
6
+ import { resolveServer } from '../../unifiedConfig.js';
6
7
  import { isPluginTaskActive } from '@mearl/browser-core';
7
8
  import { pluginExecutionError } from '../runtime/pluginExecutorProtocol.js';
8
9
  function localWait(promise, signal, timeoutMs = Infinity) {
@@ -62,15 +63,12 @@ export class PluginTaskClient {
62
63
  }
63
64
  async start(plugin, invocation, options = {}) {
64
65
  const { cwd = process.cwd(), environment = process.env, executionTimeoutMs, idempotencyKey, ...routing } = options;
65
- if (!this.connection.hasInvocationBridge &&
66
- routing.browser &&
67
- !decodeBrowserTarget(routing.browser)) {
68
- const client = new UnifiedClient();
66
+ if (!this.connection.hasInvocationBridge && routing.browser) {
67
+ const client = new UnifiedClient(resolveServer());
69
68
  try {
70
- const selection = await client.invoke('browser_select_browser', { browser: routing.browser }, routing);
71
- if (!selection?.selected?.browserId)
72
- throw new Error('Cannot resolve plugin task browser target');
73
- routing.browser = selection.selected.browserId;
69
+ const target = await client.pinBrowserTarget(routing);
70
+ routing.browser = target.browser;
71
+ routing.connector = target.connector;
74
72
  }
75
73
  finally {
76
74
  client.disconnect();
@@ -8,6 +8,8 @@ import { keyedDir } from '@mearl/daemon-core';
8
8
  import { capturePluginRevision } from './pluginRevision.js';
9
9
  import { findPluginRegistration } from '../sdk/plugin.js';
10
10
  import { UnifiedClient, decodeBrowserTarget } from '../../unified.js';
11
+ import { resolveServer } from '../../unifiedConfig.js';
12
+ import { isShortBrowserId } from '../../browserRoutes.js';
11
13
  import { pluginHostPaths } from './pluginHostPaths.js';
12
14
  import { serializePluginExecutionError, pluginExecutionError } from './pluginExecutorProtocol.js';
13
15
  import { isPluginTaskActive } from '@mearl/browser-core';
@@ -283,8 +285,11 @@ export class PluginPageManager {
283
285
  if (operation === 'attach' || operation === 'activation') {
284
286
  if (Object.keys(options).some(key => !['browser', 'connector', 'session', 'local', 'transport', 'timeoutSec'].includes(key)))
285
287
  throw new Error('Invalid plugin page routing options');
286
- if (bridge.scope.bridge === 'service' && !decodeBrowserTarget(options.browser))
287
- throw new Error('Plugin pages require a stable browser ID');
288
+ if (bridge.scope.bridge === 'service' && !isShortBrowserId(options.browser)) {
289
+ const target = decodeBrowserTarget(options.browser);
290
+ if (!target || target.connector)
291
+ throw new Error('Plugin pages require a stable browser ID');
292
+ }
288
293
  if (!execution ||
289
294
  !isAbsolute(execution.cwd) ||
290
295
  !statSync(execution.cwd).isDirectory() ||
@@ -294,7 +299,7 @@ export class PluginPageManager {
294
299
  throw new Error('Invalid plugin page execution context');
295
300
  }
296
301
  if (operation === 'activation' && input.enabled !== true) {
297
- const client = bridge.scope.bridge === 'service' ? new UnifiedClient() : undefined;
302
+ const client = bridge.scope.bridge === 'service' ? new UnifiedClient(resolveServer()) : undefined;
298
303
  try {
299
304
  return client
300
305
  ? await client.invoke('page_runtime', { ...input, plugin }, options)
@@ -310,7 +315,7 @@ export class PluginPageManager {
310
315
  throw failure('PLUGIN_PAGE_INSTALLATION_CHANGED', 'Page activation belongs to another plugin installation');
311
316
  const release = this.tasks.pinRevision(revision);
312
317
  let retained = false;
313
- const client = bridge.scope.bridge === 'service' ? new UnifiedClient() : undefined;
318
+ const client = bridge.scope.bridge === 'service' ? new UnifiedClient(resolveServer()) : undefined;
314
319
  const invoke = (data) => client
315
320
  ? client.invoke('page_runtime', data, options)
316
321
  : bridge.invoke('page_runtime', data, options);
@@ -13,6 +13,8 @@ import { pluginHostPaths } from './pluginHostPaths.js';
13
13
  import { PluginTaskStore, pluginTaskExecutionUnconfirmed } from './pluginTaskStore.js';
14
14
  import { isPluginTaskActive } from '@mearl/browser-core';
15
15
  import { UnifiedClient, decodeBrowserTarget } from '../../unified.js';
16
+ import { resolveServer } from '../../unifiedConfig.js';
17
+ import { isShortBrowserId } from '../../browserRoutes.js';
16
18
  import { COMMAND_MAP } from '../../commands.js';
17
19
  function error(code, message) {
18
20
  return Object.assign(new Error(message), { code });
@@ -242,8 +244,11 @@ export class PluginTaskManager {
242
244
  throw new Error('Invalid plugin task local routing option');
243
245
  if (bridge.scope.bridge === 'service' &&
244
246
  request.options.browser &&
245
- !decodeBrowserTarget(request.options.browser))
246
- throw error('PLUGIN_TASK_TARGET_REQUIRED', 'Background tasks require a stable global browser ID');
247
+ !isShortBrowserId(request.options.browser)) {
248
+ const target = decodeBrowserTarget(request.options.browser);
249
+ if (!target || target.connector)
250
+ throw error('PLUGIN_TASK_TARGET_REQUIRED', 'Background tasks require a stable global browser ID');
251
+ }
247
252
  if (request.executionTimeoutMs !== undefined &&
248
253
  (!Number.isSafeInteger(request.executionTimeoutMs) ||
249
254
  request.executionTimeoutMs < 1 ||
@@ -695,7 +700,9 @@ export class PluginTaskManager {
695
700
  }
696
701
  }
697
702
  async execute(taskId, { request, revision, bridge, controller, guard, page, recovery, parentIdentity, documentTarget, }) {
698
- const client = bridge.scope.bridge === 'service' ? new UnifiedClient() : undefined;
703
+ const client = bridge.scope.bridge === 'service'
704
+ ? new UnifiedClient(request.options.browser || request.options.connector ? resolveServer() : {})
705
+ : undefined;
699
706
  try {
700
707
  await guard?.();
701
708
  const identity = Object.freeze({
package/dist/socket.d.ts CHANGED
@@ -18,6 +18,8 @@ export declare const SOCKET_PATH: string;
18
18
  export type ControlSource = 'local' | 'remote';
19
19
  type CompatibleControlSource = ControlSource | 'cloud';
20
20
  export interface InvokeOptions {
21
+ /** Identity of the connector receiving a browser target over the cloud transport. */
22
+ connectorId?: string;
21
23
  controlSessionId?: string;
22
24
  /** Pin a known local endpoint for a sequence of transport requests. */
23
25
  socketPath?: string;
package/dist/socket.js CHANGED
@@ -18,6 +18,7 @@ import { assertProviderControlSessionMode, ensureProviderControlHost, listInstal
18
18
  import { MEARL_PROVIDER_PROTOCOL_VERSION, assertProviderProtocolVersion, validateProviderLaunchForm, } from '@mearl/provider';
19
19
  import { readLiveProvider, ensureInstalledProvidersRunning } from '@mearl/provider/runtime';
20
20
  import { resolveFileRefs } from './fileRefs.js';
21
+ import { decodeBrowserTarget, encodeBrowserTarget } from './browserTarget.js';
21
22
  import { listLiveBrowsers, findBrowser, describeBrowser, } from './browserRegistry.js';
22
23
  import { resolveActionTimeoutSec } from './actionTimeouts.js';
23
24
  import { browserActionResponseError, isBrowserCapabilityAction, isCdpExportOperation, normalizeControlSource, parseBrowserListParams, parseBrowserManageParams, parseSessionManageParams, } from '@mearl/browser-core';
@@ -319,6 +320,12 @@ async function loadLocalBrowserList(timeoutSec, controlSource, requestDeadline)
319
320
  * legacy well-known socket,并在 socket 不存在或已残留时自动拉起 native host。
320
321
  */
321
322
  export function invoke(action, data = {}, options = {}) {
323
+ const target = decodeBrowserTarget(options.browser);
324
+ if (target?.connector) {
325
+ if (target.connector !== options.connectorId)
326
+ return Promise.reject(new Error('The browser belongs to a different cloud connector'));
327
+ options = { ...options, browser: encodeBrowserTarget({ browser: target.browser }) };
328
+ }
322
329
  if (action === '__resolve_action_target') {
323
330
  if (!isBrowserCapabilityAction(data.action))
324
331
  return Promise.reject(new Error('Invalid browser capability action'));
@@ -504,12 +511,15 @@ function isUnavailableConnection(error) {
504
511
  return isConnError(cause) || isSocketSandboxError(cause) || code === 'EACCES';
505
512
  }
506
513
  async function dispatchInvoke(action, data, timeoutSec, selector, controlSource, socketPath, deadline) {
514
+ const pinnedTarget = decodeBrowserTarget(selector);
515
+ if (pinnedTarget?.connector)
516
+ throw new Error('An IPC browser target must be local to this host');
507
517
  const opensBrowser = action === 'browser_manage' && (data.operation === 'launch' || data.operation === 'attach');
508
518
  const instanceOperation = action === 'browser_manage' && (data.operation === 'close' || data.operation === 'detach');
509
519
  if (instanceOperation && !selector)
510
520
  throw new Error('Specify the browser with --browser <id|name>');
511
521
  const send = (path, target) => invokeOnce(action, action === 'browser_manage' && data.operation === 'close' && target?.transport !== 'provider'
512
- ? { ...data, browser: target?.browserId ?? selector }
522
+ ? { ...data, browser: pinnedTarget ? selector : (target?.browserId ?? selector) }
513
523
  : data, timeoutSec, path, controlSource, target?.transport === 'provider' ? target.browserId : undefined, target?.capabilities?.controlSessionMode, deadline);
514
524
  const configuredSocketPath = socketPath ?? process.env.MEARL_SOCKET_PATH?.trim();
515
525
  if (configuredSocketPath && (socketPath || !selector)) {
package/dist/unified.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { BrowserArtifact } from '@mearl/browser-core';
2
2
  import { type CloudConnectorListResult } from '@mearl/cloud-types';
3
3
  import { type PluginInvocationSource } from '@mearl/browser-core';
4
4
  import type { PluginInvocation, PluginInvokeOptions } from './plugins/sdk/plugin.js';
5
+ export { decodeBrowserTarget } from './browserTarget.js';
5
6
  /** The Native Host authorizes the connection. The MCP browser API omits extension endpoints. */
6
7
  export declare function invokeBrowserOnSurface(action: string, operation: unknown, source: PluginInvocationSource | undefined, invoke: () => Promise<any>): Promise<any>;
7
8
  export interface UnifiedInvokeOptions {
@@ -27,14 +28,10 @@ export interface UnifiedClientOptions {
27
28
  defaultBrowser?: string;
28
29
  defaultConnector?: string;
29
30
  }
30
- interface BrowserTarget {
31
- browser: string;
32
- connector?: string;
33
- }
34
- export declare function decodeBrowserTarget(selector: string | undefined): BrowserTarget | undefined;
35
31
  export declare function normalizeBrowserSelector(selector: string): string;
36
32
  export declare class UnifiedClient {
37
33
  private readonly requestDeadline?;
34
+ private readonly routes;
38
35
  private readonly controlSessions;
39
36
  private readonly options;
40
37
  private defaultBrowser;
@@ -56,6 +53,7 @@ export declare class UnifiedClient {
56
53
  bytes: number;
57
54
  }>;
58
55
  pinBrowserTarget(options?: UnifiedInvokeOptions): Promise<UnifiedInvokeOptions>;
56
+ private resolveBrowserOptions;
59
57
  private pinPageEvalTarget;
60
58
  private invokeRouted;
61
59
  private invokeExplicitLocal;
@@ -69,6 +67,7 @@ export declare class UnifiedClient {
69
67
  private decorateListing;
70
68
  private applyConfiguredDefault;
71
69
  private listConnectorBrowsers;
70
+ private decorateConnectorListing;
72
71
  private listSessions;
73
72
  private listAllBrowsers;
74
73
  private invokeLocal;
@@ -86,4 +85,3 @@ export declare class UnifiedClient {
86
85
  export declare function invoke(action: string, data?: Record<string, any>, options?: UnifiedInvokeOptions): Promise<any>;
87
86
  export declare function invokePlugin(name: string, invocation: PluginInvocation, options?: PluginInvokeOptions): Promise<unknown>;
88
87
  export declare function listCloudConnectors(): Promise<CloudConnectorListResult>;
89
- export {};
package/dist/unified.js CHANGED
@@ -5,9 +5,11 @@ import { DEFAULT_CONNECT_TIMEOUT, DEFAULT_HEARTBEAT_INTERVAL, DEFAULT_REQUEST_TI
5
5
  import { resolveActionTimeoutSec } from './actionTimeouts.js';
6
6
  import { browserActionResponseError, isCdpExportOperation, validateRequiredActionTabId, parseBrowserListParams, parseBrowserManageParams, parseSessionManageParams, resolveSessionManageId, } from '@mearl/browser-core';
7
7
  import { invoke as invokeLocalBrowser, resolveLocalActionTarget } from './socket.js';
8
- import { loadCloudServerConfig, loadLocalConnectorId } from './unifiedConfig.js';
8
+ import { loadCloudServerConfig, loadLocalConnectorId, resolveServer } from './unifiedConfig.js';
9
+ import { BrowserRoutes, isShortBrowserId } from './browserRoutes.js';
10
+ import { decodeBrowserTarget, encodeBrowserTarget, GLOBAL_BROWSER_PREFIX, } from './browserTarget.js';
11
+ export { decodeBrowserTarget } from './browserTarget.js';
9
12
  const RESPONSE_GRACE_MS = 1_000;
10
- const GLOBAL_BROWSER_PREFIX = 'mearl:';
11
13
  /** The Native Host authorizes the connection. The MCP browser API omits extension endpoints. */
12
14
  export async function invokeBrowserOnSurface(action, operation, source, invoke) {
13
15
  if (source !== 'mcp')
@@ -19,11 +21,8 @@ export async function invokeBrowserOnSurface(action, operation, source, invoke)
19
21
  throw new Error('Extension CDP access is available through the local CLI and SDK');
20
22
  return result;
21
23
  }
22
- function encodeBrowserTarget(target) {
23
- const browser = encodeURIComponent(target.browser).replace(/%3A/g, ':');
24
- return target.connector
25
- ? `${GLOBAL_BROWSER_PREFIX}remote:${encodeURIComponent(target.connector)}:${browser}`
26
- : `${GLOBAL_BROWSER_PREFIX}local:${browser}`;
24
+ function cloudConnectorSelector(connector) {
25
+ return connector.pinnedBrowserTargets ? { id: connector.connectorId } : connector.connectorId;
27
26
  }
28
27
  function omitTransientBrowserSecrets(browser) {
29
28
  const safeBrowser = { ...browser };
@@ -33,44 +32,23 @@ function omitTransientBrowserSecrets(browser) {
33
32
  }
34
33
  return safeBrowser;
35
34
  }
36
- export function decodeBrowserTarget(selector) {
37
- if (!selector?.startsWith(GLOBAL_BROWSER_PREFIX))
38
- return undefined;
39
- try {
40
- const target = selector.slice(GLOBAL_BROWSER_PREFIX.length);
41
- if (target.startsWith('local:')) {
42
- const browser = decodeURIComponent(target.slice('local:'.length));
43
- return browser ? { browser } : undefined;
44
- }
45
- if (target.startsWith('remote:')) {
46
- const remoteTarget = target.slice('remote:'.length);
47
- const separator = remoteTarget.indexOf(':');
48
- if (separator < 0)
49
- return undefined;
50
- const connector = decodeURIComponent(remoteTarget.slice(0, separator));
51
- const browser = decodeURIComponent(remoteTarget.slice(separator + 1));
52
- return connector && browser ? { connector, browser } : undefined;
53
- }
54
- }
55
- catch {
56
- return undefined;
57
- }
58
- return undefined;
59
- }
60
35
  export function normalizeBrowserSelector(selector) {
61
36
  const decodedTarget = decodeBrowserTarget(selector);
62
37
  return (decodedTarget ? encodeBrowserTarget(decodedTarget) : selector.trim()).toLowerCase();
63
38
  }
64
- function decorateBrowser(browser, source) {
39
+ function browserTarget(browser, source) {
40
+ return { browser, ...(source.connectorId ? { connector: source.connectorId } : {}) };
41
+ }
42
+ function routeBrowser(browser) {
43
+ return encodeBrowserTarget(browserTarget(browser.originalBrowserId, browser.source));
44
+ }
45
+ function decorateBrowser(browser, source, routes) {
65
46
  const safeBrowser = omitTransientBrowserSecrets(browser);
66
47
  const originalBrowserId = String(browser.browserId);
67
48
  const originalName = String(browser.name);
68
49
  return {
69
50
  ...safeBrowser,
70
- browserId: encodeBrowserTarget({
71
- browser: originalBrowserId,
72
- ...(source.connectorId ? { connector: source.connectorId } : {}),
73
- }),
51
+ browserId: routes.remember(browserTarget(originalBrowserId, source)),
74
52
  name: source.kind === 'local'
75
53
  ? `[this machine] ${originalName}`
76
54
  : `[${source.connectorName}] ${originalName}`,
@@ -82,19 +60,29 @@ function decorateBrowser(browser, source) {
82
60
  }
83
61
  function browserMatches(browser, selector) {
84
62
  const normalized = normalizeBrowserSelector(selector);
63
+ if (isShortBrowserId(normalized))
64
+ return browser.browserId === normalized;
65
+ if (normalized.startsWith(GLOBAL_BROWSER_PREFIX)) {
66
+ const target = decodeBrowserTarget(selector.trim());
67
+ return (target?.browser === browser.originalBrowserId &&
68
+ target.connector === browser.source.connectorId);
69
+ }
85
70
  return (browser.browserId.toLowerCase() === normalized ||
86
- browser.originalBrowserId?.toLowerCase() === normalized ||
71
+ browser.originalBrowserId.toLowerCase() === normalized ||
87
72
  browser.name.toLowerCase() === normalized ||
88
- browser.originalName?.toLowerCase() === normalized);
73
+ browser.originalName.toLowerCase() === normalized);
89
74
  }
90
75
  function findBrowsers(browsers, selector, connectedOnly = true, exactOnly = false) {
91
76
  const candidates = connectedOnly
92
77
  ? browsers.filter(browser => browser.status === 'connected')
93
78
  : browsers;
94
79
  const exact = candidates.filter(browser => browserMatches(browser, selector));
95
- if (exact.length > 0 || exactOnly)
96
- return exact;
97
80
  const normalized = normalizeBrowserSelector(selector);
81
+ if (exact.length > 0 ||
82
+ exactOnly ||
83
+ isShortBrowserId(normalized) ||
84
+ normalized.startsWith(GLOBAL_BROWSER_PREFIX))
85
+ return exact;
98
86
  return candidates.filter(browser => browser.browserId.toLowerCase().includes(normalized) ||
99
87
  browser.originalBrowserId?.toLowerCase().includes(normalized) ||
100
88
  browser.name.toLowerCase().includes(normalized) ||
@@ -105,6 +93,7 @@ function errorMessage(error) {
105
93
  }
106
94
  export class UnifiedClient {
107
95
  requestDeadline;
96
+ routes;
108
97
  controlSessions = new Map();
109
98
  options;
110
99
  defaultBrowser;
@@ -117,6 +106,7 @@ export class UnifiedClient {
117
106
  closing = false;
118
107
  constructor(options = {}) {
119
108
  this.requestDeadline = options.requestDeadline;
109
+ this.routes = new BrowserRoutes(options.serverUrl);
120
110
  this.options = {
121
111
  ...(options.serverUrl ? { serverUrl: options.serverUrl } : {}),
122
112
  connectTimeoutSec: options.connectTimeoutSec ?? DEFAULT_CONNECT_TIMEOUT,
@@ -200,6 +190,10 @@ export class UnifiedClient {
200
190
  const pinned = ['attach', 'activation'].includes(data.operation)
201
191
  ? await this.pinBrowserTarget(options)
202
192
  : options;
193
+ if (isShortBrowserId(pinned.browser) &&
194
+ this.routes.get(pinned.browser)?.connector &&
195
+ resolveServer().serverUrl !== this.options.serverUrl)
196
+ throw new Error('Configure the same Cloud Server for the plugin page service and the caller.');
203
197
  return await pages.call(String(data.plugin ?? ''), data.operation, data, pinned);
204
198
  }
205
199
  finally {
@@ -224,7 +218,7 @@ export class UnifiedClient {
224
218
  throw new Error('session_list does not accept a session override');
225
219
  if (Object.keys(data).length)
226
220
  throw new Error('session_list does not accept a payload');
227
- return this.listSessions(options);
221
+ return this.listSessions(await this.resolveBrowserOptions(options));
228
222
  }
229
223
  if (action === 'session_manage') {
230
224
  const command = parseSessionManageParams(data);
@@ -247,6 +241,11 @@ export class UnifiedClient {
247
241
  }
248
242
  }
249
243
  }
244
+ if (!['browser_list', 'connector_list', 'browser_select_browser'].includes(action)) {
245
+ validateRequiredActionTabId(action, data);
246
+ const defaultBrowser = !options.session || options.session === 'new' ? this.defaultBrowser : undefined;
247
+ options = await this.resolveBrowserOptions(options, defaultBrowser);
248
+ }
250
249
  if (options.session && options.session !== 'new') {
251
250
  const session = await this.resolveControlSession(options.session, options);
252
251
  const selected = decodeBrowserTarget(options.browser);
@@ -304,8 +303,8 @@ export class UnifiedClient {
304
303
  for (const file of data.files) {
305
304
  if (file.filePath) {
306
305
  const uploaded = await stageFile(this, file.filePath, options);
307
- options = uploaded.options;
308
306
  temporary.push(uploaded.artifactId);
307
+ options = await this.resolveBrowserOptions(uploaded.options);
309
308
  staged.push({ artifactId: uploaded.artifactId });
310
309
  }
311
310
  else
@@ -324,9 +323,11 @@ export class UnifiedClient {
324
323
  return exportArtifact(this, artifact, outputPath, options);
325
324
  }
326
325
  async pinBrowserTarget(options = {}) {
326
+ options = await this.resolveBrowserOptions(options, this.defaultBrowser);
327
327
  const selector = options.browser ?? this.defaultBrowser;
328
- if (decodeBrowserTarget(selector))
329
- return { ...options, browser: selector };
328
+ const pinnedTarget = decodeBrowserTarget(selector);
329
+ if (pinnedTarget)
330
+ return { ...options, browser: this.routes.remember(pinnedTarget) };
330
331
  const listing = (await this.invoke('browser_list', {}, {
331
332
  ...options,
332
333
  ...(options.connector || !this.defaultConnector
@@ -344,6 +345,26 @@ export class UnifiedClient {
344
345
  delete pinned.connector;
345
346
  return pinned;
346
347
  }
348
+ async resolveBrowserOptions(options, defaultBrowser) {
349
+ const selector = (options.browser ?? defaultBrowser)?.trim().toLowerCase();
350
+ if (!isShortBrowserId(selector))
351
+ return options;
352
+ const cached = this.routes.get(selector);
353
+ if (cached)
354
+ return { ...options, browser: encodeBrowserTarget(cached) };
355
+ const timeoutSec = options.timeoutSec ?? this.options.requestTimeoutSec;
356
+ const listing = options.local
357
+ ? await this.listLocalBrowsers(timeoutSec)
358
+ : options.connector
359
+ ? await this.listConnectorBrowsers(options.connector, timeoutSec)
360
+ : await this.listAllBrowsers(timeoutSec);
361
+ const matches = findBrowsers(listing.browsers, selector, false, true);
362
+ if (matches.length !== 1)
363
+ throw new Error(matches.length
364
+ ? `Browser ID is ambiguous: ${selector}`
365
+ : `No browser matches "${selector}". Run \`mearl browser_list\`.`);
366
+ return { ...options, browser: routeBrowser(matches[0]) };
367
+ }
347
368
  async pinPageEvalTarget(options, data) {
348
369
  const target = decodeBrowserTarget(options.browser);
349
370
  if (target && !options.connector)
@@ -361,7 +382,7 @@ export class UnifiedClient {
361
382
  if (options.connector && !options.browser) {
362
383
  const timeoutSec = options.timeoutSec ?? this.options.requestTimeoutSec;
363
384
  const connector = await this.resolveConnector(options.connector, timeoutSec);
364
- const resolved = await this.requestRemote('__resolve_action_target', { action: 'page_eval', data }, timeoutSec, undefined, connector.connectorId);
385
+ const resolved = await this.requestRemote('__resolve_action_target', { action: 'page_eval', data }, timeoutSec, undefined, cloudConnectorSelector(connector));
365
386
  if (!resolved?.browser)
366
387
  throw new Error('Cannot pin the connector browser for large page_eval arguments. Pass --browser <global-id>.');
367
388
  const pinned = {
@@ -387,7 +408,7 @@ export class UnifiedClient {
387
408
  if (candidates.length !== 1)
388
409
  throw new Error('Large page_eval arguments require a unique connected browser. Pass --browser <global-id>.');
389
410
  const browser = candidates[0];
390
- const pinned = { ...options, browser: browser.browserId };
411
+ const pinned = { ...options, browser: routeBrowser(browser) };
391
412
  delete pinned.connector;
392
413
  return pinned;
393
414
  }
@@ -426,20 +447,17 @@ export class UnifiedClient {
426
447
  const defaultTarget = options.browser ? undefined : decodeBrowserTarget(this.defaultBrowser);
427
448
  const target = optionTarget ?? defaultTarget;
428
449
  const connector = target?.connector ?? options.connector ?? this.defaultConnector;
429
- const browser = optionTarget?.browser ??
430
- defaultTarget?.browser ??
431
- (options.browser && !optionTarget ? options.browser : undefined) ??
432
- (this.defaultBrowser && !defaultTarget ? this.defaultBrowser : undefined);
450
+ const browser = target ? encodeBrowserTarget(target) : (options.browser ?? this.defaultBrowser);
433
451
  if (target && !target.connector) {
434
452
  if (options.connector) {
435
453
  throw new Error('A local browser cannot be used together with --connector.');
436
454
  }
437
- return this.invokeLocal(action, data, timeoutSec, target.browser, options.controlSessionId);
455
+ return this.invokeLocal(action, data, timeoutSec, browser, options.controlSessionId);
438
456
  }
439
457
  if (connector) {
440
- const selected = target?.connector && !options.connector && !this.defaultConnector
458
+ const selected = target?.connector && !options.connector
441
459
  ? { connectorId: target.connector, name: target.connector }
442
- : await this.resolveConnector(connector, timeoutSec);
460
+ : await this.resolveConnector(options.connector ?? connector, timeoutSec);
443
461
  if (target?.connector && selected.connectorId !== target.connector) {
444
462
  throw new Error('The selected browser belongs to a different cloud connector.');
445
463
  }
@@ -465,7 +483,7 @@ export class UnifiedClient {
465
483
  if (optionTarget?.connector || defaultTarget?.connector) {
466
484
  throw new Error('A remote browser cannot be used together with --local.');
467
485
  }
468
- const browser = optionTarget?.browser ?? defaultTarget?.browser ?? options.browser ?? this.defaultBrowser;
486
+ const browser = options.browser ?? this.defaultBrowser;
469
487
  return this.invokeLocal(action, data, timeoutSec, browser, options.controlSessionId);
470
488
  }
471
489
  async invokeOpenWithoutControlBrowser(data, timeoutSec) {
@@ -525,13 +543,14 @@ export class UnifiedClient {
525
543
  if (matches.length === 0) {
526
544
  throw new Error(`No browser matches "${selector}". Run \`mearl browser_list\`.`);
527
545
  }
528
- return matches[0].browserId;
546
+ return routeBrowser(matches[0]);
529
547
  }
530
- if (listing.defaultBrowserId)
531
- return listing.defaultBrowserId;
548
+ const defaultBrowser = listing.browsers.find(browser => browser.browserId === listing.defaultBrowserId);
549
+ if (defaultBrowser)
550
+ return routeBrowser(defaultBrowser);
532
551
  const connected = listing.browsers.filter(browser => browser.status === 'connected');
533
552
  if (connected.length === 1)
534
- return connected[0].browserId;
553
+ return routeBrowser(connected[0]);
535
554
  if (connected.length > 1) {
536
555
  throw new Error('Multiple browsers are connected and there is no unique default. Pass --browser <global-id>.');
537
556
  }
@@ -572,7 +591,7 @@ export class UnifiedClient {
572
591
  const rawBrowsers = Array.isArray(result?.browsers)
573
592
  ? result.browsers
574
593
  : [];
575
- const browsers = rawBrowsers.map(browser => decorateBrowser(browser, source));
594
+ const browsers = rawBrowsers.map(browser => decorateBrowser(browser, source, this.routes));
576
595
  const providers = result?.installedProviders;
577
596
  const installedProviders = Array.isArray(providers)
578
597
  ? providers.map(provider => ({ ...provider, source }))
@@ -584,10 +603,7 @@ export class UnifiedClient {
584
603
  count: browsers.length,
585
604
  connectedCount: browsers.filter(browser => browser.status === 'connected').length,
586
605
  defaultBrowserId: typeof result?.defaultBrowserId === 'string'
587
- ? encodeBrowserTarget({
588
- browser: result.defaultBrowserId,
589
- ...(source.connectorId ? { connector: source.connectorId } : {}),
590
- })
606
+ ? this.routes.remember(browserTarget(result.defaultBrowserId, source))
591
607
  : null,
592
608
  browsers,
593
609
  ...(installedProviders.length ? { installedProviders } : {}),
@@ -606,12 +622,21 @@ export class UnifiedClient {
606
622
  }
607
623
  async listConnectorBrowsers(selector, timeoutSec) {
608
624
  const connector = await this.resolveConnector(selector, timeoutSec);
609
- const result = await this.requestRemote('browser_list', {}, timeoutSec, undefined, connector.connectorId);
610
- return this.applyConfiguredDefault(this.decorateListing(result, {
625
+ const result = await this.requestRemote('browser_list', {}, timeoutSec, undefined, cloudConnectorSelector(connector));
626
+ return this.applyConfiguredDefault(this.decorateConnectorListing(result, connector));
627
+ }
628
+ decorateConnectorListing(listing, connector) {
629
+ const result = this.decorateListing(listing, {
611
630
  kind: 'remote',
612
631
  connectorId: connector.connectorId,
613
632
  connectorName: connector.name,
614
- }));
633
+ });
634
+ if (result.browsers.length && !connector.pinnedBrowserTargets)
635
+ result.warnings = [
636
+ ...(result.warnings ?? []),
637
+ `${connector.name}: Update Cloud Server and Cloud Connector to use short browser IDs.`,
638
+ ];
639
+ return result;
615
640
  }
616
641
  async listSessions(options) {
617
642
  const timeoutSec = options.timeoutSec ?? this.options.requestTimeoutSec;
@@ -620,6 +645,7 @@ export class UnifiedClient {
620
645
  throw new Error('Use either --local or a remote connector');
621
646
  if (target && !target.connector && options.connector)
622
647
  throw new Error('A local browser cannot be used together with --connector.');
648
+ const browser = options.browser;
623
649
  const connector = target?.connector ?? options.connector;
624
650
  if (connector) {
625
651
  const selected = target?.connector && !options.connector
@@ -627,10 +653,10 @@ export class UnifiedClient {
627
653
  : await this.resolveConnector(options.connector ?? connector, timeoutSec);
628
654
  if (target?.connector && target.connector !== selected.connectorId)
629
655
  throw new Error('The selected browser belongs to a different cloud connector.');
630
- return this.invokeRemote('session_list', {}, timeoutSec, target?.browser ?? options.browser, selected);
656
+ return this.invokeRemote('session_list', {}, timeoutSec, browser, selected);
631
657
  }
632
658
  if (options.local || target || !this.options.serverUrl)
633
- return this.invokeLocal('session_list', {}, timeoutSec, target?.browser ?? options.browser);
659
+ return this.invokeLocal('session_list', {}, timeoutSec, browser);
634
660
  if (options.browser) {
635
661
  const browser = await this.resolveUnifiedBrowser(options.browser, timeoutSec, true);
636
662
  if (!browser)
@@ -684,7 +710,7 @@ export class UnifiedClient {
684
710
  : connectors;
685
711
  const settled = await Promise.allSettled(remoteConnectors.map(async (connector) => ({
686
712
  connector,
687
- listing: await this.requestRemote('browser_list', {}, timeoutSec, undefined, connector.connectorId),
713
+ listing: await this.requestRemote('browser_list', {}, timeoutSec, undefined, cloudConnectorSelector(connector)),
688
714
  })));
689
715
  const remoteListings = [];
690
716
  for (let index = 0; index < settled.length; index += 1) {
@@ -699,11 +725,7 @@ export class UnifiedClient {
699
725
  if (localResult)
700
726
  listings.push(this.decorateListing(localResult, { kind: 'local' }));
701
727
  for (const { connector, listing } of remoteListings) {
702
- listings.push(this.decorateListing(listing, {
703
- kind: 'remote',
704
- connectorId: connector.connectorId,
705
- connectorName: connector.name,
706
- }));
728
+ listings.push(this.decorateConnectorListing(listing, connector));
707
729
  }
708
730
  for (const listing of listings)
709
731
  warnings.push(...(listing.warnings ?? []));
@@ -741,7 +763,7 @@ export class UnifiedClient {
741
763
  return this.decorateActionResult(action, result, { kind: 'local' });
742
764
  }
743
765
  async invokeRemote(action, data, timeoutSec, browser, connector, controlSessionId) {
744
- const result = await this.requestRemote(action, data, timeoutSec, browser, connector.connectorId, controlSessionId);
766
+ const result = await this.requestRemote(action, data, timeoutSec, browser, cloudConnectorSelector(connector), controlSessionId);
745
767
  return this.decorateActionResult(action, result, {
746
768
  kind: 'remote',
747
769
  connectorId: connector.connectorId,
@@ -750,13 +772,11 @@ export class UnifiedClient {
750
772
  }
751
773
  decorateActionResult(action, result, source) {
752
774
  if (result?.session?.sessionId) {
753
- const browserId = encodeBrowserTarget({
754
- browser: result.session.browserId,
755
- ...(source.connectorId ? { connector: source.connectorId } : {}),
756
- });
775
+ const target = browserTarget(result.session.browserId, source);
776
+ const route = encodeBrowserTarget(target);
757
777
  if (action !== '__control_session_resolve') {
758
778
  this.controlSessions.set(result.session.sessionId, {
759
- browser: browserId,
779
+ browser: route,
760
780
  id: result.session.sessionId,
761
781
  transport: result.session.transport,
762
782
  });
@@ -765,7 +785,7 @@ export class UnifiedClient {
765
785
  ...result,
766
786
  session: {
767
787
  ...result.session,
768
- browserId,
788
+ browserId: action === '__control_session_resolve' ? route : this.routes.remember(target),
769
789
  },
770
790
  };
771
791
  }
@@ -773,10 +793,7 @@ export class UnifiedClient {
773
793
  (action.startsWith('__artifact_') || action === 'page_record')) {
774
794
  result = {
775
795
  ...result,
776
- browserId: encodeBrowserTarget({
777
- browser: result.browserId,
778
- ...(source.connectorId ? { connector: source.connectorId } : {}),
779
- }),
796
+ browserId: this.routes.remember(browserTarget(result.browserId, source)),
780
797
  };
781
798
  }
782
799
  const artifactKey = action === 'page_record' ? 'recording' : 'download';
@@ -786,10 +803,7 @@ export class UnifiedClient {
786
803
  ...result,
787
804
  [artifactKey]: {
788
805
  ...artifact,
789
- browserId: encodeBrowserTarget({
790
- browser: artifact.browserId,
791
- ...(source.connectorId ? { connector: source.connectorId } : {}),
792
- }),
806
+ browserId: this.routes.remember(browserTarget(artifact.browserId, source)),
793
807
  },
794
808
  };
795
809
  if (action === 'session_list' && Array.isArray(result?.sessions)) {
@@ -797,23 +811,17 @@ export class UnifiedClient {
797
811
  ...result,
798
812
  sessions: result.sessions.map((session) => ({
799
813
  ...session,
800
- browserId: encodeBrowserTarget({
801
- browser: session.browserId,
802
- connector: source.connectorId,
803
- }),
814
+ browserId: this.routes.remember(browserTarget(session.browserId, source)),
804
815
  })),
805
816
  };
806
817
  }
807
818
  if (action !== 'browser_manage' || typeof result?.browserId !== 'string')
808
819
  return result;
809
820
  return typeof result.name === 'string'
810
- ? decorateBrowser(result, source)
821
+ ? decorateBrowser(result, source, this.routes)
811
822
  : {
812
823
  ...result,
813
- browserId: encodeBrowserTarget({
814
- browser: result.browserId,
815
- connector: source.connectorId,
816
- }),
824
+ browserId: this.routes.remember(browserTarget(result.browserId, source)),
817
825
  };
818
826
  }
819
827
  async resolveControlSession(id, options) {
@@ -823,18 +831,31 @@ export class UnifiedClient {
823
831
  const target = decodeBrowserTarget(options.browser);
824
832
  if (options.local && (target?.connector || options.connector))
825
833
  throw new Error('Use either --local or a remote connector');
834
+ if (target && !target.connector && options.connector)
835
+ throw new Error('A local browser cannot be used together with --connector.');
826
836
  const connector = options.connector ?? target?.connector;
827
- if (cached && !connector && (!options.local || !decodeBrowserTarget(cached.browser)?.connector))
837
+ const cachedTarget = decodeBrowserTarget(cached?.browser);
838
+ if (cachedTarget &&
839
+ cached &&
840
+ (!options.connector || options.connector === cachedTarget.connector) &&
841
+ (!options.local || !cachedTarget.connector) &&
842
+ (!target ||
843
+ (target.connector === cachedTarget.connector && target.browser === cachedTarget.browser)))
828
844
  return cached;
829
845
  const timeoutSec = options.timeoutSec ?? 15;
830
846
  const localLookup = connector
831
847
  ? Promise.resolve({ session: null })
832
848
  : this.invokeLocal('__control_session_resolve', { sessionId: id }, timeoutSec, undefined);
833
849
  const discover = async () => {
834
- const sources = connector
835
- ? [await this.resolveConnector(connector, timeoutSec)]
836
- : (await this.listConnectors(timeoutSec)).connectors;
837
- return Promise.allSettled(sources.map(connector => this.invokeRemote('__control_session_resolve', { sessionId: id }, timeoutSec, undefined, connector)));
850
+ const selected = options.connector
851
+ ? await this.resolveConnector(options.connector, timeoutSec)
852
+ : target?.connector
853
+ ? { connectorId: target.connector, name: target.connector }
854
+ : undefined;
855
+ if (selected && target?.connector && selected.connectorId !== target.connector)
856
+ throw new Error('The selected browser belongs to a different cloud connector.');
857
+ const sources = selected ? [selected] : (await this.listConnectors(timeoutSec)).connectors;
858
+ return Promise.allSettled(sources.map(connector => this.invokeRemote('__control_session_resolve', { sessionId: id }, timeoutSec, target?.connector ? encodeBrowserTarget(target) : undefined, connector)));
838
859
  };
839
860
  const queryRemote = this.options.serverUrl && !options.local && (!target || connector);
840
861
  const [local, remote] = await Promise.allSettled([
@@ -983,7 +1004,15 @@ export class UnifiedClient {
983
1004
  const message = { id, action, data, timeoutSec };
984
1005
  if (browser)
985
1006
  message.browser = browser;
986
- if (connector)
1007
+ const pinned = decodeBrowserTarget(browser)?.connector ??
1008
+ (typeof connector === 'object'
1009
+ ? connector.id
1010
+ : action === 'browser_manage'
1011
+ ? connector
1012
+ : undefined);
1013
+ if (pinned)
1014
+ message.connector = { id: pinned };
1015
+ else if (connector)
987
1016
  message.connector = connector;
988
1017
  if (controlSessionId)
989
1018
  message.controlSessionId = controlSessionId;
@@ -995,7 +1024,8 @@ export class UnifiedClient {
995
1024
  return new Promise((resolve, reject) => {
996
1025
  const timer = setTimeout(() => {
997
1026
  this.pendingRequests.delete(id);
998
- reject(new Error(`Request timeout after ${timeoutSec}s`));
1027
+ const help = pinned ? '. Check the Cloud Server and Cloud Connector versions.' : '';
1028
+ reject(new Error(`Request timeout after ${timeoutSec}s${help}`));
999
1029
  }, timeoutSec * 1_000 + RESPONSE_GRACE_MS);
1000
1030
  this.pendingRequests.set(id, { resolve, reject, timer });
1001
1031
  ws.send(serialized);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mearl/client",
3
- "version": "3.3.0",
3
+ "version": "3.3.2-beta.0",
4
4
  "description": "Unified Mearl SDK & CLI for local and remote browsers",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -69,11 +69,11 @@
69
69
  "commander": "^14.0.3",
70
70
  "fastest-levenshtein": "^1.0.16",
71
71
  "ws": "^8.18.0",
72
- "@mearl/daemon-core": "3.3.0",
73
- "@mearl/cloud-types": "3.3.0",
74
- "@mearl/provider": "3.3.0",
75
- "@mearl/agent-runtime": "3.3.0",
76
- "@mearl/browser-core": "3.3.0"
72
+ "@mearl/daemon-core": "3.3.2-beta.0",
73
+ "@mearl/cloud-types": "3.3.2-beta.0",
74
+ "@mearl/provider": "3.3.2-beta.0",
75
+ "@mearl/agent-runtime": "3.3.2-beta.0",
76
+ "@mearl/browser-core": "3.3.2-beta.0"
77
77
  },
78
78
  "devDependencies": {
79
79
  "@types/node": "^24.9.1",