@maplewf/dsh-web-update 0.0.0-stage → 0.1.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/index.js ADDED
@@ -0,0 +1,766 @@
1
+ /**
2
+ * dsh-version-update — check and install updates of the dsh web runtime.
3
+ *
4
+ * Host half: checks the published dist-tags once at startup, exposes the
5
+ * authenticated Fetch route `/api/dsh-version-update` (status / check / update)
6
+ * and a read-only `check_dsh_update` agent tool for the same information.
7
+ *
8
+ * The update installs the published package into the same global prefix the
9
+ * running entry point came from. When that prefix is not writable by the
10
+ * service user (a root-owned `/usr/lib/node_modules` is the common case) the
11
+ * install runs through `sudo -n`, so the operator either grants passwordless
12
+ * sudo or makes the tree writable once.
13
+ *
14
+ * After a successful install the host schedules one restart through a transient
15
+ * `systemd-run --user` timer: the dsh web process runs inside the unit it
16
+ * restarts, and the unit's `KillMode=control-group` would kill any helper
17
+ * spawned from inside that cgroup. The timer lives outside it, so it survives
18
+ * the stop and brings the new generation up.
19
+ */
20
+
21
+ import { spawn } from "node:child_process";
22
+ import { existsSync } from "node:fs";
23
+ import { createRequire } from "node:module";
24
+ import path from "node:path";
25
+
26
+ import {
27
+ evaluateUpdate,
28
+ installArgs,
29
+ installInvocation,
30
+ formatInvocation,
31
+ isWritable,
32
+ packageRootFromEntry,
33
+ parseDistTags,
34
+ pickChannelVersion,
35
+ readRuntimeVersion,
36
+ restartInnerCommand,
37
+ systemdRunTimerArgs,
38
+ tail,
39
+ } from "./lib/core.js";
40
+
41
+ export const name = "dsh-web-update";
42
+
43
+ /** `connection` provides the exact Fetch route registry; `tools` the agent tool. */
44
+ export const inject = ["connection", "tools"];
45
+
46
+ /**
47
+ * The declared Config schema needs schemastery, which the harness ships but
48
+ * does not expose to plugin packages: a bare import does not resolve from the
49
+ * plugin's real path (the profile loads the plugin by its real path). Load the
50
+ * harness's own copy with createRequire anchored at the dsh install root,
51
+ * mirroring how the kube plugin loads node-pty.
52
+ * @returns {string | null} the dsh installation root, or null.
53
+ */
54
+ function harnessRoot() {
55
+ const entry = typeof process.argv[1] === "string" ? process.argv[1] : "";
56
+ if (entry !== "") {
57
+ try {
58
+ const root = packageRootFromEntry(entry);
59
+ if (root !== null) return root;
60
+ } catch {
61
+ /* fall through to the common global install roots */
62
+ }
63
+ }
64
+ for (const guess of ["/usr/lib/node_modules/@deepseek-ai/dsh", "/usr/local/lib/node_modules/@deepseek-ai/dsh"]) {
65
+ if (existsSync(path.join(guess, "package.json"))) return guess;
66
+ }
67
+ return null;
68
+ }
69
+
70
+ /** Schemastery schema builder, loaded from the harness's own node_modules. */
71
+ const z = (() => {
72
+ const root = harnessRoot();
73
+ if (root === null) {
74
+ throw new Error("无法加载 @deepseek-ai/schemastery:找不到 dsh 安装目录");
75
+ }
76
+ return createRequire(path.join(root, "package.json"))("@deepseek-ai/schemastery");
77
+ })();
78
+
79
+ /** Absolute path below `/api`; the shared channel authenticates the owner peer. */
80
+ const ROUTE_PATH = "/api/dsh-version-update";
81
+
82
+ const DEFAULT_UNIT = "deepseek-harness-web.service";
83
+ const DEFAULT_PACKAGE = "@deepseek-ai/dsh";
84
+ const DEFAULT_CHANNEL = "latest";
85
+
86
+ /** dist-tags the UI may select between; mirrors npm release channels. */
87
+ const ALLOWED_CHANNELS = ["latest", "next", "alpha"];
88
+ const CHECK_TIMEOUT_MS = 60_000;
89
+ const COMMAND_TIMEOUT_MS = 600_000;
90
+ const DEFAULT_RESTART_DELAY_SECONDS = 3;
91
+ const MAX_RESTART_DELAY_SECONDS = 120;
92
+
93
+ const NPM_PATH = existsSync("/usr/bin/npm") ? "/usr/bin/npm" : "npm";
94
+ const SYSTEMCTL_PATH = existsSync("/usr/bin/systemctl") ? "/usr/bin/systemctl" : "systemctl";
95
+ const SYSTEMD_RUN_PATH = existsSync("/usr/bin/systemd-run") ? "/usr/bin/systemd-run" : "systemd-run";
96
+
97
+ /**
98
+ * Declared row config. `restartCommand` is volatile: the Plugins page config
99
+ * dialog edits it in place (no plugin restart), and the restart scheduled
100
+ * after the next install reads the live value.
101
+ */
102
+ export const Config = z.object({
103
+ unit: z.string(),
104
+ package: z.string(),
105
+ channel: z.string(),
106
+ restartDelaySeconds: z.number().min(0).max(MAX_RESTART_DELAY_SECONDS),
107
+ commandTimeoutSeconds: z.number().min(30),
108
+ checkOnStart: z.boolean(),
109
+ tool: z.boolean(),
110
+ npmPath: z.string(),
111
+ restartCommand: z.string().volatile(),
112
+ });
113
+
114
+ /** Process identity that changes whenever the service is restarted. */
115
+ const STARTED_AT = Date.now() - Math.round(process.uptime() * 1000);
116
+ const INSTANCE_ID = `${process.pid}-${STARTED_AT}`;
117
+
118
+ /** Volatile schema fields arrive as live getters; read the underlying value. */
119
+ function fieldValue(source, key) {
120
+ const value = source[key];
121
+ return value !== null && typeof value === "object" && typeof value.get === "function"
122
+ ? value.get()
123
+ : value;
124
+ }
125
+
126
+ /**
127
+ * Resolve the row config; an invalid field falls back to a safe default.
128
+ * @param {unknown} config - row config from the bundle patch.
129
+ * @returns {object} resolved settings.
130
+ */
131
+ function resolveSettings(config) {
132
+ const source = config !== null && typeof config === "object" ? config : {};
133
+ const unit = typeof source.unit === "string" && source.unit.trim() !== ""
134
+ ? source.unit.trim()
135
+ : DEFAULT_UNIT;
136
+ const packageName = typeof source.package === "string" && source.package.trim() !== ""
137
+ ? source.package.trim()
138
+ : DEFAULT_PACKAGE;
139
+ const channel = typeof source.channel === "string" && source.channel.trim() !== ""
140
+ ? source.channel.trim()
141
+ : DEFAULT_CHANNEL;
142
+ const delay = source.restartDelaySeconds;
143
+ const restartDelaySeconds = Number.isInteger(delay) && delay >= 0 && delay <= MAX_RESTART_DELAY_SECONDS
144
+ ? delay
145
+ : DEFAULT_RESTART_DELAY_SECONDS;
146
+ const timeout = source.commandTimeoutSeconds;
147
+ const commandTimeoutSeconds = Number.isInteger(timeout) && timeout >= 30
148
+ ? timeout
149
+ : COMMAND_TIMEOUT_MS / 1000;
150
+ return {
151
+ unit,
152
+ packageName,
153
+ channel,
154
+ restartDelaySeconds,
155
+ commandTimeoutSeconds,
156
+ checkOnStart: source.checkOnStart !== false,
157
+ tool: source.tool !== false,
158
+ npmPath: typeof source.npmPath === "string" && source.npmPath !== "" ? source.npmPath : NPM_PATH,
159
+ restartCommand: "",
160
+ };
161
+ }
162
+
163
+ /**
164
+ * Child processes need the user systemd manager socket; a service started with
165
+ * a non-default HOME can miss `XDG_RUNTIME_DIR`, so derive it from the uid.
166
+ * @returns {NodeJS.ProcessEnv} environment for helper commands.
167
+ */
168
+ function userEnvironment() {
169
+ const environment = { ...process.env };
170
+ if (environment.XDG_RUNTIME_DIR === undefined && typeof process.getuid === "function") {
171
+ environment.XDG_RUNTIME_DIR = `/run/user/${process.getuid()}`;
172
+ }
173
+ return environment;
174
+ }
175
+
176
+ /**
177
+ * Spawn one short-lived helper and capture a bounded amount of its output.
178
+ * @param {string} command - absolute or PATH-resolved executable.
179
+ * @param {string[]} args - arguments.
180
+ * @param {{ timeoutMs?: number }} [options] - optional hard timeout.
181
+ * @returns {Promise<{ ok: boolean, stdout: string, stderr: string, timedOut?: boolean, error?: string }>} outcome.
182
+ */
183
+ function runCapture(command, args, options = {}) {
184
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 0;
185
+ return new Promise((resolve) => {
186
+ let child;
187
+ try {
188
+ child = spawn(command, args, {
189
+ env: userEnvironment(),
190
+ stdio: ["ignore", "pipe", "pipe"],
191
+ detached: true,
192
+ });
193
+ } catch (error) {
194
+ resolve({ ok: false, stdout: "", stderr: "", error: String(error?.message ?? error) });
195
+ return;
196
+ }
197
+ let stdout = "";
198
+ let stderr = "";
199
+ const keep = (current, chunk) => (current.length >= 16_384 ? current : current + chunk.toString());
200
+ child.stdout?.on("data", (chunk) => { stdout = keep(stdout, chunk); });
201
+ child.stderr?.on("data", (chunk) => { stderr = keep(stderr, chunk); });
202
+
203
+ let settled = false;
204
+ let timedOut = false;
205
+ let timer = null;
206
+ let hardKill = null;
207
+ const finish = (value) => {
208
+ if (settled) return;
209
+ settled = true;
210
+ if (timer !== null) clearTimeout(timer);
211
+ if (hardKill !== null) clearTimeout(hardKill);
212
+ resolve(value);
213
+ };
214
+ if (timeoutMs > 0) {
215
+ timer = setTimeout(() => {
216
+ timedOut = true;
217
+ try { child.kill("SIGTERM"); } catch { /* already gone */ }
218
+ hardKill = setTimeout(() => {
219
+ try { child.kill("SIGKILL"); } catch { /* already gone */ }
220
+ }, 3_000);
221
+ hardKill.unref?.();
222
+ }, timeoutMs);
223
+ timer.unref?.();
224
+ }
225
+ child.once("error", (error) => finish({
226
+ ok: false,
227
+ stdout,
228
+ stderr,
229
+ error: `${error?.code ?? "spawn-error"}: ${error?.message ?? String(error)}`,
230
+ }));
231
+ child.once("exit", (code, signal) => finish({
232
+ ok: code === 0 && timedOut !== true,
233
+ stdout,
234
+ stderr: signal === null || timedOut === true ? stderr : `${stderr}signal ${signal}`,
235
+ timedOut,
236
+ }));
237
+ child.unref();
238
+ });
239
+ }
240
+
241
+ /** One in-flight version check at a time; concurrent callers share it. */
242
+ let activeCheck = null;
243
+
244
+ /**
245
+ * Query the published version for the configured channel.
246
+ * Uses the npm CLI first (it honours the machine's npm configuration and
247
+ * network path) and falls back to the registry endpoint.
248
+ * @param {object} settings - resolved row settings.
249
+ * @param {string} channel - dist-tag to resolve (e.g. latest/next/alpha).
250
+ * @returns {Promise<{ version: string, source: string, tags: Record<string, string> }>} latest version.
251
+ */
252
+ async function queryLatest(settings, channel) {
253
+ const viewed = await runCapture(
254
+ settings.npmPath,
255
+ ["view", settings.packageName, "dist-tags", "--json", "--prefer-online"],
256
+ { timeoutMs: CHECK_TIMEOUT_MS },
257
+ );
258
+ if (viewed.ok) {
259
+ const tags = parseDistTags(viewed.stdout);
260
+ const version = pickChannelVersion(tags, channel);
261
+ if (version !== null) return { version, source: "npm-view", tags };
262
+ }
263
+
264
+ const url = `https://registry.npmjs.org/${settings.packageName.replace("/", "%2F")}/latest`;
265
+ let response;
266
+ try {
267
+ response = await fetch(url, {
268
+ headers: { accept: "application/json", "user-agent": "dsh-version-update" },
269
+ signal: AbortSignal.timeout(20_000),
270
+ });
271
+ } catch (error) {
272
+ throw new Error(`无法查询 npm registry:${error?.message ?? error}`);
273
+ }
274
+ if (!response.ok) throw new Error(`npm registry 返回 HTTP ${response.status}`);
275
+ const document = await response.json();
276
+ if (typeof document?.version !== "string") throw new Error("npm registry 响应缺少 version 字段");
277
+ return { version: document.version, source: "registry-fetch", tags: { latest: document.version } };
278
+ }
279
+
280
+ /** JSON response with no-store so a browser never serves a cached status. */
281
+ function jsonResponse(body, status = 200) {
282
+ return Response.json(body, {
283
+ status,
284
+ headers: { "cache-control": "no-store" },
285
+ });
286
+ }
287
+
288
+ /**
289
+ * Host plugin body: state, startup check, route and agent tool.
290
+ * @param {object} ctx - host plugin context.
291
+ * @param {unknown} config - bundle row config.
292
+ */
293
+ export function apply(ctx, config) {
294
+ const settings = resolveSettings(config);
295
+ const logger = ctx.logger;
296
+ const log = (message) => logger?.info?.(`[dsh-version-update] ${message}`);
297
+
298
+ /** Everything the UI reads; mutated only through the helpers below. */
299
+ const state = {
300
+ phase: "idle",
301
+ currentVersion: "unknown",
302
+ currentRoot: null,
303
+ sudoRequired: true,
304
+ channel: settings.channel,
305
+ packageName: settings.packageName,
306
+ latestVersion: null,
307
+ updateAvailable: false,
308
+ relation: "unknown",
309
+ checkedAt: null,
310
+ checkError: null,
311
+ checkSource: null,
312
+ checkDurationMs: null,
313
+ update: {
314
+ state: "idle",
315
+ target: null,
316
+ startedAt: null,
317
+ finishedAt: null,
318
+ command: null,
319
+ log: "",
320
+ error: null,
321
+ },
322
+ restart: { scheduled: false, skipped: false, runAt: null, timerUnit: null, command: null, error: null },
323
+ };
324
+
325
+ /**
326
+ * Live value of the volatile `restartCommand` config field: the Plugins page
327
+ * can edit it in place, so read it again whenever a restart is scheduled.
328
+ * @returns {string} trimmed command; "" keeps the built-in default.
329
+ */
330
+ function liveRestartCommand() {
331
+ const value = fieldValue(config, "restartCommand");
332
+ return typeof value === "string" ? value.trim() : "";
333
+ }
334
+
335
+ /**
336
+ * Re-read the version of the package that hosts this process.
337
+ * @returns {{ root: string, version: string } | null} identity or null.
338
+ */
339
+ function refreshIdentity() {
340
+ const entry = typeof process.argv[1] === "string" ? process.argv[1] : "";
341
+ if (entry === "") return null;
342
+ try {
343
+ const identity = readRuntimeVersion(entry);
344
+ state.currentRoot = identity.root;
345
+ state.currentVersion = identity.version;
346
+ state.sudoRequired = !isWritable(identity.root);
347
+ return identity;
348
+ } catch (error) {
349
+ logger?.warn?.(`[dsh-version-update] cannot read the installed version: ${error?.message ?? error}`);
350
+ return null;
351
+ }
352
+ }
353
+
354
+ /** Refreshed at activation; also re-read after every install. */
355
+ refreshIdentity();
356
+
357
+ /**
358
+ * Compare the running version against the published one.
359
+ * @param {string} reason - who asked (startup, user, tool).
360
+ * @param {string} [channelOverride] - dist-tag to check against; when a valid
361
+ * one is given it becomes the active channel for this and later checks.
362
+ * @returns {Promise<object>} the new status snapshot.
363
+ */
364
+ function checkForUpdate(reason, channelOverride) {
365
+ if (activeCheck !== null) return activeCheck;
366
+ if (typeof channelOverride === "string" && ALLOWED_CHANNELS.includes(channelOverride)) {
367
+ state.channel = channelOverride;
368
+ }
369
+ const channel = state.channel;
370
+ state.phase = "checking";
371
+ state.checkError = null;
372
+ const startedAt = Date.now();
373
+ activeCheck = (async () => {
374
+ try {
375
+ refreshIdentity();
376
+ const latest = await queryLatest(settings, channel);
377
+ const decision = evaluateUpdate(state.currentVersion, latest.version);
378
+ state.latestVersion = latest.version;
379
+ state.updateAvailable = decision.updateAvailable;
380
+ state.relation = decision.relation;
381
+ state.checkSource = latest.source;
382
+ state.checkedAt = new Date().toISOString();
383
+ state.checkError = null;
384
+ state.phase = "idle";
385
+ log(
386
+ `checked ${settings.packageName} (${reason}): current=${state.currentVersion} `
387
+ + `latest(${channel})=${latest.version} updateAvailable=${decision.updateAvailable}`,
388
+ );
389
+ } catch (error) {
390
+ state.updateAvailable = false;
391
+ state.relation = "unknown";
392
+ state.checkError = String(error?.message ?? error);
393
+ state.checkedAt = new Date().toISOString();
394
+ state.phase = "error";
395
+ logger?.warn?.(`[dsh-version-update] version check failed (${reason}): ${state.checkError}`);
396
+ } finally {
397
+ state.checkDurationMs = Date.now() - startedAt;
398
+ activeCheck = null;
399
+ }
400
+ return statusSnapshot();
401
+ })();
402
+ return activeCheck;
403
+ }
404
+
405
+ /**
406
+ * Snapshot for the route, the tool and the client poll.
407
+ * @returns {object} JSON-ready status.
408
+ */
409
+ function statusSnapshot() {
410
+ return {
411
+ ok: true,
412
+ instanceId: INSTANCE_ID,
413
+ pid: process.pid,
414
+ unit: settings.unit,
415
+ phase: state.phase,
416
+ packageName: state.packageName,
417
+ channel: state.channel,
418
+ availableChannels: ALLOWED_CHANNELS.slice(),
419
+ currentVersion: state.currentVersion,
420
+ latestVersion: state.latestVersion,
421
+ updateAvailable: state.updateAvailable,
422
+ relation: state.relation,
423
+ checkedAt: state.checkedAt,
424
+ checkError: state.checkError,
425
+ checkSource: state.checkSource,
426
+ checkDurationMs: state.checkDurationMs,
427
+ sudoRequired: state.sudoRequired,
428
+ restartCommand: liveRestartCommand(),
429
+ update: state.update,
430
+ restart: state.restart,
431
+ };
432
+ }
433
+
434
+ /**
435
+ * Validate that the configured systemd user unit exists.
436
+ * @returns {Promise<{ ok: true } | { ok: false, error: string }>} probe result.
437
+ */
438
+ async function checkUnit() {
439
+ const probe = await runCapture(
440
+ SYSTEMCTL_PATH,
441
+ ["--user", "show", "-p", "LoadState", "--value", settings.unit],
442
+ { timeoutMs: 15_000 },
443
+ );
444
+ if (!probe.ok) {
445
+ const detail = probe.stderr.trim() || probe.error || "unknown error";
446
+ return { ok: false, error: `无法查询 systemd 用户单元 ${settings.unit}:${detail}` };
447
+ }
448
+ const loadState = probe.stdout.trim();
449
+ if (loadState === "" || loadState === "not-found") {
450
+ return { ok: false, error: `systemd 用户单元不存在:${settings.unit}` };
451
+ }
452
+ return { ok: true };
453
+ }
454
+
455
+ /**
456
+ * Schedule one restart of the dsh web unit through a transient timer.
457
+ * The timer runs outside the unit's cgroup, so KillMode=control-group
458
+ * cannot kill it while the service stops. The executed command comes from
459
+ * config.restartCommand: empty uses the built-in `systemctl --user restart`,
460
+ * a non-empty string runs via `/bin/sh -c` (with `{unit}` substituted).
461
+ * @returns {Promise<object>} JSON-ready restart payload.
462
+ */
463
+ async function scheduleRestart() {
464
+ const command = liveRestartCommand();
465
+ // The unit probe only guards the built-in command: a custom command may
466
+ // legitimately target a unit that is not a user unit (e.g. sudo systemctl
467
+ // restart a system-level service), so it would fail the probe wrongly.
468
+ if (command === "") {
469
+ const unit = await checkUnit();
470
+ if (unit.ok !== true) {
471
+ state.restart = { scheduled: false, skipped: false, runAt: null, timerUnit: null, command: null, error: unit.error };
472
+ logger?.warn?.(`[dsh-version-update] restart not scheduled: ${unit.error}`);
473
+ return state.restart;
474
+ }
475
+ }
476
+ const delaySeconds = settings.restartDelaySeconds;
477
+ const stamp = Date.now().toString(36);
478
+ const salt = Math.random().toString(36).slice(2, 6);
479
+ const timerUnit = `dsh-version-update-${stamp}-${salt}`;
480
+ const runAt = new Date(Date.now() + delaySeconds * 1000).toISOString();
481
+ const inner = restartInnerCommand({
482
+ command,
483
+ systemctlPath: SYSTEMCTL_PATH,
484
+ unit: settings.unit,
485
+ });
486
+ const args = systemdRunTimerArgs({ timerUnit, delaySeconds, innerCommand: inner });
487
+ const scheduled = await runCapture(SYSTEMD_RUN_PATH, args, { timeoutMs: 20_000 });
488
+ if (!scheduled.ok) {
489
+ const detail = scheduled.stderr.trim() || scheduled.error || "unknown error";
490
+ state.restart = {
491
+ scheduled: false,
492
+ skipped: false,
493
+ runAt: null,
494
+ timerUnit: null,
495
+ command: null,
496
+ error: `systemd-run 调度重启失败:${detail}`,
497
+ };
498
+ logger?.warn?.(`[dsh-version-update] restart not scheduled: ${state.restart.error}`);
499
+ return state.restart;
500
+ }
501
+ const printable = formatInvocation({ command: SYSTEMD_RUN_PATH, args });
502
+ state.restart = { scheduled: true, skipped: false, runAt, timerUnit, command: printable, error: null };
503
+ log(`restart of ${settings.unit} scheduled in ${delaySeconds}s (${timerUnit}): ${printable}`);
504
+ return state.restart;
505
+ }
506
+
507
+ /**
508
+ * Install one published version and restart the service onto it.
509
+ * @param {string} target - exact version to install.
510
+ * @returns {Promise<object>} JSON-ready update payload.
511
+ */
512
+ async function installVersion(target) {
513
+ state.update = {
514
+ state: "running",
515
+ target,
516
+ startedAt: new Date().toISOString(),
517
+ finishedAt: null,
518
+ command: null,
519
+ log: "",
520
+ error: null,
521
+ };
522
+ state.phase = "updating";
523
+
524
+ const args = installArgs(settings.packageName, target);
525
+ const invocation = installInvocation(
526
+ { npmPath: settings.npmPath, needsSudo: state.sudoRequired },
527
+ args,
528
+ );
529
+ const printable = formatInvocation(invocation);
530
+ state.update.command = printable;
531
+ state.update.log = `$ ${printable}\n`;
532
+ log(`installing ${settings.packageName}@${target} (sudo=${invocation.sudo})`);
533
+
534
+ const install = await runCapture(invocation.command, invocation.args, {
535
+ timeoutMs: settings.commandTimeoutSeconds * 1000,
536
+ });
537
+ state.update.log = tail(`${state.update.log}${install.stdout}\n${install.stderr}`.trim(), 6000);
538
+
539
+ if (!install.ok) {
540
+ const detail = install.timedOut === true
541
+ ? `安装超时(${settings.commandTimeoutSeconds}s)`
542
+ : (install.stderr.trim().split("\n").slice(-6).join("\n") || install.error || "未知错误");
543
+ state.update.state = "error";
544
+ state.update.finishedAt = new Date().toISOString();
545
+ state.update.error = `安装 ${settings.packageName}@${target} 失败:${detail}`;
546
+ state.phase = "error";
547
+ logger?.warn?.(`[dsh-version-update] ${state.update.error}`);
548
+ return state.update;
549
+ }
550
+
551
+ const identity = refreshIdentity();
552
+ const installedVersion = identity?.version ?? "unknown";
553
+ if (installedVersion !== target) {
554
+ state.update.state = "error";
555
+ state.update.finishedAt = new Date().toISOString();
556
+ state.update.error = `安装结束但磁盘上的版本是 ${installedVersion},期望 ${target}`;
557
+ state.phase = "error";
558
+ logger?.warn?.(`[dsh-version-update] ${state.update.error}`);
559
+ return state.update;
560
+ }
561
+
562
+ state.update.state = "installed";
563
+ state.update.finishedAt = new Date().toISOString();
564
+ state.currentVersion = installedVersion;
565
+ state.latestVersion = installedVersion;
566
+ state.updateAvailable = false;
567
+ state.relation = "same";
568
+ state.phase = "restarting";
569
+ log(`installed ${settings.packageName}@${installedVersion}; scheduling restart`);
570
+ await scheduleRestart();
571
+ return state.update;
572
+ }
573
+
574
+ /**
575
+ * Handle one exact-route request.
576
+ * @param {Request} request - authenticated same-origin Fetch request.
577
+ * @returns {Promise<Response>} JSON response.
578
+ */
579
+ async function persistRestartCommand(command) {
580
+ const editor = ctx.get("configEditor");
581
+ if (editor === undefined || typeof editor.edit !== "function") {
582
+ throw new Error("configEditor 服务不可用");
583
+ }
584
+ const entry = ctx.fiber?.entry;
585
+ if (entry === undefined) {
586
+ throw new Error("无法定位插件配置条目");
587
+ }
588
+ await editor.edit(entry, (current) => ({ ...(current ?? {}), restartCommand: command }));
589
+ }
590
+
591
+ async function handleFetch(request) {
592
+ const url = new URL(request.url);
593
+ const action = url.searchParams.get("action")
594
+ ?? (request.method === "GET" ? "status" : "status");
595
+
596
+ if (action === "status") {
597
+ return jsonResponse(statusSnapshot());
598
+ }
599
+
600
+ if (action === "check") {
601
+ const channel = url.searchParams.get("channel") ?? null;
602
+ if (channel !== null && !ALLOWED_CHANNELS.includes(channel)) {
603
+ return jsonResponse({
604
+ ...statusSnapshot(),
605
+ ok: false,
606
+ error: `未知更新通道:${channel}(可选:${ALLOWED_CHANNELS.join("/")})`,
607
+ }, 400);
608
+ }
609
+ const snapshot = await checkForUpdate("user", channel ?? undefined);
610
+ return jsonResponse(snapshot, snapshot.phase === "error" ? 503 : 200);
611
+ }
612
+
613
+ if (action === "update") {
614
+ if (state.update.state === "running") {
615
+ return jsonResponse({ ...statusSnapshot(), ok: false, error: "已有更新正在进行" }, 409);
616
+ }
617
+ if (state.phase === "restarting") {
618
+ return jsonResponse({ ...statusSnapshot(), ok: false, error: "更新已完成,正在重启服务" }, 409);
619
+ }
620
+ refreshIdentity();
621
+ if (state.latestVersion === null || state.checkedAt === null) {
622
+ await checkForUpdate("pre-update");
623
+ }
624
+ if (state.checkError !== null) {
625
+ return jsonResponse({ ...statusSnapshot(), ok: false, error: `无法确认最新版本:${state.checkError}` }, 503);
626
+ }
627
+ if (state.updateAvailable !== true) {
628
+ return jsonResponse({
629
+ ...statusSnapshot(),
630
+ ok: false,
631
+ error: state.relation === "older"
632
+ ? `当前版本 ${state.currentVersion} 高于 ${state.channel} 通道的 ${state.latestVersion},无需更新`
633
+ : `已是最新版本(${state.currentVersion})`,
634
+ }, 409);
635
+ }
636
+ const target = state.latestVersion;
637
+ void installVersion(target).catch((error) => {
638
+ logger?.warn?.(`[dsh-version-update] update crashed: ${error?.message ?? error}`);
639
+ state.update.state = "error";
640
+ state.update.error = String(error?.message ?? error);
641
+ state.phase = "error";
642
+ });
643
+ return jsonResponse({ ok: true, started: true, target, ...statusSnapshot() });
644
+ }
645
+
646
+ if (action === "set-restart-command") {
647
+ let body = {};
648
+ try {
649
+ body = await request.json();
650
+ } catch {
651
+ body = {};
652
+ }
653
+ if (typeof body.command !== "string") {
654
+ return jsonResponse({ ...statusSnapshot(), ok: false, error: "缺少 command 字段" }, 400);
655
+ }
656
+ const command = body.command.trim();
657
+ if (command.length > 500) {
658
+ return jsonResponse({ ...statusSnapshot(), ok: false, error: "重启命令过长(上限 500 字符)" }, 400);
659
+ }
660
+ try {
661
+ await persistRestartCommand(command);
662
+ } catch (error) {
663
+ logger?.warn?.(`[dsh-version-update] set-restart-command failed: ${error?.message ?? error}`);
664
+ return jsonResponse(
665
+ { ...statusSnapshot(), ok: false, error: `保存重启命令失败:${error?.message ?? error}` },
666
+ 500,
667
+ );
668
+ }
669
+ log(`restart command updated: ${command === "" ? "(default)" : command}`);
670
+ return jsonResponse({ ok: true, ...statusSnapshot() });
671
+ }
672
+
673
+ return jsonResponse({ ok: false, error: `未知操作:${action}` }, 400);
674
+ }
675
+
676
+ ctx.effect(() => {
677
+ const connection = Reflect.get(ctx, "connection");
678
+ const register = connection?.fetch?.register;
679
+ if (typeof register !== "function") {
680
+ logger?.warn?.("[dsh-version-update] connection fetch registry unavailable; update route not mounted");
681
+ return () => {};
682
+ }
683
+ return register({
684
+ path: ROUTE_PATH,
685
+ methods: ["GET", "POST"],
686
+ requestBody: "buffered",
687
+ fetch: handleFetch,
688
+ });
689
+ }, "dsh-version-update: /api/dsh-version-update route");
690
+
691
+ if (settings.checkOnStart === true) {
692
+ ctx.effect(() => {
693
+ let cancelled = false;
694
+ const timer = setTimeout(() => {
695
+ if (cancelled) return;
696
+ void checkForUpdate("startup");
697
+ }, 1_500);
698
+ timer.unref?.();
699
+ return () => {
700
+ cancelled = true;
701
+ clearTimeout(timer);
702
+ };
703
+ }, "dsh-version-update: startup check");
704
+ }
705
+
706
+ if (settings.tool !== true) return;
707
+
708
+ try {
709
+ ctx.tools.register({
710
+ name: "check_dsh_update",
711
+ description: "Read the dsh web runtime version and, when asked, check the npm registry for a newer published version. Read-only: it never installs anything. Use it when the user asks whether the harness has an update available.",
712
+ parameters: {
713
+ type: "object",
714
+ properties: {
715
+ action: {
716
+ type: "string",
717
+ enum: ["status", "check"],
718
+ description: "status returns the last known result; check queries npm now.",
719
+ },
720
+ },
721
+ additionalProperties: false,
722
+ },
723
+ output: {
724
+ schema: {
725
+ type: "object",
726
+ properties: {
727
+ currentVersion: { type: "string" },
728
+ latestVersion: { type: ["string", "null"] },
729
+ updateAvailable: { type: "boolean" },
730
+ channel: { type: "string" },
731
+ checkedAt: { type: ["string", "null"] },
732
+ checkError: { type: ["string", "null"] },
733
+ sudoRequired: { type: "boolean" },
734
+ },
735
+ required: ["currentVersion", "latestVersion", "updateAvailable", "channel", "checkedAt", "checkError", "sudoRequired"],
736
+ additionalProperties: false,
737
+ },
738
+ render: (_args, value) => [{
739
+ type: "text",
740
+ text: value.latestVersion === null
741
+ ? `dsh ${value.currentVersion}; no successful check yet${value.checkError === null ? "" : ` (${value.checkError})`}.`
742
+ : `dsh ${value.currentVersion} (${value.channel} channel: ${value.latestVersion}); `
743
+ + (value.updateAvailable ? "an update is available." : "up to date."),
744
+ }],
745
+ },
746
+ execute: async (args) => {
747
+ const action = args !== null && typeof args === "object" && args.action === "check"
748
+ ? "check"
749
+ : "status";
750
+ if (action === "check") await checkForUpdate("tool");
751
+ const snapshot = statusSnapshot();
752
+ return {
753
+ currentVersion: snapshot.currentVersion,
754
+ latestVersion: snapshot.latestVersion,
755
+ updateAvailable: snapshot.updateAvailable,
756
+ channel: snapshot.channel,
757
+ checkedAt: snapshot.checkedAt,
758
+ checkError: snapshot.checkError,
759
+ sudoRequired: snapshot.sudoRequired,
760
+ };
761
+ },
762
+ });
763
+ } catch (error) {
764
+ logger?.warn?.(`[dsh-version-update] check_dsh_update tool not registered: ${error?.message ?? error}`);
765
+ }
766
+ }