yukari-dsh-plugin 0.0.0-stage → 0.7.2
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/LICENSE +21 -0
- package/README.md +17 -2
- package/client.js +8340 -0
- package/cordis.patch.yml +95 -0
- package/host/browser/index.js +397 -0
- package/host/browser/lib/browser.js +885 -0
- package/host/browser/lib/cdp.js +302 -0
- package/host/browser/lib/libraries.js +309 -0
- package/host/browser/lib/page-scripts.js +243 -0
- package/host/browser/lib/runtime.js +351 -0
- package/host/browser/lib/url-guard.js +122 -0
- package/host/browser/locale/en.json +6 -0
- package/host/browser/locale/zh.json +6 -0
- package/host/chats/index.js +254 -0
- package/host/chats/lib/admin.js +893 -0
- package/host/chats/lib/cleanup.js +272 -0
- package/host/chats/lib/paths.js +108 -0
- package/host/chats/lib/preview.js +74 -0
- package/host/chats/locale/en.json +6 -0
- package/host/chats/locale/zh.json +6 -0
- package/host/files/index.js +403 -0
- package/host/files/locale/en.json +6 -0
- package/host/files/locale/zh.json +6 -0
- package/host/github/index.js +121 -0
- package/host/github/lib/api.js +310 -0
- package/host/github/lib/atomic.js +42 -0
- package/host/github/lib/controller.js +450 -0
- package/host/github/lib/git.js +389 -0
- package/host/github/lib/redact.js +22 -0
- package/host/github/lib/signing.js +124 -0
- package/host/github/lib/store.js +181 -0
- package/host/github/locale/en.json +6 -0
- package/host/github/locale/zh.json +6 -0
- package/host/presets/index.js +450 -0
- package/host/presets/lib/definition.js +267 -0
- package/host/presets/lib/sources.js +278 -0
- package/host/presets/lib/store.js +136 -0
- package/host/presets/locale/en.json +6 -0
- package/host/presets/locale/zh.json +6 -0
- package/host/proxy/index.js +236 -0
- package/host/proxy/lib/controller.js +1151 -0
- package/host/proxy/lib/egress.js +120 -0
- package/host/proxy/lib/local-proxy.js +422 -0
- package/host/proxy/lib/shadowsocks.js +335 -0
- package/host/proxy/lib/ss-uri.js +501 -0
- package/host/proxy/lib/subscriptions.js +140 -0
- package/host/proxy/locale/en.json +6 -0
- package/host/proxy/locale/zh.json +6 -0
- package/host/purge/index.js +538 -0
- package/host/purge/lib/preset.js +140 -0
- package/host/purge/lib/prompts.js +95 -0
- package/host/purge/lib/retry-gate.js +97 -0
- package/host/purge/lib/rewriter.js +322 -0
- package/host/purge/lib/settings.js +54 -0
- package/host/purge/lib/stream-retry.js +255 -0
- package/host/purge/locale/en.json +6 -0
- package/host/purge/locale/zh.json +6 -0
- package/host/purge/presets/unrestricted/agent.cordis.yml +273 -0
- package/host/purge/presets/unrestricted/preset.json +75 -0
- package/host/purge/presets/unrestricted/preset.yml +3 -0
- package/host/rewind/index.js +127 -0
- package/host/rewind/lib/controller.js +449 -0
- package/host/rewind/lib/marker.js +53 -0
- package/host/rewind/lib/safe-path.js +47 -0
- package/host/rewind/lib/store.js +585 -0
- package/host/rewind/lib/surface.js +108 -0
- package/host/rewind/locale/en.json +6 -0
- package/host/rewind/locale/zh.json +6 -0
- package/host/rules/index.js +624 -0
- package/host/rules/lib/paths.js +87 -0
- package/host/rules/lib/render.js +92 -0
- package/host/rules/lib/scope.js +146 -0
- package/host/rules/lib/settings.js +55 -0
- package/host/rules/lib/store.js +222 -0
- package/host/rules/locale/en.json +6 -0
- package/host/rules/locale/zh.json +6 -0
- package/host/runtime/index.js +577 -0
- package/host/runtime/lib/npm.js +293 -0
- package/host/runtime/lib/restart.js +105 -0
- package/host/runtime/lib/update-guard.js +70 -0
- package/host/runtime/lib/versions.js +188 -0
- package/host/runtime/locale/en.json +6 -0
- package/host/runtime/locale/zh.json +6 -0
- package/host/shared/busy.js +40 -0
- package/host/shared/home.js +27 -0
- package/host/shared/http.js +159 -0
- package/host/shared/migrate.js +60 -0
- package/host/shared/mounted.js +54 -0
- package/host/shared/zip-writer.js +319 -0
- package/host/shared/zip.js +180 -0
- package/host/sites/index.js +258 -0
- package/host/sites/lib/sites.js +630 -0
- package/host/sites/locale/en.json +6 -0
- package/host/sites/locale/zh.json +6 -0
- package/host/skills/index.js +176 -0
- package/host/skills/lib/frontmatter.js +149 -0
- package/host/skills/lib/library.js +408 -0
- package/host/skills/lib/upload.js +115 -0
- package/host/skills/locale/en.json +6 -0
- package/host/skills/locale/zh.json +6 -0
- package/icon.png +0 -0
- package/index.js +702 -0
- package/locale/en.json +5 -0
- package/locale/zh.json +5 -0
- package/package.json +113 -4
|
@@ -0,0 +1,577 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime control for a containerised Harness: restart the process, upgrade the
|
|
3
|
+
* npm package it runs from, from a sidebar panel or from the agent.
|
|
4
|
+
*
|
|
5
|
+
* The Host half owns three things and exposes each of them twice — once as a
|
|
6
|
+
* small JSON API the panel calls, once as an agent tool:
|
|
7
|
+
*
|
|
8
|
+
* 1. the version actually running (walked up from the entry script) versus the
|
|
9
|
+
* version on disk (read from the npm global prefix);
|
|
10
|
+
* 2. the upgrade, `npm i -g @deepseek-ai/dsh@<channel-max>` with a cache under
|
|
11
|
+
* `DSH_HOME` so root-owned cache directories in the image cannot break it;
|
|
12
|
+
* 3. the restart, which re-execs the process in place so a Docker install comes
|
|
13
|
+
* back on the same port and follows the same volume.
|
|
14
|
+
*
|
|
15
|
+
* There is no Docker socket in the image, so a restart never asks the daemon to
|
|
16
|
+
* do anything. `restartMode: command` exists for deployments that mount one.
|
|
17
|
+
* @module @local/dsh-control
|
|
18
|
+
*/
|
|
19
|
+
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
|
|
20
|
+
import path from 'node:path'
|
|
21
|
+
import { markMounted } from '../shared/mounted.js'
|
|
22
|
+
import { NpmRunner, locateRunningPackage } from './lib/npm.js'
|
|
23
|
+
import { planRestart, scheduleRestart } from './lib/restart.js'
|
|
24
|
+
import { candidatesOf, compare, isVersionText, normalizeChannel, satisfiesRange } from './lib/versions.js'
|
|
25
|
+
import { appError, guardRoute, readJsonBody, sendJson, messageOf } from '../shared/http.js'
|
|
26
|
+
import { busyLabel, runExclusive } from '../shared/busy.js'
|
|
27
|
+
|
|
28
|
+
/** JSON API prefix served to the Web panel. */
|
|
29
|
+
export const API_PATH = '/dshctl/api'
|
|
30
|
+
|
|
31
|
+
/** How long a cached "installed on disk" reading stays fresh. */
|
|
32
|
+
const INSTALLED_TTL_MS = 30_000
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Whether this deployment can update the Harness with npm.
|
|
36
|
+
*
|
|
37
|
+
* The Windows client ships without npm, and every npm call there fails with a
|
|
38
|
+
* shell error the panel cannot act on. The update controls are hidden there;
|
|
39
|
+
* the client has its own updater.
|
|
40
|
+
* @param platform - platform to answer for; tests pass `win32`.
|
|
41
|
+
*/
|
|
42
|
+
export function supportsDshUpdate(platform = process.platform) {
|
|
43
|
+
return platform !== 'win32'
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Whether the panel may restart the Harness.
|
|
48
|
+
*
|
|
49
|
+
* The Windows client owns its process lifecycle; a restart issued from the
|
|
50
|
+
* plugin would either do nothing or close the client, so the control is hidden
|
|
51
|
+
* and the API refuses.
|
|
52
|
+
* @param platform - platform to answer for; tests pass `win32`.
|
|
53
|
+
*/
|
|
54
|
+
export function supportsDshRestart(platform = process.platform) {
|
|
55
|
+
return platform !== 'win32'
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Services this plugin needs. */
|
|
59
|
+
export const inject = ['tools', 'webServer', 'connection']
|
|
60
|
+
|
|
61
|
+
/** Turn any thrown value into a message. */
|
|
62
|
+
/** Seconds as a compact human duration. */
|
|
63
|
+
function duration(seconds) {
|
|
64
|
+
const value = Math.max(0, Math.round(seconds))
|
|
65
|
+
if (value < 60) return `${value}s`
|
|
66
|
+
const minutes = Math.floor(value / 60)
|
|
67
|
+
if (minutes < 60) return `${minutes}m`
|
|
68
|
+
const hours = Math.floor(minutes / 60)
|
|
69
|
+
if (hours < 48) return `${hours}h${minutes % 60 === 0 ? '' : ` ${minutes % 60}m`}`
|
|
70
|
+
return `${Math.floor(hours / 24)}d ${hours % 24}h`
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 升级前的两个前置条件:装到的位置必须就是正在运行的那份,目标版本要能在
|
|
75
|
+
* 本机 Node 上跑。两条都只在事后才发现——一个装到别处,一个重启后起不来。
|
|
76
|
+
* @param {{ runningDir?: string | null, globalRoot?: string | null, nodeVersion: string, engines?: object | null }} facts - 观测值。
|
|
77
|
+
* @returns {string | null} 拒绝理由;通过时为 null。
|
|
78
|
+
*/
|
|
79
|
+
export function preflightUpgrade({ runningDir, globalRoot, nodeVersion, engines }) {
|
|
80
|
+
if (typeof runningDir === 'string' && typeof globalRoot === 'string' && globalRoot !== '') {
|
|
81
|
+
const prefix = globalRoot.endsWith(path.sep) ? globalRoot : `${globalRoot}${path.sep}`
|
|
82
|
+
if (!`${runningDir}${path.sep}`.startsWith(prefix)) {
|
|
83
|
+
return `当前运行的是 ${runningDir} 这份副本,不在 npm 全局前缀 ${globalRoot} 内;全局安装不会替换它,请按这份副本的安装方式更新`
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const range = engines?.node
|
|
87
|
+
if (typeof range === 'string' && !satisfiesRange(nodeVersion, range)) {
|
|
88
|
+
return `目标版本要求 Node ${range},当前是 ${nodeVersion};重启后会起不来,已取消`
|
|
89
|
+
}
|
|
90
|
+
return null
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 上一次成功安装的记录。`applied` 说明新版本是否真的成了当前运行的版本。
|
|
95
|
+
* @param {string} file - 记录文件。
|
|
96
|
+
* @param {string | undefined} runningVersion - 当前运行版本。
|
|
97
|
+
*/
|
|
98
|
+
function readLastUpdate(file, runningVersion) {
|
|
99
|
+
try {
|
|
100
|
+
const record = JSON.parse(readFileSync(file, 'utf8'))
|
|
101
|
+
if (typeof record?.to !== 'string' || record.to === '') return null
|
|
102
|
+
return {
|
|
103
|
+
from: typeof record.from === 'string' && record.from !== '' ? record.from : null,
|
|
104
|
+
to: record.to,
|
|
105
|
+
at: typeof record.at === 'string' ? record.at : null,
|
|
106
|
+
applied: runningVersion === undefined ? null : record.to === runningVersion,
|
|
107
|
+
}
|
|
108
|
+
} catch {
|
|
109
|
+
return null
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Register the Host half.
|
|
115
|
+
* @param ctx - plugin context.
|
|
116
|
+
* @param config - channel, registry, restartMode, restartCommand, restartDelayMs.
|
|
117
|
+
*/
|
|
118
|
+
export function apply(ctx, config = {}) {
|
|
119
|
+
markMounted(ctx, 'runtime')
|
|
120
|
+
const running = locateRunningPackage()
|
|
121
|
+
const startedAt = Date.now()
|
|
122
|
+
const dshHome = process.env.DSH_HOME ?? path.join(process.env.HOME ?? '', '.dsh')
|
|
123
|
+
const journalFile = path.join(dshHome, '.dsh-control', 'restarts.jsonl')
|
|
124
|
+
const updateFile = path.join(dshHome, '.dsh-control', 'last-update.json')
|
|
125
|
+
const channel = normalizeChannel(config.channel) ?? normalizeChannel(process.env.DSH_CHANNEL) ?? 'rc'
|
|
126
|
+
const restartMode = String(config.restartMode ?? 'auto')
|
|
127
|
+
const restartCommand = String(config.restartCommand ?? '')
|
|
128
|
+
const restartDelayMs = Number.isFinite(Number(config.restartDelayMs)) ? Number(config.restartDelayMs) : 800
|
|
129
|
+
const npm = new NpmRunner({ registry: config.registry, cacheDir: config.cacheDir })
|
|
130
|
+
/** Windows clients have no npm and own their process lifecycle. */
|
|
131
|
+
const updateSupported = supportsDshUpdate()
|
|
132
|
+
const restartSupported = supportsDshRestart()
|
|
133
|
+
|
|
134
|
+
/** Latest reading of the copy on disk; `null` until something asked for it. */
|
|
135
|
+
let installed = { value: running?.version ?? null, at: 0, error: null }
|
|
136
|
+
/** Outcome of the last channel check. */
|
|
137
|
+
let update = { latest: null, checkedAt: null }
|
|
138
|
+
/** What the panel shows under "recent activity". */
|
|
139
|
+
let lastAction = null
|
|
140
|
+
/** Name of the operation holding the lock, or null. */
|
|
141
|
+
let busy = null
|
|
142
|
+
/** 上一次安装留在这里;面板据此提示"没生效"并提供回撤。 */
|
|
143
|
+
let lastUpdate = readLastUpdate(updateFile, running?.version)
|
|
144
|
+
/** Set while a restart is scheduled but has not fired yet. */
|
|
145
|
+
let restartPending = false
|
|
146
|
+
|
|
147
|
+
/** What the lock holder is doing, in the panel's words. */
|
|
148
|
+
const BUSY_LABELS = { check: '检查更新', update: '安装更新' }
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Run one operation under the single-operation lock.
|
|
152
|
+
*
|
|
153
|
+
* `busy` is only what the panel shows; the ordering that matters is shared
|
|
154
|
+
* with the main row, which installs the plugin into the same profile while
|
|
155
|
+
* this row installs the harness — two installers in one node_modules end with
|
|
156
|
+
* a prefix that neither of them planned.
|
|
157
|
+
*/
|
|
158
|
+
async function exclusive(name, work) {
|
|
159
|
+
const label = BUSY_LABELS[name] ?? name
|
|
160
|
+
if (busy !== null) throw new Error(`正在${BUSY_LABELS[busy] ?? busy},等它跑完再试`)
|
|
161
|
+
return await runExclusive(label, async () => {
|
|
162
|
+
busy = name
|
|
163
|
+
try {
|
|
164
|
+
return await work()
|
|
165
|
+
} finally {
|
|
166
|
+
busy = null
|
|
167
|
+
}
|
|
168
|
+
})
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Read the on-disk version, refreshed at most once per TTL. */
|
|
172
|
+
async function installState(force = false) {
|
|
173
|
+
if (!updateSupported) return { value: running?.version ?? null, at: Date.now(), error: null }
|
|
174
|
+
if (!force && Date.now() - installed.at < INSTALLED_TTL_MS) return installed
|
|
175
|
+
try {
|
|
176
|
+
const value = await npm.installedVersion()
|
|
177
|
+
installed = { value, at: Date.now(), error: null }
|
|
178
|
+
} catch (error) {
|
|
179
|
+
installed = { value: null, at: Date.now(), error: messageOf(error) }
|
|
180
|
+
}
|
|
181
|
+
return installed
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The plan a restart would use right now. */
|
|
185
|
+
function restartPlan() {
|
|
186
|
+
return planRestart({ mode: restartMode, command: restartCommand })
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Everything the panel renders on load. */
|
|
190
|
+
async function snapshot() {
|
|
191
|
+
const disk = await installState()
|
|
192
|
+
const plan = restartPlan()
|
|
193
|
+
const current = running?.version ?? disk.value ?? null
|
|
194
|
+
const latest = update.latest
|
|
195
|
+
return {
|
|
196
|
+
runtime: {
|
|
197
|
+
version: current,
|
|
198
|
+
pid: process.pid,
|
|
199
|
+
node: process.version,
|
|
200
|
+
channel,
|
|
201
|
+
uptimeSec: Math.round((Date.now() - startedAt) / 1000),
|
|
202
|
+
uptime: duration((Date.now() - startedAt) / 1000),
|
|
203
|
+
},
|
|
204
|
+
disk: {
|
|
205
|
+
version: disk.value,
|
|
206
|
+
stale: disk.value !== null && current !== null && compare(disk.value, current) !== 0,
|
|
207
|
+
error: disk.error,
|
|
208
|
+
},
|
|
209
|
+
update: {
|
|
210
|
+
supported: updateSupported,
|
|
211
|
+
latest: updateSupported ? latest : null,
|
|
212
|
+
checkedAt: update.checkedAt,
|
|
213
|
+
available:
|
|
214
|
+
updateSupported && (latest !== null && current !== null ? compare(latest, current) > 0 : latest !== null && current === null),
|
|
215
|
+
},
|
|
216
|
+
restart: {
|
|
217
|
+
supported: restartSupported,
|
|
218
|
+
mode: restartMode,
|
|
219
|
+
strategy: plan.strategy,
|
|
220
|
+
delayMs: restartDelayMs,
|
|
221
|
+
},
|
|
222
|
+
lastUpdate,
|
|
223
|
+
lastAction,
|
|
224
|
+
busy,
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Query the registry and remember the channel maximum. */
|
|
229
|
+
async function check() {
|
|
230
|
+
if (!updateSupported) throw appError('Windows 客户端不提供 dsh 自更新,请使用客户端自身的更新入口', 'runtime-update-unsupported')
|
|
231
|
+
return await exclusive('check', async () => {
|
|
232
|
+
const at = new Date().toISOString()
|
|
233
|
+
try {
|
|
234
|
+
const versions = await npm.versions()
|
|
235
|
+
const latest = await preferred(candidatesOf(versions, channel))
|
|
236
|
+
update = { latest: latest ?? null, checkedAt: at }
|
|
237
|
+
lastAction = { kind: 'check', at, detail: update.latest }
|
|
238
|
+
return { versions: versions.length, latest: update.latest, checkedAt: at }
|
|
239
|
+
} catch (error) {
|
|
240
|
+
update = { ...update, checkedAt: at }
|
|
241
|
+
lastAction = { kind: 'check', at, detail: messageOf(error) }
|
|
242
|
+
throw error
|
|
243
|
+
}
|
|
244
|
+
})
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* 自动选版时跳过已废弃的发布:装上只会得到一条警告,还会一直被选回来。
|
|
249
|
+
* 前三名都废弃时仍取最高版,不因此卡住更新。
|
|
250
|
+
* @param {string[]} candidates - 同通道版本,新到旧。
|
|
251
|
+
*/
|
|
252
|
+
async function preferred(candidates) {
|
|
253
|
+
if (candidates.length === 0) return undefined
|
|
254
|
+
for (const candidate of candidates.slice(0, 3)) {
|
|
255
|
+
if ((await npm.deprecationOf(candidate)) === null) return candidate
|
|
256
|
+
}
|
|
257
|
+
return candidates[0]
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Install a version and optionally schedule the restart that activates it.
|
|
262
|
+
* @param {{ version?: string, restart?: boolean }} request - target version or "newest of the channel".
|
|
263
|
+
*/
|
|
264
|
+
async function upgrade(request = {}) {
|
|
265
|
+
if (!updateSupported) throw appError('Windows 客户端不提供 dsh 自更新,请使用客户端自身的更新入口', 'runtime-update-unsupported')
|
|
266
|
+
return await exclusive('update', async () => {
|
|
267
|
+
const at = new Date().toISOString()
|
|
268
|
+
let target = typeof request.version === 'string' && request.version.trim() !== '' ? request.version.trim() : null
|
|
269
|
+
if (target === null) {
|
|
270
|
+
const versions = await npm.versions()
|
|
271
|
+
target = await preferred(candidatesOf(versions, channel)) ?? null
|
|
272
|
+
if (target === null) throw new Error(`通道 ${channel} 没有匹配的版本`)
|
|
273
|
+
update = { latest: target, checkedAt: at }
|
|
274
|
+
} else {
|
|
275
|
+
// Only an exact published version is installable. A range, tag or path
|
|
276
|
+
// would make npm resolve something else than the version the user read.
|
|
277
|
+
if (!isVersionText(target)) {
|
|
278
|
+
const error = new Error(`版本号格式不正确:${target}`)
|
|
279
|
+
error.status = 400
|
|
280
|
+
error.appCode = 'version-invalid'
|
|
281
|
+
error.params = { version: target }
|
|
282
|
+
throw error
|
|
283
|
+
}
|
|
284
|
+
const versions = await npm.versions()
|
|
285
|
+
if (!versions.includes(target)) {
|
|
286
|
+
const error = new Error(`npm 上没有 ${target} 这个版本`)
|
|
287
|
+
error.status = 400
|
|
288
|
+
error.appCode = 'version-unknown'
|
|
289
|
+
error.params = { version: target }
|
|
290
|
+
throw error
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const before = (await installState(true)).value
|
|
294
|
+
if (before === target) {
|
|
295
|
+
lastAction = { kind: 'update', at, detail: `已在 ${target}`, output: '' }
|
|
296
|
+
return { target, installed: before, changed: false, restarted: false }
|
|
297
|
+
}
|
|
298
|
+
// 装错地方和装到起不来的版本,都只有在重启之后才看得出来;先问清楚。
|
|
299
|
+
const refusal = preflightUpgrade({
|
|
300
|
+
runningDir: running?.dir ?? null,
|
|
301
|
+
globalRoot: await npm.globalRoot(),
|
|
302
|
+
nodeVersion: process.versions.node,
|
|
303
|
+
engines: await npm.enginesOf(target),
|
|
304
|
+
})
|
|
305
|
+
if (refusal !== null) {
|
|
306
|
+
const error = new Error(refusal)
|
|
307
|
+
error.status = 409
|
|
308
|
+
error.appCode = 'upgrade-refused'
|
|
309
|
+
lastAction = { kind: 'update', at, detail: refusal, output: '' }
|
|
310
|
+
throw error
|
|
311
|
+
}
|
|
312
|
+
const result = await npm.install(target)
|
|
313
|
+
if (result.code !== 0 || result.installed === null) {
|
|
314
|
+
const detail = (result.stderr || result.stdout).trim() || `npm exited ${result.code}`
|
|
315
|
+
// 失败也可能改过前缀,缓存不能继续报旧数字。
|
|
316
|
+
await installState(true)
|
|
317
|
+
lastAction = { kind: 'update', at, detail, output: result.stdout }
|
|
318
|
+
throw new Error(detail)
|
|
319
|
+
}
|
|
320
|
+
if (result.installed !== target) {
|
|
321
|
+
await installState(true)
|
|
322
|
+
const detail = `npm 退出码为 0,但磁盘上是 ${result.installed},不是 ${target}`
|
|
323
|
+
lastAction = { kind: 'update', at, detail, output: result.stdout }
|
|
324
|
+
throw new Error(detail)
|
|
325
|
+
}
|
|
326
|
+
const repair = await npm.repairNativeModules()
|
|
327
|
+
await installState(true)
|
|
328
|
+
let restarted = false
|
|
329
|
+
if (request.restart === true) {
|
|
330
|
+
scheduleRestart(restartPlan(), { delayMs: restartDelayMs, journalFile, reason: `update ${target}` })
|
|
331
|
+
restartPending = true
|
|
332
|
+
restarted = true
|
|
333
|
+
}
|
|
334
|
+
lastUpdate = { from: before ?? null, to: target, at, applied: false }
|
|
335
|
+
try {
|
|
336
|
+
mkdirSync(path.dirname(updateFile), { recursive: true })
|
|
337
|
+
writeFileSync(updateFile, JSON.stringify({ from: before ?? null, to: target, at }))
|
|
338
|
+
} catch {
|
|
339
|
+
// 记录只服务于"回撤"和"没生效"提示,写不下不该让更新失败。
|
|
340
|
+
}
|
|
341
|
+
lastAction = {
|
|
342
|
+
kind: 'update',
|
|
343
|
+
at,
|
|
344
|
+
detail: `${before ?? '未知'} → ${result.installed}${restarted ? ' · 已安排重启' : ''}`,
|
|
345
|
+
output: [result.stdout.trim(), repair ?? ''].filter((part) => part !== '').join('\n').trim(),
|
|
346
|
+
}
|
|
347
|
+
return { target, installed: result.installed, changed: true, restarted, output: lastAction.output }
|
|
348
|
+
})
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Schedule a restart.
|
|
353
|
+
* @param {{ dryRun?: boolean, delayMs?: number, reason?: string }} request - plan-only or real.
|
|
354
|
+
*/
|
|
355
|
+
async function restart(request = {}) {
|
|
356
|
+
const plan = restartPlan()
|
|
357
|
+
if (request.dryRun === true) return { scheduled: false, dryRun: true, strategy: plan.strategy, reason: plan.reason }
|
|
358
|
+
if (restartPending) throw appError('重启已经在队列里', 'restart-queued')
|
|
359
|
+
// A restart during an install is the failure this lock exists to prevent.
|
|
360
|
+
const holder = busyLabel()
|
|
361
|
+
if (holder !== null) {
|
|
362
|
+
const error = new Error(`正在${holder},请等待完成后再试`)
|
|
363
|
+
error.status = 409
|
|
364
|
+
throw error
|
|
365
|
+
}
|
|
366
|
+
const delayMs = Number.isFinite(Number(request.delayMs)) && Number(request.delayMs) >= 0
|
|
367
|
+
? Number(request.delayMs)
|
|
368
|
+
: restartDelayMs
|
|
369
|
+
const ack = scheduleRestart(plan, {
|
|
370
|
+
delayMs,
|
|
371
|
+
journalFile,
|
|
372
|
+
reason: typeof request.reason === 'string' ? request.reason : 'panel',
|
|
373
|
+
})
|
|
374
|
+
restartPending = true
|
|
375
|
+
lastAction = {
|
|
376
|
+
kind: 'restart',
|
|
377
|
+
at: new Date().toISOString(),
|
|
378
|
+
detail: `${plan.strategy} · ${delayMs}ms`,
|
|
379
|
+
output: '',
|
|
380
|
+
}
|
|
381
|
+
return { ...ack, reason: plan.reason }
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
ctx.tools.register({
|
|
385
|
+
name: 'dsh_runtime_status',
|
|
386
|
+
description:
|
|
387
|
+
'Report the Harness version that is running, the version installed on disk (they differ right after an upgrade), the release channel, and the restart strategy this deployment would use.',
|
|
388
|
+
parameters: { type: 'object', additionalProperties: false, properties: {} },
|
|
389
|
+
output: {
|
|
390
|
+
schema: {
|
|
391
|
+
type: 'object',
|
|
392
|
+
additionalProperties: false,
|
|
393
|
+
required: ['version', 'channel'],
|
|
394
|
+
properties: {
|
|
395
|
+
version: { type: 'string', description: 'Version the running process loaded.' },
|
|
396
|
+
installed: { type: 'string', description: 'Version present in the global npm prefix.' },
|
|
397
|
+
channel: { type: 'string', description: 'Release channel used when picking an upgrade target.' },
|
|
398
|
+
latest: { type: 'string', description: 'Newest version of that channel, when a check has run.' },
|
|
399
|
+
updateAvailable: { type: 'boolean', description: 'Whether latest is newer than the running version.' },
|
|
400
|
+
restartStrategy: { type: 'string', description: 'execve, exit or command.' },
|
|
401
|
+
uptime: { type: 'string', description: 'How long this process has been up.' },
|
|
402
|
+
},
|
|
403
|
+
},
|
|
404
|
+
render: (_args, value) => [
|
|
405
|
+
{
|
|
406
|
+
type: 'text',
|
|
407
|
+
text: `${value.version} (channel ${value.channel}, installed ${value.installed ?? '?'}, restart ${value.restartStrategy}, up ${value.uptime})${value.latest === undefined ? '' : ` · latest ${value.latest}`}${value.updateAvailable ? ' · update available' : ''}`,
|
|
408
|
+
},
|
|
409
|
+
],
|
|
410
|
+
},
|
|
411
|
+
async execute() {
|
|
412
|
+
const state = await snapshot()
|
|
413
|
+
// Only real values: `undefined` is not lossless JSON and the tool layer
|
|
414
|
+
// refuses a payload that carries it.
|
|
415
|
+
const value = {
|
|
416
|
+
version: state.runtime.version ?? '未知',
|
|
417
|
+
channel: state.runtime.channel,
|
|
418
|
+
updateAvailable: state.update.available,
|
|
419
|
+
restartStrategy: state.restart.strategy,
|
|
420
|
+
uptime: state.runtime.uptime,
|
|
421
|
+
}
|
|
422
|
+
if (state.disk.version !== null) value.installed = state.disk.version
|
|
423
|
+
if (state.update.latest !== null) value.latest = state.update.latest
|
|
424
|
+
return value
|
|
425
|
+
},
|
|
426
|
+
})
|
|
427
|
+
|
|
428
|
+
ctx.tools.register({
|
|
429
|
+
name: 'dsh_check_update',
|
|
430
|
+
description:
|
|
431
|
+
'Ask npm for every published @deepseek-ai/dsh version and pick the newest one on the deployment channel. Reports whether it is newer than the running version. Not available in the Windows client, which has no npm.',
|
|
432
|
+
parameters: { type: 'object', additionalProperties: false, properties: {} },
|
|
433
|
+
output: {
|
|
434
|
+
schema: {
|
|
435
|
+
type: 'object',
|
|
436
|
+
additionalProperties: false,
|
|
437
|
+
required: ['channel', 'current', 'updateAvailable'],
|
|
438
|
+
properties: {
|
|
439
|
+
channel: { type: 'string', description: 'Channel queried.' },
|
|
440
|
+
current: { type: 'string', description: 'Version running now.' },
|
|
441
|
+
latest: { type: 'string', description: 'Newest version on the channel.' },
|
|
442
|
+
updateAvailable: { type: 'boolean', description: 'Whether latest is newer than current.' },
|
|
443
|
+
},
|
|
444
|
+
},
|
|
445
|
+
render: (_args, value) => [
|
|
446
|
+
{
|
|
447
|
+
type: 'text',
|
|
448
|
+
text: value.updateAvailable
|
|
449
|
+
? `${value.current} -> ${value.latest} available on ${value.channel}`
|
|
450
|
+
: `${value.current} is the newest on ${value.channel}${value.latest === undefined ? '' : ` (${value.latest})`}`,
|
|
451
|
+
},
|
|
452
|
+
],
|
|
453
|
+
},
|
|
454
|
+
async execute() {
|
|
455
|
+
const result = await check()
|
|
456
|
+
const current = running?.version ?? (await installState(true)).value ?? '未知'
|
|
457
|
+
const value = {
|
|
458
|
+
channel,
|
|
459
|
+
current,
|
|
460
|
+
updateAvailable: result.latest !== null ? compare(result.latest, current) > 0 : false,
|
|
461
|
+
}
|
|
462
|
+
if (result.latest !== null) value.latest = result.latest
|
|
463
|
+
return value
|
|
464
|
+
},
|
|
465
|
+
})
|
|
466
|
+
|
|
467
|
+
ctx.tools.register({
|
|
468
|
+
name: 'dsh_update',
|
|
469
|
+
description:
|
|
470
|
+
'Install a newer @deepseek-ai/dsh globally with npm (default: the newest version on the deployment channel), then optionally restart the process so the new code is loaded. A restart ends the current session and re-execs the Host in place. Not available in the Windows client, which has no npm.',
|
|
471
|
+
parameters: {
|
|
472
|
+
type: 'object',
|
|
473
|
+
additionalProperties: false,
|
|
474
|
+
properties: {
|
|
475
|
+
version: { type: 'string', description: 'Exact version to install; omit for the channel maximum.' },
|
|
476
|
+
restart: { type: 'boolean', description: 'Restart immediately after a successful install. Defaults to false.' },
|
|
477
|
+
},
|
|
478
|
+
},
|
|
479
|
+
output: {
|
|
480
|
+
schema: {
|
|
481
|
+
type: 'object',
|
|
482
|
+
additionalProperties: false,
|
|
483
|
+
required: ['installed', 'changed'],
|
|
484
|
+
properties: {
|
|
485
|
+
installed: { type: 'string', description: 'Version now present in the global prefix.' },
|
|
486
|
+
changed: { type: 'boolean', description: 'Whether anything was installed.' },
|
|
487
|
+
restarted: { type: 'boolean', description: 'Whether a restart was scheduled.' },
|
|
488
|
+
},
|
|
489
|
+
},
|
|
490
|
+
render: (_args, value) => [
|
|
491
|
+
{
|
|
492
|
+
type: 'text',
|
|
493
|
+
text: value.changed
|
|
494
|
+
? `installed ${value.installed}${value.restarted ? ' · restart scheduled' : ' · restart to activate'}`
|
|
495
|
+
: `${value.installed} was already installed`,
|
|
496
|
+
},
|
|
497
|
+
],
|
|
498
|
+
},
|
|
499
|
+
async execute(args) {
|
|
500
|
+
const result = await upgrade({ version: args.version, restart: args.restart === true })
|
|
501
|
+
return {
|
|
502
|
+
installed: result.installed ?? '未知',
|
|
503
|
+
changed: result.changed,
|
|
504
|
+
restarted: result.restarted ?? false,
|
|
505
|
+
}
|
|
506
|
+
},
|
|
507
|
+
})
|
|
508
|
+
|
|
509
|
+
ctx.tools.register({
|
|
510
|
+
name: 'dsh_restart',
|
|
511
|
+
description:
|
|
512
|
+
'Restart the Harness process. Re-execs it in place when this Node supports it, otherwise exits and lets the container supervisor bring it back. The current session and this tool call stop immediately; the UI reconnects afterwards. Not available in the Windows client, which owns its own process lifecycle.',
|
|
513
|
+
parameters: { type: 'object', additionalProperties: false, properties: {} },
|
|
514
|
+
output: {
|
|
515
|
+
schema: {
|
|
516
|
+
type: 'object',
|
|
517
|
+
additionalProperties: false,
|
|
518
|
+
required: ['scheduled', 'strategy'],
|
|
519
|
+
properties: {
|
|
520
|
+
scheduled: { type: 'boolean', description: 'Whether a restart was queued.' },
|
|
521
|
+
strategy: { type: 'string', description: 'execve, exit or command.' },
|
|
522
|
+
},
|
|
523
|
+
},
|
|
524
|
+
render: (_args, value) => [{ type: 'text', text: `restart scheduled (${value.strategy})` }],
|
|
525
|
+
},
|
|
526
|
+
async execute() {
|
|
527
|
+
if (!restartSupported) throw appError('Windows 客户端不支持从面板重启 dsh', 'runtime-restart-unsupported')
|
|
528
|
+
const result = await restart({ reason: 'agent tool' })
|
|
529
|
+
return { scheduled: result.scheduled === true, strategy: result.strategy }
|
|
530
|
+
},
|
|
531
|
+
})
|
|
532
|
+
|
|
533
|
+
ctx.effect(
|
|
534
|
+
() =>
|
|
535
|
+
ctx.webServer.register({
|
|
536
|
+
kind: 'prefix',
|
|
537
|
+
path: API_PATH,
|
|
538
|
+
handler: guardRoute(ctx, async (req, res) => {
|
|
539
|
+
const url = new URL(String(req.url), 'http://localhost')
|
|
540
|
+
const action = url.pathname.slice(API_PATH.length).replace(/^\/+|\/+$/g, '')
|
|
541
|
+
|
|
542
|
+
if (action === '' || action === 'state') {
|
|
543
|
+
if (req.method !== 'GET') {
|
|
544
|
+
sendJson(res, 405, { ok: false, error: 'use GET' })
|
|
545
|
+
return
|
|
546
|
+
}
|
|
547
|
+
sendJson(res, 200, { ok: true, state: await snapshot() })
|
|
548
|
+
return
|
|
549
|
+
}
|
|
550
|
+
if (req.method !== 'POST') {
|
|
551
|
+
sendJson(res, 405, { ok: false, error: 'use POST' })
|
|
552
|
+
return
|
|
553
|
+
}
|
|
554
|
+
const body = await readJsonBody(req)
|
|
555
|
+
if (action === 'check') {
|
|
556
|
+
const result = await check()
|
|
557
|
+
sendJson(res, 200, { ok: true, ...result, state: await snapshot() })
|
|
558
|
+
return
|
|
559
|
+
}
|
|
560
|
+
if (action === 'update') {
|
|
561
|
+
const result = await upgrade({ version: body.version, restart: body.restart === true })
|
|
562
|
+
sendJson(res, 200, { ok: true, ...result, state: await snapshot() })
|
|
563
|
+
return
|
|
564
|
+
}
|
|
565
|
+
if (action === 'restart') {
|
|
566
|
+
if (!restartSupported) throw appError('Windows 客户端不支持从面板重启 dsh', 'runtime-restart-unsupported')
|
|
567
|
+
const result = await restart({ dryRun: body.dryRun === true, delayMs: body.delayMs, reason: 'panel' })
|
|
568
|
+
sendJson(res, 202, { ok: true, ...result })
|
|
569
|
+
return
|
|
570
|
+
}
|
|
571
|
+
sendJson(res, 404, { ok: false, error: `unknown action "${action}"` })
|
|
572
|
+
|
|
573
|
+
}),
|
|
574
|
+
}),
|
|
575
|
+
`dsh-control: ${API_PATH}/*`,
|
|
576
|
+
)
|
|
577
|
+
}
|