@leiyi-works/dsh-auto-restart 0.3.4 → 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 +99 -20
- 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,20 +309,30 @@ function ensureWatchdogFiles() {
|
|
|
307
309
|
const target = join(dataDir(), file)
|
|
308
310
|
try {
|
|
309
311
|
if (!existsSync(source)) continue
|
|
310
|
-
|
|
311
|
-
// Windows PowerShell 5.1 decodes a BOM-less .ps1 as ANSI, which turns the
|
|
312
|
-
// Chinese messages in the installer into mojibake and a parse error. Always
|
|
313
|
-
// write the runtime copy with a UTF-8 BOM, whatever the package shipped.
|
|
314
|
-
const needsBom = /\.ps1$/i.test(file)
|
|
315
|
-
&& !(bytes.length >= 3 && bytes[0] === 0xEF && bytes[1] === 0xBB && bytes[2] === 0xBF)
|
|
316
|
-
if (needsBom) writeFileSync(target, Buffer.concat([Buffer.from([0xEF, 0xBB, 0xBF]), bytes]))
|
|
317
|
-
else writeFileSync(target, bytes)
|
|
312
|
+
writeFileSync(target, ps1Bytes(file))
|
|
318
313
|
} catch (error) {
|
|
319
314
|
logLine('warn', `同步看门狗文件失败 ${file}: ${String(error?.message ?? error)}`)
|
|
320
315
|
}
|
|
321
316
|
}
|
|
322
317
|
}
|
|
323
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
|
+
|
|
324
336
|
/**
|
|
325
337
|
* Runs the boot resume once `sessionController` is available. Cordis may not have
|
|
326
338
|
* provided it yet when this plugin applies, so the optional service is looked up
|
|
@@ -349,12 +361,30 @@ function resumeWithController(ctx, cfg) {
|
|
|
349
361
|
/** SHA1 of the watchdog script shipped with this plugin version. */
|
|
350
362
|
function watchdogScriptHash() {
|
|
351
363
|
try {
|
|
352
|
-
return createHash('sha1').update(
|
|
364
|
+
return createHash('sha1').update(ps1Bytes('watchdog.ps1')).digest('hex')
|
|
353
365
|
} catch {
|
|
354
366
|
return ''
|
|
355
367
|
}
|
|
356
368
|
}
|
|
357
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
|
+
|
|
358
388
|
/** The watchdog's heartbeat, when it is fresh enough to be trusted. */
|
|
359
389
|
function readWatchdogHeartbeat() {
|
|
360
390
|
const parsed = readJsonFile(watchdogHeartbeatPath())
|
|
@@ -376,8 +406,10 @@ function readWatchdogHeartbeat() {
|
|
|
376
406
|
* stops it and starts the new script, so this is worth re-prompting for.
|
|
377
407
|
*/
|
|
378
408
|
function watchdogScriptStale(heartbeat) {
|
|
379
|
-
|
|
380
|
-
|
|
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)
|
|
381
413
|
}
|
|
382
414
|
|
|
383
415
|
function watchdogAlive() {
|
|
@@ -589,6 +621,7 @@ function sanitizeConfig(raw) {
|
|
|
589
621
|
cfg.enabled = bool(raw.enabled, cfg.enabled)
|
|
590
622
|
cfg.dryRun = bool(raw.dryRun, cfg.dryRun)
|
|
591
623
|
cfg.waitForIdle = bool(raw.waitForIdle, cfg.waitForIdle)
|
|
624
|
+
cfg.jobWaitQuietMs = num(raw.jobWaitQuietMs, cfg.jobWaitQuietMs, 30000, 3600000)
|
|
592
625
|
cfg.continueInterrupted = bool(raw.continueInterrupted, cfg.continueInterrupted)
|
|
593
626
|
cfg.continueWindowMs = num(raw.continueWindowMs, cfg.continueWindowMs, 60000, 86400000)
|
|
594
627
|
if (typeof raw.continueText === 'string' && raw.continueText.trim() !== '') cfg.continueText = raw.continueText.slice(0, 200)
|
|
@@ -909,6 +942,8 @@ function createState(profileDir) {
|
|
|
909
942
|
waitingSince: 0,
|
|
910
943
|
lastActivityAt: 0,
|
|
911
944
|
pendingInputIds: new Set(),
|
|
945
|
+
sessionLastEventAt: new Map(),
|
|
946
|
+
activeTools: new Map(),
|
|
912
947
|
lastRestartAt: persisted.lastRestartAt,
|
|
913
948
|
restarts: persisted.restarts.filter((t) => now - t < 3600000),
|
|
914
949
|
lastManagerAt: 0,
|
|
@@ -1036,24 +1071,32 @@ function tick(baseConfig) {
|
|
|
1036
1071
|
}
|
|
1037
1072
|
|
|
1038
1073
|
// A Session blocked on a running background job (job_*, e.g. an npm polling
|
|
1039
|
-
// loop) is
|
|
1040
|
-
//
|
|
1041
|
-
// sends one "继续" after the
|
|
1042
|
-
//
|
|
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.
|
|
1043
1080
|
const jobBlocked = []
|
|
1044
1081
|
const hardBusy = []
|
|
1045
1082
|
for (const id of state.busy) {
|
|
1046
|
-
|
|
1047
|
-
|
|
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)
|
|
1048
1091
|
}
|
|
1049
1092
|
if (hardBusy.length > 0) {
|
|
1050
1093
|
if (state.waitingSince === 0) {
|
|
1051
1094
|
state.waitingSince = now
|
|
1052
|
-
logLine('info', `有 ${hardBusy.length}
|
|
1095
|
+
logLine('info', `有 ${hardBusy.length} 个会话正在回答/干活,等它们空闲后再重启${jobBlocked.length > 0 ? `;另外 ${jobBlocked.length} 个会话在等后台任务,重启会打断它们并在重启后发“继续”` : ''}`)
|
|
1053
1096
|
}
|
|
1054
1097
|
return
|
|
1055
1098
|
}
|
|
1056
|
-
logLine('info', `其余 ${jobBlocked.length}
|
|
1099
|
+
logLine('info', `其余 ${jobBlocked.length} 个会话都卡在后台任务工具上(job_*);本次重启会打断它们,重启后自动发“继续”`)
|
|
1057
1100
|
}
|
|
1058
1101
|
state.waitingSince = 0
|
|
1059
1102
|
|
|
@@ -1278,6 +1321,7 @@ export function apply(ctx, config) {
|
|
|
1278
1321
|
if (running === false) state.busy.delete(id)
|
|
1279
1322
|
else state.busy.add(id)
|
|
1280
1323
|
state.lastActivityAt = Date.now()
|
|
1324
|
+
if (state.sessionLastEventAt instanceof Map) state.sessionLastEventAt.set(id, Date.now())
|
|
1281
1325
|
}), 'auto-restart: session status')
|
|
1282
1326
|
|
|
1283
1327
|
ctx.effect(() => ctx.on('agent/status', (payload) => {
|
|
@@ -1287,8 +1331,43 @@ export function apply(ctx, config) {
|
|
|
1287
1331
|
if (status === 'idle') state.busy.delete(String(id))
|
|
1288
1332
|
else if (ACTIVE_STATUSES.has(status)) state.busy.add(String(id))
|
|
1289
1333
|
state.lastActivityAt = Date.now()
|
|
1334
|
+
if (state.sessionLastEventAt instanceof Map) state.sessionLastEventAt.set(String(id), Date.now())
|
|
1290
1335
|
}), 'auto-restart: agent status')
|
|
1291
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
|
+
|
|
1292
1371
|
// User-authored messages: the turn may not have started yet, but the text was
|
|
1293
1372
|
// just sent, so a restart here would swallow it and restore the draft.
|
|
1294
1373
|
safeOn(ctx, 'api-session/activity', () => { state.lastActivityAt = Date.now() }, 'auto-restart: session activity')
|
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 守护先杀主进程再拉起(可最大化窗口),带冷却、试运行、日志和右侧原生侧边栏面板。",
|