@mearl/client 3.1.7 → 3.1.8-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
@@ -363,7 +363,9 @@ try {
363
363
  }
364
364
  ```
365
365
 
366
- `wait` timeout or signal abort ends waiting only; `cancel(taskId)` cancels execution. Browser tasks require explicit `browser`, resolved to fixed IDs before acceptance. `get/list` return snapshots/result references; `list` has bounded pagination/`nextCursor`; `events` provides cursors, gaps, and snapshots; `subscribe` wraps long polling. `result(taskId)` losslessly reads and verifies chunks up to 64 MiB. Terminal records/results remain seven days.
366
+ `wait` timeout or signal abort ends waiting only; `cancel(taskId)` cancels execution. Browser tasks require explicit `browser`, resolved to fixed IDs before acceptance. `get/list` return snapshots/result references; `list` has bounded pagination/`nextCursor`; `events` provides cursors, gaps, and snapshots; `subscribe` wraps long polling. `result(taskId)` losslessly reads and verifies chunks up to 64 MiB. Regular terminal records and results remain seven days. Page event and attach handlers use input during execution and record completion status. Regular cleanup can remove their records one hour after completion.
367
+
368
+ To troubleshoot background plugin service startup, set `MEARL_DEBUG=1` in the launching process. It captures service output in `.host/service.log` under the plugin directory.
367
369
 
368
370
  Handshakes and `tasks.status()` return `version/buildId`; build IDs identify running code, while protocol versions determine compatibility. With matching protocols, different/missing version/build IDs do not interrupt tasks, models, pages, or state. To switch builds, confirm no active tasks/page operations, call `tasks.stopHost()`, and let the next business call start the current build. Reregistration does not restart services. After local client/host changes, root `pnpm build` generates matching fingerprints and both artifacts; `tsc --watch` alone does not.
369
371
 
package/README.md CHANGED
@@ -363,7 +363,9 @@ try {
363
363
  }
364
364
  ```
365
365
 
366
- `wait` 超时或其 signal 中止只结束等待;`cancel(taskId)` 才取消执行。浏览器任务需显式传 `browser`,名称会在接受前解析为固定 ID。`get/list` 返回任务快照与结果引用,`list` 返回有界分页及 `nextCursor`;`events` 返回游标、缺口标记和最新快照,`subscribe` 封装长轮询。`result(taskId)` 分块读取并校验完整业务结果,最大 64 MiB;终态记录和结果保留 7 天。
366
+ `wait` 超时或其 signal 中止只结束等待;`cancel(taskId)` 才取消执行。浏览器任务需显式传 `browser`,名称会在接受前解析为固定 ID。`get/list` 返回任务快照与结果引用,`list` 返回有界分页及 `nextCursor`;`events` 返回游标、缺口标记和最新快照,`subscribe` 封装长轮询。`result(taskId)` 分块读取并校验完整业务结果,最大 64 MiB。普通任务终态记录和结果保留 7 天。页面事件和页面挂载回调的输入仅供执行使用,记录包含完成状态,结束 1 小时后可被定期清理。
367
+
368
+ 需要排查后台插件服务启动时,可在启动它的进程中设置 `MEARL_DEBUG=1`,将服务输出保存到插件目录下的 `.host/service.log`。
367
369
 
368
370
  插件宿主握手与 `tasks.status()` 返回 `version/buildId`,构建标识用于定位运行代码,兼容性由握手中的协议版本决定。协议相同时,即使版本、构建标识不同或旧宿主未提供标识,任务、模型、页面和状态请求仍可继续使用现有服务,不中断活动任务或页面实例。需要切换到新构建时,确认没有活动任务及页面操作后调用 `tasks.stopHost()`,下次业务调用将启动当前构建;重新注册插件不会重启宿主。本地修改客户端或宿主代码后执行根目录 `pnpm build`,同步生成指纹并构建双方产物;仅运行 `tsc --watch` 不会更新构建指纹。
369
371
 
@@ -8,6 +8,12 @@ import { PLUGIN_TASK_PROTOCOL_VERSION } from '@mearl/browser-core';
8
8
  import { readPluginTaskMessages, writePluginTaskMessage } from '../pluginTaskWire.js';
9
9
  import { pluginExecutionError, serializePluginExecutionError, } from '../runtime/pluginExecutorProtocol.js';
10
10
  const starting = new Map();
