@mebular/mcp 0.1.1 → 0.2.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.
@@ -0,0 +1,1074 @@
1
+ // 共享 Runtime 更新检查(Phase 5b1):固定来源、只读、无遥测。
2
+ //
3
+ // 范围:
4
+ // - 只查询官方 npm registry 的固定 stable 通道
5
+ // `https://registry.npmjs.org/@mebular/core/latest`;
6
+ // 不接受调用方传入 URL/registry/版本作为“源”。`fetchImpl` 只用于离线测试。
7
+ // - 只读 registry 元数据中的 `version`,不下载 tarball、不安装、不改 current/
8
+ // provider/service,也不启动/停止 daemon。
9
+ // - 状态/锁与 App/Plugin 两个入口共享:
10
+ // `<cloudRoot>/runtime/update-state.json`(原子写、0600、非敏感字段)
11
+ // `<cloudRoot>/runtime/update.lock`(wx + PID 存活 + 陈旧回收)
12
+ // - 24h TTL;失败有独立 TTL 防抖。失败不推进 `lastCheckedAt`,只写
13
+ // `lastAttemptAt/lastAttemptOk/failureReason`,避免把失败污染成“成功”。
14
+ //
15
+ // 稳定 JSON 语义:
16
+ // - `status`:本次调用层面发生了什么(update_available / up_to_date / skipped /
17
+ // current_missing / throttled / busy / offline / registry_unreachable /
18
+ // http_error / timeout / invalid_response / prerelease_ignored / lock_error /
19
+ // cloud_unavailable / unexpected_error)。
20
+ // - `decision`:版本比较结论(update_available / up_to_date / skipped /
21
+ // current_missing / unknown)。fresh 结果的 status 与 decision 相同;throttled
22
+ // 时 status 是 throttled,decision 是缓存比较结论。
23
+ // - `ok:true` 表示得到了可消费的答复(包含 no-update、throttled、busy、
24
+ // current_missing);`ok:false` 只用于 registry/传输/lock/上下文失败。
25
+ // CLI 因此对 `ok:true` 退出 0,对 `ok:false` 退出 2;启动检查应只读取 JSON,
26
+ // 不因退出码阻塞入口。
27
+ // - 失败时 `available:false`,避免离线/HTTP 失败触发更新提示;缓存的
28
+ // `latestVersion` 仅用于诊断。
29
+
30
+ import { randomUUID } from 'node:crypto';
31
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
32
+ import { homedir } from 'node:os';
33
+ import { join, resolve } from 'node:path';
34
+ import { cloudError, pidAlive, resolveCloudRoot } from './profiles.mjs';
35
+ import { readRuntimeCurrent } from './runtime-current.mjs';
36
+
37
+ export const RUNTIME_UPDATE_FILE = 'update-state.json';
38
+ export const RUNTIME_UPDATE_LOCK_FILE = 'update.lock';
39
+ export const RUNTIME_UPDATE_VERSION = 1;
40
+
41
+ export const RUNTIME_UPDATE_SOURCE_URL = 'https://registry.npmjs.org/@mebular/core/latest';
42
+ export const RUNTIME_UPDATE_SOURCE = Object.freeze({
43
+ kind: 'npm',
44
+ package: '@mebular/core',
45
+ channel: 'stable',
46
+ registry: 'https://registry.npmjs.org',
47
+ url: RUNTIME_UPDATE_SOURCE_URL,
48
+ });
49
+
50
+ export const RUNTIME_UPDATE_TTL_MS = 24 * 60 * 60 * 1000;
51
+ export const RUNTIME_UPDATE_FAILURE_TTL_MS = 5 * 60 * 1000;
52
+ export const RUNTIME_UPDATE_TIMEOUT_MS = 5000;
53
+ export const RUNTIME_UPDATE_LOCK_STALE_MS = 30 * 1000;
54
+ export const RUNTIME_UPDATE_LOCK_ATTEMPTS = 3;
55
+ export const RUNTIME_UPDATE_LOCK_RETRY_MS = 20;
56
+ export const RUNTIME_UPDATE_STATE_WRITE_WARNING = 'update_state_write_failed';
57
+
58
+ const MAX_VERSION_LENGTH = 128;
59
+ const NUMERIC_IDENTIFIER = '0|[1-9]\\d*';
60
+ const PRERELEASE_IDENTIFIER = `(?:${NUMERIC_IDENTIFIER}|\\d*[A-Za-z-][0-9A-Za-z-]*)`;
61
+ const SEMVER_PATTERN = new RegExp(
62
+ `^(${NUMERIC_IDENTIFIER})\\.(${NUMERIC_IDENTIFIER})\\.(${NUMERIC_IDENTIFIER})`
63
+ + `(?:-(${PRERELEASE_IDENTIFIER}(?:\\.${PRERELEASE_IDENTIFIER})*))?`
64
+ + `(?:\\+([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$`,
65
+ );
66
+ const REASON_RE = /^[a-z0-9][a-z0-9_.:-]{0,79}$/;
67
+
68
+ const FETCH_FAILURE_MESSAGES = Object.freeze({
69
+ offline: '无法连接 npm registry(离线);本次跳过更新检查',
70
+ registry_unreachable: 'npm registry 不可达;本次跳过更新检查',
71
+ http_error: 'npm registry 返回异常状态;本次跳过更新检查',
72
+ timeout: '更新检查超时;本次跳过更新检查',
73
+ invalid_response: 'npm registry 返回的版本信息无效;本次跳过更新检查',
74
+ prerelease_ignored: 'npm registry 的 latest 为非稳定版本;已忽略,不当作 stable 更新',
75
+ });
76
+
77
+ export function runtimeUpdateDir(root) {
78
+ return join(root, 'runtime');
79
+ }
80
+
81
+ export function runtimeUpdateStatePath(root) {
82
+ return join(root, 'runtime', RUNTIME_UPDATE_FILE);
83
+ }
84
+
85
+ export function runtimeUpdateLockPath(root) {
86
+ return join(root, 'runtime', RUNTIME_UPDATE_LOCK_FILE);
87
+ }
88
+
89
+ /** 宽松 semver 解析(支持 prerelease/build;数字部分保留字符串以避免大数精度问题)。 */
90
+ export function parseSemver(value) {
91
+ if (typeof value !== 'string') return null;
92
+ const text = value.trim();
93
+ if (text.length === 0 || text.length > MAX_VERSION_LENGTH) return null;
94
+ const match = SEMVER_PATTERN.exec(text);
95
+ if (!match) return null;
96
+ return {
97
+ raw: text,
98
+ major: match[1],
99
+ minor: match[2],
100
+ patch: match[3],
101
+ prerelease: match[4] ? match[4].split('.') : [],
102
+ build: match[5] ? match[5].split('.') : [],
103
+ };
104
+ }
105
+
106
+ function compareNumericIdentifiers(left, right) {
107
+ if (left.length !== right.length) return left.length < right.length ? -1 : 1;
108
+ if (left === right) return 0;
109
+ return left < right ? -1 : 1;
110
+ }
111
+
112
+ /**
113
+ * 严格 semver 优先级比较(忽略 build metadata;prerelease 按 semver §11 排序)。
114
+ * 非法输入抛 `unsupported_version`;调用方在读 current/latest 时已先校验。
115
+ */
116
+ export function compareSemver(left, right) {
117
+ const a = parseSemver(left);
118
+ const b = parseSemver(right);
119
+ if (!a || !b) {
120
+ throw cloudError('unsupported_version', `无法比较版本:${String(left)} / ${String(right)}`);
121
+ }
122
+ for (const key of ['major', 'minor', 'patch']) {
123
+ const compared = compareNumericIdentifiers(a[key], b[key]);
124
+ if (compared !== 0) return compared;
125
+ }
126
+ if (a.prerelease.length === 0 && b.prerelease.length === 0) return 0;
127
+ if (a.prerelease.length === 0) return 1;
128
+ if (b.prerelease.length === 0) return -1;
129
+
130
+ const length = Math.min(a.prerelease.length, b.prerelease.length);
131
+ for (let index = 0; index < length; index += 1) {
132
+ const leftId = a.prerelease[index];
133
+ const rightId = b.prerelease[index];
134
+ const leftNumeric = /^\d+$/.test(leftId);
135
+ const rightNumeric = /^\d+$/.test(rightId);
136
+ if (leftNumeric && rightNumeric) {
137
+ const compared = compareNumericIdentifiers(leftId, rightId);
138
+ if (compared !== 0) return compared;
139
+ continue;
140
+ }
141
+ if (leftNumeric) return -1;
142
+ if (rightNumeric) return 1;
143
+ if (leftId !== rightId) return leftId < rightId ? -1 : 1;
144
+ }
145
+ if (a.prerelease.length === b.prerelease.length) return 0;
146
+ return a.prerelease.length < b.prerelease.length ? -1 : 1;
147
+ }
148
+
149
+ /** stable 版本:合法 semver 且没有 prerelease 标识;build metadata 不影响稳定性。 */
150
+ export function isStableSemver(value) {
151
+ const parsed = parseSemver(value);
152
+ return parsed !== null && parsed.prerelease.length === 0;
153
+ }
154
+
155
+ function maybeVersion(value) {
156
+ const parsed = parseSemver(typeof value === 'string' ? value : '');
157
+ return parsed ? parsed.raw : null;
158
+ }
159
+
160
+ function assertStableVersion(value) {
161
+ const version = maybeVersion(value);
162
+ if (version === null || !isStableSemver(version)) {
163
+ throw cloudError('unsupported_version', `不是 stable semver:${String(value).slice(0, MAX_VERSION_LENGTH)}`);
164
+ }
165
+ return version;
166
+ }
167
+
168
+ function isIsoTime(value) {
169
+ return typeof value === 'string' && Number.isFinite(Date.parse(value));
170
+ }
171
+
172
+ function safeReason(value) {
173
+ return typeof value === 'string' && REASON_RE.test(value) ? value : null;
174
+ }
175
+
176
+ function clockDate(now) {
177
+ let value;
178
+ try {
179
+ value = typeof now === 'function' ? now() : now;
180
+ } catch {
181
+ value = null;
182
+ }
183
+ if (value instanceof Date && Number.isFinite(value.getTime())) return value;
184
+ if (typeof value === 'number' && Number.isFinite(value)) return new Date(value);
185
+ if (typeof value === 'string' && Number.isFinite(Date.parse(value))) return new Date(value);
186
+ return new Date();
187
+ }
188
+
189
+ function ageMs(iso, nowMs) {
190
+ if (!isIsoTime(iso)) return null;
191
+ return nowMs - Date.parse(iso);
192
+ }
193
+
194
+ function addIso(iso, ms) {
195
+ if (!isIsoTime(iso)) return null;
196
+ return new Date(Date.parse(iso) + ms).toISOString();
197
+ }
198
+
199
+ function delay(ms) {
200
+ return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
201
+ }
202
+
203
+ export function emptyRuntimeUpdateState() {
204
+ return {
205
+ v: RUNTIME_UPDATE_VERSION,
206
+ lastCheckedAt: null,
207
+ lastAttemptAt: null,
208
+ lastAttemptOk: null,
209
+ latest: null,
210
+ current: null,
211
+ runningVersion: null,
212
+ available: false,
213
+ skippedVersion: null,
214
+ promptedVersion: null,
215
+ promptedAt: null,
216
+ reason: null,
217
+ failureReason: null,
218
+ source: RUNTIME_UPDATE_SOURCE_URL,
219
+ updatedAt: null,
220
+ };
221
+ }
222
+
223
+ /**
224
+ * 结构规范化(只保留白名单字段,避免 state 变成秘密/任意字段仓库)。
225
+ * 读取时任何非法字段会让整份 state 回退为空;写入时严格抛错。
226
+ */
227
+ export function normalizeRuntimeUpdateState(input, { now = new Date().toISOString() } = {}) {
228
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
229
+ throw cloudError('RUNTIME_UPDATE_STATE_INVALID', 'update-state 必须是对象');
230
+ }
231
+ if (input.v !== undefined && input.v !== RUNTIME_UPDATE_VERSION) {
232
+ throw cloudError('RUNTIME_UPDATE_STATE_INVALID', `update-state 版本必须是 v${RUNTIME_UPDATE_VERSION}`);
233
+ }
234
+ const timeField = (name) => {
235
+ const value = input[name];
236
+ if (value === undefined || value === null) return null;
237
+ if (!isIsoTime(value)) {
238
+ throw cloudError('RUNTIME_UPDATE_STATE_INVALID', `update-state.${name} 必须是 ISO 时间或 null`);
239
+ }
240
+ return value;
241
+ };
242
+ const versionField = (name, { stable = false } = {}) => {
243
+ const value = input[name];
244
+ if (value === undefined || value === null) return null;
245
+ const version = maybeVersion(value);
246
+ if (version === null || (stable && !isStableSemver(version))) {
247
+ throw cloudError('RUNTIME_UPDATE_STATE_INVALID', `update-state.${name} 不是合法版本`);
248
+ }
249
+ return version;
250
+ };
251
+ if (input.lastAttemptOk !== undefined && input.lastAttemptOk !== null && typeof input.lastAttemptOk !== 'boolean') {
252
+ throw cloudError('RUNTIME_UPDATE_STATE_INVALID', 'update-state.lastAttemptOk 必须是布尔或 null');
253
+ }
254
+ if (input.available !== undefined && typeof input.available !== 'boolean') {
255
+ throw cloudError('RUNTIME_UPDATE_STATE_INVALID', 'update-state.available 必须是布尔');
256
+ }
257
+ return {
258
+ v: RUNTIME_UPDATE_VERSION,
259
+ lastCheckedAt: timeField('lastCheckedAt'),
260
+ lastAttemptAt: timeField('lastAttemptAt'),
261
+ lastAttemptOk: typeof input.lastAttemptOk === 'boolean' ? input.lastAttemptOk : null,
262
+ latest: versionField('latest', { stable: true }),
263
+ current: versionField('current'),
264
+ runningVersion: versionField('runningVersion'),
265
+ available: input.available === true,
266
+ skippedVersion: versionField('skippedVersion', { stable: true }),
267
+ promptedVersion: versionField('promptedVersion', { stable: true }),
268
+ promptedAt: timeField('promptedAt'),
269
+ reason: safeReason(input.reason),
270
+ failureReason: safeReason(input.failureReason),
271
+ // 来源始终归一为固定官方 URL;文件里出现别的来源也不采用。
272
+ source: RUNTIME_UPDATE_SOURCE_URL,
273
+ updatedAt: isIsoTime(input.updatedAt) ? input.updatedAt : now,
274
+ };
275
+ }
276
+
277
+ async function readJsonFile(path) {
278
+ try {
279
+ return { ok: true, value: JSON.parse(await readFile(path, 'utf-8')) };
280
+ } catch (error) {
281
+ return { ok: false, missing: error?.code === 'ENOENT', error };
282
+ }
283
+ }
284
+
285
+ /** 读取 state(永不抛错):missing/invalid 都回退为空 + warning,不阻塞入口。 */
286
+ export async function readRuntimeUpdateState(root) {
287
+ const base = {
288
+ state: emptyRuntimeUpdateState(),
289
+ source: 'missing',
290
+ warnings: [],
291
+ path: null,
292
+ };
293
+ if (typeof root !== 'string' || root.length === 0) {
294
+ return { ...base, source: 'unavailable', warnings: ['cloudRoot 不可用'] };
295
+ }
296
+ const path = runtimeUpdateStatePath(root);
297
+ const raw = await readJsonFile(path);
298
+ if (!raw.ok) {
299
+ if (raw.missing) return { ...base, path };
300
+ return {
301
+ ...base,
302
+ source: 'invalid',
303
+ path,
304
+ warnings: [`update-state 无法解析:${raw.error?.code ?? raw.error?.message ?? raw.error}`],
305
+ };
306
+ }
307
+ try {
308
+ return {
309
+ state: normalizeRuntimeUpdateState(raw.value),
310
+ source: 'main',
311
+ warnings: [],
312
+ path,
313
+ };
314
+ } catch (error) {
315
+ return {
316
+ ...base,
317
+ source: 'invalid',
318
+ path,
319
+ warnings: [`update-state 无效:${error?.message ?? error}`],
320
+ };
321
+ }
322
+ }
323
+
324
+ /** 原子写 state:tmp → rename,0600;失败只抛给调用方,由 check 转成 warning。 */
325
+ export async function writeRuntimeUpdateState(root, input, { now = new Date().toISOString() } = {}) {
326
+ if (typeof root !== 'string' || root.length === 0) {
327
+ throw cloudError('CLOUD_UNAVAILABLE', '缺少 cloudRoot,无法写 update-state');
328
+ }
329
+ const state = normalizeRuntimeUpdateState({
330
+ ...input,
331
+ v: input?.v ?? RUNTIME_UPDATE_VERSION,
332
+ source: RUNTIME_UPDATE_SOURCE_URL,
333
+ updatedAt: input?.updatedAt ?? now,
334
+ }, { now });
335
+ const dir = runtimeUpdateDir(root);
336
+ await mkdir(dir, { recursive: true, mode: 0o700 });
337
+ const path = runtimeUpdateStatePath(root);
338
+ const tmp = `${path}.tmp-${process.pid}-${randomUUID()}`;
339
+ try {
340
+ await writeFile(tmp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
341
+ await chmod(tmp, 0o600).catch(() => undefined);
342
+ await rename(tmp, path);
343
+ await chmod(path, 0o600).catch(() => undefined);
344
+ } catch (error) {
345
+ await rm(tmp, { force: true }).catch(() => undefined);
346
+ throw error;
347
+ }
348
+ return state;
349
+ }
350
+
351
+ /** 只读公开摘要(所有字段本身即非敏感;保留旧 state 兼容)。 */
352
+ export function publicRuntimeUpdateState(state) {
353
+ if (!state || typeof state !== 'object') return emptyRuntimeUpdateState();
354
+ return {
355
+ v: state.v ?? RUNTIME_UPDATE_VERSION,
356
+ lastCheckedAt: state.lastCheckedAt ?? null,
357
+ lastAttemptAt: state.lastAttemptAt ?? null,
358
+ lastAttemptOk: state.lastAttemptOk ?? null,
359
+ latest: state.latest ?? null,
360
+ current: state.current ?? null,
361
+ runningVersion: state.runningVersion ?? null,
362
+ available: state.available === true,
363
+ skippedVersion: state.skippedVersion ?? null,
364
+ promptedVersion: state.promptedVersion ?? null,
365
+ promptedAt: state.promptedAt ?? null,
366
+ reason: state.reason ?? null,
367
+ failureReason: state.failureReason ?? null,
368
+ source: RUNTIME_UPDATE_SOURCE_URL,
369
+ updatedAt: state.updatedAt ?? null,
370
+ };
371
+ }
372
+
373
+ async function readLock(path) {
374
+ try {
375
+ return JSON.parse(await readFile(path, 'utf-8'));
376
+ } catch {
377
+ return null;
378
+ }
379
+ }
380
+
381
+ /**
382
+ * 跨入口检查互斥:wx 创建;持有者 PID 存活且未超时才 busy。
383
+ * 有界重试(默认 3 次 × 20ms),绝不无限等待;陈旧/损坏锁直接回收。
384
+ */
385
+ export async function acquireRuntimeUpdateLock(root, options = {}) {
386
+ const {
387
+ now = () => new Date(),
388
+ pidAliveFn = pidAlive,
389
+ staleMs = RUNTIME_UPDATE_LOCK_STALE_MS,
390
+ attempts = RUNTIME_UPDATE_LOCK_ATTEMPTS,
391
+ retryMs = RUNTIME_UPDATE_LOCK_RETRY_MS,
392
+ token = randomUUID(),
393
+ } = options;
394
+ if (typeof root !== 'string' || root.length === 0) {
395
+ return { ok: false, reason: 'lock_error', message: '缺少 cloudRoot,无法获取 update.lock', holder: null };
396
+ }
397
+ const path = runtimeUpdateLockPath(root);
398
+ const nowMs = () => clockDate(now).getTime();
399
+ try {
400
+ await mkdir(runtimeUpdateDir(root), { recursive: true, mode: 0o700 });
401
+ } catch (error) {
402
+ return {
403
+ ok: false,
404
+ reason: 'lock_error',
405
+ message: `无法创建 runtime 目录:${error?.code ?? error?.message ?? error}`,
406
+ holder: null,
407
+ };
408
+ }
409
+
410
+ let staleRecovered = false;
411
+ let holder = null;
412
+ for (let attempt = 0; attempt < Math.max(1, attempts); attempt += 1) {
413
+ const startedAt = new Date(nowMs()).toISOString();
414
+ const payload = {
415
+ v: 1,
416
+ pid: process.pid,
417
+ token,
418
+ startedAt,
419
+ command: 'check-update',
420
+ };
421
+ try {
422
+ await writeFile(path, `${JSON.stringify(payload)}\n`, { mode: 0o600, flag: 'wx' });
423
+ return {
424
+ ok: true,
425
+ path,
426
+ token,
427
+ pid: process.pid,
428
+ startedAt,
429
+ staleRecovered,
430
+ holder: null,
431
+ release: async () => {
432
+ try {
433
+ const held = await readLock(path);
434
+ if (!held || held.token !== token) return false;
435
+ await rm(path, { force: true });
436
+ return true;
437
+ } catch {
438
+ return false;
439
+ }
440
+ },
441
+ };
442
+ } catch (error) {
443
+ if (error?.code !== 'EEXIST') {
444
+ return {
445
+ ok: false,
446
+ reason: 'lock_error',
447
+ message: `无法创建 update.lock:${error?.code ?? error?.message ?? error}`,
448
+ holder: null,
449
+ };
450
+ }
451
+ }
452
+
453
+ const held = await readLock(path);
454
+ const holderPid = Number(held?.pid);
455
+ const heldAt = Date.parse(held?.startedAt ?? '');
456
+ const holderAge = Number.isFinite(heldAt) ? Math.max(0, nowMs() - heldAt) : null;
457
+ const alive = Number.isInteger(holderPid) && holderPid > 0
458
+ ? pidAliveFn(holderPid) !== false
459
+ : false;
460
+ holder = {
461
+ pid: Number.isInteger(holderPid) && holderPid > 0 ? holderPid : null,
462
+ startedAt: isIsoTime(held?.startedAt) ? held.startedAt : null,
463
+ ageMs: holderAge,
464
+ };
465
+ const stale = holder.pid === null
466
+ || !alive
467
+ || (holderAge !== null && holderAge > staleMs);
468
+ if (stale) {
469
+ await rm(path, { force: true }).catch(() => undefined);
470
+ staleRecovered = true;
471
+ continue;
472
+ }
473
+ if (attempt < Math.max(1, attempts) - 1) {
474
+ await delay(retryMs);
475
+ continue;
476
+ }
477
+ }
478
+
479
+ return {
480
+ ok: false,
481
+ reason: 'busy',
482
+ path,
483
+ holder,
484
+ staleRecovered,
485
+ message: holder?.pid
486
+ ? `另一个入口正在检查 runtime 更新(pid ${holder.pid});本次不重复请求`
487
+ : '另一个入口正在检查 runtime 更新;本次不重复请求',
488
+ };
489
+ }
490
+
491
+ /** 5b2 的「跳过此版本」入口:只写 skippedVersion,不触发网络检查。 */
492
+ export async function setRuntimeUpdateSkippedVersion(root, version, { now = new Date().toISOString() } = {}) {
493
+ if (typeof root !== 'string' || root.length === 0) {
494
+ throw cloudError('CLOUD_UNAVAILABLE', '缺少 cloudRoot,无法写 update-state');
495
+ }
496
+ const skippedVersion = version === null || version === undefined ? null : assertStableVersion(version);
497
+ const current = await readRuntimeUpdateState(root);
498
+ // 跳过当前 latest 时同步把 available 置 false,让直接读 state 的另一入口也不会再提示;
499
+ // 取消跳过(null)不动 available,交给下一次 check 重新计算。
500
+ const skippingLatest = skippedVersion !== null
501
+ && current.state.latest !== null
502
+ && compareSemver(skippedVersion, current.state.latest) === 0;
503
+ const state = await writeRuntimeUpdateState(root, {
504
+ ...current.state,
505
+ skippedVersion,
506
+ // 「跳过」本身也是用户已看过该版本提示的显式动作;另一入口不应再自动弹同一版本。
507
+ ...(skippedVersion === null
508
+ ? {}
509
+ : { promptedVersion: skippedVersion, promptedAt: now }),
510
+ ...(skippingLatest ? { available: false, reason: 'skipped' } : {}),
511
+ updatedAt: now,
512
+ }, { now });
513
+ return { state, source: current.source, warnings: current.warnings, path: runtimeUpdateStatePath(root) };
514
+ }
515
+
516
+ /**
517
+ * 跨入口已提示去重:记录最近一次真正展示过更新提示的 latestVersion。
518
+ * 只写非敏感版本/时间;不改变 available/skippedVersion,也不触发检查/安装。
519
+ * 传 null 清除;损坏 state 在读取时已回退为空,写入原子覆盖。
520
+ */
521
+ export async function setRuntimeUpdatePromptedVersion(root, version, { now = new Date().toISOString() } = {}) {
522
+ if (typeof root !== 'string' || root.length === 0) {
523
+ throw cloudError('CLOUD_UNAVAILABLE', '缺少 cloudRoot,无法写 update-state');
524
+ }
525
+ const promptedVersion = version === null || version === undefined ? null : assertStableVersion(version);
526
+ const current = await readRuntimeUpdateState(root);
527
+ const state = await writeRuntimeUpdateState(root, {
528
+ ...current.state,
529
+ promptedVersion,
530
+ promptedAt: promptedVersion === null ? null : now,
531
+ updatedAt: now,
532
+ }, { now });
533
+ return { state, source: current.source, warnings: current.warnings, path: runtimeUpdateStatePath(root) };
534
+ }
535
+
536
+ function mapFetchError(error, signal) {
537
+ if (signal?.aborted === true || error?.name === 'AbortError' || error?.name === 'TimeoutError') {
538
+ return 'timeout';
539
+ }
540
+ const code = error?.cause?.code ?? error?.code ?? '';
541
+ if (['ENOTFOUND', 'EAI_AGAIN', 'ENETUNREACH', 'EHOSTUNREACH'].includes(code)) return 'offline';
542
+ if ([
543
+ 'ECONNREFUSED',
544
+ 'ECONNRESET',
545
+ 'ETIMEDOUT',
546
+ 'UND_ERR_CONNECT_TIMEOUT',
547
+ 'UND_ERR_HEADERS_TIMEOUT',
548
+ 'UND_ERR_BODY_TIMEOUT',
549
+ 'UND_ERR_SOCKET',
550
+ ].includes(code)) {
551
+ return 'registry_unreachable';
552
+ }
553
+ return 'registry_unreachable';
554
+ }
555
+
556
+ /**
557
+ * 固定 URL 的只读查询。返回 `{ok, reason, version?, httpStatus?}`,永不抛错。
558
+ * 版本必须是 stable semver;prerelease 显式标记为 `prerelease_ignored`。
559
+ */
560
+ async function fetchLatestRuntimeVersion({ fetchImpl, timeoutMs }) {
561
+ if (typeof fetchImpl !== 'function') {
562
+ return { ok: false, reason: 'registry_unreachable', httpStatus: null };
563
+ }
564
+ const controller = new AbortController();
565
+ const timer = setTimeout(() => controller.abort(), Math.max(1, timeoutMs));
566
+ timer.unref?.();
567
+ try {
568
+ let response;
569
+ try {
570
+ response = await fetchImpl(RUNTIME_UPDATE_SOURCE_URL, {
571
+ method: 'GET',
572
+ redirect: 'error',
573
+ headers: { accept: 'application/json' },
574
+ signal: controller.signal,
575
+ });
576
+ } catch (error) {
577
+ return { ok: false, reason: mapFetchError(error, controller.signal), httpStatus: null };
578
+ }
579
+ const status = Number(response?.status);
580
+ if (!response || response.ok !== true) {
581
+ return {
582
+ ok: false,
583
+ reason: 'http_error',
584
+ httpStatus: Number.isInteger(status) && status > 0 ? status : null,
585
+ };
586
+ }
587
+ let body;
588
+ try {
589
+ body = typeof response.json === 'function' ? await response.json() : null;
590
+ } catch {
591
+ if (controller.signal.aborted) {
592
+ return { ok: false, reason: 'timeout', httpStatus: status || null };
593
+ }
594
+ return { ok: false, reason: 'invalid_response', httpStatus: status || null };
595
+ }
596
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
597
+ return { ok: false, reason: 'invalid_response', httpStatus: status || null };
598
+ }
599
+ if (body.name !== undefined && body.name !== RUNTIME_UPDATE_SOURCE.package) {
600
+ return { ok: false, reason: 'invalid_response', httpStatus: status || null };
601
+ }
602
+ const version = typeof body.version === 'string' ? body.version.trim() : '';
603
+ const parsed = parseSemver(version);
604
+ if (!parsed) {
605
+ return { ok: false, reason: 'invalid_response', httpStatus: status || null };
606
+ }
607
+ if (parsed.prerelease.length > 0) {
608
+ return { ok: false, reason: 'prerelease_ignored', httpStatus: status || null };
609
+ }
610
+ return { ok: true, reason: null, version: parsed.raw, httpStatus: status || null };
611
+ } finally {
612
+ clearTimeout(timer);
613
+ }
614
+ }
615
+
616
+ function decide(latest, currentVersion, skippedVersion) {
617
+ if (!currentVersion) {
618
+ return { decision: 'current_missing', available: false, skipped: false };
619
+ }
620
+ if (!latest) {
621
+ return { decision: 'unknown', available: false, skipped: false };
622
+ }
623
+ if (skippedVersion !== null && compareSemver(skippedVersion, latest) === 0) {
624
+ return { decision: 'skipped', available: false, skipped: true };
625
+ }
626
+ if (compareSemver(latest, currentVersion) > 0) {
627
+ return { decision: 'update_available', available: true, skipped: false };
628
+ }
629
+ return { decision: 'up_to_date', available: false, skipped: false };
630
+ }
631
+
632
+ function messageForDecision(decision, latest, currentVersion) {
633
+ if (decision === 'update_available') return `发现共享 runtime 新版本 ${latest}(当前 ${currentVersion});仅提示,不自动安装`;
634
+ if (decision === 'skipped') return `版本 ${latest} 已被用户跳过`;
635
+ if (decision === 'current_missing') return '未找到 runtime/current.json,无法判断更新;不会自动升级';
636
+ return '共享 runtime 已是最新(stable 通道)';
637
+ }
638
+
639
+ /**
640
+ * 检查共享 runtime 更新。
641
+ *
642
+ * 选项均为内部/测试注入,其中 `fetchImpl` 不是“源”覆盖:请求 URL 固定为
643
+ * `RUNTIME_UPDATE_SOURCE_URL`。任何 `url/registry/source` 选项都会被忽略。
644
+ *
645
+ * 返回稳定 JSON;不抛错、不安装、不下载、不动 daemon/current/provider/service。
646
+ */
647
+ export async function checkRuntimeUpdate(options = {}) {
648
+ const {
649
+ root: explicitRoot,
650
+ env = process.env,
651
+ userHome = homedir(),
652
+ force = false,
653
+ skipVersion: skipOption,
654
+ ttlMs = RUNTIME_UPDATE_TTL_MS,
655
+ failureTtlMs = RUNTIME_UPDATE_FAILURE_TTL_MS,
656
+ timeoutMs = RUNTIME_UPDATE_TIMEOUT_MS,
657
+ fetchImpl = globalThis.fetch,
658
+ now = () => new Date(),
659
+ pidAliveFn = pidAlive,
660
+ lockStaleMs = RUNTIME_UPDATE_LOCK_STALE_MS,
661
+ lockAttempts = RUNTIME_UPDATE_LOCK_ATTEMPTS,
662
+ lockRetryMs = RUNTIME_UPDATE_LOCK_RETRY_MS,
663
+ runningVersion: runningOption,
664
+ detectRunningVersion = null,
665
+ writeStateFn = writeRuntimeUpdateState,
666
+ entry = null,
667
+ } = options;
668
+
669
+ const clock = () => clockDate(now);
670
+ const startedAt = clock().toISOString();
671
+
672
+ let root = explicitRoot;
673
+ let context = null;
674
+ if (typeof root !== 'string' || root.length === 0) {
675
+ context = resolveCloudRoot({ env, userHome });
676
+ if (!context.available) {
677
+ return {
678
+ ok: false,
679
+ action: 'check-update',
680
+ command: 'check-update',
681
+ status: 'cloud_unavailable',
682
+ reason: 'cloud_unavailable',
683
+ message: `runtime 上下文不可用(${context.reason ?? 'cloud_unavailable'})`,
684
+ cloudReason: context.reason ?? 'cloud_unavailable',
685
+ available: false,
686
+ skipped: false,
687
+ decision: null,
688
+ cached: false,
689
+ stale: true,
690
+ throttled: false,
691
+ busy: false,
692
+ force: force === true,
693
+ entry: typeof entry === 'string' ? entry : null,
694
+ root: context.root ?? null,
695
+ cloudRoot: context.root ?? null,
696
+ source: RUNTIME_UPDATE_SOURCE,
697
+ currentVersion: null,
698
+ runningVersion: maybeVersion(runningOption),
699
+ latestVersion: null,
700
+ skippedVersion: null,
701
+ currentSource: 'unavailable',
702
+ currentUsable: false,
703
+ lastCheckedAt: null,
704
+ lastAttemptAt: null,
705
+ lastAttemptOk: null,
706
+ nextCheckAt: null,
707
+ httpStatus: null,
708
+ failureReason: null,
709
+ lock: null,
710
+ warnings: [],
711
+ checkedAt: startedAt,
712
+ };
713
+ }
714
+ root = context.root;
715
+ }
716
+ root = resolve(root);
717
+
718
+ const currentState = await readRuntimeCurrent(root, { userHome });
719
+ const stateRead = await readRuntimeUpdateState(root);
720
+ const stored = stateRead.state;
721
+ const warnings = [...stateRead.warnings, ...currentState.warnings];
722
+ const currentVersion = currentState.current?.version ?? null;
723
+ const explicitRunning = maybeVersion(runningOption);
724
+ const skippedVersion = skipOption !== undefined
725
+ ? maybeVersion(skipOption)
726
+ : stored.skippedVersion;
727
+
728
+ const makeResult = (fields = {}) => {
729
+ const status = fields.status ?? null;
730
+ const decision = fields.decision !== undefined ? fields.decision : status;
731
+ const currentVersionValue = fields.currentVersion !== undefined ? fields.currentVersion : currentVersion;
732
+ const currentSourceValue = fields.currentSource !== undefined ? fields.currentSource : currentState.source;
733
+ const currentUsableValue = fields.currentUsable !== undefined ? fields.currentUsable : currentState.usable === true;
734
+ const extraWarnings = Array.isArray(fields.warnings) ? fields.warnings : [];
735
+ const latestVersionValue = fields.latestVersion !== undefined ? fields.latestVersion : null;
736
+ const promptedVersionValue = fields.promptedVersion !== undefined
737
+ ? fields.promptedVersion
738
+ : stored.promptedVersion;
739
+ const promptedValue = fields.prompted !== undefined
740
+ ? fields.prompted === true
741
+ : (latestVersionValue !== null && promptedVersionValue === latestVersionValue);
742
+ return {
743
+ ok: fields.ok !== undefined ? fields.ok === true : true,
744
+ action: 'check-update',
745
+ command: 'check-update',
746
+ status,
747
+ reason: fields.reason ?? null,
748
+ message: fields.message ?? null,
749
+ available: fields.available === true,
750
+ skipped: fields.skipped === true,
751
+ prompted: promptedValue,
752
+ decision,
753
+ cached: fields.cached === true,
754
+ stale: fields.stale === true,
755
+ throttled: status === 'throttled',
756
+ busy: status === 'busy',
757
+ force: force === true,
758
+ entry: typeof entry === 'string' ? entry : null,
759
+ root,
760
+ cloudRoot: root,
761
+ source: RUNTIME_UPDATE_SOURCE,
762
+ currentVersion: currentVersionValue,
763
+ runningVersion: fields.runningVersion !== undefined
764
+ ? fields.runningVersion
765
+ : (explicitRunning ?? stored.runningVersion),
766
+ latestVersion: latestVersionValue,
767
+ skippedVersion: fields.skippedVersion !== undefined ? fields.skippedVersion : skippedVersion,
768
+ promptedVersion: promptedVersionValue,
769
+ promptedAt: fields.promptedAt !== undefined ? fields.promptedAt : stored.promptedAt,
770
+ currentSource: currentSourceValue,
771
+ currentUsable: currentUsableValue,
772
+ lastCheckedAt: fields.lastCheckedAt !== undefined ? fields.lastCheckedAt : stored.lastCheckedAt,
773
+ lastAttemptAt: fields.lastAttemptAt !== undefined ? fields.lastAttemptAt : stored.lastAttemptAt,
774
+ lastAttemptOk: fields.lastAttemptOk !== undefined ? fields.lastAttemptOk : stored.lastAttemptOk,
775
+ nextCheckAt: fields.nextCheckAt !== undefined ? fields.nextCheckAt : null,
776
+ httpStatus: fields.httpStatus ?? null,
777
+ failureReason: fields.failureReason ?? null,
778
+ lock: fields.lock ?? null,
779
+ warnings: extraWarnings.length > 0 ? [...warnings, ...extraWarnings] : [...warnings],
780
+ checkedAt: clock().toISOString(),
781
+ };
782
+ };
783
+
784
+ const persist = async (state, at) => {
785
+ try {
786
+ await writeStateFn(root, state, { now: at });
787
+ return null;
788
+ } catch {
789
+ return RUNTIME_UPDATE_STATE_WRITE_WARNING;
790
+ }
791
+ };
792
+
793
+ const cachedResult = (state, { reason, stale, runningVersion }) => {
794
+ const comparison = decide(state.latest, currentVersion, skippedVersion);
795
+ return makeResult({
796
+ status: 'throttled',
797
+ reason,
798
+ decision: comparison.decision,
799
+ available: reason === null && comparison.available,
800
+ skipped: comparison.skipped,
801
+ cached: true,
802
+ stale,
803
+ currentVersion,
804
+ currentSource: currentState.source,
805
+ currentUsable: currentState.usable === true,
806
+ runningVersion,
807
+ latestVersion: state.latest,
808
+ skippedVersion,
809
+ lastCheckedAt: state.lastCheckedAt,
810
+ lastAttemptAt: state.lastAttemptAt,
811
+ lastAttemptOk: state.lastAttemptOk,
812
+ nextCheckAt: addIso(state.lastCheckedAt, ttlMs),
813
+ failureReason: state.failureReason,
814
+ message: reason === 'failure_backoff'
815
+ ? `更新检查处于失败防抖(${state.failureReason ?? 'unknown'});本次不重复请求`
816
+ : messageForDecision(comparison.decision, state.latest, currentVersion),
817
+ });
818
+ };
819
+
820
+ const nowMs = clock().getTime();
821
+ const successAge = ageMs(stored.lastCheckedAt, nowMs);
822
+ const attemptAge = ageMs(stored.lastAttemptAt, nowMs);
823
+ const successFresh = successAge !== null && successAge < ttlMs;
824
+ const failureBackoff = !force
825
+ && stored.lastAttemptOk === false
826
+ && attemptAge !== null
827
+ && attemptAge < failureTtlMs;
828
+
829
+ if (!force) {
830
+ if (failureBackoff) {
831
+ return makeResult({
832
+ status: 'throttled',
833
+ reason: 'failure_backoff',
834
+ decision: null,
835
+ available: false,
836
+ cached: true,
837
+ stale: true,
838
+ latestVersion: stored.latest,
839
+ runningVersion: explicitRunning ?? stored.runningVersion,
840
+ lastCheckedAt: stored.lastCheckedAt,
841
+ lastAttemptAt: stored.lastAttemptAt,
842
+ lastAttemptOk: false,
843
+ failureReason: stored.failureReason,
844
+ nextCheckAt: addIso(stored.lastAttemptAt, failureTtlMs),
845
+ message: `更新检查处于失败防抖(${stored.failureReason ?? 'unknown'});本次不重复请求`,
846
+ });
847
+ }
848
+ if (successFresh) {
849
+ return cachedResult(stored, {
850
+ reason: null,
851
+ stale: false,
852
+ runningVersion: explicitRunning ?? stored.runningVersion,
853
+ });
854
+ }
855
+ }
856
+
857
+ const lock = await acquireRuntimeUpdateLock(root, {
858
+ now,
859
+ pidAliveFn,
860
+ staleMs: lockStaleMs,
861
+ attempts: lockAttempts,
862
+ retryMs: lockRetryMs,
863
+ });
864
+ if (!lock.ok && lock.reason === 'busy') {
865
+ return makeResult({
866
+ status: 'busy',
867
+ reason: 'busy',
868
+ decision: null,
869
+ available: false,
870
+ cached: stored.lastCheckedAt !== null,
871
+ stale: !successFresh,
872
+ latestVersion: stored.latest,
873
+ runningVersion: explicitRunning ?? stored.runningVersion,
874
+ lastCheckedAt: stored.lastCheckedAt,
875
+ lastAttemptAt: stored.lastAttemptAt,
876
+ lastAttemptOk: stored.lastAttemptOk,
877
+ failureReason: stored.failureReason,
878
+ lock: lock.holder ?? null,
879
+ nextCheckAt: addIso(stored.lastAttemptAt, failureTtlMs),
880
+ message: lock.message ?? '另一个入口正在检查 runtime 更新;本次不重复请求',
881
+ });
882
+ }
883
+ if (!lock.ok) {
884
+ return makeResult({
885
+ ok: false,
886
+ status: 'lock_error',
887
+ reason: 'lock_error',
888
+ decision: null,
889
+ cached: false,
890
+ stale: true,
891
+ latestVersion: stored.latest,
892
+ runningVersion: explicitRunning ?? stored.runningVersion,
893
+ failureReason: 'lock_error',
894
+ warnings: ['update_lock_unavailable'],
895
+ message: lock.message ?? '无法获取 update.lock',
896
+ });
897
+ }
898
+
899
+ try {
900
+ // 拿到锁后重读:另一个入口可能刚完成检查并写入了新 state/current。
901
+ const [lockedState, lockedCurrent] = await Promise.all([
902
+ readRuntimeUpdateState(root),
903
+ readRuntimeCurrent(root, { userHome }),
904
+ ]);
905
+ const currentNow = lockedCurrent.current?.version ?? null;
906
+ if (!force) {
907
+ const lockedNowMs = clock().getTime();
908
+ const lockedAttemptAge = ageMs(lockedState.state.lastAttemptAt, lockedNowMs);
909
+ if (lockedState.state.lastAttemptOk === false
910
+ && lockedAttemptAge !== null
911
+ && lockedAttemptAge < failureTtlMs) {
912
+ return makeResult({
913
+ status: 'throttled',
914
+ reason: 'failure_backoff',
915
+ decision: null,
916
+ available: false,
917
+ cached: true,
918
+ stale: true,
919
+ currentVersion: currentNow,
920
+ currentSource: lockedCurrent.source,
921
+ currentUsable: lockedCurrent.usable === true,
922
+ latestVersion: lockedState.state.latest,
923
+ runningVersion: explicitRunning ?? lockedState.state.runningVersion,
924
+ lastCheckedAt: lockedState.state.lastCheckedAt,
925
+ lastAttemptAt: lockedState.state.lastAttemptAt,
926
+ lastAttemptOk: false,
927
+ failureReason: lockedState.state.failureReason,
928
+ nextCheckAt: addIso(lockedState.state.lastAttemptAt, failureTtlMs),
929
+ message: `更新检查处于失败防抖(${lockedState.state.failureReason ?? 'unknown'});本次不重复请求`,
930
+ });
931
+ }
932
+ const lockedSuccessAge = ageMs(lockedState.state.lastCheckedAt, lockedNowMs);
933
+ if (lockedSuccessAge !== null && lockedSuccessAge < ttlMs) {
934
+ const comparison = decide(lockedState.state.latest, currentNow, skippedVersion);
935
+ return makeResult({
936
+ status: 'throttled',
937
+ reason: null,
938
+ decision: comparison.decision,
939
+ available: comparison.available,
940
+ skipped: comparison.skipped,
941
+ cached: true,
942
+ stale: false,
943
+ currentVersion: currentNow,
944
+ currentSource: lockedCurrent.source,
945
+ currentUsable: lockedCurrent.usable === true,
946
+ latestVersion: lockedState.state.latest,
947
+ runningVersion: explicitRunning ?? lockedState.state.runningVersion,
948
+ lastCheckedAt: lockedState.state.lastCheckedAt,
949
+ lastAttemptAt: lockedState.state.lastAttemptAt,
950
+ lastAttemptOk: lockedState.state.lastAttemptOk,
951
+ nextCheckAt: addIso(lockedState.state.lastCheckedAt, ttlMs),
952
+ message: messageForDecision(comparison.decision, lockedState.state.latest, currentNow),
953
+ });
954
+ }
955
+ }
956
+
957
+ let detectedRunning = null;
958
+ if (explicitRunning === null && typeof detectRunningVersion === 'function') {
959
+ try {
960
+ detectedRunning = maybeVersion(await detectRunningVersion({ root, env, userHome }));
961
+ } catch {
962
+ detectedRunning = null;
963
+ }
964
+ }
965
+ const runningVersion = explicitRunning ?? detectedRunning ?? lockedState.state.runningVersion ?? null;
966
+
967
+ const fetched = await fetchLatestRuntimeVersion({ fetchImpl, timeoutMs });
968
+ const attemptAt = clock().toISOString();
969
+
970
+ if (!fetched.ok) {
971
+ const failureReason = fetched.reason;
972
+ const stateWriteWarning = await persist({
973
+ ...lockedState.state,
974
+ lastAttemptAt: attemptAt,
975
+ lastAttemptOk: false,
976
+ failureReason,
977
+ reason: failureReason,
978
+ current: currentNow,
979
+ runningVersion,
980
+ updatedAt: attemptAt,
981
+ }, attemptAt);
982
+ return makeResult({
983
+ ok: false,
984
+ status: failureReason,
985
+ reason: failureReason,
986
+ decision: null,
987
+ available: false,
988
+ cached: false,
989
+ stale: true,
990
+ currentVersion: currentNow,
991
+ currentSource: lockedCurrent.source,
992
+ currentUsable: lockedCurrent.usable === true,
993
+ latestVersion: lockedState.state.latest,
994
+ runningVersion,
995
+ lastCheckedAt: lockedState.state.lastCheckedAt,
996
+ lastAttemptAt: attemptAt,
997
+ lastAttemptOk: false,
998
+ failureReason,
999
+ httpStatus: fetched.httpStatus ?? null,
1000
+ nextCheckAt: addIso(attemptAt, failureTtlMs),
1001
+ warnings: stateWriteWarning ? [stateWriteWarning] : [],
1002
+ message: FETCH_FAILURE_MESSAGES[failureReason] ?? '更新检查失败;本次跳过',
1003
+ });
1004
+ }
1005
+
1006
+ const latest = fetched.version;
1007
+ const comparison = decide(latest, currentNow, skippedVersion);
1008
+ const stateWriteWarning = await persist({
1009
+ ...lockedState.state,
1010
+ lastCheckedAt: attemptAt,
1011
+ lastAttemptAt: attemptAt,
1012
+ lastAttemptOk: true,
1013
+ failureReason: null,
1014
+ latest,
1015
+ current: currentNow,
1016
+ runningVersion,
1017
+ available: comparison.available,
1018
+ skippedVersion: skippedVersion ?? null,
1019
+ reason: comparison.decision === 'skipped' || comparison.decision === 'current_missing'
1020
+ ? comparison.decision
1021
+ : null,
1022
+ updatedAt: attemptAt,
1023
+ }, attemptAt);
1024
+
1025
+ return makeResult({
1026
+ ok: true,
1027
+ status: comparison.decision,
1028
+ reason: comparison.decision === 'skipped' || comparison.decision === 'current_missing'
1029
+ ? comparison.decision
1030
+ : null,
1031
+ decision: comparison.decision,
1032
+ available: comparison.available,
1033
+ skipped: comparison.skipped,
1034
+ cached: false,
1035
+ stale: false,
1036
+ currentVersion: currentNow,
1037
+ currentSource: lockedCurrent.source,
1038
+ currentUsable: lockedCurrent.usable === true,
1039
+ latestVersion: latest,
1040
+ runningVersion,
1041
+ skippedVersion,
1042
+ lastCheckedAt: attemptAt,
1043
+ lastAttemptAt: attemptAt,
1044
+ lastAttemptOk: true,
1045
+ failureReason: null,
1046
+ httpStatus: fetched.httpStatus ?? null,
1047
+ nextCheckAt: addIso(attemptAt, ttlMs),
1048
+ warnings: stateWriteWarning ? [stateWriteWarning] : [],
1049
+ message: messageForDecision(comparison.decision, latest, currentNow),
1050
+ });
1051
+ } catch (error) {
1052
+ return makeResult({
1053
+ ok: false,
1054
+ status: 'unexpected_error',
1055
+ reason: 'unexpected_error',
1056
+ decision: null,
1057
+ available: false,
1058
+ cached: false,
1059
+ stale: true,
1060
+ latestVersion: stored.latest,
1061
+ runningVersion: explicitRunning ?? stored.runningVersion,
1062
+ failureReason: 'unexpected_error',
1063
+ warnings: [`更新检查异常:${error?.code ?? error?.message ?? error}`],
1064
+ message: '更新检查异常;本次跳过,不阻塞入口',
1065
+ });
1066
+ } finally {
1067
+ await lock.release?.();
1068
+ }
1069
+ }
1070
+
1071
+ /** CLI 退出码:可消费答复(含 throttled/busy/current_missing)为 0,失败为 2。 */
1072
+ export function runtimeUpdateExitCode(result) {
1073
+ return result?.ok === true ? 0 : 2;
1074
+ }