dsh-aupdate 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/README.md +290 -2
- package/client.js +708 -0
- package/cordis.patch.yml +6 -0
- package/index.js +1811 -0
- package/package.json +45 -4
package/index.js
ADDED
|
@@ -0,0 +1,1811 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-aupdate
|
|
3
|
+
*
|
|
4
|
+
* 定时查询可更新的 DSH 插件 → 串行安装 → 借 hmr 服务就地换掉插件代码。全程不重启应用。
|
|
5
|
+
*
|
|
6
|
+
* 安全边界:
|
|
7
|
+
* - 只更新 registry 上的普通版本依赖;link: / file: / workspace: 一律跳过。
|
|
8
|
+
* - 安装严格串行(同一 profile 并行 pnpm 会抢锁失败)。
|
|
9
|
+
* - 热生效只用公开契约 reconcileProfile + runExclusive;服务不在就降级为「已装好,等重启」。
|
|
10
|
+
* - 有子任务在跑时不换代码(换了会把它们全部中止)。
|
|
11
|
+
* - 每个定时回调和启动项都包在 try 里:开机项抛错会让整个桌面壳退出。
|
|
12
|
+
*/
|
|
13
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
14
|
+
import { spawn } from 'node:child_process'
|
|
15
|
+
import { homedir } from 'node:os'
|
|
16
|
+
import { basename, dirname, join } from 'node:path'
|
|
17
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
18
|
+
|
|
19
|
+
export const name = 'dsh-aupdate'
|
|
20
|
+
|
|
21
|
+
const LOG_MAX_BYTES = 1_000_000
|
|
22
|
+
/** 一次查询里同时在飞的 registry 请求数。 */
|
|
23
|
+
const FETCH_CONCURRENCY = 6
|
|
24
|
+
/** 单个包安装的上限;实测最慢 1m51s。 */
|
|
25
|
+
const INSTALL_TIMEOUT_MS = 420_000
|
|
26
|
+
const RELOAD_TIMEOUT_MS = 180_000
|
|
27
|
+
/** 这些包的 dist-tags.latest 落后于 next。 */
|
|
28
|
+
const NEXT_TAG_SCOPES = ['@deepseek-ai/dsh-']
|
|
29
|
+
const NPM_NAME_RE = /^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/iu
|
|
30
|
+
/** 会话目录多久没写入才算「真的闲」。 */
|
|
31
|
+
const SESSION_IDLE_MINUTES = 2
|
|
32
|
+
/** 跨进程的安装锁:同一 profile 同时跑两个 pnpm 会抢锁失败。 */
|
|
33
|
+
const LOCK_STALE_MS = 30 * 60 * 1000
|
|
34
|
+
|
|
35
|
+
let lastRun = null
|
|
36
|
+
let running = null
|
|
37
|
+
|
|
38
|
+
function oneLine(value, limit = 2000) {
|
|
39
|
+
const text = String(value ?? '')
|
|
40
|
+
.replace(/[\r\n\u2028\u2029]+/gu, ' ')
|
|
41
|
+
.replace(/[\u0000-\u001f\u007f-\u009f]+/gu, ' ')
|
|
42
|
+
return text.length > limit ? text.slice(0, limit) + '\u2026' : text
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function logPath() {
|
|
46
|
+
const fromEnv = process.env.DSH_AUTO_UPDATE_LOG
|
|
47
|
+
if (typeof fromEnv === 'string' && fromEnv !== '') return fromEnv
|
|
48
|
+
return join(homedir(), '.dsh', 'aupdate.log')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 日志改成异步批量写。
|
|
53
|
+
*
|
|
54
|
+
* 原来每写一行都要 statSync + 判定 + appendFileSync,三个同步系统调用落在主线程上;
|
|
55
|
+
* 一轮检查会写好几行,热重载时还会跟着 apply 连写。现在只把行推进队列,
|
|
56
|
+
* 由一次 setImmediate 合批写盘,体积检查最多每 30 秒做一次。
|
|
57
|
+
* 任何一步失败都只丢日志,不影响更新逻辑本身。
|
|
58
|
+
*/
|
|
59
|
+
let logDirTried = false
|
|
60
|
+
let logQueue = []
|
|
61
|
+
let logFlushing = false
|
|
62
|
+
let logCheckedAt = 0
|
|
63
|
+
|
|
64
|
+
function flushLog() {
|
|
65
|
+
if (logQueue.length === 0) {
|
|
66
|
+
logFlushing = false
|
|
67
|
+
return
|
|
68
|
+
}
|
|
69
|
+
const payload = logQueue.join('')
|
|
70
|
+
logQueue = []
|
|
71
|
+
logFlushing = false
|
|
72
|
+
const file = logPath()
|
|
73
|
+
try {
|
|
74
|
+
if (!logDirTried) {
|
|
75
|
+
logDirTried = true
|
|
76
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
77
|
+
}
|
|
78
|
+
// 体积检查本来每行都做,现在最多 30 秒一次:日志超限不是实时需求。
|
|
79
|
+
if (Date.now() - logCheckedAt > 30000) {
|
|
80
|
+
logCheckedAt = Date.now()
|
|
81
|
+
try {
|
|
82
|
+
if (statSync(file).size > LOG_MAX_BYTES) renameSync(file, file + '.old')
|
|
83
|
+
} catch {}
|
|
84
|
+
}
|
|
85
|
+
appendFileSync(file, payload, 'utf8')
|
|
86
|
+
} catch {
|
|
87
|
+
// 落盘失败就算了,绝不能把日志问题抛进更新流程。
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function writeLog(message) {
|
|
92
|
+
try {
|
|
93
|
+
console.log('[dsh-aupdate] ' + oneLine(message, 400))
|
|
94
|
+
} catch {}
|
|
95
|
+
try {
|
|
96
|
+
logQueue.push('[' + new Date().toISOString() + '] ' + oneLine(message) + '\n')
|
|
97
|
+
// 队列异常长说明写盘一直失败,直接丢掉最老的,避免吃内存。
|
|
98
|
+
if (logQueue.length > 500) logQueue = logQueue.slice(-500)
|
|
99
|
+
if (!logFlushing) {
|
|
100
|
+
logFlushing = true
|
|
101
|
+
setImmediate(flushLog).unref?.()
|
|
102
|
+
}
|
|
103
|
+
} catch {}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 进程要退出时把队列里剩下的写完,否则最后几行会丢。 */
|
|
107
|
+
function flushLogNow() {
|
|
108
|
+
try {
|
|
109
|
+
flushLog()
|
|
110
|
+
} catch {}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 防御性读属性:Cordis 对未声明的读会抛。 */
|
|
114
|
+
function propOf(target, key) {
|
|
115
|
+
try {
|
|
116
|
+
return target?.[key]
|
|
117
|
+
} catch {
|
|
118
|
+
return undefined
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function serviceOf(ctx, key) {
|
|
123
|
+
try {
|
|
124
|
+
return (typeof ctx?.get === 'function' ? ctx.get(key) : undefined) ?? null
|
|
125
|
+
} catch {
|
|
126
|
+
return null
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function numberSetting(config, key, fallback, min, max) {
|
|
131
|
+
const raw = config?.[key]
|
|
132
|
+
const value = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : NaN
|
|
133
|
+
if (!Number.isFinite(value)) return fallback
|
|
134
|
+
return Math.min(Math.max(value, min), max)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function booleanSetting(config, key, fallback) {
|
|
138
|
+
const value = config?.[key]
|
|
139
|
+
if (value === undefined || value === null) return fallback
|
|
140
|
+
return typeof value === 'boolean' ? value : false
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function stringList(value) {
|
|
144
|
+
if (!Array.isArray(value)) return []
|
|
145
|
+
const seen = new Set()
|
|
146
|
+
const rows = []
|
|
147
|
+
for (const item of value) {
|
|
148
|
+
if (typeof item !== 'string') continue
|
|
149
|
+
// 设置页是手输的,前后空格一定有;重复项也去掉,免得白名单看起来比实际多。
|
|
150
|
+
const text = item.trim()
|
|
151
|
+
if (text === '' || seen.has(text)) continue
|
|
152
|
+
seen.add(text)
|
|
153
|
+
rows.push(text)
|
|
154
|
+
}
|
|
155
|
+
return rows
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* 设置覆盖层。
|
|
160
|
+
*
|
|
161
|
+
* 设置页是客户端代码,它没法直接改宿主的 config 对象,所以把用户改过的项写进
|
|
162
|
+
* 这个 JSON;settingsOf 读的时候叠在 config 之上。只有设置页写过的键才在文件里,
|
|
163
|
+
* 其余仍然走 config / 默认值,两边不会互相打架。
|
|
164
|
+
*
|
|
165
|
+
* 读文件带 mtime 缓存:settingsOf 每轮都会调用,不做缓存等于每轮读一次盘。
|
|
166
|
+
*/
|
|
167
|
+
function settingsPath() {
|
|
168
|
+
const fromEnv = process.env.DSH_AUPDATE_SETTINGS
|
|
169
|
+
if (typeof fromEnv === 'string' && fromEnv !== '') return fromEnv
|
|
170
|
+
return join(homedir(), '.dsh', 'aupdate-settings.json')
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const OVERRIDEABLE = [
|
|
174
|
+
'enabled', 'autoApply', 'hotReload', 'checkOnStart', 'idleOnly',
|
|
175
|
+
'intervalMinutes', 'firstDelayMinutes', 'exclude',
|
|
176
|
+
'allow', 'allowMajor', 'allowPrerelease',
|
|
177
|
+
// 调度:四种节奏 + 失败抑制时长。这些键不写进 Config schema,
|
|
178
|
+
// 只活在覆盖层里——Config 的字段类型是宿主校验的,加错一个类型
|
|
179
|
+
// 会在加载期直接抛错,而覆盖层是我们自己的文件,改坏了只影响这一项。
|
|
180
|
+
'scheduleMode', 'dailyAt', 'everyHours', 'everyDays', 'suppressHours',
|
|
181
|
+
// 效率闸门:一轮最多装几个、会话多静才算闲。
|
|
182
|
+
'maxPerCycle', 'sessionIdleMinutes',
|
|
183
|
+
]
|
|
184
|
+
|
|
185
|
+
/** 四种调度模式。minutes 是原来的「间隔 N 分钟」,其余照抄竞品。 */
|
|
186
|
+
const SCHEDULE_MODES = ['minutes', 'hours', 'days', 'daily']
|
|
187
|
+
|
|
188
|
+
/** 数值型覆盖项的边界:写坏了钳进范围,而不是让设置页把插件配废。 */
|
|
189
|
+
const NUMBER_BOUNDS = {
|
|
190
|
+
intervalMinutes: [10, 10080],
|
|
191
|
+
firstDelayMinutes: [0, 1440],
|
|
192
|
+
everyHours: [1, 168],
|
|
193
|
+
everyDays: [1, 30],
|
|
194
|
+
suppressHours: [0, 720],
|
|
195
|
+
maxPerCycle: [0, 50],
|
|
196
|
+
sessionIdleMinutes: [0, 120],
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
let overrideCache = { stamp: null, value: {} }
|
|
200
|
+
|
|
201
|
+
function readOverrides() {
|
|
202
|
+
const file = settingsPath()
|
|
203
|
+
let stamp = 'missing'
|
|
204
|
+
try {
|
|
205
|
+
const info = statSync(file)
|
|
206
|
+
stamp = info.mtimeMs + ':' + info.size
|
|
207
|
+
} catch {
|
|
208
|
+
// 文件不存在是正常状态:用户还没改过任何设置。
|
|
209
|
+
overrideCache = { stamp: 'missing', value: {} }
|
|
210
|
+
return overrideCache.value
|
|
211
|
+
}
|
|
212
|
+
if (overrideCache.stamp === stamp) return overrideCache.value
|
|
213
|
+
const raw = readJson(file)
|
|
214
|
+
const value = {}
|
|
215
|
+
if (raw !== null && typeof raw === 'object') {
|
|
216
|
+
for (const key of OVERRIDEABLE) {
|
|
217
|
+
if (raw[key] !== undefined) value[key] = raw[key]
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
overrideCache = { stamp, value }
|
|
221
|
+
return value
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* 只落盘校验过的字段:设置页传什么都可能,写坏了下次读出来会把插件配废。
|
|
226
|
+
*/
|
|
227
|
+
function writeOverrides(patch) {
|
|
228
|
+
const current = { ...readOverrides() }
|
|
229
|
+
const next = { ...current }
|
|
230
|
+
for (const key of OVERRIDEABLE) {
|
|
231
|
+
if (patch === null || typeof patch !== 'object' || patch[key] === undefined) continue
|
|
232
|
+
const raw = patch[key]
|
|
233
|
+
if (key === 'exclude' || key === 'allow') {
|
|
234
|
+
next[key] = stringList(raw)
|
|
235
|
+
continue
|
|
236
|
+
}
|
|
237
|
+
if (key === 'dailyAt') {
|
|
238
|
+
const text = typeof raw === 'string' ? raw.trim() : ''
|
|
239
|
+
if (!/^([01]?\d|2[0-3]):([0-5]\d)$/u.test(text)) continue
|
|
240
|
+
const [hour, minute] = text.split(':')
|
|
241
|
+
next[key] = String(hour).padStart(2, '0') + ':' + minute
|
|
242
|
+
continue
|
|
243
|
+
}
|
|
244
|
+
if (key === 'scheduleMode') {
|
|
245
|
+
const text = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
|
|
246
|
+
if (SCHEDULE_MODES.includes(text)) next[key] = text
|
|
247
|
+
continue
|
|
248
|
+
}
|
|
249
|
+
const bounds = NUMBER_BOUNDS[key]
|
|
250
|
+
if (bounds !== undefined) {
|
|
251
|
+
const value = typeof raw === 'number' ? raw : Number(raw)
|
|
252
|
+
if (!Number.isFinite(value)) continue
|
|
253
|
+
next[key] = Math.min(Math.max(Math.round(value), bounds[0]), bounds[1])
|
|
254
|
+
continue
|
|
255
|
+
}
|
|
256
|
+
if (typeof raw === 'boolean') next[key] = raw
|
|
257
|
+
else if (raw === 'true' || raw === 'false') next[key] = raw === 'true'
|
|
258
|
+
}
|
|
259
|
+
const file = settingsPath()
|
|
260
|
+
try {
|
|
261
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
262
|
+
writeFileSync(file, JSON.stringify(next, null, 2) + '\n', 'utf8')
|
|
263
|
+
} catch (error) {
|
|
264
|
+
return { ok: false, error: oneLine(error?.message ?? error, 200) }
|
|
265
|
+
}
|
|
266
|
+
// 缓存立刻跟上,否则这一轮读到的还是旧值。
|
|
267
|
+
overrideCache = { stamp: null, value: {} }
|
|
268
|
+
return { ok: true, value: next }
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** 只接受四种已知模式,写错了退回 minutes,绝不让调度器拿到一个不认识的字符串。 */
|
|
272
|
+
function scheduleModeOf(config) {
|
|
273
|
+
const raw = config?.scheduleMode
|
|
274
|
+
const value = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
|
|
275
|
+
return SCHEDULE_MODES.includes(value) ? value : 'minutes'
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* HH:MM 时钟。故意不接受秒、不接受 12 小时制、不接受 25:00:
|
|
280
|
+
* 一个写错的时刻会让「每天几点」永远不触发,而用户不会去看日志。
|
|
281
|
+
*/
|
|
282
|
+
function clockOf(config, key, fallback) {
|
|
283
|
+
const raw = config?.[key]
|
|
284
|
+
const text = typeof raw === 'string' ? raw.trim() : ''
|
|
285
|
+
const matched = /^([01]?\d|2[0-3]):([0-5]\d)$/u.exec(text)
|
|
286
|
+
if (matched === null) return fallback
|
|
287
|
+
return String(matched[1]).padStart(2, '0') + ':' + matched[2]
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* 这一轮跑完之后,隔多少分钟再跑。
|
|
292
|
+
*
|
|
293
|
+
* 竞品 niubi 的四种调度模式确实有用:有人想「每天凌晨三点跑一次」,
|
|
294
|
+
* 有人想「每 6 小时」。但定时器本身仍然是「跑完再排下一次」——
|
|
295
|
+
* 不是 setInterval 对齐到墙钟,因为一轮检查可能跑几分钟,
|
|
296
|
+
* 对齐反而会让两次执行重叠。所以这里返回的是「从现在起多久」。
|
|
297
|
+
*/
|
|
298
|
+
function nextDelayMinutes(live, now) {
|
|
299
|
+
switch (live.scheduleMode) {
|
|
300
|
+
case 'hours':
|
|
301
|
+
return live.everyHours * 60
|
|
302
|
+
case 'days':
|
|
303
|
+
return live.everyDays * 24 * 60
|
|
304
|
+
case 'daily': {
|
|
305
|
+
// 算出下一个 HH:MM 还有多久;刚好过点就顺延到明天,不留 0 分钟的空转。
|
|
306
|
+
const [hour, minute] = live.dailyAt.split(':').map(Number)
|
|
307
|
+
const target = new Date(now.getTime())
|
|
308
|
+
target.setHours(hour, minute, 0, 0)
|
|
309
|
+
let wait = target.getTime() - now.getTime()
|
|
310
|
+
if (wait <= 0) wait += 24 * 60 * 60 * 1000
|
|
311
|
+
return Math.round(wait / 60000)
|
|
312
|
+
}
|
|
313
|
+
default:
|
|
314
|
+
return live.intervalMinutes
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function settingsOf(config) {
|
|
319
|
+
const overrides = readOverrides()
|
|
320
|
+
const merged = { ...(config !== null && typeof config === 'object' ? config : {}), ...overrides }
|
|
321
|
+
config = merged
|
|
322
|
+
return {
|
|
323
|
+
enabled: booleanSetting(config, 'enabled', true),
|
|
324
|
+
autoApply: booleanSetting(config, 'autoApply', true),
|
|
325
|
+
hotReload: booleanSetting(config, 'hotReload', true),
|
|
326
|
+
checkOnStart: booleanSetting(config, 'checkOnStart', true),
|
|
327
|
+
idleOnly: booleanSetting(config, 'idleOnly', true),
|
|
328
|
+
intervalMinutes: numberSetting(config, 'intervalMinutes', 1440, 10, 10080),
|
|
329
|
+
firstDelayMinutes: numberSetting(config, 'firstDelayMinutes', 5, 0, 1440),
|
|
330
|
+
exclude: stringList(config?.exclude),
|
|
331
|
+
allow: stringList(config?.allow),
|
|
332
|
+
// 默认允许跨大版本:这些都是 0.x 插件,按 semver 卡大版本等于几乎不更新。
|
|
333
|
+
allowMajor: booleanSetting(config, 'allowMajor', true),
|
|
334
|
+
// 默认不装预发布。注意:走 next 标签的包(@deepseek-ai/dsh-*)是显式选择,
|
|
335
|
+
// 不受这一条限制,否则 DSH 本体永远停在旧版本上。
|
|
336
|
+
allowPrerelease: booleanSetting(config, 'allowPrerelease', false),
|
|
337
|
+
// 调度模式:intervalMinutes 只在 minutes 模式下生效,
|
|
338
|
+
// 其余三种各有自己的参数,切模式不丢原来的值。
|
|
339
|
+
scheduleMode: scheduleModeOf(config),
|
|
340
|
+
dailyAt: clockOf(config, 'dailyAt', '03:00'),
|
|
341
|
+
everyHours: numberSetting(config, 'everyHours', 6, 1, 168),
|
|
342
|
+
everyDays: numberSetting(config, 'everyDays', 1, 1, 30),
|
|
343
|
+
// 装失败的 pkg@版本 在这么多小时内不再重试。0 = 不抑制,每轮都试。
|
|
344
|
+
suppressHours: numberSetting(config, 'suppressHours', 6, 0, 720),
|
|
345
|
+
// 一轮最多装几个。0 = 不限(保持原有行为)。
|
|
346
|
+
// 装包会一直占着 pnpm 锁,20 个包连着装能把 profile 占住几十分钟;
|
|
347
|
+
// 限一个数就把单次占用封顶,剩下的下一轮再来。
|
|
348
|
+
maxPerCycle: numberSetting(config, 'maxPerCycle', 0, 0, 50),
|
|
349
|
+
// 会话目录多少分钟内没有写入才算「闲」。0 = 不看会话写入,只看子任务。
|
|
350
|
+
sessionIdleMinutes: numberSetting(config, 'sessionIdleMinutes', SESSION_IDLE_MINUTES, 0, 120),
|
|
351
|
+
// 说明:这两个键不进 Config schema(见 OVERRIDEABLE 上的注释),
|
|
352
|
+
// 所以只能通过设置页/覆盖层改,改坏了不会影响插件加载。
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const FIELDS = {
|
|
357
|
+
enabled: { type: 'boolean', meta: { default: true, description: '启用定时检查' } },
|
|
358
|
+
autoApply: { type: 'boolean', meta: { default: true, description: '发现新版本就安装' } },
|
|
359
|
+
hotReload: { type: 'boolean', meta: { default: true, description: '安装后就地生效不重启' } },
|
|
360
|
+
checkOnStart: { type: 'boolean', meta: { default: true, description: '启动后先查一次' } },
|
|
361
|
+
idleOnly: { type: 'boolean', meta: { default: true, description: '有子任务在跑时不换代码' } },
|
|
362
|
+
intervalMinutes: { type: 'number', meta: { default: 1440, description: '检查间隔(分钟)' } },
|
|
363
|
+
firstDelayMinutes: { type: 'number', meta: { default: 5, description: '启动后多久开始第一次' } },
|
|
364
|
+
exclude: { type: 'array', meta: { default: [], description: '不要自动更新的包' } },
|
|
365
|
+
allow: { type: 'array', meta: { default: [], description: '只更新这些包(留空表示全部)' } },
|
|
366
|
+
allowMajor: { type: 'boolean', meta: { default: true, description: '允许跨大版本更新' } },
|
|
367
|
+
allowPrerelease: { type: 'boolean', meta: { default: false, description: '允许安装预发布版本' } },
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const DICT = {
|
|
371
|
+
enabled: 1, autoApply: 2, hotReload: 3, checkOnStart: 4, idleOnly: 5,
|
|
372
|
+
intervalMinutes: 6, firstDelayMinutes: 7, exclude: 8,
|
|
373
|
+
allow: 11, allowMajor: 12, allowPrerelease: 13,
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export const Config = {
|
|
377
|
+
uid: 9,
|
|
378
|
+
refs: {
|
|
379
|
+
1: FIELDS.enabled,
|
|
380
|
+
2: FIELDS.autoApply,
|
|
381
|
+
3: FIELDS.hotReload,
|
|
382
|
+
4: FIELDS.checkOnStart,
|
|
383
|
+
5: FIELDS.idleOnly,
|
|
384
|
+
6: FIELDS.intervalMinutes,
|
|
385
|
+
7: FIELDS.firstDelayMinutes,
|
|
386
|
+
8: FIELDS.exclude,
|
|
387
|
+
11: FIELDS.allow,
|
|
388
|
+
12: FIELDS.allowMajor,
|
|
389
|
+
13: FIELDS.allowPrerelease,
|
|
390
|
+
10: { type: 'object', meta: { default: {} }, dict: DICT },
|
|
391
|
+
},
|
|
392
|
+
type: 'object',
|
|
393
|
+
dict: FIELDS,
|
|
394
|
+
meta: { default: {} },
|
|
395
|
+
toJSON() {
|
|
396
|
+
return { uid: 9, refs: Config.refs }
|
|
397
|
+
},
|
|
398
|
+
'~standard': {
|
|
399
|
+
version: 1,
|
|
400
|
+
vendor: 'dsh-aupdate',
|
|
401
|
+
validate(value) {
|
|
402
|
+
const source = value !== null && typeof value === 'object' ? value : {}
|
|
403
|
+
return { value: { ...source, ...settingsOf(source) } }
|
|
404
|
+
},
|
|
405
|
+
},
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* 更新历史。
|
|
410
|
+
*
|
|
411
|
+
* 竞品里 publieople 的「动手前快照、随时回滚」和 chendaleiQ 的「更新记录:谁、从哪个版本、
|
|
412
|
+
* 到哪个版本、什么时候、成没成」都是同一件事的两面:出问题时人得知道刚才动了什么。
|
|
413
|
+
* 这里把两者并起来——每成功装上一个包就留一条,带上旧版本,回滚就靠它。
|
|
414
|
+
*/
|
|
415
|
+
const HISTORY_MAX = 200
|
|
416
|
+
|
|
417
|
+
function historyPath() {
|
|
418
|
+
return join(dirname(settingsPath()), 'aupdate-history.json')
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// 和失败表一样按 mtime+size 判新旧:这个文件也在 ~/.dsh 下跨 profile 共用,
|
|
422
|
+
// 读到一次就永久缓存会让另一个进程刚写的记录在这边看不见。
|
|
423
|
+
let historyCache = { stamp: null, value: [] }
|
|
424
|
+
|
|
425
|
+
function readHistory() {
|
|
426
|
+
const file = historyPath()
|
|
427
|
+
let stamp = 'missing'
|
|
428
|
+
try {
|
|
429
|
+
const info = statSync(file)
|
|
430
|
+
stamp = info.mtimeMs + ':' + info.size
|
|
431
|
+
} catch {
|
|
432
|
+
historyCache = { stamp: 'missing', value: [] }
|
|
433
|
+
return historyCache.value
|
|
434
|
+
}
|
|
435
|
+
if (historyCache.stamp === stamp) return historyCache.value
|
|
436
|
+
const raw = readJson(file)
|
|
437
|
+
const rows = Array.isArray(raw?.entries) ? raw.entries : []
|
|
438
|
+
historyCache = {
|
|
439
|
+
stamp,
|
|
440
|
+
value: rows.filter((row) => row !== null && typeof row === 'object'),
|
|
441
|
+
}
|
|
442
|
+
return historyCache.value
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function saveHistory(rows) {
|
|
446
|
+
const value = rows.slice(0, HISTORY_MAX)
|
|
447
|
+
try {
|
|
448
|
+
const file = historyPath()
|
|
449
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
450
|
+
writeFileSync(file, JSON.stringify({ entries: value }, null, 2) + '\n', 'utf8')
|
|
451
|
+
const info = statSync(file)
|
|
452
|
+
historyCache = { stamp: info.mtimeMs + ':' + info.size, value }
|
|
453
|
+
return true
|
|
454
|
+
} catch {
|
|
455
|
+
// 记不上历史不影响更新本身,绝不能让它把这一轮搞挂。
|
|
456
|
+
historyCache = { stamp: null, value: [] }
|
|
457
|
+
return false
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* 写一条历史。
|
|
463
|
+
*
|
|
464
|
+
* 去重抄的是 chendaleiQ:同一个包、同样的 from→to,只留最新那条。
|
|
465
|
+
* 否则「装了但磁盘上没变」这类失败每一轮都写一条,几十轮之后记录里
|
|
466
|
+
* 全是同一行,回滚时反而找不到真正要回的那个点。
|
|
467
|
+
* 注意只合并 from/to 完全相同的:1.0→1.1 和 1.0→1.2 是两件事,不能并。
|
|
468
|
+
*/
|
|
469
|
+
function appendHistory(row) {
|
|
470
|
+
const rows = readHistory().slice()
|
|
471
|
+
const duplicate = rows.findIndex((item) =>
|
|
472
|
+
item.name === row.name &&
|
|
473
|
+
item.from === row.from &&
|
|
474
|
+
item.to === row.to &&
|
|
475
|
+
item.profile === row.profile &&
|
|
476
|
+
item.rolledBack !== true &&
|
|
477
|
+
row.rolledBack !== true,
|
|
478
|
+
)
|
|
479
|
+
if (duplicate >= 0) rows.splice(duplicate, 1)
|
|
480
|
+
rows.unshift(row)
|
|
481
|
+
saveHistory(rows)
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* 失败抑制。
|
|
486
|
+
*
|
|
487
|
+
* 抄的是 publieople 的做法:装失败的 pkg@版本 记下来,短时间内不再重试。
|
|
488
|
+
* 没有这一条时,一个坏版本会让每一轮检查都去装一次、失败一次——
|
|
489
|
+
* 日志被刷满,pnpm 被占着,而结果是注定的。注意键是「包名@版本」
|
|
490
|
+
* 而不是包名:升级到新版本之后仍要重新试一次,那是新的事实。
|
|
491
|
+
*/
|
|
492
|
+
const FAILURE_MAX = 100
|
|
493
|
+
|
|
494
|
+
function failurePath() {
|
|
495
|
+
return join(dirname(settingsPath()), 'aupdate-failures.json')
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// 这个文件在 ~/.dsh 下,是所有 profile 共用的;两个进程都会写它,
|
|
499
|
+
// 所以和设置覆盖层一样按 mtime 判新旧,不能读到一次就永久缓存。
|
|
500
|
+
let failureCache = { stamp: null, value: [] }
|
|
501
|
+
|
|
502
|
+
function readFailures() {
|
|
503
|
+
const file = failurePath()
|
|
504
|
+
let stamp = 'missing'
|
|
505
|
+
try {
|
|
506
|
+
const info = statSync(file)
|
|
507
|
+
stamp = info.mtimeMs + ':' + info.size
|
|
508
|
+
} catch {
|
|
509
|
+
failureCache = { stamp: 'missing', value: [] }
|
|
510
|
+
return failureCache.value
|
|
511
|
+
}
|
|
512
|
+
if (failureCache.stamp === stamp) return failureCache.value
|
|
513
|
+
const raw = readJson(file)
|
|
514
|
+
const rows = Array.isArray(raw?.entries) ? raw.entries : []
|
|
515
|
+
failureCache = {
|
|
516
|
+
stamp,
|
|
517
|
+
value: rows.filter((row) => row !== null && typeof row === 'object' && typeof row.key === 'string'),
|
|
518
|
+
}
|
|
519
|
+
return failureCache.value
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function saveFailures(rows) {
|
|
523
|
+
const value = rows.slice(0, FAILURE_MAX)
|
|
524
|
+
try {
|
|
525
|
+
const file = failurePath()
|
|
526
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
527
|
+
writeFileSync(file, JSON.stringify({ entries: value }, null, 2) + '\n', 'utf8')
|
|
528
|
+
// 写成功后把缓存指向刚写的内容,下次读不必再解析一遍。
|
|
529
|
+
const info = statSync(file)
|
|
530
|
+
failureCache = { stamp: info.mtimeMs + ':' + info.size, value }
|
|
531
|
+
return true
|
|
532
|
+
} catch {
|
|
533
|
+
failureCache = { stamp: null, value: [] }
|
|
534
|
+
return false
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function noteFailure(pkgName, version) {
|
|
539
|
+
const key = pkgName + '@' + version
|
|
540
|
+
const rows = readFailures().filter((row) => row.key !== key)
|
|
541
|
+
rows.unshift({ key, at: new Date().toISOString() })
|
|
542
|
+
saveFailures(rows)
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function clearFailure(pkgName, version) {
|
|
546
|
+
const key = pkgName + '@' + version
|
|
547
|
+
const rows = readFailures()
|
|
548
|
+
if (!rows.some((row) => row.key === key)) return
|
|
549
|
+
saveFailures(rows.filter((row) => row.key !== key))
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** 这个 pkg@版本 是否还在抑制窗口内。suppressHours 为 0 时永不抑制。 */
|
|
553
|
+
function suppressedUntil(pkgName, version, settings, now) {
|
|
554
|
+
if (settings.suppressHours <= 0) return null
|
|
555
|
+
const key = pkgName + '@' + version
|
|
556
|
+
const row = readFailures().find((item) => item.key === key)
|
|
557
|
+
if (row === undefined) return null
|
|
558
|
+
const at = Date.parse(String(row.at ?? ''))
|
|
559
|
+
if (!Number.isFinite(at)) return null
|
|
560
|
+
const until = at + settings.suppressHours * 3600_000
|
|
561
|
+
return until > now.getTime() ? new Date(until) : null
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* 该不该从这个版本升到那个版本。
|
|
566
|
+
*
|
|
567
|
+
* 三条规则,对应竞品的三种默认值:
|
|
568
|
+
* - 预发布:默认不装(chendaleiQ 同款),但 next 标签是显式选择,不受限;
|
|
569
|
+
* - 跨大版本:默认允许。这些插件基本都是 0.x,按 semver 把 0.1 -> 0.2 当大版本卡住,
|
|
570
|
+
* 等于永远不更新(publieople 就把这类行标成「范围外」);
|
|
571
|
+
* - 降级:不装。
|
|
572
|
+
*/
|
|
573
|
+
function upgradeVerdict(target, current, tag, settings) {
|
|
574
|
+
const a = parseVersion(target)
|
|
575
|
+
const b = parseVersion(current)
|
|
576
|
+
if (a === null || b === null) return { ok: false, why: '版本号无法比较' }
|
|
577
|
+
if (compareVersions(target, current) <= 0) return { ok: false, why: '已经是最新' }
|
|
578
|
+
// parseVersion 对正式版返回的是空数组而不是 null,判空得看长度。
|
|
579
|
+
if (a.pre.length > 0 && tag !== 'next' && !settings.allowPrerelease) {
|
|
580
|
+
return { ok: false, why: '是预发布版本,未允许' }
|
|
581
|
+
}
|
|
582
|
+
// 版本段存在 core 里:core[0] 是主版本。
|
|
583
|
+
if (!settings.allowMajor && a.core[0] !== b.core[0]) {
|
|
584
|
+
return { ok: false, why: '跨大版本(' + b.core[0] + ' -> ' + a.core[0] + '),未允许' }
|
|
585
|
+
}
|
|
586
|
+
return { ok: true }
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
function parseVersion(text) {
|
|
590
|
+
const raw = String(text ?? '').trim().replace(/^v/iu, '')
|
|
591
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/u.exec(raw)
|
|
592
|
+
if (match === null) return null
|
|
593
|
+
return {
|
|
594
|
+
core: [Number(match[1]), Number(match[2]), Number(match[3])],
|
|
595
|
+
pre: match[4] === undefined ? [] : match[4].split('.'),
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
function comparePre(a, b) {
|
|
600
|
+
if (a.length === 0 && b.length === 0) return 0
|
|
601
|
+
if (a.length === 0) return 1
|
|
602
|
+
if (b.length === 0) return -1
|
|
603
|
+
for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
|
|
604
|
+
const x = a[i]
|
|
605
|
+
const y = b[i]
|
|
606
|
+
if (x === undefined) return -1
|
|
607
|
+
if (y === undefined) return 1
|
|
608
|
+
const nx = /^\d+$/u.test(x)
|
|
609
|
+
const ny = /^\d+$/u.test(y)
|
|
610
|
+
if (nx && ny) {
|
|
611
|
+
const diff = Number(x) - Number(y)
|
|
612
|
+
if (diff !== 0) return diff > 0 ? 1 : -1
|
|
613
|
+
continue
|
|
614
|
+
}
|
|
615
|
+
if (nx !== ny) return nx ? -1 : 1
|
|
616
|
+
if (x !== y) return x > y ? 1 : -1
|
|
617
|
+
}
|
|
618
|
+
return 0
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** 1 = a 更新,0 = 相同,-1 = a 更旧;解析不了返回 null。 */
|
|
622
|
+
function compareVersions(a, b) {
|
|
623
|
+
const left = parseVersion(a)
|
|
624
|
+
const right = parseVersion(b)
|
|
625
|
+
if (left === null || right === null) return null
|
|
626
|
+
for (let i = 0; i < 3; i += 1) {
|
|
627
|
+
if (left.core[i] !== right.core[i]) return left.core[i] > right.core[i] ? 1 : -1
|
|
628
|
+
}
|
|
629
|
+
return comparePre(left.pre, right.pre)
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
function distTagFor(pkgName) {
|
|
633
|
+
return NEXT_TAG_SCOPES.some((prefix) => pkgName.startsWith(prefix)) ? 'next' : 'latest'
|
|
634
|
+
}
|
|
635
|
+
function profileDirOf(ctx) {
|
|
636
|
+
const base = propOf(serviceOf(ctx, 'hmr'), 'baseDir')
|
|
637
|
+
if (typeof base === 'string' && base !== '') return base
|
|
638
|
+
return process.cwd()
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function readJson(file) {
|
|
642
|
+
try {
|
|
643
|
+
const value = JSON.parse(readFileSync(file, 'utf8'))
|
|
644
|
+
return value !== null && typeof value === 'object' ? value : null
|
|
645
|
+
} catch {
|
|
646
|
+
return null
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** 要被检查的依赖:dependencies 里非 link/file 的那些。 */
|
|
651
|
+
function dependencyList(profileDir, exclude, allow = []) {
|
|
652
|
+
const manifest = readJson(join(profileDir, 'package.json'))
|
|
653
|
+
const deps = manifest?.dependencies
|
|
654
|
+
if (deps === null || typeof deps !== 'object') return []
|
|
655
|
+
const skip = new Set(exclude)
|
|
656
|
+
// 白名单非空时就是「只更新这些」;空数组表示不启用白名单。
|
|
657
|
+
const only = new Set(allow)
|
|
658
|
+
const rows = []
|
|
659
|
+
for (const [pkgName, spec] of Object.entries(deps)) {
|
|
660
|
+
if (typeof spec !== 'string') continue
|
|
661
|
+
if (/^(link|file|workspace|portal):/iu.test(spec)) continue
|
|
662
|
+
if (!NPM_NAME_RE.test(pkgName) || skip.has(pkgName)) continue
|
|
663
|
+
if (only.size > 0 && !only.has(pkgName)) continue
|
|
664
|
+
rows.push({ name: pkgName, spec })
|
|
665
|
+
}
|
|
666
|
+
return rows
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* 已装版本带缓存。
|
|
671
|
+
*
|
|
672
|
+
* 每个依赖每轮都 readFileSync 一次 package.json,24 个包就是 24 次同步读盘,
|
|
673
|
+
* 而且这些文件在两次检查之间几乎不会变。缓存以 package.json 的 mtime+size 为键:
|
|
674
|
+
* 版本真被装上去了 mtime 必变,缓存自然失效,不会读到旧值。
|
|
675
|
+
*/
|
|
676
|
+
const versionCache = new Map()
|
|
677
|
+
|
|
678
|
+
function installedVersion(profileDir, pkgName, spec) {
|
|
679
|
+
const manifestPath = join(profileDir, 'node_modules', pkgName, 'package.json')
|
|
680
|
+
let stamp = null
|
|
681
|
+
try {
|
|
682
|
+
const info = statSync(manifestPath)
|
|
683
|
+
stamp = info.mtimeMs + ':' + info.size
|
|
684
|
+
} catch {}
|
|
685
|
+
const cacheKey = manifestPath
|
|
686
|
+
if (stamp !== null) {
|
|
687
|
+
const hit = versionCache.get(cacheKey)
|
|
688
|
+
if (hit !== undefined && hit.stamp === stamp) return hit.version
|
|
689
|
+
}
|
|
690
|
+
const manifest = readJson(manifestPath)
|
|
691
|
+
const version = manifest?.version
|
|
692
|
+
if (typeof version === 'string' && version !== '') {
|
|
693
|
+
if (stamp !== null) {
|
|
694
|
+
if (versionCache.size > 400) versionCache.clear()
|
|
695
|
+
versionCache.set(cacheKey, { stamp, version })
|
|
696
|
+
}
|
|
697
|
+
return version
|
|
698
|
+
}
|
|
699
|
+
const cleaned = String(spec ?? '').replace(/^[~^<>=]*/u, '').replace(/\s.*$/u, '')
|
|
700
|
+
return parseVersion(cleaned) === null ? null : cleaned
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* 只取 dist-tags,不取整份 packument。
|
|
705
|
+
*
|
|
706
|
+
* 原来的地址返回的是完整 packument:24 个包合计 2.88 MB,单个最大的 439 KB,
|
|
707
|
+
* 客户端只是要找 dist-tags 里那十几个字节。registry 有专门的轻量端点,
|
|
708
|
+
* 24 个包合计约 655 B —— 相差三个数量级,这是这一轮最大的浪费。
|
|
709
|
+
*/
|
|
710
|
+
const tagCache = new Map()
|
|
711
|
+
const TAG_TTL_MS = 10 * 60 * 1000
|
|
712
|
+
|
|
713
|
+
function tagCacheGet(pkgName) {
|
|
714
|
+
const hit = tagCache.get(pkgName)
|
|
715
|
+
if (hit === undefined) return null
|
|
716
|
+
if (Date.now() - hit.at > TAG_TTL_MS) {
|
|
717
|
+
tagCache.delete(pkgName)
|
|
718
|
+
return null
|
|
719
|
+
}
|
|
720
|
+
return hit.tags
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function tagCacheSet(pkgName, tags) {
|
|
724
|
+
tagCache.set(pkgName, { at: Date.now(), tags })
|
|
725
|
+
// 缓存不设上限会随着 profile 换包一直长;几百个包就够用,超出就丢最旧的。
|
|
726
|
+
if (tagCache.size > 400) {
|
|
727
|
+
const oldest = tagCache.keys().next()
|
|
728
|
+
if (!oldest.done) tagCache.delete(oldest.value)
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
async function registryTags(pkgName) {
|
|
733
|
+
const cached = tagCacheGet(pkgName)
|
|
734
|
+
if (cached !== null) return cached
|
|
735
|
+
const url = 'https://registry.npmjs.org/-/package/' + pkgName.replace('/', '%2f') + '/dist-tags'
|
|
736
|
+
const response = await fetch(url, {
|
|
737
|
+
headers: { accept: 'application/json' },
|
|
738
|
+
signal: AbortSignal.timeout(10000),
|
|
739
|
+
})
|
|
740
|
+
if (!response.ok) throw new Error('registry ' + response.status)
|
|
741
|
+
const tags = await response.json()
|
|
742
|
+
if (tags === null || typeof tags !== 'object') throw new Error('没有 dist-tags')
|
|
743
|
+
tagCacheSet(pkgName, tags)
|
|
744
|
+
return tags
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* dsh plugin 的入口:优先用宿主自己的 Electron 可执行文件加 cli.js,
|
|
748
|
+
* 不必经 cmd.exe 转一层,也就没有引号与元字符的问题。
|
|
749
|
+
*/
|
|
750
|
+
function cliRunner(exe = process.execPath) {
|
|
751
|
+
const inner = join('app.asar', 'dsh', 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'lib', 'cli.js')
|
|
752
|
+
const beside = dirname(exe)
|
|
753
|
+
// app.asar 是文件而不是目录,进不去也 stat 不到里面;看得见它本身就说明布局对,
|
|
754
|
+
// cli.js 由 Electron 自己进 asar 去读,这正是 dsh.cmd 的做法。
|
|
755
|
+
const roots = [join(beside, 'resources'), join(beside, '..', 'Resources'), beside]
|
|
756
|
+
for (const root of roots) {
|
|
757
|
+
if (!existsSync(join(root, 'app.asar'))) continue
|
|
758
|
+
return { command: exe, prefix: ['--expose-internals', join(root, inner)], env: { ELECTRON_RUN_AS_NODE: '1' } }
|
|
759
|
+
}
|
|
760
|
+
const local = process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local')
|
|
761
|
+
const base = join(local, 'Programs', 'DeepSeek Harness', 'resources', 'runtime', 'cli', 'bin')
|
|
762
|
+
for (const leaf of ['dsh.cmd', 'dsh']) {
|
|
763
|
+
const file = join(base, leaf)
|
|
764
|
+
if (!existsSync(file)) continue
|
|
765
|
+
// .cmd 必须交给 shell;直接 spawn 时 Node 会替我们补一对引号,路径里有空格就废了。
|
|
766
|
+
if (/[.]cmd$/iu.test(file)) return { command: file, prefix: [], env: {}, shell: true }
|
|
767
|
+
return { command: file, prefix: [], env: {} }
|
|
768
|
+
}
|
|
769
|
+
return null
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
function runOnce(command, args, options) {
|
|
773
|
+
return new Promise((resolvePromise) => {
|
|
774
|
+
let settled = false
|
|
775
|
+
const finish = (value) => {
|
|
776
|
+
if (settled) return
|
|
777
|
+
settled = true
|
|
778
|
+
resolvePromise(value)
|
|
779
|
+
}
|
|
780
|
+
let child = null
|
|
781
|
+
try {
|
|
782
|
+
// shell 为真时不能把参数数组交给 shell(Node 只拼接不转义,DEP0190 就是这件事),
|
|
783
|
+
// 自己按 Windows 规矩加引号拼成一条命令行再交给 shell。
|
|
784
|
+
const quote = (value) => (/[\s"]/u.test(value) ? '"' + value.replace(/"/gu, '""') + '"' : value)
|
|
785
|
+
// 整条命令行由我们拼:带空格的路径必须加引号,否则 cmd.exe 会在空格处截断。
|
|
786
|
+
const line = [command, ...args].map(quote).join(' ')
|
|
787
|
+
child = spawn(options.shell === true ? line : command, options.shell === true ? [] : args, {
|
|
788
|
+
cwd: options.cwd,
|
|
789
|
+
env: { ...process.env, ...options.env },
|
|
790
|
+
windowsHide: true,
|
|
791
|
+
shell: options.shell === true,
|
|
792
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
793
|
+
})
|
|
794
|
+
} catch (error) {
|
|
795
|
+
finish({ ok: false, output: String(error?.message ?? error) })
|
|
796
|
+
return
|
|
797
|
+
}
|
|
798
|
+
let output = ''
|
|
799
|
+
const collect = (chunk) => {
|
|
800
|
+
if (output.length < 20000) output += String(chunk)
|
|
801
|
+
}
|
|
802
|
+
child.stdout?.on('data', collect)
|
|
803
|
+
child.stderr?.on('data', collect)
|
|
804
|
+
const timer = setTimeout(() => {
|
|
805
|
+
try {
|
|
806
|
+
child.kill()
|
|
807
|
+
} catch {}
|
|
808
|
+
finish({ ok: false, output: output + ' 超时' })
|
|
809
|
+
}, options.timeoutMs)
|
|
810
|
+
timer.unref?.()
|
|
811
|
+
child.on('error', (error) => {
|
|
812
|
+
clearTimeout(timer)
|
|
813
|
+
finish({ ok: false, output: String(error?.message ?? error) })
|
|
814
|
+
})
|
|
815
|
+
child.on('close', (code) => {
|
|
816
|
+
clearTimeout(timer)
|
|
817
|
+
finish({ ok: code === 0, output })
|
|
818
|
+
})
|
|
819
|
+
})
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
async function installOne(runner, profileName, profileDir, pkgName, version) {
|
|
823
|
+
const args = [...runner.prefix, 'plugin', '--profile', profileName, 'add', pkgName + '@' + version]
|
|
824
|
+
const result = await runOnce(runner.command, args, {
|
|
825
|
+
cwd: profileDir,
|
|
826
|
+
env: { ...runner.env, CI: '1' },
|
|
827
|
+
shell: runner.shell === true,
|
|
828
|
+
timeoutMs: INSTALL_TIMEOUT_MS,
|
|
829
|
+
})
|
|
830
|
+
const tail = String(result.output ?? '').trim().split('\n').slice(-4).join(' / ')
|
|
831
|
+
if (!result.ok) return { name: pkgName, version, ok: false, detail: oneLine(tail, 600) }
|
|
832
|
+
// 命令返回 0 不等于装上了:pnpm 可能只是「已是最新」什么也没做。
|
|
833
|
+
// 回读磁盘上的真实版本,才能说这一条到底成没成。
|
|
834
|
+
versionCache.delete(join(profileDir, 'node_modules', pkgName, 'package.json'))
|
|
835
|
+
const onDisk = installedVersion(profileDir, pkgName, null)
|
|
836
|
+
if (onDisk === version) return { name: pkgName, version, ok: true, detail: oneLine(tail, 600) }
|
|
837
|
+
return {
|
|
838
|
+
name: pkgName,
|
|
839
|
+
version,
|
|
840
|
+
ok: false,
|
|
841
|
+
detail: oneLine('装上去了但磁盘上是 ' + (onDisk ?? '读不到') + ';' + tail, 600),
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
function transactionContext(service) {
|
|
845
|
+
try {
|
|
846
|
+
if (typeof service?.executing?.exit === 'function') return service.executing
|
|
847
|
+
for (const value of Object.values(service ?? {})) if (value instanceof AsyncLocalStorage) return value
|
|
848
|
+
} catch {}
|
|
849
|
+
return null
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
function isNestedTransaction(error) {
|
|
853
|
+
return /\btransactions? cannot be nested\b/iu.test(String(error?.message ?? error))
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
/**
|
|
857
|
+
* 会话目录里最近一次写入距今多少分钟;目录不存在时返回 null(未知)。
|
|
858
|
+
*
|
|
859
|
+
* 为什么还要看文件 mtime,而不是只看 agent.status:竞品 niubi 实测踩过这个坑——
|
|
860
|
+
* turn 结束后 status 可能长期停在 running。只看 status 的话,「有子任务在跑」
|
|
861
|
+
* 会变成永久成立,自动更新永远不落地,而且用户从界面上看不出原因。
|
|
862
|
+
* 文件 mtime 是磁盘事实,谁在写会话一目了然。
|
|
863
|
+
*
|
|
864
|
+
* 代价也很清楚:深遍历会 stat 很多文件,所以限深四层、逐层只 readdir 一次。
|
|
865
|
+
* 实测本机 ~/.dsh/sessions 只有 251 个文件,扫一遍是毫秒级。
|
|
866
|
+
*/
|
|
867
|
+
function sessionAgeMinutes(now, root = null) {
|
|
868
|
+
const home = typeof root === 'string' && root !== ''
|
|
869
|
+
? root
|
|
870
|
+
: (typeof process.env.DSH_HOME === 'string' && process.env.DSH_HOME !== ''
|
|
871
|
+
? process.env.DSH_HOME
|
|
872
|
+
: join(homedir(), '.dsh'))
|
|
873
|
+
const base = join(home, 'sessions')
|
|
874
|
+
let newest = 0
|
|
875
|
+
let seen = 0
|
|
876
|
+
const walk = (dir, depth) => {
|
|
877
|
+
let entries
|
|
878
|
+
try {
|
|
879
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
880
|
+
} catch {
|
|
881
|
+
return
|
|
882
|
+
}
|
|
883
|
+
for (const entry of entries) {
|
|
884
|
+
// 单个条目 stat 失败就跳过:它可能是刚被删掉的文件,也可能权限不对。
|
|
885
|
+
// 读不到就当没看见,让判断回落到其它文件;全都读不到时 seen 为 0,
|
|
886
|
+
// 返回 null 表示「不知道」,调用方据此不拦更新——宁可照常跑,
|
|
887
|
+
// 也不因为一个读不了的文件把自动更新永久停掉。
|
|
888
|
+
const full = join(dir, entry.name)
|
|
889
|
+
if (entry.isDirectory()) {
|
|
890
|
+
if (depth < 4) walk(full, depth + 1)
|
|
891
|
+
continue
|
|
892
|
+
}
|
|
893
|
+
try {
|
|
894
|
+
const info = statSync(full)
|
|
895
|
+
seen += 1
|
|
896
|
+
if (info.mtimeMs > newest) newest = info.mtimeMs
|
|
897
|
+
} catch {}
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
walk(base, 0)
|
|
901
|
+
if (seen === 0 || newest === 0) return null
|
|
902
|
+
return (now.getTime() - newest) / 60000
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/**
|
|
906
|
+
* 现在为什么不该动手(安装或换代码)。
|
|
907
|
+
*
|
|
908
|
+
* 两件事都会被「有人在用」否决,但理由不同:子任务在跑时换代码会把它中止;
|
|
909
|
+
* 会话在写说明用户正干着活,装包会占住 pnpm 并让界面变卡。
|
|
910
|
+
* 探测失败时返回空数组——宁可照常跑,也不因为读不到目录就把更新永久停掉。
|
|
911
|
+
*/
|
|
912
|
+
function activityReasons(ctx, now, idleMinutes) {
|
|
913
|
+
const reasons = []
|
|
914
|
+
const agents = runningSubagents(ctx)
|
|
915
|
+
if (agents.length > 0) reasons.push(agents.length + ' 个子任务在跑')
|
|
916
|
+
if (!(idleMinutes > 0)) return reasons
|
|
917
|
+
const age = sessionAgeMinutes(now)
|
|
918
|
+
if (age !== null && age < idleMinutes) {
|
|
919
|
+
reasons.push('会话在 ' + (age < 1 ? '不到 1' : Math.round(age)) + ' 分钟前还在写入')
|
|
920
|
+
}
|
|
921
|
+
return reasons
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
/**
|
|
925
|
+
* 跨进程的安装锁。
|
|
926
|
+
*
|
|
927
|
+
* 原来的 running 只是进程内的互斥:自己的两轮不会叠在一起,但管不了别的进程
|
|
928
|
+
* (另一个窗口、另一个 profile 的宿主、用户自己开的终端)。而 pnpm 的锁是
|
|
929
|
+
* 按 profile 目录算的,两个进程同时装就会撞 pnpm-workspace.yaml 的瞬时 EPERM。
|
|
930
|
+
* 这个文件锁把「同一 profile 同时只有一个安装」这件事落到磁盘上。
|
|
931
|
+
*
|
|
932
|
+
* 超时接管是为了不让一次崩溃永久堵住更新:锁超过 LOCK_STALE_MS 就当作没主。
|
|
933
|
+
*/
|
|
934
|
+
/** 动手前要留底的文件。这四个丢了任何一个,profile 都可能起不来。 */
|
|
935
|
+
const SNAPSHOT_FILES = ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.patch.yml']
|
|
936
|
+
/** 留最近几份。一份约 100KB,三份足够覆盖「刚才那次装坏了」。 */
|
|
937
|
+
const SNAPSHOT_KEEP = 3
|
|
938
|
+
|
|
939
|
+
function snapshotRoot() {
|
|
940
|
+
return join(dirname(settingsPath()), 'aupdate-snapshots')
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/**
|
|
944
|
+
* 动手前把 manifest 那一套拷一份。
|
|
945
|
+
*
|
|
946
|
+
* 这一条抄自 publieople 和 z460440448,但只抄一半:他们还会「还原快照并重装」,
|
|
947
|
+
* 我们不做自动还原。原因是还原 manifest 会和已经装好的 node_modules 打架——
|
|
948
|
+
* 把旧的 pnpm-lock.yaml 盖回去、再让 pnpm 重装,等于用一次更长的高风险操作
|
|
949
|
+
* 去修一次可能的失败,判错的代价比原问题还大。
|
|
950
|
+
* 所以这里只留底、记下路径、在设置页显示出来;要不要用它,人自己决定。
|
|
951
|
+
* 这也让它和已有的「按包回滚」完全不重叠:那个是「我要旧版本」,这个是「留个现场」。
|
|
952
|
+
*/
|
|
953
|
+
function snapshotProfile(profileDir, now) {
|
|
954
|
+
try {
|
|
955
|
+
const stamp = now.toISOString().replace(/[:.]/gu, '-')
|
|
956
|
+
const dir = join(snapshotRoot(), stamp)
|
|
957
|
+
mkdirSync(dir, { recursive: true })
|
|
958
|
+
const saved = []
|
|
959
|
+
for (const file of SNAPSHOT_FILES) {
|
|
960
|
+
const from = join(profileDir, file)
|
|
961
|
+
if (!existsSync(from)) continue
|
|
962
|
+
writeFileSync(join(dir, file), readFileSync(from))
|
|
963
|
+
saved.push(file)
|
|
964
|
+
}
|
|
965
|
+
if (saved.length === 0) return null
|
|
966
|
+
pruneSnapshots()
|
|
967
|
+
return { dir, files: saved }
|
|
968
|
+
} catch (error) {
|
|
969
|
+
// 留底失败不该拦住更新本身:它只是事后证据,不是前置条件。
|
|
970
|
+
writeLog('snapshot failed: ' + oneLine(error?.message ?? error, 200))
|
|
971
|
+
return null
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
function pruneSnapshots() {
|
|
976
|
+
try {
|
|
977
|
+
const root = snapshotRoot()
|
|
978
|
+
const dirs = readdirSync(root, { withFileTypes: true })
|
|
979
|
+
.filter((entry) => entry.isDirectory())
|
|
980
|
+
.map((entry) => entry.name)
|
|
981
|
+
.sort()
|
|
982
|
+
.reverse()
|
|
983
|
+
for (const stale of dirs.slice(SNAPSHOT_KEEP)) {
|
|
984
|
+
rmSync(join(root, stale), { recursive: true, force: true })
|
|
985
|
+
}
|
|
986
|
+
} catch {}
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
function profileLockPath(profileDir) {
|
|
990
|
+
return join(profileDir, '.aupdate-install.lock')
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
function lockHolder(file) {
|
|
994
|
+
try {
|
|
995
|
+
return readFileSync(file, 'utf8').trim().slice(0, 200)
|
|
996
|
+
} catch {
|
|
997
|
+
return ''
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
function takeProfileLock(profileDir, now) {
|
|
1002
|
+
const file = profileLockPath(profileDir)
|
|
1003
|
+
const stamp = process.pid + ' ' + now.toISOString()
|
|
1004
|
+
try {
|
|
1005
|
+
writeFileSync(file, stamp + '\n', { encoding: 'utf8', flag: 'wx' })
|
|
1006
|
+
return { ok: true, file }
|
|
1007
|
+
} catch (error) {
|
|
1008
|
+
if (error?.code !== 'EEXIST') return { ok: false, reason: oneLine(error?.message ?? error, 160) }
|
|
1009
|
+
}
|
|
1010
|
+
// 锁已存在:只有确认它过期(持有者崩了)才接管,否则老老实实让开。
|
|
1011
|
+
let ageMinutes = null
|
|
1012
|
+
try {
|
|
1013
|
+
ageMinutes = Math.round((now.getTime() - statSync(file).mtimeMs) / 60000)
|
|
1014
|
+
} catch {
|
|
1015
|
+
ageMinutes = null
|
|
1016
|
+
}
|
|
1017
|
+
if (ageMinutes === null || ageMinutes * 60000 <= LOCK_STALE_MS) {
|
|
1018
|
+
return {
|
|
1019
|
+
ok: false,
|
|
1020
|
+
reason: '另一个进程正在装(' + (lockHolder(file) === '' ? '看不见持有者' : lockHolder(file))
|
|
1021
|
+
+ (ageMinutes === null ? '' : ',' + ageMinutes + ' 分钟前') + ')',
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
try {
|
|
1025
|
+
unlinkSync(file)
|
|
1026
|
+
} catch {}
|
|
1027
|
+
try {
|
|
1028
|
+
writeFileSync(file, stamp + '\n', { encoding: 'utf8', flag: 'wx' })
|
|
1029
|
+
writeLog('took over a stale install lock (' + ageMinutes + ' min old)')
|
|
1030
|
+
return { ok: true, file }
|
|
1031
|
+
} catch (error) {
|
|
1032
|
+
return { ok: false, reason: '抢锁失败:' + oneLine(error?.message ?? error, 160) }
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
function releaseProfileLock(lock) {
|
|
1037
|
+
if (lock === null || lock === undefined || typeof lock.file !== 'string') return
|
|
1038
|
+
try {
|
|
1039
|
+
unlinkSync(lock.file)
|
|
1040
|
+
} catch {}
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
/** 正在跑的子任务;有它们时换代码会把它们中止。 */
|
|
1044
|
+
function runningSubagents(ctx) {
|
|
1045
|
+
try {
|
|
1046
|
+
const agents = serviceOf(ctx, 'agents')
|
|
1047
|
+
if (typeof agents?.list !== 'function' || typeof agents?.roots !== 'function') return []
|
|
1048
|
+
const list = agents.list()
|
|
1049
|
+
const roots = agents.roots()
|
|
1050
|
+
if (!Array.isArray(list) || !Array.isArray(roots)) return []
|
|
1051
|
+
const top = new Set(roots)
|
|
1052
|
+
return list
|
|
1053
|
+
.filter((agent) => agent !== null && typeof agent === 'object' && !top.has(agent) && agent.status !== 'idle')
|
|
1054
|
+
.map((agent) => String(agent.id ?? ''))
|
|
1055
|
+
} catch {
|
|
1056
|
+
return []
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
/** 现在在跑的 Loader 条目;热生效用它们判断换完之后谁没起来。 */
|
|
1061
|
+
function activeEntryIds(ctx) {
|
|
1062
|
+
try {
|
|
1063
|
+
const loader = serviceOf(ctx, 'loader')
|
|
1064
|
+
if (typeof loader?.entries !== 'function') return []
|
|
1065
|
+
const ids = []
|
|
1066
|
+
for (const entry of loader.entries()) {
|
|
1067
|
+
const id = entry?.options?.id
|
|
1068
|
+
if (typeof id === 'string' && id !== '' && entry?.fiber?.state === 2) ids.push(id)
|
|
1069
|
+
}
|
|
1070
|
+
return ids
|
|
1071
|
+
} catch {
|
|
1072
|
+
return []
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
/**
|
|
1077
|
+
* 就地换掉插件代码。只用公开契约:reconcileProfile 做换,runExclusive 排队。
|
|
1078
|
+
* 服务不在、或换的过程中抛错,都退化成「已装好,等重启」,绝不让宿主崩。
|
|
1079
|
+
*/
|
|
1080
|
+
async function hotApply(ctx, requiredBefore) {
|
|
1081
|
+
const hmr = serviceOf(ctx, 'hmr')
|
|
1082
|
+
if (hmr === null || typeof hmr.reconcileProfile !== 'function' || typeof hmr.runExclusive !== 'function') {
|
|
1083
|
+
return { status: 'unavailable', reason: '这里没有能换插件的服务,已装好但要重启才生效' }
|
|
1084
|
+
}
|
|
1085
|
+
const context = transactionContext(hmr)
|
|
1086
|
+
const baseline = requiredBefore.filter((id) => id !== name)
|
|
1087
|
+
const inside = async () => hmr.reconcileProfile(baseline)
|
|
1088
|
+
const run = () => (context === null ? hmr.runExclusive(inside) : context.exit(() => hmr.runExclusive(inside)))
|
|
1089
|
+
let timedOut = false
|
|
1090
|
+
const timeout = new Promise((resolvePromise) => {
|
|
1091
|
+
// 这个定时器被 await 着,不能 unref:一旦没有别的句柄撑着事件循环,
|
|
1092
|
+
// unref 的定时器永远不会触发,Promise.race 就永远停在那儿。
|
|
1093
|
+
setTimeout(() => {
|
|
1094
|
+
timedOut = true
|
|
1095
|
+
resolvePromise(null)
|
|
1096
|
+
}, RELOAD_TIMEOUT_MS)
|
|
1097
|
+
})
|
|
1098
|
+
try {
|
|
1099
|
+
let result = null
|
|
1100
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
1101
|
+
try {
|
|
1102
|
+
result = await Promise.race([run(), timeout])
|
|
1103
|
+
if (timedOut) return { status: 'applying', reason: '换代码还没结束,稍后再看一次' }
|
|
1104
|
+
break
|
|
1105
|
+
} catch (error) {
|
|
1106
|
+
if (isNestedTransaction(error) && attempt < 9) {
|
|
1107
|
+
await new Promise((resolvePromise) => {
|
|
1108
|
+
setTimeout(resolvePromise, 250 * (attempt + 1))
|
|
1109
|
+
})
|
|
1110
|
+
if (timedOut) return { status: 'applying', reason: '换代码还在排队,稍后再看一次' }
|
|
1111
|
+
continue
|
|
1112
|
+
}
|
|
1113
|
+
throw error
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
const warnings = Array.isArray(result?.warnings) ? result.warnings.map((item) => oneLine(item, 300)) : []
|
|
1117
|
+
const restartReason = typeof result?.restartReason === 'string' ? result.restartReason : null
|
|
1118
|
+
if (restartReason !== null) return { status: 'restart', reason: oneLine(restartReason, 400), warnings }
|
|
1119
|
+
if (warnings.length > 0) return { status: 'blocked', reason: oneLine(warnings[0], 400), warnings }
|
|
1120
|
+
return { status: 'done', reason: '插件已换好,界面没重开', warnings }
|
|
1121
|
+
} catch (error) {
|
|
1122
|
+
return { status: 'failed', reason: oneLine(error?.message ?? error, 400) }
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
function beginningRun(mode, ctxRef) {
|
|
1126
|
+
if (running !== null) return null
|
|
1127
|
+
const promise = runCycle(mode, ctxRef).finally(() => {
|
|
1128
|
+
running = null
|
|
1129
|
+
})
|
|
1130
|
+
running = promise
|
|
1131
|
+
return promise
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
async function runCycle(mode, ctxRef) {
|
|
1135
|
+
const settings = settingsOf(ctxRef.config)
|
|
1136
|
+
const report = {
|
|
1137
|
+
status: 'done',
|
|
1138
|
+
startedAt: new Date().toISOString(),
|
|
1139
|
+
mode,
|
|
1140
|
+
checked: 0,
|
|
1141
|
+
updates: [],
|
|
1142
|
+
skipped: [],
|
|
1143
|
+
installed: [],
|
|
1144
|
+
reload: null,
|
|
1145
|
+
reason: '',
|
|
1146
|
+
snapshot: '',
|
|
1147
|
+
}
|
|
1148
|
+
try {
|
|
1149
|
+
const profileDir = profileDirOf(ctxRef.ctx)
|
|
1150
|
+
const profileName = basename(profileDir)
|
|
1151
|
+
const deps = dependencyList(profileDir, settings.exclude, settings.allow)
|
|
1152
|
+
report.checked = deps.length
|
|
1153
|
+
if (deps.length === 0) {
|
|
1154
|
+
report.reason = '这个 profile 里没有可检查的依赖'
|
|
1155
|
+
return report
|
|
1156
|
+
}
|
|
1157
|
+
for (let i = 0; i < deps.length; i += FETCH_CONCURRENCY) {
|
|
1158
|
+
// 每批之间让出一次事件循环:同步读 package.json 和结果合批都在主线程上,
|
|
1159
|
+
// 一口气跑完 24 个包会让界面掉帧。setImmediate 只让一次,代价可以忽略。
|
|
1160
|
+
if (i > 0) await new Promise((settle) => setImmediate(settle))
|
|
1161
|
+
const batch = deps.slice(i, i + FETCH_CONCURRENCY)
|
|
1162
|
+
const answers = await Promise.all(batch.map(async (dep) => {
|
|
1163
|
+
const current = installedVersion(profileDir, dep.name, dep.spec)
|
|
1164
|
+
try {
|
|
1165
|
+
const tags = await registryTags(dep.name)
|
|
1166
|
+
const tag = distTagFor(dep.name)
|
|
1167
|
+
const target = typeof tags[tag] === 'string' ? tags[tag] : null
|
|
1168
|
+
if (target === null) return { name: dep.name, current, why: '没有 ' + tag + ' 标签' }
|
|
1169
|
+
if (current === null) return { name: dep.name, current, why: '读不到已装版本' }
|
|
1170
|
+
const verdict = upgradeVerdict(target, current, tag, settings)
|
|
1171
|
+
if (!verdict.ok) {
|
|
1172
|
+
// 「已经是最新」不算异常,不必出现在 skipped 里。
|
|
1173
|
+
if (verdict.why === '已经是最新') return null
|
|
1174
|
+
return { name: dep.name, current, target, why: verdict.why }
|
|
1175
|
+
}
|
|
1176
|
+
// 这个版本之前装失败过、还在抑制窗口内:这一轮不再试它。
|
|
1177
|
+
const until = suppressedUntil(dep.name, target, settings, new Date())
|
|
1178
|
+
if (until !== null) {
|
|
1179
|
+
return {
|
|
1180
|
+
name: dep.name,
|
|
1181
|
+
current,
|
|
1182
|
+
target,
|
|
1183
|
+
why: '上次安装失败,' + until.toISOString().slice(0, 16).replace('T', ' ') + ' 前不再重试',
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
return { name: dep.name, current, target, tag }
|
|
1187
|
+
} catch (error) {
|
|
1188
|
+
return { name: dep.name, current, why: '查不到:' + oneLine(error?.message ?? error, 120) }
|
|
1189
|
+
}
|
|
1190
|
+
}))
|
|
1191
|
+
for (const answer of answers) {
|
|
1192
|
+
if (answer === null) continue
|
|
1193
|
+
if (typeof answer.target === 'string') report.updates.push(answer)
|
|
1194
|
+
else report.skipped.push(answer)
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
writeLog('checked ' + report.checked + ' package(s), ' + report.updates.length + ' update(s) available')
|
|
1198
|
+
if (report.updates.length === 0) {
|
|
1199
|
+
report.reason = '没有可更新的插件'
|
|
1200
|
+
return report
|
|
1201
|
+
}
|
|
1202
|
+
// 单轮上限:装包会一直占着 pnpm 锁,一轮装 20 个能把 profile 占住几十分钟。
|
|
1203
|
+
// 超出部分留在 updates 里,下一轮接着装——「发现」和「这一轮装到哪」是两件事。
|
|
1204
|
+
const deferred = settings.maxPerCycle > 0 ? report.updates.length - settings.maxPerCycle : 0
|
|
1205
|
+
if (deferred > 0) {
|
|
1206
|
+
report.updates = report.updates.slice(0, settings.maxPerCycle)
|
|
1207
|
+
writeLog('capped this cycle at ' + settings.maxPerCycle + ', ' + deferred + ' left for next round')
|
|
1208
|
+
}
|
|
1209
|
+
if (mode === 'check' || !settings.autoApply) {
|
|
1210
|
+
report.reason = '只查不装'
|
|
1211
|
+
return report
|
|
1212
|
+
}
|
|
1213
|
+
// 空闲门槛:装包会常驻占住 pnpm 并让界面变卡,换代码会把子任务中止。
|
|
1214
|
+
// 只有 update 且真的有事可做时才检查——check 模式什么都没装,打断不了任何人。
|
|
1215
|
+
if (settings.idleOnly) {
|
|
1216
|
+
// sessionIdleMinutes=0 表示不看会话写入,只保留「有子任务在跑」这一条。
|
|
1217
|
+
const idleWindow = settings.sessionIdleMinutes
|
|
1218
|
+
const why = activityReasons(ctxRef.ctx, new Date(), idleWindow)
|
|
1219
|
+
if (why.length > 0) {
|
|
1220
|
+
report.status = 'blocked'
|
|
1221
|
+
report.reason = why.join(';') + ',这一轮不安装'
|
|
1222
|
+
writeLog('apply skipped: ' + why.join('; '))
|
|
1223
|
+
return report
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
const runner = cliRunner()
|
|
1227
|
+
if (runner === null) {
|
|
1228
|
+
report.status = 'failed'
|
|
1229
|
+
report.reason = '找不到 dsh 命令行入口,无法安装'
|
|
1230
|
+
return report
|
|
1231
|
+
}
|
|
1232
|
+
// 进程内的 running 管得住自己的两轮,管不住别的进程;pnpm 的锁是按 profile 算的。
|
|
1233
|
+
const lock = takeProfileLock(profileDir, new Date())
|
|
1234
|
+
if (!lock.ok) {
|
|
1235
|
+
report.status = 'blocked'
|
|
1236
|
+
report.reason = lock.reason
|
|
1237
|
+
writeLog('apply skipped: ' + lock.reason)
|
|
1238
|
+
return report
|
|
1239
|
+
}
|
|
1240
|
+
try {
|
|
1241
|
+
// 动手之前留个现场。装失败了至少有东西可查,而不是只剩日志。
|
|
1242
|
+
const snapshot = snapshotProfile(profileDir, new Date())
|
|
1243
|
+
if (snapshot !== null) {
|
|
1244
|
+
report.snapshot = snapshot.dir
|
|
1245
|
+
writeLog('snapshot -> ' + snapshot.dir + ' (' + snapshot.files.join(',') + ')')
|
|
1246
|
+
}
|
|
1247
|
+
return await applyUpdates(ctxRef, report, settings, runner, profileDir, profileName)
|
|
1248
|
+
} finally {
|
|
1249
|
+
releaseProfileLock(lock)
|
|
1250
|
+
}
|
|
1251
|
+
} catch (error) {
|
|
1252
|
+
report.status = 'failed'
|
|
1253
|
+
report.reason = oneLine(error?.message ?? error, 400)
|
|
1254
|
+
writeLog('cycle failed: ' + report.reason)
|
|
1255
|
+
return report
|
|
1256
|
+
} finally {
|
|
1257
|
+
report.finishedAt = new Date().toISOString()
|
|
1258
|
+
lastRun = {
|
|
1259
|
+
status: report.status,
|
|
1260
|
+
at: report.finishedAt,
|
|
1261
|
+
checked: report.checked,
|
|
1262
|
+
updates: report.updates.map((item) => item.name + ' ' + (item.current ?? '?') + ' -> ' + item.target),
|
|
1263
|
+
installed: report.installed.map((item) => item.name + '@' + item.version + (item.ok ? '' : ' 失败')),
|
|
1264
|
+
reload: report.reload?.status ?? 'none',
|
|
1265
|
+
reason: report.reason,
|
|
1266
|
+
snapshot: report.snapshot,
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
/** 真正去装的那一段;从 runCycle 里拆出来,好让锁的释放有明确的 finally。 */
|
|
1272
|
+
async function applyUpdates(ctxRef, report, settings, runner, profileDir, profileName) {
|
|
1273
|
+
// 安装与换代码。锁由外层 runCycle 持有并在 finally 里释放,
|
|
1274
|
+
// 所以这里只管把包一个个装上、最后换一次代码,不碰锁。
|
|
1275
|
+
{
|
|
1276
|
+
const requiredBefore = activeEntryIds(ctxRef.ctx)
|
|
1277
|
+
// 自身放到最后:换掉自身之后,这一轮剩下的代码就来自旧模块了。
|
|
1278
|
+
const ordered = report.updates.slice().sort((a, b) => (a.name === name ? 1 : b.name === name ? -1 : 0))
|
|
1279
|
+
for (const update of ordered) {
|
|
1280
|
+
const outcome = await installOne(runner, profileName, profileDir, update.name, update.target)
|
|
1281
|
+
report.installed.push(outcome)
|
|
1282
|
+
writeLog('install ' + update.name + '@' + update.target + ' -> ' + (outcome.ok ? 'ok' : 'failed: ' + outcome.detail))
|
|
1283
|
+
if (outcome.ok) {
|
|
1284
|
+
clearFailure(update.name, update.target)
|
|
1285
|
+
appendHistory({
|
|
1286
|
+
at: new Date().toISOString(),
|
|
1287
|
+
name: update.name,
|
|
1288
|
+
from: update.current,
|
|
1289
|
+
to: update.target,
|
|
1290
|
+
tag: update.tag,
|
|
1291
|
+
profile: profileName,
|
|
1292
|
+
rolledBack: false,
|
|
1293
|
+
})
|
|
1294
|
+
} else {
|
|
1295
|
+
// 记下失败,下一轮跳过这个版本,而不是每轮都撞一次同样的墙。
|
|
1296
|
+
noteFailure(update.name, update.target)
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
const okCount = report.installed.filter((item) => item.ok).length
|
|
1300
|
+
if (okCount === 0) {
|
|
1301
|
+
report.status = 'failed'
|
|
1302
|
+
report.reason = '一个包都没装成'
|
|
1303
|
+
return report
|
|
1304
|
+
}
|
|
1305
|
+
if (!settings.hotReload) {
|
|
1306
|
+
report.reload = { status: 'skipped', reason: '装好了,热生效是关的,重启后生效' }
|
|
1307
|
+
report.reason = '已安装 ' + okCount + ' 个,待重启'
|
|
1308
|
+
return report
|
|
1309
|
+
}
|
|
1310
|
+
// 装完之后再确认一次:安装可能耗时几分钟,期间可能有人开了子任务。
|
|
1311
|
+
// 这里只看子任务,不看会话写入——换代码不会打断正在打字的用户,
|
|
1312
|
+
// 但会因为「刚有写入」就放弃热生效,让装好的东西白等一次重启。
|
|
1313
|
+
if (settings.idleOnly && runningSubagents(ctxRef.ctx).length > 0) {
|
|
1314
|
+
report.reload = { status: 'cancelled', reason: '安装期间有子任务开跑,这一次不换代码' }
|
|
1315
|
+
report.reason = '已安装 ' + okCount + ' 个,未热生效'
|
|
1316
|
+
return report
|
|
1317
|
+
}
|
|
1318
|
+
report.reload = await hotApply(ctxRef.ctx, requiredBefore)
|
|
1319
|
+
writeLog('hot apply -> ' + report.reload.status + (report.reload.reason ? ': ' + report.reload.reason : ''))
|
|
1320
|
+
report.reason = '已安装 ' + okCount + ' 个;' + (report.reload.reason ?? '')
|
|
1321
|
+
if (report.reload.status === 'failed') report.status = 'failed'
|
|
1322
|
+
else if (report.reload.status === 'blocked' || report.reload.status === 'restart') report.status = 'partial'
|
|
1323
|
+
return report
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* 挑出可以回滚的那一条记录。
|
|
1328
|
+
*
|
|
1329
|
+
* 「哪条已经被回滚过」不靠改标志位,而是从回滚记录反推:只要存在一条更晚的
|
|
1330
|
+
* 回滚记录、把同一个包退回了这条的旧版本,这条就算用掉了。这样即使写历史失败,
|
|
1331
|
+
* 同一个操作也不可能被重放——之前用可变标志位就踩过这个坑,第二次回滚
|
|
1332
|
+
* 又摸回原始更新行,等于降级可以无限重复。
|
|
1333
|
+
*/
|
|
1334
|
+
function pickRollbackTarget(rows, entryName) {
|
|
1335
|
+
const rollbacks = rows.filter((item) => item?.tag === 'rollback')
|
|
1336
|
+
for (const item of rows) {
|
|
1337
|
+
if (item?.name !== entryName) continue
|
|
1338
|
+
if (item.tag === 'rollback') continue
|
|
1339
|
+
if (item.rolledBack === true) continue
|
|
1340
|
+
if (typeof item.from !== 'string' || typeof item.to !== 'string') continue
|
|
1341
|
+
// 只有「更晚发生的、把这个版本退回去的」回滚才算消费了这条更新。
|
|
1342
|
+
// 光看 (包名, 版本对) 会误伤:同一对版本后来又更新过一次时,
|
|
1343
|
+
// 上一次的回滚记录会把新的那条也判成已经用掉。
|
|
1344
|
+
const stamp = String(item.at ?? '')
|
|
1345
|
+
const used = rollbacks.some((rb) =>
|
|
1346
|
+
rb.name === item.name &&
|
|
1347
|
+
rb.from === item.to &&
|
|
1348
|
+
rb.to === item.from &&
|
|
1349
|
+
String(rb.at ?? '') > stamp,
|
|
1350
|
+
)
|
|
1351
|
+
if (used) continue
|
|
1352
|
+
return item
|
|
1353
|
+
}
|
|
1354
|
+
return undefined
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
/**
|
|
1358
|
+
* 回滚到某一次更新之前的版本。
|
|
1359
|
+
*
|
|
1360
|
+
* 只允许回滚「本插件自己装上去的那一次」:from 必须是历史上记下来的旧版本,
|
|
1361
|
+
* 否则就成了任意版本降级出口,风险比自动更新本身还大。
|
|
1362
|
+
*/
|
|
1363
|
+
async function rollbackOne(ctxRef, entryName) {
|
|
1364
|
+
const settings = settingsOf(ctxRef.config)
|
|
1365
|
+
const rows = readHistory()
|
|
1366
|
+
const row = pickRollbackTarget(rows, entryName)
|
|
1367
|
+
if (row === undefined) return { ok: false, reason: '没有可回滚的记录:' + entryName }
|
|
1368
|
+
const profileDir = profileDirOf(ctxRef.ctx)
|
|
1369
|
+
const profileName = basename(profileDir)
|
|
1370
|
+
const runner = cliRunner()
|
|
1371
|
+
if (runner === null) return { ok: false, reason: '找不到 dsh 命令行入口' }
|
|
1372
|
+
// 回滚也是一次 pnpm 安装,和定时轮次抢同一把 profile 锁。
|
|
1373
|
+
// 拿不到就明确告诉用户「有别的进程在装」,而不是让两个 pnpm 撞锁报 EPERM。
|
|
1374
|
+
const lock = takeProfileLock(profileDir, new Date())
|
|
1375
|
+
if (!lock.ok) return { ok: false, reason: lock.reason }
|
|
1376
|
+
let outcome
|
|
1377
|
+
try {
|
|
1378
|
+
outcome = await installOne(runner, profileName, profileDir, row.name, row.from)
|
|
1379
|
+
} finally {
|
|
1380
|
+
releaseProfileLock(lock)
|
|
1381
|
+
}
|
|
1382
|
+
writeLog('rollback ' + row.name + ' ' + row.to + ' -> ' + row.from + ' -> ' + (outcome.ok ? 'ok' : 'failed: ' + outcome.detail))
|
|
1383
|
+
if (!outcome.ok) return { ok: false, reason: outcome.detail }
|
|
1384
|
+
const next = rows.slice()
|
|
1385
|
+
next.unshift({
|
|
1386
|
+
at: new Date().toISOString(),
|
|
1387
|
+
name: row.name,
|
|
1388
|
+
from: row.to,
|
|
1389
|
+
to: row.from,
|
|
1390
|
+
tag: 'rollback',
|
|
1391
|
+
profile: profileName,
|
|
1392
|
+
rolledBack: true,
|
|
1393
|
+
})
|
|
1394
|
+
saveHistory(next)
|
|
1395
|
+
let reload = { status: 'skipped', reason: '回滚完成,重启后生效' }
|
|
1396
|
+
if (settings.hotReload) reload = await hotApply(ctxRef.ctx, [])
|
|
1397
|
+
return { ok: true, name: row.name, to: row.from, reload: reload.status }
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
function registerTool(ctx, config) {
|
|
1401
|
+
const tools = serviceOf(ctx, 'tools')
|
|
1402
|
+
if (tools === null || typeof tools.register !== 'function') return false
|
|
1403
|
+
const effect = propOf(ctx, 'effect')
|
|
1404
|
+
if (typeof effect !== 'function') return false
|
|
1405
|
+
const empty = { status: 'busy', reason: '上一轮还没跑完', checked: 0, updates: [], installed: [], reload: 'none' }
|
|
1406
|
+
try {
|
|
1407
|
+
effect.call(ctx, () => tools.register({
|
|
1408
|
+
name: 'plugin_updater',
|
|
1409
|
+
description: '查可更新的 DSH 插件,装好后就地生效不重启',
|
|
1410
|
+
parameters: {
|
|
1411
|
+
type: 'object',
|
|
1412
|
+
properties: {
|
|
1413
|
+
action: {
|
|
1414
|
+
type: 'string',
|
|
1415
|
+
enum: ['check', 'update', 'status'],
|
|
1416
|
+
description: 'check 只查;update 查并装;status 看上一次的结果',
|
|
1417
|
+
},
|
|
1418
|
+
},
|
|
1419
|
+
additionalProperties: false,
|
|
1420
|
+
},
|
|
1421
|
+
output: {
|
|
1422
|
+
presentationMeta: (_args, value) => ({ kind: 'plugin-updater', status: value?.status ?? 'done' }),
|
|
1423
|
+
schema: {
|
|
1424
|
+
type: 'object',
|
|
1425
|
+
properties: {
|
|
1426
|
+
status: { type: 'string' },
|
|
1427
|
+
reason: { type: 'string' },
|
|
1428
|
+
checked: { type: 'number' },
|
|
1429
|
+
updates: { type: 'array', items: { type: 'string' } },
|
|
1430
|
+
installed: { type: 'array', items: { type: 'string' } },
|
|
1431
|
+
skipped: { type: 'array', items: { type: 'string' } },
|
|
1432
|
+
reload: { type: 'string' },
|
|
1433
|
+
},
|
|
1434
|
+
required: ['status'],
|
|
1435
|
+
additionalProperties: false,
|
|
1436
|
+
},
|
|
1437
|
+
render: (_args, value) => [{ type: 'text', text: '插件更新 · ' + (value?.reason || value?.status || '') }],
|
|
1438
|
+
},
|
|
1439
|
+
execute: async (args) => {
|
|
1440
|
+
try {
|
|
1441
|
+
const action = args?.action === 'check' || args?.action === 'update' ? args.action : 'status'
|
|
1442
|
+
if (action === 'status') {
|
|
1443
|
+
const seen = lastRun
|
|
1444
|
+
if (seen === null) return { status: 'done', reason: '还没跑过', checked: 0, updates: [], installed: [], reload: 'none' }
|
|
1445
|
+
return {
|
|
1446
|
+
status: seen.status,
|
|
1447
|
+
reason: '上一次:' + seen.at + ';' + (seen.reason || seen.status),
|
|
1448
|
+
checked: seen.checked,
|
|
1449
|
+
updates: seen.updates,
|
|
1450
|
+
installed: seen.installed,
|
|
1451
|
+
reload: seen.reload,
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
const report = await beginningRun(action, { ctx, config })
|
|
1455
|
+
if (report === null) return empty
|
|
1456
|
+
return {
|
|
1457
|
+
status: report.status,
|
|
1458
|
+
reason: report.reason || '',
|
|
1459
|
+
checked: report.checked,
|
|
1460
|
+
updates: report.updates.map((item) => item.name + ' ' + (item.current ?? '?') + ' -> ' + item.target),
|
|
1461
|
+
installed: report.installed.map((item) => item.name + '@' + item.version + (item.ok ? '' : ' 失败')),
|
|
1462
|
+
reload: report.reload?.status ?? 'none',
|
|
1463
|
+
skipped: report.skipped.map((item) => item.name + ':' + item.why),
|
|
1464
|
+
}
|
|
1465
|
+
} catch (error) {
|
|
1466
|
+
writeLog('tool failed: ' + oneLine(error?.message ?? error, 300))
|
|
1467
|
+
return { status: 'failed', reason: '没能完成,插件状态需要核对', checked: 0, updates: [], installed: [], reload: 'none' }
|
|
1468
|
+
}
|
|
1469
|
+
},
|
|
1470
|
+
}), 'dsh-aupdate: plugin_updater')
|
|
1471
|
+
return true
|
|
1472
|
+
} catch (error) {
|
|
1473
|
+
writeLog('cannot offer the tool: ' + oneLine(error?.message ?? error, 300))
|
|
1474
|
+
return false
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
/**
|
|
1479
|
+
* 设置页的后端:一个小前缀路由。
|
|
1480
|
+
*
|
|
1481
|
+
* 客户端要读当前设置、写设置、立刻跑一次、看上次结果;这些都没法只靠 config 解决
|
|
1482
|
+
* (config 是宿主的,客户端改不到)。webServer 是插件注册 HTTP 的正式途径,
|
|
1483
|
+
* 取不到就用空实现降级 —— 没有它插件照样能自动更新,只是设置页会报告不可用。
|
|
1484
|
+
*/
|
|
1485
|
+
const ROUTE_PREFIX = '/api/dsh-aupdate'
|
|
1486
|
+
|
|
1487
|
+
function sendJson(res, status, value) {
|
|
1488
|
+
try {
|
|
1489
|
+
const body = JSON.stringify(value)
|
|
1490
|
+
res.writeHead(status, {
|
|
1491
|
+
'content-type': 'application/json; charset=utf-8',
|
|
1492
|
+
'cache-control': 'no-store',
|
|
1493
|
+
'content-length': Buffer.byteLength(body),
|
|
1494
|
+
})
|
|
1495
|
+
res.end(body)
|
|
1496
|
+
} catch {}
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
function readBody(req) {
|
|
1500
|
+
return new Promise((settle) => {
|
|
1501
|
+
let size = 0
|
|
1502
|
+
const chunks = []
|
|
1503
|
+
let done = false
|
|
1504
|
+
const finish = (value) => {
|
|
1505
|
+
if (done) return
|
|
1506
|
+
done = true
|
|
1507
|
+
settle(value)
|
|
1508
|
+
}
|
|
1509
|
+
req.on('data', (chunk) => {
|
|
1510
|
+
size += chunk.length
|
|
1511
|
+
// 设置项都很小,超过 64KB 一定是打错了,直接丢。
|
|
1512
|
+
if (size > 65536) {
|
|
1513
|
+
finish(null)
|
|
1514
|
+
try { req.destroy() } catch {}
|
|
1515
|
+
return
|
|
1516
|
+
}
|
|
1517
|
+
chunks.push(chunk)
|
|
1518
|
+
})
|
|
1519
|
+
req.on('end', () => {
|
|
1520
|
+
try {
|
|
1521
|
+
const text = Buffer.concat(chunks).toString('utf8')
|
|
1522
|
+
finish(text === '' ? {} : JSON.parse(text))
|
|
1523
|
+
} catch {
|
|
1524
|
+
finish(null)
|
|
1525
|
+
}
|
|
1526
|
+
})
|
|
1527
|
+
req.on('error', () => finish(null))
|
|
1528
|
+
// 没人发数据时别一直挂着。
|
|
1529
|
+
setTimeout(() => finish(null), 10000).unref?.()
|
|
1530
|
+
})
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
function settingsSnapshot(config, ctxRef) {
|
|
1534
|
+
const settings = settingsOf(config)
|
|
1535
|
+
return {
|
|
1536
|
+
settings,
|
|
1537
|
+
overrides: readOverrides(),
|
|
1538
|
+
lastRun: lastRun === null ? null : {
|
|
1539
|
+
status: lastRun.status,
|
|
1540
|
+
reason: lastRun.reason,
|
|
1541
|
+
at: lastRun.at,
|
|
1542
|
+
checked: lastRun.checked,
|
|
1543
|
+
updates: lastRun.updates,
|
|
1544
|
+
installed: lastRun.installed,
|
|
1545
|
+
reload: lastRun.reload,
|
|
1546
|
+
snapshot: lastRun.snapshot ?? '',
|
|
1547
|
+
},
|
|
1548
|
+
path: settingsPath(),
|
|
1549
|
+
history: readHistory().slice(0, 40),
|
|
1550
|
+
historyPath: historyPath(),
|
|
1551
|
+
// 下一轮什么时候跑:设置页把它直接显示出来,用户不用自己推算。
|
|
1552
|
+
nextInMinutes: nextDelayMinutes(settings, new Date()),
|
|
1553
|
+
// 被抑制的 pkg@版本:让人看得见「为什么这个包不更新了」。
|
|
1554
|
+
failures: readFailures().slice(0, 20).map((row) => {
|
|
1555
|
+
const at = Date.parse(String(row.at ?? ''))
|
|
1556
|
+
const until = Number.isFinite(at) && settings.suppressHours > 0
|
|
1557
|
+
? new Date(at + settings.suppressHours * 3600_000).toISOString()
|
|
1558
|
+
: null
|
|
1559
|
+
return { key: row.key, at: row.at, until: until !== null && Date.parse(until) > Date.now() ? until : null }
|
|
1560
|
+
}),
|
|
1561
|
+
failurePath: failurePath(),
|
|
1562
|
+
// 动手前留的现场:设置页把它显示出来,出问题时有地方可查。
|
|
1563
|
+
snapshotPath: snapshotRoot(),
|
|
1564
|
+
// 为什么这一轮没动手:设置页把这两个直接显示出来,用户不用翻日志猜。
|
|
1565
|
+
// 尤其 sessionIdleMinutes —— 它太短会挡住大半夜的更新,太长又不该挡,
|
|
1566
|
+
// 得让人一眼看到「现在到底算不算闲」。
|
|
1567
|
+
gate: (() => {
|
|
1568
|
+
try {
|
|
1569
|
+
const profileDir = profileDirOf(ctxRef?.ctx ?? null)
|
|
1570
|
+
const lockFile = profileLockPath(profileDir)
|
|
1571
|
+
const held = existsSync(lockFile)
|
|
1572
|
+
return {
|
|
1573
|
+
idleOnly: settings.idleOnly,
|
|
1574
|
+
sessionIdleMinutes: settings.sessionIdleMinutes,
|
|
1575
|
+
maxPerCycle: settings.maxPerCycle,
|
|
1576
|
+
sessionAgeMinutes: (() => {
|
|
1577
|
+
const age = sessionAgeMinutes(new Date())
|
|
1578
|
+
return age === null ? null : Math.round(age * 10) / 10
|
|
1579
|
+
})(),
|
|
1580
|
+
lock: held ? lockHolder(lockFile) : '',
|
|
1581
|
+
}
|
|
1582
|
+
} catch {
|
|
1583
|
+
return null
|
|
1584
|
+
}
|
|
1585
|
+
})(),
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
function registerRoutes(ctx, ctxRef) {
|
|
1590
|
+
const webServer = serviceOf(ctx, 'webServer')
|
|
1591
|
+
if (webServer === null || typeof webServer.register !== 'function') {
|
|
1592
|
+
writeLog('webServer unavailable: settings page will report it')
|
|
1593
|
+
return false
|
|
1594
|
+
}
|
|
1595
|
+
const handler = async (req, res) => {
|
|
1596
|
+
try {
|
|
1597
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
1598
|
+
const suffix = url.pathname.slice(ROUTE_PREFIX.length)
|
|
1599
|
+
const method = req.method ?? 'GET'
|
|
1600
|
+
if (method === 'GET' || method === 'HEAD') {
|
|
1601
|
+
if (suffix === '/state') {
|
|
1602
|
+
sendJson(res, 200, settingsSnapshot(ctxRef.config, ctxRef))
|
|
1603
|
+
return
|
|
1604
|
+
}
|
|
1605
|
+
sendJson(res, 404, { error: 'unknown endpoint' })
|
|
1606
|
+
return
|
|
1607
|
+
}
|
|
1608
|
+
if (method === 'POST') {
|
|
1609
|
+
if (suffix === '/state') {
|
|
1610
|
+
const body = await readBody(req)
|
|
1611
|
+
if (body === null) {
|
|
1612
|
+
sendJson(res, 400, { error: 'bad json' })
|
|
1613
|
+
return
|
|
1614
|
+
}
|
|
1615
|
+
const result = writeOverrides(body)
|
|
1616
|
+
if (!result.ok) {
|
|
1617
|
+
sendJson(res, 500, { error: result.error })
|
|
1618
|
+
return
|
|
1619
|
+
}
|
|
1620
|
+
writeLog('settings updated by page: ' + Object.keys(body).join(','))
|
|
1621
|
+
// 改完立刻按新设置重排,否则要等下一次触发才换节奏。
|
|
1622
|
+
try {
|
|
1623
|
+
if (typeof ctxRef.reschedule === 'function') ctxRef.reschedule()
|
|
1624
|
+
} catch (error) {
|
|
1625
|
+
writeLog('reschedule failed: ' + oneLine(error?.message ?? error, 200))
|
|
1626
|
+
}
|
|
1627
|
+
sendJson(res, 200, settingsSnapshot(ctxRef.config, ctxRef))
|
|
1628
|
+
return
|
|
1629
|
+
}
|
|
1630
|
+
if (suffix === '/rollback') {
|
|
1631
|
+
const body = await readBody(req)
|
|
1632
|
+
const target = typeof body?.name === 'string' ? body.name : ''
|
|
1633
|
+
if (target === '') {
|
|
1634
|
+
sendJson(res, 400, { error: 'missing name' })
|
|
1635
|
+
return
|
|
1636
|
+
}
|
|
1637
|
+
const outcome = await rollbackOne(ctxRef, target)
|
|
1638
|
+
writeLog('rollback request ' + target + ' -> ' + (outcome.ok ? 'ok' : 'failed: ' + outcome.reason))
|
|
1639
|
+
sendJson(res, outcome.ok ? 200 : 409, outcome)
|
|
1640
|
+
return
|
|
1641
|
+
}
|
|
1642
|
+
if (suffix === '/run') {
|
|
1643
|
+
const body = await readBody(req)
|
|
1644
|
+
const mode = body?.mode === 'check' ? 'check' : 'update'
|
|
1645
|
+
const report = await beginningRun(mode, ctxRef)
|
|
1646
|
+
if (report === null) {
|
|
1647
|
+
sendJson(res, 200, { started: false, reason: '已经有一轮在跑' })
|
|
1648
|
+
return
|
|
1649
|
+
}
|
|
1650
|
+
sendJson(res, 200, { started: true, status: report.status, reason: report.reason })
|
|
1651
|
+
return
|
|
1652
|
+
}
|
|
1653
|
+
sendJson(res, 404, { error: 'unknown endpoint' })
|
|
1654
|
+
return
|
|
1655
|
+
}
|
|
1656
|
+
sendJson(res, 405, { error: 'method not allowed' })
|
|
1657
|
+
} catch (error) {
|
|
1658
|
+
writeLog('route failed: ' + oneLine(error?.message ?? error, 300))
|
|
1659
|
+
try { sendJson(res, 500, { error: 'internal' }) } catch {}
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
try {
|
|
1663
|
+
const effect = propOf(ctx, 'effect')
|
|
1664
|
+
const register = () => webServer.register({ kind: 'prefix', path: ROUTE_PREFIX, handler })
|
|
1665
|
+
if (typeof effect === 'function') {
|
|
1666
|
+
effect.call(ctx, register, 'dsh-aupdate: settings routes')
|
|
1667
|
+
writeLog('settings route ready: ' + ROUTE_PREFIX)
|
|
1668
|
+
return true
|
|
1669
|
+
}
|
|
1670
|
+
register()
|
|
1671
|
+
writeLog('settings route ready (no effect scope): ' + ROUTE_PREFIX)
|
|
1672
|
+
return true
|
|
1673
|
+
} catch (error) {
|
|
1674
|
+
writeLog('cannot register settings route: ' + oneLine(error?.message ?? error, 300))
|
|
1675
|
+
return false
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
export { compareVersions, upgradeVerdict, pickRollbackTarget, readHistory, historyPath, distTagFor, cliRunner, dependencyList, installedVersion, registryTags, hotApply, runCycle, settingsOf, readOverrides, writeOverrides, takeProfileLock, releaseProfileLock, sessionAgeMinutes, activityReasons, settingsSnapshot, snapshotProfile, snapshotRoot, pruneSnapshots, nextDelayMinutes }
|
|
1680
|
+
|
|
1681
|
+
export function apply(ctx, config) {
|
|
1682
|
+
const ctxRef = { ctx, config }
|
|
1683
|
+
const settings = settingsOf(config)
|
|
1684
|
+
const timers = []
|
|
1685
|
+
|
|
1686
|
+
// 工具放在动态 inject 作用域里注册:热重载时 tools 服务可能还没就绪,
|
|
1687
|
+
// 一次性注册会静默失败且永不重试;作用域会在服务重新出现时重放。
|
|
1688
|
+
let toolService = null
|
|
1689
|
+
const offerTool = (scope) => {
|
|
1690
|
+
try {
|
|
1691
|
+
const tools = serviceOf(scope, 'tools')
|
|
1692
|
+
if (tools === null || typeof tools.register !== 'function') {
|
|
1693
|
+
writeLog('tool registered: false')
|
|
1694
|
+
return
|
|
1695
|
+
}
|
|
1696
|
+
if (toolService === tools) return
|
|
1697
|
+
toolService = tools
|
|
1698
|
+
const ok = registerTool(scope, config)
|
|
1699
|
+
writeLog('tool registered: ' + ok)
|
|
1700
|
+
} catch (error) {
|
|
1701
|
+
writeLog('tool registration threw: ' + oneLine(error?.message ?? error, 300))
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
const inject = propOf(ctx, 'inject')
|
|
1705
|
+
if (typeof inject === 'function') {
|
|
1706
|
+
try {
|
|
1707
|
+
const fiber = inject.call(ctx, ['tools'], offerTool)
|
|
1708
|
+
Promise.resolve(fiber).catch((error) => {
|
|
1709
|
+
writeLog('tool scope ended: ' + oneLine(error?.message ?? error, 300))
|
|
1710
|
+
})
|
|
1711
|
+
} catch (error) {
|
|
1712
|
+
writeLog('cannot offer the tool: ' + oneLine(error?.message ?? error, 300))
|
|
1713
|
+
offerTool(ctx)
|
|
1714
|
+
}
|
|
1715
|
+
} else {
|
|
1716
|
+
offerTool(ctx)
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
const runSafely = (mode) => {
|
|
1720
|
+
const go = async () => {
|
|
1721
|
+
try {
|
|
1722
|
+
const report = await beginningRun(mode, ctxRef)
|
|
1723
|
+
if (report !== null) writeLog('cycle ' + mode + ' -> ' + report.status + ': ' + report.reason)
|
|
1724
|
+
} catch (error) {
|
|
1725
|
+
writeLog('cycle threw: ' + oneLine(error?.message ?? error, 300))
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
void go()
|
|
1729
|
+
}
|
|
1730
|
+
|
|
1731
|
+
/**
|
|
1732
|
+
* 定时器改成「每次重排」,而不是一次性 setInterval。
|
|
1733
|
+
*
|
|
1734
|
+
* setInterval 把间隔焊死在注册那一刻:用户在设置页把间隔从 1440 分钟改成 60,
|
|
1735
|
+
* 旧定时器还会按 1440 走,等于设置没生效。现在每次触发后按当前设置重新排,
|
|
1736
|
+
* 设置页改完顺手重排一次,改完立刻按新节奏走。
|
|
1737
|
+
*
|
|
1738
|
+
* 这里不因为启动时 enabled=false 就提前 return:那样 ctxRef.reschedule 永远不会赋值,
|
|
1739
|
+
* 用户在设置页重新打开定时检查后没有任何东西能把它启动起来。调度器一律建好,
|
|
1740
|
+
* 由 scheduleNext 自己看 enabled 决定排不排。
|
|
1741
|
+
*/
|
|
1742
|
+
let scheduled = null
|
|
1743
|
+
let stopped = false
|
|
1744
|
+
let firstPending = true
|
|
1745
|
+
|
|
1746
|
+
const clearScheduled = () => {
|
|
1747
|
+
if (scheduled === null) return
|
|
1748
|
+
try {
|
|
1749
|
+
clearTimeout(scheduled)
|
|
1750
|
+
} catch {}
|
|
1751
|
+
scheduled = null
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
const scheduleNext = () => {
|
|
1755
|
+
if (stopped) return
|
|
1756
|
+
clearScheduled()
|
|
1757
|
+
const live = settingsOf(ctxRef.config)
|
|
1758
|
+
if (!live.enabled) {
|
|
1759
|
+
writeLog('settings say disabled; scheduler parked')
|
|
1760
|
+
return
|
|
1761
|
+
}
|
|
1762
|
+
// 启动后第一次仍然只看 firstDelayMinutes,之后按当前调度模式算。
|
|
1763
|
+
const minutes = firstPending && live.checkOnStart ? live.firstDelayMinutes : nextDelayMinutes(live, new Date())
|
|
1764
|
+
firstPending = false
|
|
1765
|
+
const handle = setTimeout(() => {
|
|
1766
|
+
scheduled = null
|
|
1767
|
+
runSafely('update')
|
|
1768
|
+
scheduleNext()
|
|
1769
|
+
}, Math.max(minutes, 0) * 60000)
|
|
1770
|
+
handle.unref?.()
|
|
1771
|
+
scheduled = handle
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
/** 设置页保存后调用:立即按新设置重排。 */
|
|
1775
|
+
const reschedule = () => {
|
|
1776
|
+
firstPending = false
|
|
1777
|
+
scheduleNext()
|
|
1778
|
+
}
|
|
1779
|
+
ctxRef.reschedule = reschedule
|
|
1780
|
+
|
|
1781
|
+
scheduleNext()
|
|
1782
|
+
timers.push(() => {
|
|
1783
|
+
stopped = true
|
|
1784
|
+
clearScheduled()
|
|
1785
|
+
})
|
|
1786
|
+
|
|
1787
|
+
// 设置页要能读到运行状态并改设置,所以路由最后注册、且与 enabled 无关:
|
|
1788
|
+
// 关掉定时检查之后,用户仍然要能看到这一页并把它重新打开。
|
|
1789
|
+
registerRoutes(ctx, ctxRef)
|
|
1790
|
+
if (!settings.enabled) writeLog('disabled by config; scheduler parked, settings page still live')
|
|
1791
|
+
|
|
1792
|
+
const stop = () => {
|
|
1793
|
+
for (const off of timers.splice(0)) {
|
|
1794
|
+
try {
|
|
1795
|
+
off()
|
|
1796
|
+
} catch {}
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
const on = propOf(ctx, 'on')
|
|
1800
|
+
if (typeof on === 'function') {
|
|
1801
|
+
try {
|
|
1802
|
+
on.call(ctx, 'dispose', stop)
|
|
1803
|
+
} catch {}
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
writeLog('ready: every ' + settings.intervalMinutes + ' min, autoApply=' + settings.autoApply + ', hotReload=' + settings.hotReload)
|
|
1807
|
+
}
|
|
1808
|
+
|
|
1809
|
+
|
|
1810
|
+
|
|
1811
|
+
|