@leiyi-works/dsh-auto-restart 0.3.3 → 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.
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
- copyFileSync(source, target)
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(readFileSync(join(PKG_DIR, 'lib', 'watchdog.ps1'))).digest('hex')
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
- const current = watchdogScriptHash()
348
- 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)
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,7 @@ function createState(profileDir) {
877
942
  waitingSince: 0,
878
943
  lastActivityAt: 0,
879
944
  pendingInputIds: new Set(),
945
+ sessionLastEventAt: new Map(),
880
946
  lastRestartAt: persisted.lastRestartAt,
881
947
  restarts: persisted.restarts.filter((t) => now - t < 3600000),
882
948
  lastManagerAt: 0,
@@ -1004,24 +1070,29 @@ function tick(baseConfig) {
1004
1070
  }
1005
1071
 
1006
1072
  // A Session blocked on a running background job (job_*, e.g. an npm polling
1007
- // loop) is deliberately NOT counted as busy: its job dies with the Host and
1008
- // cannot recover on its own, so the restart interrupts it and resumeInterrupted
1009
- // sends one "继续" after the new process is up. Only Sessions doing real work
1010
- // (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.
1011
1078
  const jobBlocked = []
1012
1079
  const hardBusy = []
1013
1080
  for (const id of state.busy) {
1014
- if (runningJobsFor(String(id)).length > 0) jobBlocked.push(String(id))
1015
- 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)
1016
1087
  }
1017
1088
  if (hardBusy.length > 0) {
1018
1089
  if (state.waitingSince === 0) {
1019
1090
  state.waitingSince = now
1020
- logLine('info', `有 ${hardBusy.length} 个会话正在回答/干活,等它们空闲后再重启(会一直等)${jobBlocked.length > 0 ? `;另外 ${jobBlocked.length} 个会话在等后台任务,重启会打断它们并在重启后发“继续”` : ''}`)
1091
+ logLine('info', `有 ${hardBusy.length} 个会话正在回答/干活,等它们空闲后再重启${jobBlocked.length > 0 ? `;另外 ${jobBlocked.length} 个会话安静地在等后台任务,重启会打断它们并在重启后发“继续”` : ''}`)
1021
1092
  }
1022
1093
  return
1023
1094
  }
1024
- logLine('info', `其余 ${jobBlocked.length} 个会话都在等后台任务(job_*);本次重启会打断它们,重启后自动发“继续”`)
1095
+ logLine('info', `其余 ${jobBlocked.length} 个会话都在等后台任务(job_*,已安静 ${Math.round(cfg.jobWaitQuietMs / 1000)}s 以上);本次重启会打断它们,重启后自动发“继续”`)
1025
1096
  }
1026
1097
  state.waitingSince = 0
1027
1098
 
@@ -1238,7 +1309,7 @@ export function apply(ctx, config) {
1238
1309
  cleanForeignRequests()
1239
1310
  bootWatchdogCheck(state)
1240
1311
  // Sessions that a previous restart interrupted get one "继续" after boot.
1241
- void resumeInterrupted(ctx, cfg)
1312
+ resumeWithController(ctx, cfg)
1242
1313
 
1243
1314
  // Track busy sessions so a restart never cuts an answer.
1244
1315
  ctx.effect(() => ctx.on('api-session/status', (sessionId, running) => {
@@ -1246,6 +1317,7 @@ export function apply(ctx, config) {
1246
1317
  if (running === false) state.busy.delete(id)
1247
1318
  else state.busy.add(id)
1248
1319
  state.lastActivityAt = Date.now()
1320
+ if (state.sessionLastEventAt instanceof Map) state.sessionLastEventAt.set(id, Date.now())
1249
1321
  }), 'auto-restart: session status')
1250
1322
 
1251
1323
  ctx.effect(() => ctx.on('agent/status', (payload) => {
@@ -1255,8 +1327,17 @@ export function apply(ctx, config) {
1255
1327
  if (status === 'idle') state.busy.delete(String(id))
1256
1328
  else if (ACTIVE_STATUSES.has(status)) state.busy.add(String(id))
1257
1329
  state.lastActivityAt = Date.now()
1330
+ if (state.sessionLastEventAt instanceof Map) state.sessionLastEventAt.set(String(id), Date.now())
1258
1331
  }), 'auto-restart: agent status')
1259
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
+
1260
1341
  // User-authored messages: the turn may not have started yet, but the text was
1261
1342
  // just sent, so a restart here would swallow it and restore the draft.
1262
1343
  safeOn(ctx, 'api-session/activity', () => { state.lastActivityAt = Date.now() }, 'auto-restart: session activity')
@@ -1,4 +1,4 @@
1
- param(
1
+ param(
2
2
  [switch]$Uninstall
3
3
  )
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leiyi-works/dsh-auto-restart",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "type": "module",
5
5
  "title": "自动重启",
6
6
  "description": "装/更插件后自动重启 DSH 并回到原会话:检测 profile 插件文件变化,一直等所有会话空闲且最近活动安静,由常驻后台看门狗(登录自启、不碰 WMI)或 WMI 守护先杀主进程再拉起(可最大化窗口),带冷却、试运行、日志和右侧原生侧边栏面板。",