@leiyi-works/dsh-auto-restart 0.3.4 → 0.3.5

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.
Files changed (2) hide show
  1. package/index.js +69 -20
  2. 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
- const bytes = readFileSync(source)
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(readFileSync(join(PKG_DIR, 'lib', 'watchdog.ps1'))).digest('hex')
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
- const current = watchdogScriptHash()
380
- return heartbeat !== null && current !== '' && heartbeat.script !== current
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,7 @@ function createState(profileDir) {
909
942
  waitingSince: 0,
910
943
  lastActivityAt: 0,
911
944
  pendingInputIds: new Set(),
945
+ sessionLastEventAt: new Map(),
912
946
  lastRestartAt: persisted.lastRestartAt,
913
947
  restarts: persisted.restarts.filter((t) => now - t < 3600000),
914
948
  lastManagerAt: 0,
@@ -1036,24 +1070,29 @@ function tick(baseConfig) {
1036
1070
  }
1037
1071
 
1038
1072
  // A Session blocked on a running background job (job_*, e.g. an npm polling
1039
- // loop) is deliberately NOT counted as busy: its job dies with the Host and
1040
- // cannot recover on its own, so the restart interrupts it and resumeInterrupted
1041
- // sends one "继续" after the new process is up. Only Sessions doing real work
1042
- // (streaming an answer, running the model) keep the restart waiting.
1073
+ // loop) is NOT counted as busy once it has been silent for jobWaitQuietMs:
1074
+ // its job dies with the Host, so the restart interrupts it and
1075
+ // resumeInterrupted sends one "继续" after the new process is up. A Session
1076
+ // that is busy running commands right now has recent session events, so it
1077
+ // still counts as busy and keeps the restart waiting.
1043
1078
  const jobBlocked = []
1044
1079
  const hardBusy = []
1045
1080
  for (const id of state.busy) {
1046
- if (runningJobsFor(String(id)).length > 0) jobBlocked.push(String(id))
1047
- else hardBusy.push(String(id))
1081
+ const sessionId = String(id)
1082
+ const hasJobs = runningJobsFor(sessionId).length > 0
1083
+ const lastAt = state.sessionLastEventAt instanceof Map ? (state.sessionLastEventAt.get(sessionId) ?? 0) : 0
1084
+ const quietMs = lastAt > 0 ? now - lastAt : Number.POSITIVE_INFINITY
1085
+ if (hasJobs && quietMs >= cfg.jobWaitQuietMs) jobBlocked.push(sessionId)
1086
+ else hardBusy.push(sessionId)
1048
1087
  }
1049
1088
  if (hardBusy.length > 0) {
1050
1089
  if (state.waitingSince === 0) {
1051
1090
  state.waitingSince = now
1052
- logLine('info', `有 ${hardBusy.length} 个会话正在回答/干活,等它们空闲后再重启(会一直等)${jobBlocked.length > 0 ? `;另外 ${jobBlocked.length} 个会话在等后台任务,重启会打断它们并在重启后发“继续”` : ''}`)
1091
+ logLine('info', `有 ${hardBusy.length} 个会话正在回答/干活,等它们空闲后再重启${jobBlocked.length > 0 ? `;另外 ${jobBlocked.length} 个会话安静地在等后台任务,重启会打断它们并在重启后发“继续”` : ''}`)
1053
1092
  }
1054
1093
  return
1055
1094
  }
1056
- logLine('info', `其余 ${jobBlocked.length} 个会话都在等后台任务(job_*);本次重启会打断它们,重启后自动发“继续”`)
1095
+ logLine('info', `其余 ${jobBlocked.length} 个会话都在等后台任务(job_*,已安静 ${Math.round(cfg.jobWaitQuietMs / 1000)}s 以上);本次重启会打断它们,重启后自动发“继续”`)
1057
1096
  }
1058
1097
  state.waitingSince = 0
1059
1098
 
@@ -1278,6 +1317,7 @@ export function apply(ctx, config) {
1278
1317
  if (running === false) state.busy.delete(id)
1279
1318
  else state.busy.add(id)
1280
1319
  state.lastActivityAt = Date.now()
1320
+ if (state.sessionLastEventAt instanceof Map) state.sessionLastEventAt.set(id, Date.now())
1281
1321
  }), 'auto-restart: session status')
1282
1322
 
1283
1323
  ctx.effect(() => ctx.on('agent/status', (payload) => {
@@ -1287,8 +1327,17 @@ export function apply(ctx, config) {
1287
1327
  if (status === 'idle') state.busy.delete(String(id))
1288
1328
  else if (ACTIVE_STATUSES.has(status)) state.busy.add(String(id))
1289
1329
  state.lastActivityAt = Date.now()
1330
+ if (state.sessionLastEventAt instanceof Map) state.sessionLastEventAt.set(String(id), Date.now())
1290
1331
  }), 'auto-restart: agent status')
1291
1332
 
1333
+ // Per-session activity: a Session that keeps producing events is working, so
1334
+ // even holding a background job it must not be interrupted.
1335
+ ctx.effect(() => ctx.on('session/event', (session, event) => {
1336
+ const id = session?.id ?? session?.sessionId ?? event?.sessionId
1337
+ if (id === undefined) return
1338
+ if (state.sessionLastEventAt instanceof Map) state.sessionLastEventAt.set(String(id), Date.now())
1339
+ }), 'auto-restart: session events')
1340
+
1292
1341
  // User-authored messages: the turn may not have started yet, but the text was
1293
1342
  // just sent, so a restart here would swallow it and restore the draft.
1294
1343
  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.4",
3
+ "version": "0.3.5",
4
4
  "type": "module",
5
5
  "title": "自动重启",
6
6
  "description": "装/更插件后自动重启 DSH 并回到原会话:检测 profile 插件文件变化,一直等所有会话空闲且最近活动安静,由常驻后台看门狗(登录自启、不碰 WMI)或 WMI 守护先杀主进程再拉起(可最大化窗口),带冷却、试运行、日志和右侧原生侧边栏面板。",