@leiyi-works/dsh-auto-restart 0.3.3 → 0.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +125 -14
- package/lib/install-watchdog.ps1 +1 -1
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -76,6 +76,8 @@ const DEFAULTS = Object.freeze({
|
|
|
76
76
|
waitForIdle: true,
|
|
77
77
|
/** 重启后是否自动给被后台任务打断的会话发一条“继续”。 */
|
|
78
78
|
continueInterrupted: true,
|
|
79
|
+
/** 会话持有运行中的 job 时,安静多久才算“在等后台任务”(可被重启打断);低于这个值按“正在干活”处理。 */
|
|
80
|
+
jobWaitQuietMs: 180000,
|
|
79
81
|
/** 自动继续时发送的文本。 */
|
|
80
82
|
continueText: '继续',
|
|
81
83
|
/** 多久以内的中断记录还值得自动继续(毫秒)。 */
|
|
@@ -276,7 +278,7 @@ async function resumeInterrupted(ctx, cfg) {
|
|
|
276
278
|
mode: 'queue',
|
|
277
279
|
content: [{ type: 'text', text }],
|
|
278
280
|
clientTimeZone: 'Asia/Shanghai',
|
|
279
|
-
})
|
|
281
|
+
}, new AbortController().signal)
|
|
280
282
|
logLine('info', `已给被中断的会话发“继续”:${short}`)
|
|
281
283
|
} catch (error) {
|
|
282
284
|
logLine('warn', `给 ${short} 发“继续”失败:${String(error?.message ?? error)}`)
|
|
@@ -307,22 +309,82 @@ function ensureWatchdogFiles() {
|
|
|
307
309
|
const target = join(dataDir(), file)
|
|
308
310
|
try {
|
|
309
311
|
if (!existsSync(source)) continue
|
|
310
|
-
|
|
312
|
+
writeFileSync(target, ps1Bytes(file))
|
|
311
313
|
} catch (error) {
|
|
312
314
|
logLine('warn', `同步看门狗文件失败 ${file}: ${String(error?.message ?? error)}`)
|
|
313
315
|
}
|
|
314
316
|
}
|
|
315
317
|
}
|
|
316
318
|
|
|
319
|
+
const UTF8_BOM = Buffer.from([0xEF, 0xBB, 0xBF])
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Bytes to ship for one helper file. Windows PowerShell 5.1 decodes a BOM-less
|
|
323
|
+
* .ps1 as ANSI, which turns Chinese messages into mojibake and a parse error, so
|
|
324
|
+
* any .ps1 holding non-ASCII text gets a UTF-8 BOM. Pure-ASCII scripts are left
|
|
325
|
+
* untouched (their bytes are what the running watchdog hashes).
|
|
326
|
+
*/
|
|
327
|
+
function ps1Bytes(file) {
|
|
328
|
+
const raw = readFileSync(join(PKG_DIR, 'lib', file))
|
|
329
|
+
if (!/\.ps1$/i.test(file)) return raw
|
|
330
|
+
const hasBom = raw.length >= 3 && raw[0] === 0xEF && raw[1] === 0xBB && raw[2] === 0xBF
|
|
331
|
+
if (hasBom) return raw
|
|
332
|
+
const nonAscii = raw.some((byte) => byte > 0x7F)
|
|
333
|
+
return nonAscii ? Buffer.concat([UTF8_BOM, raw]) : raw
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Runs the boot resume once `sessionController` is available. Cordis may not have
|
|
338
|
+
* provided it yet when this plugin applies, so the optional service is looked up
|
|
339
|
+
* immediately and waited for through `inject` otherwise.
|
|
340
|
+
*/
|
|
341
|
+
function resumeWithController(ctx, cfg) {
|
|
342
|
+
let started = false
|
|
343
|
+
const run = (scoped) => {
|
|
344
|
+
if (started) return
|
|
345
|
+
started = true
|
|
346
|
+
void resumeInterrupted(scoped, cfg)
|
|
347
|
+
}
|
|
348
|
+
try {
|
|
349
|
+
if (typeof ctx.get === 'function' && ctx.get('sessionController')) {
|
|
350
|
+
run(ctx)
|
|
351
|
+
return
|
|
352
|
+
}
|
|
353
|
+
} catch {}
|
|
354
|
+
try {
|
|
355
|
+
ctx.inject(['sessionController'], (scoped) => run(scoped))
|
|
356
|
+
} catch (error) {
|
|
357
|
+
logLine('warn', `等待 sessionController 失败:${String(error?.message ?? error)}`)
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
317
361
|
/** SHA1 of the watchdog script shipped with this plugin version. */
|
|
318
362
|
function watchdogScriptHash() {
|
|
319
363
|
try {
|
|
320
|
-
return createHash('sha1').update(
|
|
364
|
+
return createHash('sha1').update(ps1Bytes('watchdog.ps1')).digest('hex')
|
|
321
365
|
} catch {
|
|
322
366
|
return ''
|
|
323
367
|
}
|
|
324
368
|
}
|
|
325
369
|
|
|
370
|
+
/**
|
|
371
|
+
* Every hash the shipped watchdog.ps1 may legitimately have on disk: one older
|
|
372
|
+
* build wrote the ASCII script with a BOM, and that process keeps reporting the
|
|
373
|
+
* BOM'd hash until it is restarted.
|
|
374
|
+
*/
|
|
375
|
+
function watchdogScriptHashes() {
|
|
376
|
+
const hashes = new Set()
|
|
377
|
+
try {
|
|
378
|
+
const raw = readFileSync(join(PKG_DIR, 'lib', 'watchdog.ps1'))
|
|
379
|
+
hashes.add(createHash('sha1').update(raw).digest('hex'))
|
|
380
|
+
hashes.add(createHash('sha1').update(Buffer.concat([UTF8_BOM, raw])).digest('hex'))
|
|
381
|
+
hashes.add(createHash('sha1').update(ps1Bytes('watchdog.ps1')).digest('hex'))
|
|
382
|
+
} catch {
|
|
383
|
+
// an unreadable package simply cannot be verified
|
|
384
|
+
}
|
|
385
|
+
return hashes
|
|
386
|
+
}
|
|
387
|
+
|
|
326
388
|
/** The watchdog's heartbeat, when it is fresh enough to be trusted. */
|
|
327
389
|
function readWatchdogHeartbeat() {
|
|
328
390
|
const parsed = readJsonFile(watchdogHeartbeatPath())
|
|
@@ -344,8 +406,10 @@ function readWatchdogHeartbeat() {
|
|
|
344
406
|
* stops it and starts the new script, so this is worth re-prompting for.
|
|
345
407
|
*/
|
|
346
408
|
function watchdogScriptStale(heartbeat) {
|
|
347
|
-
|
|
348
|
-
|
|
409
|
+
if (heartbeat === null) return false
|
|
410
|
+
const hashes = watchdogScriptHashes()
|
|
411
|
+
if (hashes.size === 0) return false
|
|
412
|
+
return heartbeat.script === '' ? true : !hashes.has(heartbeat.script)
|
|
349
413
|
}
|
|
350
414
|
|
|
351
415
|
function watchdogAlive() {
|
|
@@ -557,6 +621,7 @@ function sanitizeConfig(raw) {
|
|
|
557
621
|
cfg.enabled = bool(raw.enabled, cfg.enabled)
|
|
558
622
|
cfg.dryRun = bool(raw.dryRun, cfg.dryRun)
|
|
559
623
|
cfg.waitForIdle = bool(raw.waitForIdle, cfg.waitForIdle)
|
|
624
|
+
cfg.jobWaitQuietMs = num(raw.jobWaitQuietMs, cfg.jobWaitQuietMs, 30000, 3600000)
|
|
560
625
|
cfg.continueInterrupted = bool(raw.continueInterrupted, cfg.continueInterrupted)
|
|
561
626
|
cfg.continueWindowMs = num(raw.continueWindowMs, cfg.continueWindowMs, 60000, 86400000)
|
|
562
627
|
if (typeof raw.continueText === 'string' && raw.continueText.trim() !== '') cfg.continueText = raw.continueText.slice(0, 200)
|
|
@@ -877,6 +942,8 @@ function createState(profileDir) {
|
|
|
877
942
|
waitingSince: 0,
|
|
878
943
|
lastActivityAt: 0,
|
|
879
944
|
pendingInputIds: new Set(),
|
|
945
|
+
sessionLastEventAt: new Map(),
|
|
946
|
+
activeTools: new Map(),
|
|
880
947
|
lastRestartAt: persisted.lastRestartAt,
|
|
881
948
|
restarts: persisted.restarts.filter((t) => now - t < 3600000),
|
|
882
949
|
lastManagerAt: 0,
|
|
@@ -1004,24 +1071,32 @@ function tick(baseConfig) {
|
|
|
1004
1071
|
}
|
|
1005
1072
|
|
|
1006
1073
|
// A Session blocked on a running background job (job_*, e.g. an npm polling
|
|
1007
|
-
// loop) is
|
|
1008
|
-
//
|
|
1009
|
-
// sends one "继续" after the
|
|
1010
|
-
//
|
|
1074
|
+
// loop) is NOT counted as busy while it sits in a job_* tool call (that is
|
|
1075
|
+
// exactly "waiting for the background job"): its job dies with the Host, so
|
|
1076
|
+
// the restart interrupts it and resumeInterrupted sends one "继续" after the
|
|
1077
|
+
// new process is up. Sessions running anything else (answering, bash, edits)
|
|
1078
|
+
// still count as busy and keep the restart waiting. The silence heuristic is
|
|
1079
|
+
// only a fallback for a wait that started before this plugin loaded.
|
|
1011
1080
|
const jobBlocked = []
|
|
1012
1081
|
const hardBusy = []
|
|
1013
1082
|
for (const id of state.busy) {
|
|
1014
|
-
|
|
1015
|
-
|
|
1083
|
+
const sessionId = String(id)
|
|
1084
|
+
const hasJobs = runningJobsFor(sessionId).length > 0
|
|
1085
|
+
const active = state.activeTools instanceof Map ? state.activeTools.get(sessionId) : undefined
|
|
1086
|
+
const inJobTool = active !== undefined && /^job_/i.test(String(active.name))
|
|
1087
|
+
const lastAt = state.sessionLastEventAt instanceof Map ? (state.sessionLastEventAt.get(sessionId) ?? 0) : 0
|
|
1088
|
+
const quietMs = lastAt > 0 ? now - lastAt : Number.POSITIVE_INFINITY
|
|
1089
|
+
if (hasJobs && (inJobTool || quietMs >= cfg.jobWaitQuietMs)) jobBlocked.push(sessionId)
|
|
1090
|
+
else hardBusy.push(sessionId)
|
|
1016
1091
|
}
|
|
1017
1092
|
if (hardBusy.length > 0) {
|
|
1018
1093
|
if (state.waitingSince === 0) {
|
|
1019
1094
|
state.waitingSince = now
|
|
1020
|
-
logLine('info', `有 ${hardBusy.length}
|
|
1095
|
+
logLine('info', `有 ${hardBusy.length} 个会话正在回答/干活,等它们空闲后再重启${jobBlocked.length > 0 ? `;另外 ${jobBlocked.length} 个会话在等后台任务,重启会打断它们并在重启后发“继续”` : ''}`)
|
|
1021
1096
|
}
|
|
1022
1097
|
return
|
|
1023
1098
|
}
|
|
1024
|
-
logLine('info', `其余 ${jobBlocked.length}
|
|
1099
|
+
logLine('info', `其余 ${jobBlocked.length} 个会话都卡在后台任务工具上(job_*);本次重启会打断它们,重启后自动发“继续”`)
|
|
1025
1100
|
}
|
|
1026
1101
|
state.waitingSince = 0
|
|
1027
1102
|
|
|
@@ -1238,7 +1313,7 @@ export function apply(ctx, config) {
|
|
|
1238
1313
|
cleanForeignRequests()
|
|
1239
1314
|
bootWatchdogCheck(state)
|
|
1240
1315
|
// Sessions that a previous restart interrupted get one "继续" after boot.
|
|
1241
|
-
|
|
1316
|
+
resumeWithController(ctx, cfg)
|
|
1242
1317
|
|
|
1243
1318
|
// Track busy sessions so a restart never cuts an answer.
|
|
1244
1319
|
ctx.effect(() => ctx.on('api-session/status', (sessionId, running) => {
|
|
@@ -1246,6 +1321,7 @@ export function apply(ctx, config) {
|
|
|
1246
1321
|
if (running === false) state.busy.delete(id)
|
|
1247
1322
|
else state.busy.add(id)
|
|
1248
1323
|
state.lastActivityAt = Date.now()
|
|
1324
|
+
if (state.sessionLastEventAt instanceof Map) state.sessionLastEventAt.set(id, Date.now())
|
|
1249
1325
|
}), 'auto-restart: session status')
|
|
1250
1326
|
|
|
1251
1327
|
ctx.effect(() => ctx.on('agent/status', (payload) => {
|
|
@@ -1255,8 +1331,43 @@ export function apply(ctx, config) {
|
|
|
1255
1331
|
if (status === 'idle') state.busy.delete(String(id))
|
|
1256
1332
|
else if (ACTIVE_STATUSES.has(status)) state.busy.add(String(id))
|
|
1257
1333
|
state.lastActivityAt = Date.now()
|
|
1334
|
+
if (state.sessionLastEventAt instanceof Map) state.sessionLastEventAt.set(String(id), Date.now())
|
|
1258
1335
|
}), 'auto-restart: agent status')
|
|
1259
1336
|
|
|
1337
|
+
// Per-session activity: a Session that keeps producing events is working, so
|
|
1338
|
+
// even holding a background job it must not be interrupted.
|
|
1339
|
+
ctx.effect(() => ctx.on('session/event', (session, event) => {
|
|
1340
|
+
const id = session?.id ?? session?.sessionId ?? event?.sessionId
|
|
1341
|
+
if (id === undefined) return
|
|
1342
|
+
if (state.sessionLastEventAt instanceof Map) state.sessionLastEventAt.set(String(id), Date.now())
|
|
1343
|
+
}), 'auto-restart: session events')
|
|
1344
|
+
|
|
1345
|
+
// The exact signal for "this Session is waiting on a background job": which
|
|
1346
|
+
// tool it is executing right now. job_* calls mean the model is blocked on the
|
|
1347
|
+
// job, everything else means the Session is really working.
|
|
1348
|
+
ctx.effect(() => ctx.on('tools/execute', (exec, next) => {
|
|
1349
|
+
const agentId = exec?.agent?.id
|
|
1350
|
+
const name = typeof exec?.name === 'string' ? exec.name : ''
|
|
1351
|
+
if (agentId === undefined || name === '' || !(state.activeTools instanceof Map)) return next()
|
|
1352
|
+
const key = String(agentId)
|
|
1353
|
+
const token = { name, at: Date.now() }
|
|
1354
|
+
state.activeTools.set(key, token)
|
|
1355
|
+
const settle = () => {
|
|
1356
|
+
if (state.activeTools instanceof Map && state.activeTools.get(key) === token) state.activeTools.delete(key)
|
|
1357
|
+
}
|
|
1358
|
+
let pending
|
|
1359
|
+
try {
|
|
1360
|
+
pending = next()
|
|
1361
|
+
} catch (error) {
|
|
1362
|
+
settle()
|
|
1363
|
+
throw error
|
|
1364
|
+
}
|
|
1365
|
+
return Promise.resolve(pending).then(
|
|
1366
|
+
(result) => { settle(); return result },
|
|
1367
|
+
(error) => { settle(); throw error },
|
|
1368
|
+
)
|
|
1369
|
+
}), 'auto-restart: active tools')
|
|
1370
|
+
|
|
1260
1371
|
// User-authored messages: the turn may not have started yet, but the text was
|
|
1261
1372
|
// just sent, so a restart here would swallow it and restore the draft.
|
|
1262
1373
|
safeOn(ctx, 'api-session/activity', () => { state.lastActivityAt = Date.now() }, 'auto-restart: session activity')
|
package/lib/install-watchdog.ps1
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@leiyi-works/dsh-auto-restart",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.6",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"title": "自动重启",
|
|
6
6
|
"description": "装/更插件后自动重启 DSH 并回到原会话:检测 profile 插件文件变化,一直等所有会话空闲且最近活动安静,由常驻后台看门狗(登录自启、不碰 WMI)或 WMI 守护先杀主进程再拉起(可最大化窗口),带冷却、试运行、日志和右侧原生侧边栏面板。",
|