11
+ function hostNotReady(cause) {
12
+ const diagnostic = process.env.MEARL_DEBUG === '1'
13
+ ? 'Inspect the service.log file.'
14
+ : 'Retry with MEARL_DEBUG=1 to capture startup diagnostics.';
15
+ return new Error(`Plugin execution service did not become ready. ${diagnostic}`, { cause });
16
+ }
11
17
  async function ensureHost(runtimePath) {
12
18
  const paths = pluginHostPaths();
13
19
  let work = starting.get(paths.registry);
@@ -33,13 +39,16 @@ async function ensureHost(runtimePath) {
33
39
  const owner = readRecord(paths.lease);
34
40
  if (owner && isProcessOwnerAlive(owner))
35
41
  return;
36
- mkdirSync(paths.home, { recursive: true, mode: 0o700 });
37
- rotateLogIfNeeded(paths.log);
38
- const log = openSync(paths.log, 'a', 0o600);
42
+ let log;
39
43
  try {
44
+ if (process.env.MEARL_DEBUG === '1') {
45
+ mkdirSync(paths.home, { recursive: true, mode: 0o700 });
46
+ rotateLogIfNeeded(paths.log);
47
+ log = openSync(paths.log, 'a', 0o600);
48
+ }
40
49
  const child = spawn(process.execPath, [runtimePath], {
41
50
  detached: true,
42
- stdio: ['ignore', log, log],
51
+ stdio: ['ignore', log ?? 'ignore', log ?? 'ignore'],
43
52
  windowsHide: true,
44
53
  });
45
54
  await new Promise((resolve, reject) => {
@@ -49,7 +58,8 @@ async function ensureHost(runtimePath) {
49
58
  child.unref();
50
59
  }
51
60
  finally {
52
- closeSync(log);
61
+ if (log !== undefined)
62
+ closeSync(log);
53
63
  }
54
64
  const deadline = Date.now() + 10000;
55
65
  while (Date.now() < deadline) {
@@ -67,7 +77,7 @@ async function ensureHost(runtimePath) {
67
77
  return;
68
78
  await new Promise(resolve => setTimeout(resolve, 50));
69
79
  }
70
- throw new Error('Plugin execution service startup timed out');
80
+ throw hostNotReady();
71
81
  }
72
82
  finally {
73
83
  removeRecordIfPid(lock, process.pid);
@@ -125,9 +135,7 @@ export class PluginHostConnection {
125
135
  await new Promise(resolve => setTimeout(resolve, 100));
126
136
  }
127
137
  } while (Date.now() < deadline);
128
- throw new Error('Plugin execution service did not become ready; inspect its service.log', {
129
- cause: failure,
130
- });
138
+ throw hostNotReady(failure);
131
139
  }
132
140
  async open(socketPath, generation) {
133
141
  const socket = createConnection(socketPath);
@@ -104,6 +104,11 @@ export class PluginTaskClient {
104
104
  }
105
105
  async result(taskId) {
106
106
  const task = await this.get(taskId);
107
+ if (task.state === 'success' &&
108
+ !task.result &&
109
+ task.source === 'runtime' &&
110
+ task.kind !== 'model')
111
+ return undefined;
107
112
  if (task.state !== 'success' || !task.result)
108
113
  throw new Error('Plugin task has no successful result');
109
114
  const parts = [];
@@ -1,4 +1,4 @@
1
- export declare function pluginHostPaths(): {
1
+ export declare function pluginHostPaths(registry?: string): {
2
2
  registry: string;
3
3
  home: string;
4
4
  lease: string;
@@ -2,8 +2,7 @@ import { createHash } from 'node:crypto';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join } from 'node:path';
4
4
  import { pluginDirectory } from '../pluginRegistry.js';
5
- export function pluginHostPaths() {
6
- const registry = pluginDirectory();
5
+ export function pluginHostPaths(registry = pluginDirectory()) {
7
6
  const key = createHash('sha256').update(registry).digest('hex').slice(0, 16);
8
7
  const home = join(registry, '.host');
9
8
  return {
@@ -1,2 +1,5 @@
1
1
  /** Complete uninstall discards execution caches after every plugin has been removed. */
2
- export declare function cleanupPluginRuntime(): Promise<void>;
2
+ export declare function cleanupPluginRuntime({ removeData, defaultRegistry, }?: {
3
+ removeData?: () => void;
4
+ defaultRegistry?: string;
5
+ }): Promise<void>;
@@ -1,12 +1,16 @@
1
- import { rmSync } from 'node:fs';
1
+ import { existsSync, realpathSync, rmSync } from 'node:fs';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { claimRecord, isProcessOwnerAlive, processIdentity, readRecord, removeInvalidRecord, removeRecordIfPid, } from '@mearl/daemon-core';
4
4
  import { pluginHostPaths } from './pluginHostPaths.js';
5
5
  import { listPluginNames } from '../pluginRegistry.js';
6
6
  import { PluginTaskClient } from '../clients/pluginTasks.js';
7
- import { PluginTaskStore, pluginTaskExecutionUnconfirmed } from './pluginTaskStore.js';
7
+ import { PluginTaskStore, pluginTaskExecutionUnconfirmed, pluginTaskExecutorAlive, } from './pluginTaskStore.js';
8
+ function assertTaskExecutorsStopped(store) {
9
+ if (store.list({ allowMissing: true }).some(pluginTaskExecutorAlive))
10
+ throw new Error('Plugin task executors are still running. Stop them and rerun the uninstall.');
11
+ }
8
12
  /** Complete uninstall discards execution caches after every plugin has been removed. */
9
- export async function cleanupPluginRuntime() {
13
+ export async function cleanupPluginRuntime({ removeData, defaultRegistry, } = {}) {
10
14
  const paths = pluginHostPaths();
11
15
  if (listPluginNames().length)
12
16
  throw new Error('Registered plugins still use the execution service');
@@ -19,7 +23,9 @@ export async function cleanupPluginRuntime() {
19
23
  removeInvalidRecord(lock);
20
24
  if (!claimRecord(lock, { pid: process.pid, processIdentity: processIdentity(process.pid) }))
21
25
  throw new Error('Plugin execution service is starting; caches were retained');
26
+ let ownedLock = lock;
22
27
  try {
28
+ ownedLock = realpathSync(lock);
23
29
  const lease = readRecord(paths.lease);
24
30
  if (lease && isProcessOwnerAlive(lease)) {
25
31
  const client = new PluginTaskClient({ autoStart: false });
@@ -34,22 +40,40 @@ export async function cleanupPluginRuntime() {
34
40
  if ((current && isProcessOwnerAlive(current)) || listPluginNames().length)
35
41
  throw new Error('Plugin execution service restarted during cleanup; caches were retained');
36
42
  const store = new PluginTaskStore();
37
- if (store.list().some(pluginTaskExecutionUnconfirmed))
38
- throw new Error('Plugin execution is not confirmed stopped; task records were retained');
39
- store.recover(randomUUID());
40
- if (store.list().some(pluginTaskExecutionUnconfirmed))
41
- throw new Error('Plugin execution is not confirmed stopped; task records were retained');
43
+ if (removeData) {
44
+ assertTaskExecutorsStopped(store);
45
+ if (defaultRegistry && defaultRegistry !== paths.registry) {
46
+ const local = pluginHostPaths(defaultRegistry);
47
+ const service = readRecord(local.lease);
48
+ const starter = readRecord(`${local.lease}.start`);
49
+ if ((service && isProcessOwnerAlive(service)) ||
50
+ (starter && starter.pid !== process.pid && isProcessOwnerAlive(starter)))
51
+ throw new Error('The default Mearl plugin service is running. Uninstall with the default plugin directory first.');
52
+ assertTaskExecutorsStopped(new PluginTaskStore(local.tasks));
53
+ }
54
+ }
55
+ else {
56
+ if (store.list().some(pluginTaskExecutionUnconfirmed))
57
+ throw new Error('Plugin execution is not confirmed stopped; task records were retained');
58
+ store.recover(randomUUID());
59
+ if (store.list().some(pluginTaskExecutionUnconfirmed))
60
+ throw new Error('Plugin execution is not confirmed stopped; task records were retained');
61
+ }
42
62
  const replacement = readRecord(paths.lease);
43
63
  if ((replacement && isProcessOwnerAlive(replacement)) || listPluginNames().length)
44
64
  throw new Error('Plugin execution service restarted during cleanup; caches were retained');
45
- for (const file of [paths.tasks, paths.revisions, paths.log, `${paths.log}.1`])
46
- rmSync(file, { recursive: true, force: true });
47
65
  if (current)
48
66
  removeRecordIfPid(paths.lease, current.pid);
49
67
  if (process.platform !== 'win32')
50
68
  rmSync(paths.socket, { force: true });
69
+ if (removeData)
70
+ removeData();
71
+ else
72
+ for (const file of [paths.tasks, paths.revisions, paths.log, `${paths.log}.1`])
73
+ rmSync(file, { recursive: true, force: true });
51
74
  }
52
75
  finally {
53
- removeRecordIfPid(lock, process.pid);
76
+ if (existsSync(ownedLock))
77
+ removeRecordIfPid(ownedLock, process.pid);
54
78
  }
55
79
  }
@@ -327,7 +327,7 @@ export class PluginTaskManager {
327
327
  },
328
328
  }
329
329
  : {}),
330
- input: request.input,
330
+ input: bridge.scope.access === 'runtime' ? {} : request.input,
331
331
  source: bridge.scope.source,
332
332
  cwd: request.cwd,
333
333
  state: 'queued',
@@ -945,7 +945,8 @@ export class PluginTaskManager {
945
945
  await this.stopChildren(taskId);
946
946
  if (!page && request.kind !== 'model')
947
947
  await this.services?.releaseModels?.(taskId);
948
- const reference = this.store.saveResult(taskId, result);
948
+ // Page handlers report completion through the page lifecycle and discard their return value.
949
+ const reference = page && request.kind !== 'model' ? undefined : this.store.saveResult(taskId, result);
949
950
  this.update(taskId, { state: 'success', result: reference });
950
951
  }
951
952
  catch (cause) {
@@ -1037,6 +1038,11 @@ export class PluginTaskManager {
1037
1038
  if (event.type === 'progress')
1038
1039
  onProgress?.(event.progress);
1039
1040
  if (page.task.state === 'success') {
1041
+ if (!page.task.result) {
1042
+ if (page.task.source === 'runtime' && page.task.kind !== 'model')
1043
+ return undefined;
1044
+ throw new Error('Plugin task has no successful result');
1045
+ }
1040
1046
  const chunks = [];
1041
1047
  for (let index = 0; index < page.task.result.chunks; index++)
1042
1048
  chunks.push(Buffer.from(this.resultChunk(taskId, scope, index).data, 'base64'));
@@ -22,6 +22,7 @@ export interface PluginTaskRecord {
22
22
  processIdentity?: string;
23
23
  };
24
24
  }
25
+ export declare function pluginTaskExecutorAlive(record: PluginTaskRecord): boolean;
25
26
  export declare function pluginTaskExecutionUnconfirmed(record: PluginTaskRecord): boolean;
26
27
  export declare class PluginTaskStore {
27
28
  readonly directory: string;
@@ -40,7 +41,9 @@ export declare class PluginTaskStore {
40
41
  /** The service owns writes; only active identities remain indexed in memory. */
41
42
  listActive(): PluginTaskRecord[];
42
43
  update(taskId: string, update: Partial<PluginTask>, type?: PluginTaskEvent['type'], fields?: Pick<Partial<PluginTaskRecord>, 'checkpoint' | 'diagnostics'>): PluginTask;
43
- list(): PluginTaskRecord[];
44
+ list({ allowMissing }?: {
45
+ allowMissing?: boolean;
46
+ }): PluginTaskRecord[];
44
47
  diagnosticRecords(taskId?: string): {
45
48
  records: PluginTaskRecord[];
46
49
  limited: boolean;
@@ -9,17 +9,25 @@ export const PLUGIN_TASK_RESULT_CHUNK_BYTES = 192 * 1024;
9
9
  const MAX_EVENT_BYTES = 512 * 1024;
10
10
  const MAX_RESULT_BYTES = 64 * 1024 * 1024;
11
11
  const RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
12
+ const PAGE_TASK_RETENTION_MS = 60 * 60 * 1000;
13
+ export function pluginTaskExecutorAlive(record) {
14
+ const owner = record.executorOwner;
15
+ return Boolean(owner &&
16
+ (isProcessOwnerAlive(owner) ||
17
+ (process.platform !== 'win32' && isProcessGroupAlive(owner.pid))));
18
+ }
12
19
  export function pluginTaskExecutionUnconfirmed(record) {
13
20
  const owner = record.executorOwner;
14
- if (owner && (!Number.isSafeInteger(owner.pid) || owner.pid < 1))
15
- return true;
16
- if ((owner && isProcessOwnerAlive(owner)) ||
21
+ return Boolean((owner && (!Number.isSafeInteger(owner.pid) || owner.pid < 1)) ||
22
+ pluginTaskExecutorAlive(record) ||
17
23
  record.task.error?.details?.executionStopped === false ||
18
- (process.platform === 'win32' && record.task.error?.code === 'PLUGIN_TASK_HOST_RESTARTED'))
19
- return true;
20
- if (owner && process.platform !== 'win32')
21
- return isProcessGroupAlive(owner.pid);
22
- return false;
24
+ (process.platform === 'win32' && record.task.error?.code === 'PLUGIN_TASK_HOST_RESTARTED'));
25
+ }
26
+ function canPruneTask(record, now) {
27
+ const expiresAfter = record.access === 'runtime' ? PAGE_TASK_RETENTION_MS : RETENTION_MS;
28
+ return (!isPluginTaskActive(record.task.state) &&
29
+ now - record.task.updatedAt >= expiresAfter &&
30
+ !pluginTaskExecutionUnconfirmed(record));
23
31
  }
24
32
  export class PluginTaskStore {
25
33
  directory;
@@ -158,7 +166,7 @@ export class PluginTaskStore {
158
166
  this.write(record);
159
167
  return record.task;
160
168
  }
161
- list() {
169
+ list({ allowMissing = false } = {}) {
162
170
  let names;
163
171
  try {
164
172
  names = readdirSync(this.directory);
@@ -168,7 +176,19 @@ export class PluginTaskStore {
168
176
  return [];
169
177
  throw error;
170
178
  }
171
- return names.filter(isPluginTaskId).map(name => this.read(name));
179
+ const records = [];
180
+ for (const name of names) {
181
+ if (!isPluginTaskId(name))
182
+ continue;
183
+ try {
184
+ records.push(this.read(name));
185
+ }
186
+ catch (error) {
187
+ if (!allowMissing || error.code !== 'PLUGIN_TASK_NOT_FOUND')
188
+ throw error;
189
+ }
190
+ }
191
+ return records;
172
192
  }
173
193
  diagnosticRecords(taskId) {
174
194
  const records = [];
@@ -285,6 +305,7 @@ export class PluginTaskStore {
285
305
  }
286
306
  recover(epoch) {
287
307
  this.activeTaskIds = new Set();
308
+ const now = Date.now();
288
309
  for (const record of this.list()) {
289
310
  this.indexActive(record);
290
311
  const { task } = record;
@@ -297,9 +318,7 @@ export class PluginTaskStore {
297
318
  },
298
319
  });
299
320
  }
300
- else if (!isPluginTaskActive(task.state) &&
301
- Date.now() - task.updatedAt > RETENTION_MS &&
302
- !pluginTaskExecutionUnconfirmed(record)) {
321
+ else if (canPruneTask(record, now)) {
303
322
  rmSync(join(this.directory, task.taskId), { recursive: true, force: true });
304
323
  this.forgetDedupe(task.taskId);
305
324
  }
@@ -307,12 +326,9 @@ export class PluginTaskStore {
307
326
  }
308
327
  prune(now = Date.now()) {
309
328
  for (const record of this.list()) {
310
- const { task } = record;
311
- if (!isPluginTaskActive(task.state) &&
312
- now - task.updatedAt > RETENTION_MS &&
313
- !pluginTaskExecutionUnconfirmed(record)) {
314
- rmSync(join(this.directory, task.taskId), { recursive: true, force: true });
315
- this.forgetDedupe(task.taskId);
329
+ if (canPruneTask(record, now)) {
330
+ rmSync(join(this.directory, record.task.taskId), { recursive: true, force: true });
331
+ this.forgetDedupe(record.task.taskId);
316
332
  }
317
333
  }
318
334
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mearl/client",
3
- "version": "3.1.7",
3
+ "version": "3.1.8-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/cloud-types": "3.1.7",
73
- "@mearl/provider": "3.1.7",
74
- "@mearl/daemon-core": "3.1.7",
75
- "@mearl/agent-runtime": "3.1.7",
76
- "@mearl/browser-core": "3.1.7"
72
+ "@mearl/agent-runtime": "3.1.8-beta.0",
73
+ "@mearl/browser-core": "3.1.8-beta.0",
74
+ "@mearl/provider": "3.1.8-beta.0",
75
+ "@mearl/daemon-core": "3.1.8-beta.0",
76
+ "@mearl/cloud-types": "3.1.8-beta.0"
77
77
  },
78
78
  "devDependencies": {
79
79
  "@types/node": "^24.9.1",