@mearl/client 3.0.9 → 3.0.11

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.
@@ -466,7 +466,7 @@ export declare const COMMANDS: readonly [{
466
466
  readonly examples: ["browser_close --payload '{\"browser\":\"managed:account-a\"}'", "browser_close --payload '{\"browser\":\"account-b\",\"deleteProfile\":true}'"];
467
467
  }, {
468
468
  readonly name: "tab_open";
469
- readonly description: "打开或按 URL 规则复用 Tab,并等待新页面加载完成";
469
+ readonly description: "打开或按 URL 规则复用 Tab,并观察新页面的导航状态";
470
470
  readonly aliases: readonly ["tab_new", "new_tab", "tab_create", "create_tab"];
471
471
  readonly aliasExamples: {
472
472
  readonly tab_activate: "tab_open --payload '{\"url\":\"https://example.com\",\"reuse\":\"require\",\"active\":true}'";
@@ -522,7 +522,7 @@ export declare const COMMANDS: readonly [{
522
522
  readonly description: "与 appProfile 配合;声明式覆盖桥方法,形如 {methods:{api:{behavior|response|noop,silent?}}}";
523
523
  }];
524
524
  readonly notes: readonly ["emulation / appProfile 只应用到新建 Tab;复用 Tab 要切换状态时用对应设置 action。", "closeExisting 不能与复用或 openerTabId 组合;多匹配默认报错,match.onMultiple=first 可显式选择第一个。"];
525
- readonly result: readonly ["返回 tabId、url、title、opened/reused;reused=true 的既有页面应保留。", "active=true 时 activation 包含 tabActive、windowFocused、windowState、visibilityState;emulation 返回实际生效配置。", "capture.cursor 是导航前诊断边界,可分别用于 get_logs/get_requests/get_events 的 after。"];
525
+ readonly result: readonly ["返回 tabId、url、title、opened/reused;reused=true 的既有页面应保留。", "CDP 新开页返回 navigation.status:ready 表示 DOM 可读,pending 表示尚未收到导航回执,loading 表示文档仍在加载,failed 附带浏览器错误。等待超时后仍可用返回的 tabId 检查页面。", "active=true 时 activation 包含 tabActive、windowFocused、windowState、visibilityState;emulation 返回实际生效配置。", "capture.cursor 是导航前诊断边界,可分别用于 get_logs/get_requests/get_events 的 after。"];
526
526
  readonly examples: ["tab_open --payload '{\"url\":\"https://example.com\"}'", "tab_open --payload '{\"url\":\"https://example.com/page\",\"reuse\":\"prefer\",\"match\":{\"ignoreSearch\":true}}'", "tab_open --payload '{\"url\":\"https://m.example.com\",\"emulation\":{\"preset\":\"iphone-17-pro\"}}'", "tab_open --payload '{\"url\":\"https://example.com/app/home\",\"appProfile\":\"reader\"}'", "tab_open --payload '{\"url\":\"https://example.com/app/home\",\"appProfile\":\"reader\",\"emulation\":{\"preset\":\"ipad-mini-a17-pro\",\"orientation\":\"landscape\",\"deviceShell\":true,\"splitScreen\":true}}'", "tab_open --payload '{\"url\":\"https://example.com\",\"appProfile\":\"reader\",\"os\":\"android\"}'", "tab_open --payload '{\"url\":\"https://example.com\",\"group\":\"验证任务\"}'"];
527
527
  }, {
528
528
  readonly name: "tab_close";
package/dist/commands.js CHANGED
@@ -506,7 +506,7 @@ export const COMMANDS = [
506
506
  // ── 标签页 ────────────────────────────────────────────────────────────────
507
507
  {
508
508
  name: 'tab_open',
509
- description: '打开或按 URL 规则复用 Tab,并等待新页面加载完成',
509
+ description: '打开或按 URL 规则复用 Tab,并观察新页面的导航状态',
510
510
  aliases: ['tab_new', 'new_tab', 'tab_create', 'create_tab'],
511
511
  aliasExamples: {
512
512
  tab_activate: `tab_open --payload '{"url":"https://example.com","reuse":"require","active":true}'`,
@@ -575,6 +575,7 @@ export const COMMANDS = [
575
575
  ],
576
576
  result: [
577
577
  '返回 tabId、url、title、opened/reused;reused=true 的既有页面应保留。',
578
+ 'CDP 新开页返回 navigation.status:ready 表示 DOM 可读,pending 表示尚未收到导航回执,loading 表示文档仍在加载,failed 附带浏览器错误。等待超时后仍可用返回的 tabId 检查页面。',
578
579
  'active=true 时 activation 包含 tabActive、windowFocused、windowState、visibilityState;emulation 返回实际生效配置。',
579
580
  'capture.cursor 是导航前诊断边界,可分别用于 get_logs/get_requests/get_events 的 after。',
580
581
  ],
package/dist/script.js CHANGED
@@ -25,8 +25,10 @@ export async function executeScript(code, options = {}) {
25
25
  throw new Error('executionTimeoutSec must be positive and within the timer range');
26
26
  if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1 || maxOutputBytes > 1024 * 1024)
27
27
  throw new Error('maxOutputBytes must be an integer between 1 and 1048576');
28
+ const executionDeadline = Date.now() + Math.ceil(executionTimeoutSec * 1000);
28
29
  const client = new UnifiedClient({
29
30
  serverUrl: serverUrl ?? process.env.MEARL_SERVER_URL ?? loadCloudServerConfig()?.server,
31
+ requestDeadline: executionDeadline,
30
32
  });
31
33
  let session = defaults.session && defaults.session !== 'new' ? { sessionId: defaults.session } : undefined;
32
34
  let sessionId = defaults.session;
@@ -93,7 +95,7 @@ export async function executeScript(code, options = {}) {
93
95
  }
94
96
  };
95
97
  const abort = () => stop({ code: 'SCRIPT_CANCELLED', message: 'Script execution cancelled' });
96
- const deadline = setTimeout(() => stop({ code: 'SCRIPT_TIMEOUT', message: 'Script execution deadline exceeded' }), executionTimeoutSec * 1000);
98
+ const deadline = setTimeout(() => stop({ code: 'SCRIPT_TIMEOUT', message: 'Script execution deadline exceeded' }), Math.max(0, executionDeadline - Date.now()));
97
99
  signal?.addEventListener('abort', abort, { once: true });
98
100
  if (signal?.aborted)
99
101
  abort();
@@ -208,8 +210,11 @@ export async function executeScript(code, options = {}) {
208
210
  session: sessionId,
209
211
  ...args[2],
210
212
  });
211
- const optionsOnly = (OPTIONS_ONLY.has(method) && !(method === 'browserList' && args[0] &&
212
- ('provider' in args[0] || 'launchForm' in args[0]))) || (method === 'browserRelease' && args.length < 2);
213
+ const optionsOnly = (OPTIONS_ONLY.has(method) &&
214
+ !(method === 'browserList' &&
215
+ args[0] &&
216
+ ('provider' in args[0] || 'launchForm' in args[0]))) ||
217
+ (method === 'browserRelease' && args.length < 2);
213
218
  return invoke(METHOD_ACTIONS.get(method), optionsOnly ? {} : (args[0] ?? {}), optionsOnly ? args[0] : args[1]);
214
219
  })
215
220
  .then(result => send({ type: 'response', id, result, session }), error => send({ type: 'response', id, error: serializeError(error), session }))
package/dist/socket.d.ts CHANGED
@@ -23,6 +23,8 @@ export interface InvokeOptions {
23
23
  socketPath?: string;
24
24
  /** 超时时间(秒),默认 15 */
25
25
  timeoutSec?: number;
26
+ /** Absolute cutoff for sending this request, including any routing retries. */
27
+ deadline?: number;
26
28
  /** Force CDP transport instead of extension */
27
29
  transport?: 'cdp';
28
30
  /** Target a specific browser by id / name (see the browser registry). */
package/dist/socket.js CHANGED
@@ -13,13 +13,13 @@ import os from 'node:os';
13
13
  import path from 'node:path';
14
14
  import { CLIENT_VERSION } from './runtimePaths.js';
15
15
  import { StringDecoder } from 'node:string_decoder';
16
- import { assertProviderControlSessionMode, ensureProviderControlHost, listInstalledProviders } from '@mearl/provider/host';
17
- import { MEARL_PROVIDER_PROTOCOL_VERSION, assertProviderProtocolVersion, validateProviderLaunchForm } from '@mearl/provider';
16
+ import { assertProviderControlSessionMode, ensureProviderControlHost, listInstalledProviders, } from '@mearl/provider/host';
17
+ import { MEARL_PROVIDER_PROTOCOL_VERSION, assertProviderProtocolVersion, validateProviderLaunchForm, } from '@mearl/provider';
18
18
  import { readLiveProvider, ensureInstalledProvidersRunning } from '@mearl/provider/runtime';
19
19
  import { resolveFileRefs } from './fileRefs.js';
20
20
  import { listLiveBrowsers, findBrowser, describeBrowser, } from './browserRegistry.js';
21
21
  import { resolveActionTimeoutSec } from './actionTimeouts.js';
22
- import { isBrowserCapabilityAction, parseBrowserListParams } from '@mearl/browser-core';
22
+ import { isBrowserCapabilityAction, parseBrowserListParams, } from '@mearl/browser-core';
23
23
  export { CLIENT_VERSION };
24
24
  const MAX_SOCKET_BUFFER_SIZE = 64 * 1024 * 1024;
25
25
  /**
@@ -379,7 +379,10 @@ export function invoke(action, data = {}, options = {}) {
379
379
  const discovery = parseBrowserListParams(resolvedData);
380
380
  if (discovery) {
381
381
  return (async () => {
382
- if (transport || options.socketPath || controlSource !== 'local' || options.controlSessionId)
382
+ if (transport ||
383
+ options.socketPath ||
384
+ controlSource !== 'local' ||
385
+ options.controlSessionId)
383
386
  throw new Error('Provider discovery requires the local source without a transport, socket or session override');
384
387
  const provider = listInstalledProviders().find(provider => provider.providerId === discovery.provider);
385
388
  if (!provider?.browserType.dynamicLaunchForm)
@@ -399,10 +402,10 @@ export function invoke(action, data = {}, options = {}) {
399
402
  });
400
403
  })();
401
404
  }
402
- return dispatchInvoke(action, resolvedData, timeoutSec, transport, undefined, controlSource, options.socketPath).then(result => decorateBrowserListResult(transport === 'cdp' ? cdpOnlyBrowserList(result) : result));
405
+ return dispatchInvoke(action, resolvedData, timeoutSec, transport, undefined, controlSource, options.socketPath, options.deadline).then(result => decorateBrowserListResult(transport === 'cdp' ? cdpOnlyBrowserList(result) : result));
403
406
  }
404
407
  const selector = browser ?? defaultBrowser ?? process.env.MEARL_BROWSER ?? undefined;
405
- return dispatchInvoke(action, resolvedData, timeoutSec, transport, selector, controlSource, options.socketPath);
408
+ return dispatchInvoke(action, resolvedData, timeoutSec, transport, selector, controlSource, options.socketPath, options.deadline);
406
409
  }
407
410
  /** Infrastructure calls stay on this machine even when an Agent has selected an external browser. */
408
411
  export function invokeLocalHost(action, data = {}, options = {}) {
@@ -458,11 +461,12 @@ function isUnavailableConnection(error) {
458
461
  const code = cause?.code;
459
462
  return isConnError(cause) || isSocketSandboxError(cause) || code === 'EACCES';
460
463
  }
461
- async function dispatchInvoke(action, data, timeoutSec, transport, selector, controlSource, socketPath) {
464
+ async function dispatchInvoke(action, data, timeoutSec, transport, selector, controlSource, socketPath, deadline) {
465
+ const send = (path, target) => invokeOnce(action, data, timeoutSec, transport, path, controlSource, target?.transport === 'provider' ? target.browserId : undefined, target?.capabilities?.controlSessionMode, deadline);
462
466
  const configuredSocketPath = socketPath ?? process.env.MEARL_SOCKET_PATH?.trim();
463
467
  if (configuredSocketPath && (socketPath || !selector)) {
464
468
  try {
465
- return await invokeOnce(action, data, timeoutSec, transport, configuredSocketPath, controlSource);
469
+ return await send(configuredSocketPath);
466
470
  }
467
471
  catch (error) {
468
472
  if (isConnError(error) || isSocketSandboxError(error)) {
@@ -479,7 +483,7 @@ async function dispatchInvoke(action, data, timeoutSec, transport, selector, con
479
483
  const registeredCdp = controllableBrowsers.find(browser => browser.transport === 'cdp' && isOrdinaryLocalBrowser(browser));
480
484
  if (registeredCdp) {
481
485
  try {
482
- return await invokeOnce(action, data, timeoutSec, transport, registeredCdp.socketPath, controlSource);
486
+ return await send(registeredCdp.socketPath);
483
487
  }
484
488
  catch (error) {
485
489
  if (!isConnError(error))
@@ -533,7 +537,7 @@ async function dispatchInvoke(action, data, timeoutSec, transport, selector, con
533
537
  throw new Error(`Browser ${describeBrowser(match)} does not support ${action}`);
534
538
  }
535
539
  try {
536
- return await invokeOnce(action, data, timeoutSec, transport, match.socketPath, controlSource, match.transport === 'provider' ? match.browserId : undefined, match.capabilities?.controlSessionMode);
540
+ return await send(match.socketPath, match);
537
541
  }
538
542
  catch (error) {
539
543
  if (isConnError(error) || isSocketSandboxError(error)) {
@@ -550,7 +554,7 @@ async function dispatchInvoke(action, data, timeoutSec, transport, selector, con
550
554
  if (candidates.length > 0) {
551
555
  const target = candidates[0];
552
556
  try {
553
- return await invokeOnce(action, data, timeoutSec, transport, target.socketPath, controlSource, target.transport === 'provider' ? target.browserId : undefined, target.capabilities?.controlSessionMode);
557
+ return await send(target.socketPath, target);
554
558
  }
555
559
  catch (error) {
556
560
  if (isSocketSandboxError(error)) {
@@ -575,13 +579,13 @@ async function dispatchInvoke(action, data, timeoutSec, transport, selector, con
575
579
  throw error;
576
580
  }
577
581
  }
578
- return invokeViaLegacy(action, data, timeoutSec, transport, controlSource, /* isRetry */ false);
582
+ return invokeViaLegacy(action, data, timeoutSec, transport, controlSource, false, false, deadline);
579
583
  }
580
584
  /** Legacy well-known socket, repairing a missing or stale endpoint and retrying once. */
581
- async function invokeViaLegacy(action, data, timeoutSec, transport, controlSource, isRetry, localOnly = false) {
585
+ async function invokeViaLegacy(action, data, timeoutSec, transport, controlSource, isRetry, localOnly = false, deadline) {
582
586
  const legacySocketIdentity = readOwnedLegacySocketIdentity();
583
587
  try {
584
- return await invokeOnce(action, data, timeoutSec, transport, SOCKET_PATH, controlSource);
588
+ return await invokeOnce(action, data, timeoutSec, transport, SOCKET_PATH, controlSource, undefined, undefined, deadline);
585
589
  }
586
590
  catch (error) {
587
591
  const err = error;
@@ -598,10 +602,10 @@ async function invokeViaLegacy(action, data, timeoutSec, transport, controlSourc
598
602
  !(transport === 'cdp' && browser.transport === 'provider') &&
599
603
  supportsAction(browser, action, data));
600
604
  if (target) {
601
- return invokeOnce(action, data, timeoutSec, transport, target.socketPath, controlSource, target.transport === 'provider' ? target.browserId : undefined, target.capabilities?.controlSessionMode);
605
+ return invokeOnce(action, data, timeoutSec, transport, target.socketPath, controlSource, target.transport === 'provider' ? target.browserId : undefined, target.capabilities?.controlSessionMode, deadline);
602
606
  }
603
607
  return invokeViaLegacy(action, data, timeoutSec, transport, controlSource,
604
- /* isRetry */ true, localOnly);
608
+ /* isRetry */ true, localOnly, deadline);
605
609
  }
606
610
  }
607
611
  if (err instanceof Error && !isConnError(err) && !isSocketSandboxError(err))
@@ -609,14 +613,16 @@ async function invokeViaLegacy(action, data, timeoutSec, transport, controlSourc
609
613
  throw new Error(formatConnectError(err, SOCKET_PATH), { cause: error });
610
614
  }
611
615
  }
612
- async function invokeOnce(action, data, timeoutSec, transport, socketPath, controlSource, providerTarget, controlSessionMode) {
616
+ async function invokeOnce(action, data, timeoutSec, transport, socketPath, controlSource, providerTarget, controlSessionMode, requestDeadline) {
617
+ if (requestDeadline !== undefined && Date.now() >= requestDeadline)
618
+ throw new Error('Browser request deadline exceeded before dispatch');
613
619
  if (providerTarget) {
614
620
  const host = await ensureProviderControlHost(Math.min(timeoutSec * 1000, 10_000));
615
621
  assertProviderControlSessionMode(host, controlSessionMode);
616
622
  socketPath = host.socketPath;
617
623
  }
618
624
  const id = `${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
619
- const deadline = Date.now() + Math.ceil(timeoutSec * 1000);
625
+ const deadline = Math.min(Date.now() + Math.ceil(timeoutSec * 1000), requestDeadline ?? Infinity);
620
626
  return new Promise((resolve, reject) => {
621
627
  if (process.platform !== 'win32' && fs.existsSync(socketPath) && process.getuid) {
622
628
  const ownerUid = fs.statSync(socketPath).uid;
@@ -645,8 +651,12 @@ async function invokeOnce(action, data, timeoutSec, transport, socketPath, contr
645
651
  };
646
652
  const timer = setTimeout(() => {
647
653
  settle(new Error(`请求超时,已等待 ${timeoutSec} 秒`));
648
- }, timeoutSec * 1000);
654
+ }, Math.max(0, Math.min(timeoutSec * 1000, deadline - Date.now())));
649
655
  socket.on('connect', () => {
656
+ if (Date.now() >= deadline) {
657
+ settle(new Error('Browser request deadline exceeded before dispatch'));
658
+ return;
659
+ }
650
660
  const message = {
651
661
  id,
652
662
  action,
@@ -654,6 +664,7 @@ async function invokeOnce(action, data, timeoutSec, transport, socketPath, contr
654
664
  version: CLIENT_VERSION,
655
665
  protocolVersion: MEARL_PROVIDER_PROTOCOL_VERSION,
656
666
  controlSource: toControlSourceWireValue(controlSource),
667
+ deadline,
657
668
  };
658
669
  if (data[SESSION_OPTION])
659
670
  message.controlSessionId = data[SESSION_OPTION];
@@ -661,7 +672,6 @@ async function invokeOnce(action, data, timeoutSec, transport, socketPath, contr
661
672
  message.transport = transport;
662
673
  if (providerTarget) {
663
674
  message.providerTarget = providerTarget;
664
- message.deadline = deadline;
665
675
  }
666
676
  socket.write(JSON.stringify(message) + '\n');
667
677
  });
package/dist/unified.d.ts CHANGED
@@ -18,6 +18,8 @@ export interface UnifiedInvokeOptions {
18
18
  }
19
19
  export interface UnifiedClientOptions {
20
20
  serverUrl?: string;
21
+ /** Absolute deadline shared by all requests from a script. */
22
+ requestDeadline?: number;
21
23
  connectTimeoutSec?: number;
22
24
  requestTimeoutSec?: number;
23
25
  heartbeatInterval?: number;
@@ -31,6 +33,7 @@ interface BrowserTarget {
31
33
  export declare function decodeBrowserTarget(selector: string | undefined): BrowserTarget | undefined;
32
34
  export declare function normalizeBrowserSelector(selector: string): string;
33
35
  export declare class UnifiedClient {
36
+ private readonly requestDeadline?;
34
37
  private readonly controlSessions;
35
38
  private readonly options;
36
39
  private defaultBrowser;
package/dist/unified.js CHANGED
@@ -93,6 +93,7 @@ function errorMessage(error) {
93
93
  return error instanceof Error ? error.message : String(error);
94
94
  }
95
95
  export class UnifiedClient {
96
+ requestDeadline;
96
97
  controlSessions = new Map();
97
98
  options;
98
99
  defaultBrowser;
@@ -104,6 +105,7 @@ export class UnifiedClient {
104
105
  heartbeatTimer = null;
105
106
  closing = false;
106
107
  constructor(options = {}) {
108
+ this.requestDeadline = options.requestDeadline;
107
109
  this.options = {
108
110
  ...(options.serverUrl ? { serverUrl: options.serverUrl } : {}),
109
111
  connectTimeoutSec: options.connectTimeoutSec ?? DEFAULT_CONNECT_TIMEOUT,
@@ -147,7 +149,12 @@ export class UnifiedClient {
147
149
  }
148
150
  async invoke(action, data = {}, options = {}) {
149
151
  const discovery = action === 'browser_list' ? parseBrowserListParams(data) : undefined;
150
- if (discovery && (!options.local || options.connector || options.transport || options.session || options.controlSessionId))
152
+ if (discovery &&
153
+ (!options.local ||
154
+ options.connector ||
155
+ options.transport ||
156
+ options.session ||
157
+ options.controlSessionId))
151
158
  throw new Error('Provider discovery requires explicit --local without connector, transport, socket or session overrides');
152
159
  if (action === 'plugin_state') {
153
160
  const { PluginStateClient } = await import('./plugins/clients/pluginState.js');
@@ -354,7 +361,10 @@ export class UnifiedClient {
354
361
  return this.listConnectors(timeoutSec);
355
362
  if (action === 'browser_list') {
356
363
  if (parseBrowserListParams(data)) {
357
- const result = await invokeLocalBrowser('browser_list', data, { timeoutSec, controlSource: 'local' });
364
+ const result = await invokeLocalBrowser('browser_list', data, {
365
+ timeoutSec,
366
+ controlSource: 'local',
367
+ });
358
368
  if (!result?.discovery)
359
369
  throw new Error('Provider launch-form discovery is not supported by this host');
360
370
  return this.applyConfiguredDefault(this.decorateListing(result, { kind: 'local' }));
@@ -641,6 +651,7 @@ export class UnifiedClient {
641
651
  async invokeLocal(action, data, timeoutSec, browser, transport, controlSessionId, socketPath) {
642
652
  const result = await invokeLocalBrowser(action, data, {
643
653
  timeoutSec,
654
+ ...(this.requestDeadline === undefined ? {} : { deadline: this.requestDeadline }),
644
655
  ...(browser ? { browser } : {}),
645
656
  ...(transport ? { transport } : {}),
646
657
  ...(socketPath ? { socketPath } : {}),
@@ -852,6 +863,12 @@ export class UnifiedClient {
852
863
  const ws = this.ws;
853
864
  if (!ws || ws.readyState !== WebSocket.OPEN)
854
865
  throw new Error('Connection is not open');
866
+ if (this.requestDeadline !== undefined) {
867
+ const remainingSec = (this.requestDeadline - Date.now()) / 1000;
868
+ if (remainingSec <= 0)
869
+ throw new Error('Browser request deadline exceeded before dispatch');
870
+ timeoutSec = Math.min(timeoutSec, remainingSec);
871
+ }
855
872
  const id = `${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
856
873
  const message = { id, action, data, timeoutSec };
857
874
  if (browser)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mearl/client",
3
- "version": "3.0.9",
3
+ "version": "3.0.11",
4
4
  "description": "Unified Mearl SDK & CLI for local and remote browsers",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -68,11 +68,11 @@
68
68
  "commander": "^14.0.3",
69
69
  "fastest-levenshtein": "^1.0.16",
70
70
  "ws": "^8.18.0",
71
- "@mearl/daemon-core": "3.0.9",
72
- "@mearl/cloud-types": "3.0.9",
73
- "@mearl/agent-runtime": "3.0.9",
74
- "@mearl/browser-core": "3.0.9",
75
- "@mearl/provider": "3.0.9"
71
+ "@mearl/daemon-core": "3.0.11",
72
+ "@mearl/provider": "3.0.11",
73
+ "@mearl/agent-runtime": "3.0.11",
74
+ "@mearl/cloud-types": "3.0.11",
75
+ "@mearl/browser-core": "3.0.11"
76
76
  },
77
77
  "devDependencies": {
78
78
  "@types/node": "^24.9.1",