dsh-session-superagent 0.9.115 → 0.9.118

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/lib/index.js CHANGED
@@ -1,2302 +1,2323 @@
1
- /**
2
- * dsh-session-superagent — session-level superagent for DeepSeek Harness.
3
- *
4
- * Two capabilities, one package:
5
- * 1. `github` / `repo_here` — call the GitHub API; the credential stays inside
6
- * the plugin and every result is redacted before the model sees it.
7
- * 2. `watch_start` / `watch_status` / `watch_stop` — watch one repository and
8
- * wake THIS session when something changes, by queueing a follow-up turn.
9
- *
10
- * Design constraints (see MAINTENANCE.md):
11
- * - never inject while the agent is running (draft-replay hazard);
12
- * - per-item watermarks, so our own writes never wake us (no self-echo);
13
- * - advance the watermark only after a wake actually landed.
14
- */
15
- import { execFileSync, spawn } from 'node:child_process'
16
- import { createHash, randomUUID } from 'node:crypto'
17
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
18
- import os, { homedir } from 'node:os'
19
- import { dirname, isAbsolute, join } from 'node:path'
20
- import { fileURLToPath } from 'node:url'
21
-
22
- import { zstdDecompressSync } from 'node:zlib'
23
-
24
- import { redact } from './redact.js'
25
- import { decodeBody } from './body.js'
26
- import {
27
- advanceSeen, applyWatcherAction, batchFresh, decideWake, DEFAULT_ACK_LABEL, formatWatchText,
28
- TRIAGE_SIGNALS, accessNote, buildCommentBatchQuery, classifyGhError, commentSummaryLine, parseCommentBatch, pickSuggestion, repoStructureNote, countReasons, filterReason, formatGhCall, hasAckLabel, jitterMs, parseGhInclude, retryAfterMs, throttleDelayMs, inActiveHours, newestUpdatedAt, nextDelayMs, permanentBackoffMs, pushAbsorbed, pushFiltered, normalizeFilters, partitionItems, passesFilters,
29
- shouldRunCleanup,
30
- bumpDailyWakes,
31
- busierThanUsual,
32
- countCapped,
33
- statusView,
34
- dailySummary,
35
- suggestSessionCap,
36
- itemTrace,
37
- splitBatch,
38
- mergeFilters, mergePollResult, mergeWakeTexts, pushEvent, silentStreak, msUntilActiveWindow, nextWaketimeAt, pruneSeen, sessionWakesLastHour, pruneWakeTimes, pushHistory, recordReported, staleWorktrees, worktreePlan,
39
- } from './watch.js'
40
-
41
- export const name = 'dsh-session-superagent'
42
- /** 服务端版本:随 package.json 同步(meta 测试守着)。客户端据此挑「最新的那个实例」。 */
43
- export const SERVER_VERSION = '0.9.115'
44
- export const inject = ['tools', 'agents', 'webServer']
45
- /** 一条会话每小时最多被唤醒几次(跨所有守累计)。单守上限挡不住多守叠加。 */
46
- // 本进程启动时刻:用来区分「刚重启还没轮到」与「定时器真的丢了」
47
- const PROCESS_STARTED_AT = Date.now()
48
- // 「未变化」那句两处要一模一样:单点改文案不会漏另一处
49
- // 记错误时同时记时间:面板要能说「这是 12 分钟前的」而不是默认它刚刚发生
50
- function setEntryError(entry, text) {
51
- entry.lastError = text
52
- entry.lastErrorAt = new Date().toISOString()
53
- }
54
- const UNCHANGED_TEXT = '未变化(304,不计入速率限制)'
55
- // 追溯找不到任何痕迹时的那句话:两个入口(工具 / HTTP)必须一模一样
56
- const noTraceText = (number, scope) => '#' + number + ' 在' + (scope || '所有守') + ' 里都没有痕迹 —— 可能还没被轮询到,或者编号写错了。'
57
-
58
- const DEFAULT_SESSION_WAKES = 12
59
- // 一条会话最多挂多少守:再多轮询压力与上下文都会失控(20 条 × 每 60 秒已很密)
60
- const MAX_WATCHERS_PER_SESSION = 20
61
- /** 隔离区回收的最小间隔:没有超额时不必每次唤醒都跑 git。 */
62
- const CLEANUP_INTERVAL_MS = 10 * 60 * 1000
63
-
64
- /** 仅供测试:读写状态文件(生产代码不要用)。 */
65
- export const __test = { readState, writeState, hardenSecretsFile, wakeMerged }
66
-
67
- const STATE_DIR = process.env.DSH_SUPERAGENT_STATE
68
- ? String(process.env.DSH_SUPERAGENT_STATE)
69
- : join(homedir(), '.dsh', 'state', 'session-superagent')
70
- const SECRETS_FILE = join(STATE_DIR, 'secrets.json')
71
- const STATE_FILE = join(STATE_DIR, 'watchers.json')
72
- const TRIGGER_FILE = join(STATE_DIR, 'trigger.json')
73
- // 客户端探针只认这几个键(别的键一律丢弃,防止被任意网页写盘)
74
- const CLIENT_NOTE_KEYS = new Set(['client-version', 'client-base', 'apply', 'desk-registered', 'desk-fail', 'orbit-registered', 'orbit-fail', 'orbit-mount', 'badge-registered', 'badge-mount', 'badge-state', 'error'])
75
- const DEFAULT_COOLDOWN_MS = 180_000
76
-
77
- /**
78
- * 当前挂在这个进程上的路由 disposer。
79
- *
80
- * 宿主重载时若没走 dispose,旧实例会继续吃 HTTP 请求,而它的 ctx 可能已经 dispose ——
81
- * 真机表现:面板建的 watcher 第一轮就报
82
- * `cannot get required service "agents" in inactive context`(2026-11-02 复验)。
83
- *
84
- * 关键:宿主重载常常是**重新 import 一份模块**(模块级变量全新),所以光用模块级数组
85
- * 接不过去 —— 必须挂在 `globalThis` 上(用 Symbol.for 做键,多个模块实例共享同一个)。
86
- */
87
- // 这三个结构必须跨模块实例共享:宿主重载常常是重新 import 一份模块,
88
- // 模块级变量全新,但进程只有一个。新实例要能清掉旧实例的路由与定时器,
89
- // 也要能看见旧实例「正在跑的那轮」(否则并发闸形同虚设)。
90
- const TIMERS_KEY = Symbol.for('dsh-session-superagent.timers')
91
- const INFLIGHT_KEY = Symbol.for('dsh-session-superagent.inFlight')
92
- const sharedTimers = (globalThis[TIMERS_KEY] ||= new Map())
93
- const sharedInFlight = (globalThis[INFLIGHT_KEY] ||= new Set())
94
-
95
- const DEFAULT_ROUTE_BASE = '/session-superagent'
96
- const ROUTE_GEN_KEY = Symbol.for('dsh-session-superagent.routeGeneration')
97
- /** 本实例实际使用的路由前缀(正常情况下等于默认前缀)。 */
98
- let activeBase = DEFAULT_ROUTE_BASE
99
- const ROUTES_KEY = Symbol.for('dsh-session-superagent.activeRoutes')
100
- const activeRoutes = (globalThis[ROUTES_KEY] ||= [])
101
-
102
- // 最后一次成功读取的来源:正常 / 备份恢复 / 全新。面板与 /diagnose 会带上它。
103
- let stateSource = 'new'
104
-
105
- /**
106
- * 读状态文件。主文件坏了就退回上一次的备份(`.bak`),而不是直接当空状态 ——
107
- * 当空的后果是「客户所有守一夜消失」,这比多留一个备份文件糟糕得多。
108
- * 思路同 SQLite 的 WAL:**先保证有一份已提交的好副本**,再覆盖。
109
- */
110
- function readState() {
111
- let raw
112
- try {
113
- raw = readFileSync(STATE_FILE, 'utf8')
114
- } catch {
115
- stateSource = 'new'
116
- return { watchers: {} }
117
- }
118
- try {
119
- const parsed = JSON.parse(raw)
120
- stateSource = 'ok'
121
- return parsed
122
- } catch {
123
- // 主文件坏了:试试备份
124
- try {
125
- const backup = JSON.parse(readFileSync(STATE_FILE + '.bak', 'utf8'))
126
- stateSource = 'backup'
127
- // 把备份写回主文件,避免下次还走恢复路径
128
- try { writeFileSync(STATE_FILE, JSON.stringify(backup, null, 2)) } catch {}
129
- return backup
130
- } catch {
131
- // 备份也没了/也坏了:把坏文件留个证据,再从空状态开始
132
- stateSource = 'corrupt'
133
- try { renameSync(STATE_FILE, STATE_FILE + '.corrupt-' + Date.now()) } catch {}
134
- return { watchers: {} }
135
- }
136
- }
137
- }
138
-
139
- function writeState(state) {
140
- try {
141
- mkdirSync(STATE_DIR, { recursive: true })
142
- // 合并写:调用方手里的 state 可能是很久以前读的快照(宿主重载、两个实例交替写),
143
- // 直接整份覆盖会把别人刚建的 watcher 抹掉 —— 真机上丢过两条(一条是用户的)。
144
- // 规则:盘上有、内存里没有的条目一律保留;只有墓碑里的 id 才允许消失。
145
- const disk = readState()
146
- const tombstones = { ...(disk.deleted || {}), ...(state.deleted || {}) }
147
- const merged = { ...disk, ...state }
148
- merged.watchers = { ...(disk.watchers || {}) }
149
- for (const [id, watcher] of Object.entries(state.watchers || {})) merged.watchers[id] = watcher
150
- const now = Date.now()
151
- for (const [id, at] of Object.entries(tombstones)) {
152
- delete merged.watchers[id]
153
- // 墓碑留 7 天足够覆盖任何迟到写入
154
- if (now - Date.parse(at) > 7 * 24 * 3600 * 1000) delete tombstones[id]
155
- }
156
- if (Object.keys(tombstones).length > 0) merged.deleted = tombstones
157
- else delete merged.deleted
158
-
159
- const text = JSON.stringify(merged, null, 1)
160
- // 原子写:写一半崩掉不该把全部 watcher 清空
161
- const tmp = STATE_FILE + '.tmp'
162
- writeFileSync(tmp, text)
163
- // 覆盖前先把「当前这份好的」留成备份:主文件将来被写坏(断电、磁盘满、手改),
164
- // readState 还能退回来,而不是把客户所有守当成空状态。
165
- try {
166
- const current = readFileSync(STATE_FILE, 'utf8')
167
- JSON.parse(current) // 只有当前文件是好的才备份,别把坏文件备份成"好版本"
168
- writeFileSync(STATE_FILE + '.bak', current)
169
- } catch {}
170
- try { renameSync(tmp, STATE_FILE) } catch { writeFileSync(STATE_FILE, text) }
171
- // 第一次写入时盘上还没有好文件,`.bak` 会是空的 —— 那就等于没有备份。
172
- // 主文件一坏(断电/手改/磁盘满)就会丢掉全部守。所以这里补一份引导备份。
173
- if (!existsSync(STATE_FILE + '.bak')) {
174
- try { writeFileSync(STATE_FILE + '.bak', text) } catch {}
175
- }
176
- return merged
177
- } catch { return state /* state is best-effort: a failed write must not break a turn */ }
178
- }
179
-
180
- /** Credentials the operator typed in the panel. Never returned in plain text. */
181
- function readSecrets() {
182
- try {
183
- const raw = JSON.parse(readFileSync(SECRETS_FILE, 'utf8'))
184
- return raw && typeof raw === 'object' ? raw : {}
185
- } catch { return {} }
186
- }
187
-
188
- function writeSecrets(next) {
189
- try {
190
- mkdirSync(STATE_DIR, { recursive: true })
191
- writeFileSync(SECRETS_FILE, JSON.stringify(next, null, 1), { mode: 0o600 })
192
- // mode 在 Windows 上几乎无效,补 ACL(见 hardenSecretsFile 注释)
193
- hardenSecretsFile(SECRETS_FILE)
194
- } catch {}
195
- }
196
-
197
- /** A masked view of what is configured: shape only, never the value. */
198
- function secretsSummary() {
199
- const s = readSecrets()
200
- return {
201
- token: s.token ? 'configured' : 'none',
202
- // 只回「有没有配」:连首尾各 4 个字符也算信息泄露
203
- tokenHint: s.token ? 'configured' : null,
204
- sshKeyPath: s.sshKeyPath ? 'configured' : 'none',
205
- // 从不在面板回显路径(Windows 路径里的反斜杠曾让掩码整段漏出)
206
- sshKeyHint: null,
207
- updatedAt: s.updatedAt ?? null,
208
- }
209
- }
210
-
211
- const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
212
- const titleCache = new Map()
213
-
214
- /** Decompress a multi-frame zstd session log into text. */
215
- function readFrames(buffer) {
216
- const starts = []
217
- let index = 0
218
- while ((index = buffer.indexOf(ZSTD_MAGIC, index)) !== -1) { starts.push(index); index += 4 }
219
- if (starts.length === 0 || starts[0] !== 0) starts.unshift(0)
220
- const parts = []
221
- for (let k = 0; k < starts.length; k += 1) {
222
- const end = k + 1 < starts.length ? starts[k + 1] : buffer.length
223
- try { parts.push(zstdDecompressSync(buffer.subarray(starts[k], end)).toString('utf8')) } catch {}
224
- }
225
- return parts.join('')
226
- }
227
-
228
- /** The human title the sidebar shows for a session, read from its own log. Cached by file mtime. */
229
- /** sessionId → 会话日志路径的索引缓存(60 秒 TTL;命中后只 stat 单个文件)。 */
230
- const sessionFileCache = { at: 0, byId: new Map() }
231
-
232
- function sessionTitle(sessionId) {
233
- try {
234
- if (!sessionId) return null
235
- const home = process.env.DSH_HOME && String(process.env.DSH_HOME).trim()
236
- ? String(process.env.DSH_HOME).trim()
237
- : join(homedir(), '.dsh')
238
- const root = join(home, 'sessions')
239
- // 目录索引缓存:/state 每 5 秒一次 × 每条 watcher,全量 readdir + existsSync 太亏。
240
- // 关键:miss 也要走 TTL(负缓存)—— 只要有一个 watcher 的会话日志不存在,
241
- // 每次 /state 都全量重建会把 0.6ms 拖成 130-500ms(终审实测 200/800 会话两种规模)。
242
- if (Date.now() - sessionFileCache.at > 60 * 1000) {
243
- sessionFileCache.byId.clear()
244
- for (const group of readdirSync(root)) {
245
- const dir = join(root, group)
246
- let names = []
247
- try { names = readdirSync(dir) } catch { continue }
248
- for (const name of names) {
249
- const candidate = join(dir, name, 'session.v4.jsonl.zstd')
250
- if (existsSync(candidate)) sessionFileCache.byId.set(name, candidate)
251
- }
252
- }
253
- sessionFileCache.at = Date.now()
254
- }
255
- const file = sessionFileCache.byId.get(sessionId) || null
256
- if (!file) return null
257
- const stat = statSync(file)
258
- const cached = titleCache.get(sessionId)
259
- if (cached && cached.mtime === stat.mtimeMs && cached.size === stat.size) return cached.title
260
- let title = null
261
- const lines = readFrames(readFileSync(file)).split(String.fromCharCode(10))
262
- for (let i = lines.length - 1; i >= 0; i -= 1) {
263
- const line = lines[i]
264
- if (!line || line.indexOf('"session/title"') === -1) continue
265
- try {
266
- const parsed = JSON.parse(line)
267
- if (parsed && parsed.type === 'session/title' && parsed.data && typeof parsed.data.title === 'string') {
268
- title = parsed.data.title
269
- break
270
- }
271
- } catch {}
272
- }
273
- titleCache.set(sessionId, { mtime: stat.mtimeMs, size: stat.size, title })
274
- return title
275
- } catch { return null }
276
- }
277
-
278
- /**
279
- * The session's real goal, read through the host's own goal service — the same
280
- * one `/goal` and the create_goal tool use. Returns null when the host has no
281
- * goal service or the session has no current goal.
282
- */
283
- function goalView(ctx, sessionId) {
284
- try {
285
- if (!sessionId || typeof ctx.get !== 'function') return null
286
- const goals = ctx.get('goals')
287
- const agents = ctx.get('agents')
288
- if (!goals || !agents || typeof goals.get !== 'function') return null
289
- const agent = agents.get(sessionId)
290
- if (!agent) return null
291
- const view = goals.get(agent)
292
- if (!view) return null
293
- return {
294
- objective: view.objective ?? null,
295
- phase: view.phase ?? null,
296
- revision: view.ref ? view.ref.revision : (view.revision ?? null),
297
- }
298
- } catch { return null }
299
- }
300
-
301
- /** Environment for every gh call: a panel token wins over the CLI login. */
302
- function ghEnv() {
303
- const s = readSecrets()
304
- if (!s.token) return process.env
305
- return { ...process.env, GH_TOKEN: String(s.token) }
306
- }
307
-
308
- /**
309
- * 安全地取 agents 服务。
310
- * 定时器回调跑在「非活跃上下文」里,直接读 `ctx.agents` 会抛
311
- * `cannot get required service "agents" in inactive context`(2026-11-02 真机复验踩到);
312
- * `ctx.get(name)` 不抛,取不到就返回 undefined。
313
- */
314
- function agentsService(ctx) {
315
- try {
316
- if (typeof ctx.get === 'function') {
317
- const viaGet = ctx.get('agents')
318
- if (viaGet) return viaGet
319
- }
320
- } catch {}
321
- try { return ctx.agents } catch { return undefined }
322
- }
323
-
324
- /** gh CLI 可用性探针:5 分钟缓存,别让面板每 5 秒都 spawn 一次 gh。 */
325
- const ghHealthCache = { at: 0, value: null }
326
- async function ghHealth() {
327
- if (Date.now() - ghHealthCache.at < 5 * 60 * 1000 && ghHealthCache.value) return ghHealthCache.value
328
- let value
329
- try {
330
- const res = await run('gh', ['--version'], { timeoutMs: 10000 })
331
- value = res.code === 0
332
- ? { ok: true, version: String(res.stdout || '').trim().split(String.fromCharCode(10))[0].slice(0, 80) }
333
- : { ok: false, error: redact([res.stderr, res.stdout].join(' ')).slice(0, 160) }
334
- } catch (error) {
335
- value = { ok: false, error: String((error && error.message) || error).slice(0, 160) }
336
- }
337
- ghHealthCache.at = Date.now()
338
- ghHealthCache.value = value
339
- return value
340
- }
341
-
342
- function persistEntry(entry) {
343
- try {
344
- const state = readState()
345
- state.watchers = state.watchers || {}
346
- const stored = state.watchers[entry.id]
347
- // Deleted between the tick start and its write-back: never resurrect it.
348
- if (!stored) return
349
- state.watchers[entry.id] = mergePollResult(stored, entry)
350
- writeState(state)
351
- } catch {}
352
- }
353
-
354
- /**
355
- * 失败退避:连续失败就把下一次允许轮询的时间往后推(30s → 60 → 120 … 上限 30min)。
356
- * 竞品的教训很直白 —— 401 的时候还按 30 秒撞墙,只会把配额和日志一起打光。
357
- */
358
- /**
359
- * 记一条时间线事件(有界、只存在状态里)。
360
- * 目的:回答"为什么这一轮没叫醒我" —— 以前只有 lastDeferred 一句,看不出前后因果。
361
- */
362
- function noteEvent(entry, kind, text) {
363
- try {
364
- entry.events = pushEvent(entry.events, { kind, text })
365
- } catch { /* 观测失败不能影响主流程 */ }
366
- }
367
-
368
- // 实际间隔:自己的配置与 GitHub 要求的 x-poll-interval 取大者
369
- function effectiveIntervalMs(entry, baseMs) {
370
- const floor = (Number(entry.minIntervalSec) || 0) * 1000
371
- return Math.max(Number(baseMs) || 0, floor)
372
- }
373
-
374
- function bumpFailure(entry, baseMs) {
375
- entry.consecutiveFailures = (Number(entry.consecutiveFailures) || 0) + 1
376
- entry.nextAt = new Date(Date.now() + nextDelayMs(entry, effectiveIntervalMs(entry, baseMs || 60000))).toISOString()
377
- }
378
-
379
- /**
380
- * 回收过期的隔离区:每次唤醒都会开一个新 worktree,不回收就会一直涨。
381
- * 只删 .dsh-zhuli/ 下超过 keepDays 天没动过的目录,删不掉就留着(不阻断唤醒)。
382
- */
383
- async function cleanupWorktrees(workdir, keepDays = 3, keepCount = 5, options = {}) {
384
- if (!workdir) return 0
385
- const BS = String.fromCharCode(92)
386
- const base = String(workdir).split(BS).join('/').replace(/\/+$/, '')
387
- const root = base + '/.dsh-zhuli'
388
- let names = []
389
- try { names = readdirSync(root) } catch { return 0 }
390
-
391
- // 节流:没有超额就不必每次都跑 git(remove / prune / branch -D 都是进程级开销)
392
- const decision = shouldRunCleanup({
393
- count: names.length,
394
- keepCount,
395
- lastRunAt: Number(options.lastRunAt) || 0,
396
- intervalMs: CLEANUP_INTERVAL_MS,
397
- })
398
- if (!decision.run) return 0
399
- if (typeof options.onRun === 'function') options.onRun(decision.reason)
400
- const entries = []
401
- for (const name of names) {
402
- try { entries.push({ name, mtimeMs: statSync(root + '/' + name).mtimeMs }) } catch {}
403
- }
404
- // 数量线:最近 N 个留着(默认 5),其余回收 —— 年龄线管不住"堆"
405
- const stale = staleWorktrees(entries, { keepMs: keepDays * 24 * 3600 * 1000, keepCount: Number(keepCount) || 5 })
406
- let removed = 0
407
- for (const item of stale) {
408
- const target = root + '/' + item.name
409
- const res = await run('git', ['-C', workdir, 'worktree', 'remove', '--force', target], { timeoutMs: 30000 })
410
- if (res.code !== 0) {
411
- // 已经不是工作树(孤儿目录):直接删目录,别让它永远留着
412
- try { rmSync(target, { recursive: true, force: true }) } catch {}
413
- // 关键:目录删了,但 git 的 `worktrees/<id>/` 管理文件还在 —— 不 prune 的话
414
- // `git worktree list` 会一直显示一个已经不存在的目录。
415
- // 依据:git-worktree 文档里 `prune` 的职责正是「清掉那些目录已经不在了的管理记录」。
416
- await run('git', ['-C', workdir, 'worktree', 'prune'], { timeoutMs: 20000 })
417
- } else {
418
- removed += 1
419
- }
420
- // 无论 worktree 是否删成功,都试着删分支:每次唤醒一个新分支,不删会无限涨
421
- await run('git', ['-C', workdir, 'branch', '-D', 'zhuli/' + item.name], { timeoutMs: 30000 })
422
- }
423
- return removed
424
- }
425
-
426
- /**
427
- * 给一次唤醒准备隔离工作区:在目标仓库上开一个一次性 git worktree。
428
- * 失败不阻断唤醒 —— 退化成普通模式,并在消息里说明原因。
429
- */
430
- /**
431
- * 让隔离区不污染客户的 `git status`。
432
- *
433
- * 隔离区开在仓库内的 .dsh-zhuli/ 下,默认是**未跟踪目录** ——
434
- * 客户一切 git status 就会看到它,甚至可能顺手 git add 进去。
435
- * 写到 `.git/info/exclude`(本地、不提交、不修改客户的 .gitignore)最合适。
436
- */
437
- async function ensureIsolationExcluded(workdir) {
438
- try {
439
- const res = await run('git', ['-C', workdir, 'rev-parse', '--git-path', 'info/exclude'], { timeoutMs: 15000 })
440
- if (res.code !== 0) return false
441
- const file = String(res.stdout || '').trim()
442
- if (!file) return false
443
- let current = ''
444
- try { current = readFileSync(file, 'utf8') } catch { current = '' }
445
- if (current.split(/\r?\n/).includes('.dsh-zhuli/')) return true
446
- const next = current + (current.endsWith('\n') || current === '' ? '' : '\n') + '.dsh-zhuli/' + '\n'
447
- writeFileSync(file, next)
448
- return true
449
- } catch {
450
- return false
451
- }
452
- }
453
-
454
- async function prepareIsolation(entry) {
455
- if (!entry || !entry.isolated || !entry.workdir) return null
456
- const plan = worktreePlan({ workdir: entry.workdir, repo: entry.repo, sessionTag: entry.sessionId })
457
- try {
458
- // 先回收过期隔离区,再开新的
459
- await cleanupWorktrees(entry.workdir, Number(entry.isolateKeepDays) || 3, Number(entry.maxIsolated) || 5, {
460
- lastRunAt: Number(entry.lastCleanupAt) || 0,
461
- onRun: () => { entry.lastCleanupAt = Date.now() },
462
- })
463
- await ensureIsolationExcluded(entry.workdir)
464
- const res = await run('git', ['-C', entry.workdir, 'worktree', 'add', plan.dir, '-b', plan.branch], { timeoutMs: 45000 })
465
- if (res.code !== 0) {
466
- return { error: redact([res.stderr, res.stdout].filter(Boolean).join(' ')).slice(0, 200) }
467
- }
468
- return plan
469
- } catch (error) {
470
- return { error: String((error && error.message) || error).slice(0, 200) }
471
- }
472
- }
473
-
474
- /** Spawn a command, capture both streams, never echo the credential. */
475
- function run(file, args, options = {}) {
476
- const { input, cwd, env, timeoutMs = 60000 } = options
477
- return new Promise((resolve) => {
478
- const child = spawn(file, args, { cwd, env: env ?? process.env, windowsHide: true, shell: false })
479
- let stdout = ''
480
- let stderr = ''
481
- let settled = false
482
- const timer = setTimeout(() => {
483
- if (settled) return
484
- settled = true
485
- try { child.kill('SIGKILL') } catch {}
486
- resolve({ code: 'timeout', stdout, stderr })
487
- }, timeoutMs)
488
- child.stdout.on('data', (d) => { stdout += d.toString('utf8') })
489
- child.stderr.on('data', (d) => { stderr += d.toString('utf8') })
490
- child.on('error', (e) => {
491
- if (settled) return
492
- settled = true
493
- clearTimeout(timer)
494
- resolve({ code: 'spawn-error', stdout, stderr: String((e && e.message) || e) })
495
- })
496
- child.on('close', (c) => {
497
- if (settled) return
498
- settled = true
499
- clearTimeout(timer)
500
- resolve({ code: c === null ? 0 : c, stdout, stderr })
501
- })
502
- if (input !== undefined) child.stdin.write(input)
503
- child.stdin.end()
504
- })
505
- }
506
-
507
- function defineTool(options) {
508
- const properties = {}
509
- const required = []
510
- for (const [key, spec] of Object.entries(options.parameters)) {
511
- properties[key] = {}
512
- if (spec.type) properties[key].type = spec.type
513
- if (spec.description) properties[key].description = spec.description
514
- if (spec.required) required.push(key)
515
- }
516
- return {
517
- name: options.name,
518
- description: options.description,
519
- parameters: { type: 'object', properties, ...(required.length ? { required } : {}) },
520
- output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
521
- async execute(args) {
522
- const record = args && typeof args === 'object' ? args : {}
523
- for (const key of required) {
524
- if (record[key] === undefined || record[key] === null || record[key] === '') {
525
- return `[error: missing required parameter "${key}"]`
526
- }
527
- }
528
- return options.execute(record)
529
- },
530
- }
531
- }
532
-
533
- /**
534
- * Wake one live session with a user message.
535
- *
536
- * `Agent.followup()` queues an ordinary turn AND wakes the driver; the durable
537
- * inbox alone only parks the message (the client shows it as a pending draft).
538
- */
539
-
540
- /**
541
- * 同会话几秒内的多条唤醒合并成一条再注入。
542
- *
543
- * 实测:同会话 3 个守、间隔 60 秒时,首轮抖动只把相位拉开 ≤5 秒 —— 之后每一轮都一样,
544
- * 于是三次唤醒落在约 1 秒内,会话连着收到 3 条注入(5 个守就是 5 条)。
545
- * 不做硬间隔,是因为"先到的守永远赢"会把后面的饿死;**合并**既不丢也不饿死。
546
- */
547
- // 合并窗口:生产 3 秒;测试里可用环境变量压到毫秒级,避免用例等 3 秒
548
- const WAKE_WINDOW_MS = Number(process.env.DSH_SUPERAGENT_WAKE_WINDOW_MS) || 3000
549
- const wakeBuffers = new Map()
550
-
551
- function wakeMerged(ctx, sessionId, text, onSettled) {
552
- const now = Date.now()
553
- const buf = wakeBuffers.get(sessionId) || { parts: [], timer: null, openedAt: now, settled: [] }
554
- buf.parts.push(text)
555
- if (onSettled) buf.settled.push(onSettled)
556
- if (buf.timer) return { ok: true, merged: true, pending: buf.parts.length }
557
- buf.timer = setTimeout(() => {
558
- wakeBuffers.delete(sessionId)
559
- let result = { ok: false, reason: 'merged empty' }
560
- try {
561
- const merged = mergeWakeTexts(buf.parts)
562
- if (merged) result = wake(ctx, sessionId, merged)
563
- } catch (error) {
564
- result = { ok: false, reason: String((error && error.message) || error) }
565
- }
566
- // 关键:真正发送之后才回调 —— 记账(唤醒次数、水位、历史)不能提前
567
- for (const cb of buf.settled) {
568
- try { cb(result) } catch { /* 单个回调失败不影响其它 */ }
569
- }
570
- }, WAKE_WINDOW_MS)
571
- if (buf.timer && typeof buf.timer.unref === 'function') buf.timer.unref()
572
- wakeBuffers.set(sessionId, buf)
573
- return { ok: true, merged: true, pending: buf.parts.length }
574
- }
575
-
576
- function wake(ctx, sessionId, text) {
577
- const agents = agentsService(ctx)
578
- const agent = agents && typeof agents.get === 'function' ? agents.get(sessionId) : undefined
579
- if (!agent) return { ok: false, reason: 'session not live' }
580
-
581
- const allowed = decideWake(agent.status)
582
- if (!allowed.ok) return allowed
583
-
584
- const message = {
585
- id: randomUUID(),
586
- role: 'user',
587
- content: [{ type: 'text', text }],
588
- source: { kind: 'user' },
589
- }
590
- try {
591
- if (typeof agent.followup === 'function') {
592
- agent.followup(message)
593
- return { ok: true, via: 'followup' }
594
- }
595
- if (typeof agent.steer === 'function') {
596
- agent.steer(message)
597
- return { ok: true, via: 'steer' }
598
- }
599
- const inbox = agent.inbox || (agent.session && agent.session.inbox)
600
- if (inbox && typeof inbox.append === 'function') {
601
- inbox.append('next-turn', message)
602
- return { ok: true, via: 'inbox.append' }
603
- }
604
- return { ok: false, reason: 'no followup/steer/inbox on agent' }
605
- } catch (error) {
606
- return { ok: false, reason: `throw: ${String((error && error.message) || error)}` }
607
- }
608
- }
609
-
610
-
611
-
612
- /**
613
- * 收紧凭证文件权限。
614
- *
615
- * Node 文档明确:**on Windows only the write permission can be changed, and the distinction
616
- * among the permissions of group, owner, or others is not implemented** —— 也就是说
617
- * 光靠 `mode: 0o600` 在 Windows 上约等于没有保护,同机其他账户仍可能读到 token。
618
- * 所以在 Windows 上补一条 icacls:断开继承,只给当前用户完全控制。
619
- * 出处:https://nodejs.org/api/fs.html(fs.chmod 的 Caveats)
620
- */
621
- let secretsHardened = 'unknown'
622
- function hardenSecretsFile(file) {
623
- if (process.platform !== 'win32') {
624
- try {
625
- chmodSync(file, 0o600)
626
- secretsHardened = 'posix-0600'
627
- } catch { secretsHardened = 'failed' }
628
- return secretsHardened
629
- }
630
- try {
631
- const user = os.userInfo().username
632
- execFileSync('icacls', [file, '/inheritance:r', '/grant:r', user + ':F'], { stdio: 'ignore', timeout: 15000 })
633
- secretsHardened = 'win32-acl'
634
- } catch {
635
- secretsHardened = 'failed'
636
- }
637
- return secretsHardened
638
- }
639
-
640
-
641
- /**
642
- * token 的权限范围(scopes)。
643
- *
644
- * 为什么值得看:GitHub 明确建议「最小权限」——细粒度 token 按端点授予,
645
- * 而经典 PAT 的 `repo` 一把就是全仓库读写。我们的实现只需要
646
- * 「读 issue/PR + 写评论和标签」,用 `delete:packages`、`admin:repo_hook` 这类 scope 纯属多余暴露。
647
- * 出处:https://docs.github.com/en/rest/authentication/permissions-required-for-fine-grained-personal-access-tokens
648
- *
649
- * 探测成本约 0.5 秒(起一个 gh 进程),所以缓存 5 分钟,别在每次 /state 里都跑。
650
- */
651
- let scopesCache = { at: 0, value: null }
652
- const BROAD_SCOPES = ['delete:packages', 'admin:repo_hook', 'admin:org', 'workflow', 'write:packages', 'admin:public_key']
653
-
654
- async function tokenScopes() {
655
- if (scopesCache.value && Date.now() - scopesCache.at < 5 * 60 * 1000) return scopesCache.value
656
- const res = await run('gh', ['api', '-i', 'user'], { timeoutMs: 20000, env: ghEnv() })
657
- let value = { ok: false, scopes: [], broad: [], error: null, checkedAt: new Date().toISOString() }
658
- if (res.code !== 0) {
659
- value.error = redact(res.stderr).slice(0, 160)
660
- } else {
661
- const text = String(res.stdout || '')
662
- const line = text.split(String.fromCharCode(10)).find((l) => l.toLowerCase().startsWith('x-oauth-scopes:'))
663
- const raw = line ? line.slice('x-oauth-scopes:'.length).trim() : ''
664
- const scopes = raw ? raw.split(',').map((v) => v.trim()).filter(Boolean) : []
665
- value = {
666
- ok: true,
667
- scopes,
668
- broad: scopes.filter((scope) => BROAD_SCOPES.includes(scope)),
669
- error: null,
670
- checkedAt: new Date().toISOString(),
671
- }
672
- }
673
- scopesCache = { at: Date.now(), value }
674
- return value
675
- }
676
-
677
-
678
- /**
679
- * 新增守之前的即时体检:仓库在不在、能不能写、有没有 issue。
680
- *
681
- * 为什么放在这里:`probeAccess` 是后台跑的,客户要等到下一次 /state 才看到提示;
682
- * 而"填错仓库名"是最常见的输入错误,应该在点「添加」那一刻就说。
683
- *
684
- * 依据:`GET /repos/{owner}/{repo}` 对不存在的仓库(或无权访问的私有仓库)返回 404 ——
685
- * 官方文档把这两种情况归为同一个响应,所以文案要一起说「不存在或没有权限」。
686
- * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
687
- *
688
- * 注意:**只产出警告,不阻止创建** —— 网络抖动不该让客户没法添加;
689
- * 测试环境(DSH_SUPERAGENT_NO_POLL=1)直接跳过,避免单测依赖网络。
690
- */
691
- async function precheckRepo(repo) {
692
- const warnings = []
693
- if (process.env.DSH_SUPERAGENT_NO_POLL === '1') return { warnings, skipped: true }
694
- const res = await run('gh', ['api', 'repos/' + repo, '--jq',
695
- '{push: .permissions.push, hasIssues: .has_issues, archived: .archived, disabled: .disabled, private: .private, fork: .fork, parent: (.parent.full_name // null)}',
696
- ], { timeoutMs: 10000, env: ghEnv() })
697
- if (res.code !== 0) {
698
- const detail = redact(res.stderr)
699
- if (detail.includes('404')) {
700
- let hint = ''
701
- // 只在 404 之后才搜一次:search 池是 30 次/分钟(core 是 5000),不能滥用
702
- const name = repo.split('/')[1] || repo
703
- if (name.length >= 5) {
704
- const search = await run('gh', ['api', 'search/repositories?q=' + encodeURIComponent(name + ' in:name') + '&per_page=5', '--jq', '.items[].full_name'],
705
- { timeoutMs: 10000, env: ghEnv() })
706
- if (search.code === 0) {
707
- const picked = pickSuggestion(repo, String(search.stdout || '').split(String.fromCharCode(10)).map((v) => v.trim()).filter(Boolean))
708
- if (picked) hint = ' 是不是想填 ' + picked + '?'
709
- }
710
- }
711
- warnings.push('仓库 ' + repo + ' 不存在,或当前 token 没有访问权限 —— 先确认名字(owner/name)与权限。' + hint)
712
- return { warnings, notFound: true }
713
- }
714
- warnings.push('添加前没能确认这个仓库(' + detail.slice(0, 100) + '),稍后会在面板里再次探测。')
715
- return { warnings }
716
- }
717
- let info = {}
718
- try { info = JSON.parse(res.stdout) } catch { return { warnings } }
719
- const note = repoStructureNote({
720
- repo,
721
- hasIssues: info.hasIssues !== false,
722
- archived: info.archived === true,
723
- disabled: info.disabled === true,
724
- fork: info.fork === true,
725
- parent: info.parent || null,
726
- push: info.push === true,
727
- private: info.private === true,
728
- })
729
- if (note) warnings.push(note)
730
- return { warnings, access: { repo, push: info.push === true, private: info.private === true, fork: info.fork === true, hasIssues: info.hasIssues !== false, archived: info.archived === true, disabled: info.disabled === true, parent: info.parent || null, checkedAt: new Date().toISOString() } }
731
- }
732
-
733
- /** 隔离区占用:客户长期运行会攒下一堆一次性 worktree,面板上得看得见。 */
734
- function isolationReport(entries) {
735
- const roots = new Map()
736
- for (const entry of entries) {
737
- if (!entry || entry.isolated !== true || !entry.workdir) continue
738
- roots.set(entry.workdir, true)
739
- }
740
- let totalBytes = 0
741
- const list = []
742
- for (const workdir of roots.keys()) {
743
- const base = String(workdir).replace(/[\/]+$/, '') + '/.dsh-zhuli'
744
- let count = 0
745
- let bytes = 0
746
- try {
747
- for (const name of readdirSync(base)) {
748
- const full = base + '/' + name
749
- count += 1
750
- bytes += dirSize(full, 2)
751
- }
752
- } catch { /* 目录还没有就是 0 */ }
753
- totalBytes += bytes
754
- list.push({ workdir, count, bytes })
755
- }
756
- return { roots: list, totalBytes }
757
- }
758
-
759
- /** 递归算目录大小(深度有上限,够用来判断"是不是涨到几百 MB 了")。 */
760
- function dirSize(path, depth) {
761
- if (depth <= 0) return 0
762
- let total = 0
763
- let items = []
764
- try { items = readdirSync(path, { withFileTypes: true }) } catch { return 0 }
765
- for (const item of items) {
766
- const full = path + '/' + item.name
767
- if (item.isDirectory()) total += dirSize(full, depth - 1)
768
- else {
769
- try { total += statSync(full).size } catch {}
770
- }
771
- }
772
- return total
773
- }
774
-
775
-
776
- /**
777
- * 取一批 issue 的「最后评论」。并发跑、短超时、最多 3 条、失败静默 ——
778
- * 多出来的 API 调用只在这几种条件下发生,别让它变成常态开销。
779
- */
780
-
781
-
782
- /**
783
- * 已安装版本 vs 已加载版本。
784
- *
785
- * `SERVER_VERSION` 是**当前进程里加载的代码**的版本;磁盘上 package.json 的 version 是
786
- * **装好的**版本。两者不同 = 「文件换了,但宿主还在跑老模块」—— 这正是本机反复出现的情况
787
- * (client 热重载会生效,服务端不会,界面上看不出来)。
788
- */
789
- function installedVersion() {
790
- try {
791
- const here = dirname(fileURLToPath(import.meta.url))
792
- const pkg = JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf8'))
793
- return typeof pkg.version === 'string' ? pkg.version : null
794
- } catch { return null }
795
- }
796
-
797
- /** 当前 token 对应的账号(判断"最后一条评论是不是我们自己发的")。缓存 10 分钟。 */
798
- let viewerCache = { at: 0, login: null }
799
- async function viewerLogin() {
800
- if (viewerCache.login && Date.now() - viewerCache.at < 10 * 60 * 1000) return viewerCache.login
801
- try {
802
- const res = await run('gh', ['api', 'user', '--jq', '.login'], { timeoutMs: 12000, env: ghEnv() })
803
- if (res.code === 0) {
804
- const login = String(res.stdout || '').trim()
805
- if (login) { viewerCache = { at: Date.now(), login }; return login }
806
- }
807
- } catch {}
808
- return viewerCache.login
809
- }
810
-
811
- async function fetchLastComments(repo, items, maxItems = 3) {
812
- const targets = (items || []).filter((item) => Number(item.comments) > 0).slice(0, maxItems)
813
- if (targets.length === 0) return
814
- const me = await viewerLogin()
815
- const mark = (item, info) => {
816
- item.lastComment = {
817
- login: info.login,
818
- at: info.at,
819
- self: Boolean(me && String(info.login).toLowerCase() === me.toLowerCase()),
820
- }
821
- }
822
- // 首选:一次 GraphQL 批量(N 条评论 → 1 个请求)
823
- try {
824
- const [owner, name] = String(repo).split('/')
825
- const query = buildCommentBatchQuery(targets.length)
826
- const args = ['api', 'graphql', '-f', 'query=' + query, '-F', 'owner=' + owner, '-F', 'name=' + name]
827
- targets.forEach((item, i) => args.push('-F', 'n' + i + '=' + item.number))
828
- const res = await run('gh', args, { timeoutMs: 15000, env: ghEnv() })
829
- // 有 errors 但 data 有值时仍然可用(别的 issue 不存在不影响这一条)
830
- const payload = JSON.parse(String(res.stdout || '{}'))
831
- const parsed = parseCommentBatch(payload)
832
- let hit = 0
833
- for (const item of targets) {
834
- const info = parsed[String(item.number)]
835
- if (!info) continue
836
- if (info.login) mark(item, info)
837
- if (Array.isArray(info.linked) && info.linked.length > 0) item.linkedPr = info.linked
838
- hit += 1
839
- }
840
- if (hit > 0) return
841
- } catch { /* 落到 REST 兜底 */ }
842
- // 兜底:逐条 REST(GraphQL 不可用时仍要能工作)
843
- await Promise.all(targets.map(async (item) => {
844
- try {
845
- const res = await run('gh', ['api', `repos/${repo}/issues/${item.number}/comments?per_page=1&sort=created&direction=desc`,
846
- '--jq', '.[0] | {login: .user.login, at: .created_at}'], { timeoutMs: 12000, env: ghEnv() })
847
- if (res.code !== 0) return
848
- const parsed = JSON.parse(res.stdout)
849
- if (parsed && parsed.login) mark(item, { login: parsed.login, at: parsed.at })
850
- } catch { /* 少一行信息,不阻断唤醒 */ }
851
- }))
852
- }
853
-
854
- async function pollOnce(ctx, entry, baseMs) {
855
- // 活跃时段要**在拉 API 之前**判断:以前放在后面,夜里照样每 N 秒打一次 GitHub,纯浪费。
856
- // 不在时段内就把下一次轮询安排到"开门那一刻",攒着的条目不会多等一个周期。
857
- if (entry.activeHours && !inActiveHours(entry.activeHours)) {
858
- const wait = msUntilActiveWindow(entry.activeHours)
859
- entry.nextAt = new Date(Date.now() + wait).toISOString()
860
- entry.lastDeferred = `不在活跃时段(${entry.activeHours}),${Math.round(wait / 60000)} 分钟后开始`
861
- entry.deferReason = 'active-hours'
862
- noteEvent(entry, 'defer', entry.lastDeferred)
863
- return
864
- }
865
- // 条件请求:带上上次的 ETag,没变化时 GitHub 回 304,且**不计入**速率限制
866
- const args = ['api', '--include', `repos/${entry.repo}/issues?state=all&sort=updated&direction=desc&per_page=20`]
867
- if (entry.etag) args.push('-H', 'If-None-Match: ' + entry.etag)
868
- const res = await run('gh', args, { timeoutMs: 45000, env: ghEnv() })
869
- entry.lastPoll = new Date().toISOString()
870
- if (res.code !== 0) {
871
- // gh 把 304 当失败(非 2xx 就 exit 1):这不是错误,是「条件请求命中」
872
- if (/HTTP 304|304 Not Modified|not modified/i.test(String(res.stderr || '') + String(res.stdout || ''))) {
873
- entry.lastError = null
874
- entry.consecutiveFailures = 0
875
- entry.nextAt = null
876
- entry.lastDeferred = UNCHANGED_TEXT
877
- entry.deferReason = 'unchanged'
878
- noteEvent(entry, 'unchanged', entry.lastDeferred)
879
- return
880
- }
881
- // 先看是不是被限流:GH 的 secondary limit 会给 Retry-After,照它等最准
882
- const failure = parseGhInclude(res.stdout)
883
- const wait = retryAfterMs(failure.retryAfter)
884
- if (wait > 0) {
885
- entry.nextAt = new Date(Date.now() + wait).toISOString()
886
- entry.lastDeferred = '被 GitHub 限流,按 Retry-After 等 ' + Math.round(wait / 1000) + ' 秒'
887
- entry.deferReason = 'ratelimit'
888
- noteEvent(entry, 'ratelimit', entry.lastDeferred)
889
- entry.lastError = null
890
- return
891
- }
892
- const detail = redact(res.stderr).slice(0, 240)
893
- // 常见失败给一句能照着做的提示,别只丢原始 stderr
894
- const classified = classifyGhError(detail)
895
- setEntryError(entry, (classified.short + classified.hint).slice(0, 300))
896
- bumpFailure(entry, baseMs)
1
+ /**
2
+ * dsh-session-superagent — session-level superagent for DeepSeek Harness.
3
+ *
4
+ * Two capabilities, one package:
5
+ * 1. `github` / `repo_here` — call the GitHub API; the credential stays inside
6
+ * the plugin and every result is redacted before the model sees it.
7
+ * 2. `watch_start` / `watch_status` / `watch_stop` — watch one repository and
8
+ * wake THIS session when something changes, by queueing a follow-up turn.
9
+ *
10
+ * Design constraints (see MAINTENANCE.md):
11
+ * - never inject while the agent is running (draft-replay hazard);
12
+ * - per-item watermarks, so our own writes never wake us (no self-echo);
13
+ * - advance the watermark only after a wake actually landed.
14
+ */
15
+ import { execFileSync, spawn } from 'node:child_process'
16
+ import { createHash, randomUUID } from 'node:crypto'
17
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
18
+ import os, { homedir } from 'node:os'
19
+ import { dirname, isAbsolute, join } from 'node:path'
20
+ import { fileURLToPath } from 'node:url'
21
+
22
+ import { zstdDecompressSync } from 'node:zlib'
23
+
24
+ import { redact } from './redact.js'
25
+ import { decodeBody } from './body.js'
26
+ import {
27
+ advanceSeen, applyWatcherAction, batchFresh, decideWake, DEFAULT_ACK_LABEL, formatWatchText,
28
+ TRIAGE_SIGNALS, accessNote, buildCommentBatchQuery, classifyGhError, commentSummaryLine, parseCommentBatch, pickSuggestion, repoStructureNote, countReasons, filterReason, formatGhCall, hasAckLabel, jitterMs, parseGhInclude, retryAfterMs, throttleDelayMs, inActiveHours, newestUpdatedAt, nextDelayMs, enterActiveHoursDefer, permanentBackoffMs, pushAbsorbed, pushFiltered, normalizeFilters, partitionItems, passesFilters,
29
+ shouldRunCleanup,
30
+ bumpDailyWakes,
31
+ busierThanUsual,
32
+ countCapped,
33
+ statusView,
34
+ dailySummary,
35
+ suggestSessionCap,
36
+ itemTrace,
37
+ splitBatch,
38
+ mergeFilters, mergePollResult, mergeWakeTexts, pushEvent, silentStreak, msUntilActiveWindow, nextWaketimeAt, pruneSeen, sessionWakesLastHour, pruneWakeTimes, pushHistory, recordReported, staleWorktrees, worktreePlan,
39
+ } from './watch.js'
40
+
41
+ export const name = 'dsh-session-superagent'
42
+ /** 服务端版本:随 package.json 同步(meta 测试守着)。客户端据此挑「最新的那个实例」。 */
43
+ export const SERVER_VERSION = '0.9.118'
44
+ export const inject = ['tools', 'agents', 'webServer']
45
+ /** 一条会话每小时最多被唤醒几次(跨所有守累计)。单守上限挡不住多守叠加。 */
46
+ // 本进程启动时刻:用来区分「刚重启还没轮到」与「定时器真的丢了」
47
+ const PROCESS_STARTED_AT = Date.now()
48
+ // 「未变化」那句两处要一模一样:单点改文案不会漏另一处
49
+ // 记错误时同时记时间:面板要能说「这是 12 分钟前的」而不是默认它刚刚发生
50
+ function setEntryError(entry, text) {
51
+ entry.lastError = text
52
+ entry.lastErrorAt = new Date().toISOString()
53
+ }
54
+ const UNCHANGED_TEXT = '未变化(304,不计入速率限制)'
55
+ // 追溯找不到任何痕迹时的那句话:两个入口(工具 / HTTP)必须一模一样
56
+ const noTraceText = (number, scope) => '#' + number + ' 在' + (scope || '所有守') + ' 里都没有痕迹 —— 可能还没被轮询到,或者编号写错了。'
57
+
58
+ const DEFAULT_SESSION_WAKES = 12
59
+ // 一条会话最多挂多少守:再多轮询压力与上下文都会失控(20 条 × 每 60 秒已很密)
60
+ const MAX_WATCHERS_PER_SESSION = 20
61
+ /** 隔离区回收的最小间隔:没有超额时不必每次唤醒都跑 git。 */
62
+ const CLEANUP_INTERVAL_MS = 10 * 60 * 1000
63
+
64
+ /** 仅供测试:读写状态文件(生产代码不要用)。 */
65
+ export const __test = { readState, writeState, hardenSecretsFile, wakeMerged }
66
+
67
+ const STATE_DIR = process.env.DSH_SUPERAGENT_STATE
68
+ ? String(process.env.DSH_SUPERAGENT_STATE)
69
+ : join(homedir(), '.dsh', 'state', 'session-superagent')
70
+ const SECRETS_FILE = join(STATE_DIR, 'secrets.json')
71
+ const STATE_FILE = join(STATE_DIR, 'watchers.json')
72
+ const TRIGGER_FILE = join(STATE_DIR, 'trigger.json')
73
+ // 客户端探针只认这几个键(别的键一律丢弃,防止被任意网页写盘)
74
+ const CLIENT_NOTE_KEYS = new Set(['client-version', 'client-base', 'apply', 'desk-registered', 'desk-fail', 'orbit-registered', 'orbit-fail', 'orbit-mount', 'badge-registered', 'badge-mount', 'badge-state', 'error'])
75
+ const DEFAULT_COOLDOWN_MS = 180_000
76
+
77
+ /**
78
+ * 当前挂在这个进程上的路由 disposer。
79
+ *
80
+ * 宿主重载时若没走 dispose,旧实例会继续吃 HTTP 请求,而它的 ctx 可能已经 dispose ——
81
+ * 真机表现:面板建的 watcher 第一轮就报
82
+ * `cannot get required service "agents" in inactive context`(2026-11-02 复验)。
83
+ *
84
+ * 关键:宿主重载常常是**重新 import 一份模块**(模块级变量全新),所以光用模块级数组
85
+ * 接不过去 —— 必须挂在 `globalThis` 上(用 Symbol.for 做键,多个模块实例共享同一个)。
86
+ */
87
+ // 这三个结构必须跨模块实例共享:宿主重载常常是重新 import 一份模块,
88
+ // 模块级变量全新,但进程只有一个。新实例要能清掉旧实例的路由与定时器,
89
+ // 也要能看见旧实例「正在跑的那轮」(否则并发闸形同虚设)。
90
+ const TIMERS_KEY = Symbol.for('dsh-session-superagent.timers')
91
+ const INFLIGHT_KEY = Symbol.for('dsh-session-superagent.inFlight')
92
+ const sharedTimers = (globalThis[TIMERS_KEY] ||= new Map())
93
+ const sharedInFlight = (globalThis[INFLIGHT_KEY] ||= new Set())
94
+
95
+ const DEFAULT_ROUTE_BASE = '/session-superagent'
96
+ const ROUTE_GEN_KEY = Symbol.for('dsh-session-superagent.routeGeneration')
97
+ /** 本实例实际使用的路由前缀(正常情况下等于默认前缀)。 */
98
+ let activeBase = DEFAULT_ROUTE_BASE
99
+ const ROUTES_KEY = Symbol.for('dsh-session-superagent.activeRoutes')
100
+ const activeRoutes = (globalThis[ROUTES_KEY] ||= [])
101
+
102
+ // 最后一次成功读取的来源:正常 / 备份恢复 / 全新。面板与 /diagnose 会带上它。
103
+ let stateSource = 'new'
104
+
105
+ /**
106
+ * 读状态文件。主文件坏了就退回上一次的备份(`.bak`),而不是直接当空状态 ——
107
+ * 当空的后果是「客户所有守一夜消失」,这比多留一个备份文件糟糕得多。
108
+ * 思路同 SQLite 的 WAL:**先保证有一份已提交的好副本**,再覆盖。
109
+ */
110
+ function readState() {
111
+ let raw
112
+ try {
113
+ raw = readFileSync(STATE_FILE, 'utf8')
114
+ } catch {
115
+ stateSource = 'new'
116
+ return { watchers: {} }
117
+ }
118
+ try {
119
+ const parsed = JSON.parse(raw)
120
+ stateSource = 'ok'
121
+ return parsed
122
+ } catch {
123
+ // 主文件坏了:试试备份
124
+ try {
125
+ const backup = JSON.parse(readFileSync(STATE_FILE + '.bak', 'utf8'))
126
+ stateSource = 'backup'
127
+ // 把备份写回主文件,避免下次还走恢复路径
128
+ try { writeFileSync(STATE_FILE, JSON.stringify(backup, null, 2)) } catch {}
129
+ return backup
130
+ } catch {
131
+ // 备份也没了/也坏了:把坏文件留个证据,再从空状态开始
132
+ stateSource = 'corrupt'
133
+ try { renameSync(STATE_FILE, STATE_FILE + '.corrupt-' + Date.now()) } catch {}
134
+ return { watchers: {} }
135
+ }
136
+ }
137
+ }
138
+
139
+ function writeState(state) {
140
+ try {
141
+ mkdirSync(STATE_DIR, { recursive: true })
142
+ // 合并写:调用方手里的 state 可能是很久以前读的快照(宿主重载、两个实例交替写),
143
+ // 直接整份覆盖会把别人刚建的 watcher 抹掉 —— 真机上丢过两条(一条是用户的)。
144
+ // 规则:盘上有、内存里没有的条目一律保留;只有墓碑里的 id 才允许消失。
145
+ const disk = readState()
146
+ const tombstones = { ...(disk.deleted || {}), ...(state.deleted || {}) }
147
+ const merged = { ...disk, ...state }
148
+ merged.watchers = { ...(disk.watchers || {}) }
149
+ for (const [id, watcher] of Object.entries(state.watchers || {})) merged.watchers[id] = watcher
150
+ const now = Date.now()
151
+ for (const [id, at] of Object.entries(tombstones)) {
152
+ delete merged.watchers[id]
153
+ // 墓碑留 7 天足够覆盖任何迟到写入
154
+ if (now - Date.parse(at) > 7 * 24 * 3600 * 1000) delete tombstones[id]
155
+ }
156
+ if (Object.keys(tombstones).length > 0) merged.deleted = tombstones
157
+ else delete merged.deleted
158
+
159
+ const text = JSON.stringify(merged, null, 1)
160
+ // 原子写:写一半崩掉不该把全部 watcher 清空
161
+ const tmp = STATE_FILE + '.tmp'
162
+ writeFileSync(tmp, text)
163
+ // 覆盖前先把「当前这份好的」留成备份:主文件将来被写坏(断电、磁盘满、手改),
164
+ // readState 还能退回来,而不是把客户所有守当成空状态。
165
+ try {
166
+ const current = readFileSync(STATE_FILE, 'utf8')
167
+ JSON.parse(current) // 只有当前文件是好的才备份,别把坏文件备份成"好版本"
168
+ writeFileSync(STATE_FILE + '.bak', current)
169
+ } catch {}
170
+ try { renameSync(tmp, STATE_FILE) } catch { writeFileSync(STATE_FILE, text) }
171
+ // 第一次写入时盘上还没有好文件,`.bak` 会是空的 —— 那就等于没有备份。
172
+ // 主文件一坏(断电/手改/磁盘满)就会丢掉全部守。所以这里补一份引导备份。
173
+ if (!existsSync(STATE_FILE + '.bak')) {
174
+ try { writeFileSync(STATE_FILE + '.bak', text) } catch {}
175
+ }
176
+ return merged
177
+ } catch { return state /* state is best-effort: a failed write must not break a turn */ }
178
+ }
179
+
180
+ /** Credentials the operator typed in the panel. Never returned in plain text. */
181
+ function readSecrets() {
182
+ try {
183
+ const raw = JSON.parse(readFileSync(SECRETS_FILE, 'utf8'))
184
+ return raw && typeof raw === 'object' ? raw : {}
185
+ } catch { return {} }
186
+ }
187
+
188
+ function writeSecrets(next) {
189
+ try {
190
+ mkdirSync(STATE_DIR, { recursive: true })
191
+ writeFileSync(SECRETS_FILE, JSON.stringify(next, null, 1), { mode: 0o600 })
192
+ // mode 在 Windows 上几乎无效,补 ACL(见 hardenSecretsFile 注释)
193
+ hardenSecretsFile(SECRETS_FILE)
194
+ } catch {}
195
+ }
196
+
197
+ /** A masked view of what is configured: shape only, never the value. */
198
+ function secretsSummary() {
199
+ const s = readSecrets()
200
+ return {
201
+ token: s.token ? 'configured' : 'none',
202
+ // 只回「有没有配」:连首尾各 4 个字符也算信息泄露
203
+ tokenHint: s.token ? 'configured' : null,
204
+ sshKeyPath: s.sshKeyPath ? 'configured' : 'none',
205
+ // 从不在面板回显路径(Windows 路径里的反斜杠曾让掩码整段漏出)
206
+ sshKeyHint: null,
207
+ updatedAt: s.updatedAt ?? null,
208
+ }
209
+ }
210
+
211
+ const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
212
+ const titleCache = new Map()
213
+
214
+ /** Decompress a multi-frame zstd session log into text. */
215
+ function readFrames(buffer) {
216
+ const starts = []
217
+ let index = 0
218
+ while ((index = buffer.indexOf(ZSTD_MAGIC, index)) !== -1) { starts.push(index); index += 4 }
219
+ if (starts.length === 0 || starts[0] !== 0) starts.unshift(0)
220
+ const parts = []
221
+ for (let k = 0; k < starts.length; k += 1) {
222
+ const end = k + 1 < starts.length ? starts[k + 1] : buffer.length
223
+ try { parts.push(zstdDecompressSync(buffer.subarray(starts[k], end)).toString('utf8')) } catch {}
224
+ }
225
+ return parts.join('')
226
+ }
227
+
228
+ /** The human title the sidebar shows for a session, read from its own log. Cached by file mtime. */
229
+ /** sessionId → 会话日志路径的索引缓存(60 秒 TTL;命中后只 stat 单个文件)。 */
230
+ const sessionFileCache = { at: 0, byId: new Map() }
231
+
232
+ function sessionTitle(sessionId) {
233
+ try {
234
+ if (!sessionId) return null
235
+ const home = process.env.DSH_HOME && String(process.env.DSH_HOME).trim()
236
+ ? String(process.env.DSH_HOME).trim()
237
+ : join(homedir(), '.dsh')
238
+ const root = join(home, 'sessions')
239
+ // 目录索引缓存:/state 每 5 秒一次 × 每条 watcher,全量 readdir + existsSync 太亏。
240
+ // 关键:miss 也要走 TTL(负缓存)—— 只要有一个 watcher 的会话日志不存在,
241
+ // 每次 /state 都全量重建会把 0.6ms 拖成 130-500ms(终审实测 200/800 会话两种规模)。
242
+ if (Date.now() - sessionFileCache.at > 60 * 1000) {
243
+ sessionFileCache.byId.clear()
244
+ for (const group of readdirSync(root)) {
245
+ const dir = join(root, group)
246
+ let names = []
247
+ try { names = readdirSync(dir) } catch { continue }
248
+ for (const name of names) {
249
+ const candidate = join(dir, name, 'session.v4.jsonl.zstd')
250
+ if (existsSync(candidate)) sessionFileCache.byId.set(name, candidate)
251
+ }
252
+ }
253
+ sessionFileCache.at = Date.now()
254
+ }
255
+ const file = sessionFileCache.byId.get(sessionId) || null
256
+ if (!file) return null
257
+ const stat = statSync(file)
258
+ const cached = titleCache.get(sessionId)
259
+ if (cached && cached.mtime === stat.mtimeMs && cached.size === stat.size) return cached.title
260
+ let title = null
261
+ const lines = readFrames(readFileSync(file)).split(String.fromCharCode(10))
262
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
263
+ const line = lines[i]
264
+ if (!line || line.indexOf('"session/title"') === -1) continue
265
+ try {
266
+ const parsed = JSON.parse(line)
267
+ if (parsed && parsed.type === 'session/title' && parsed.data && typeof parsed.data.title === 'string') {
268
+ title = parsed.data.title
269
+ break
270
+ }
271
+ } catch {}
272
+ }
273
+ titleCache.set(sessionId, { mtime: stat.mtimeMs, size: stat.size, title })
274
+ return title
275
+ } catch { return null }
276
+ }
277
+
278
+ /**
279
+ * The session's real goal, read through the host's own goal service — the same
280
+ * one `/goal` and the create_goal tool use. Returns null when the host has no
281
+ * goal service or the session has no current goal.
282
+ */
283
+ function goalView(ctx, sessionId) {
284
+ try {
285
+ if (!sessionId || typeof ctx.get !== 'function') return null
286
+ const goals = ctx.get('goals')
287
+ const agents = ctx.get('agents')
288
+ if (!goals || !agents || typeof goals.get !== 'function') return null
289
+ const agent = agents.get(sessionId)
290
+ if (!agent) return null
291
+ const view = goals.get(agent)
292
+ if (!view) return null
293
+ return {
294
+ objective: view.objective ?? null,
295
+ phase: view.phase ?? null,
296
+ revision: view.ref ? view.ref.revision : (view.revision ?? null),
297
+ }
298
+ } catch { return null }
299
+ }
300
+
301
+ /** Environment for every gh call: a panel token wins over the CLI login. */
302
+ function ghEnv() {
303
+ const s = readSecrets()
304
+ if (!s.token) return process.env
305
+ return { ...process.env, GH_TOKEN: String(s.token) }
306
+ }
307
+
308
+ /**
309
+ * 安全地取 agents 服务。
310
+ * 定时器回调跑在「非活跃上下文」里,直接读 `ctx.agents` 会抛
311
+ * `cannot get required service "agents" in inactive context`(2026-11-02 真机复验踩到);
312
+ * `ctx.get(name)` 不抛,取不到就返回 undefined。
313
+ */
314
+ function agentsService(ctx) {
315
+ try {
316
+ if (typeof ctx.get === 'function') {
317
+ const viaGet = ctx.get('agents')
318
+ if (viaGet) return viaGet
319
+ }
320
+ } catch {}
321
+ try { return ctx.agents } catch { return undefined }
322
+ }
323
+
324
+ /** gh CLI 可用性探针:5 分钟缓存,别让面板每 5 秒都 spawn 一次 gh。 */
325
+ const ghHealthCache = { at: 0, value: null }
326
+ async function ghHealth() {
327
+ if (Date.now() - ghHealthCache.at < 5 * 60 * 1000 && ghHealthCache.value) return ghHealthCache.value
328
+ let value
329
+ try {
330
+ const res = await run('gh', ['--version'], { timeoutMs: 10000 })
331
+ value = res.code === 0
332
+ ? { ok: true, version: String(res.stdout || '').trim().split(String.fromCharCode(10))[0].slice(0, 80) }
333
+ : { ok: false, error: redact([res.stderr, res.stdout].join(' ')).slice(0, 160) }
334
+ } catch (error) {
335
+ value = { ok: false, error: String((error && error.message) || error).slice(0, 160) }
336
+ }
337
+ ghHealthCache.at = Date.now()
338
+ ghHealthCache.value = value
339
+ return value
340
+ }
341
+
342
+ function persistEntry(entry) {
343
+ try {
344
+ const state = readState()
345
+ state.watchers = state.watchers || {}
346
+ const stored = state.watchers[entry.id]
347
+ // Deleted between the tick start and its write-back: never resurrect it.
348
+ if (!stored) return
349
+ state.watchers[entry.id] = mergePollResult(stored, entry)
350
+ writeState(state)
351
+ } catch {}
352
+ }
353
+
354
+ /**
355
+ * 失败退避:连续失败就把下一次允许轮询的时间往后推(30s → 60 → 120 … 上限 30min)。
356
+ * 竞品的教训很直白 —— 401 的时候还按 30 秒撞墙,只会把配额和日志一起打光。
357
+ */
358
+ /**
359
+ * 记一条时间线事件(有界、只存在状态里)。
360
+ * 目的:回答"为什么这一轮没叫醒我" —— 以前只有 lastDeferred 一句,看不出前后因果。
361
+ */
362
+ function noteEvent(entry, kind, text) {
363
+ try {
364
+ entry.events = pushEvent(entry.events, { kind, text })
365
+ } catch { /* 观测失败不能影响主流程 */ }
366
+ }
367
+
368
+ // 实际间隔:自己的配置与 GitHub 要求的 x-poll-interval 取大者
369
+ function effectiveIntervalMs(entry, baseMs) {
370
+ const floor = (Number(entry.minIntervalSec) || 0) * 1000
371
+ return Math.max(Number(baseMs) || 0, floor)
372
+ }
373
+
374
+ function bumpFailure(entry, baseMs) {
375
+ entry.consecutiveFailures = (Number(entry.consecutiveFailures) || 0) + 1
376
+ entry.nextAt = new Date(Date.now() + nextDelayMs(entry, effectiveIntervalMs(entry, baseMs || 60000))).toISOString()
377
+ }
378
+
379
+ /**
380
+ * 回收过期的隔离区:每次唤醒都会开一个新 worktree,不回收就会一直涨。
381
+ * 只删 .dsh-zhuli/ 下超过 keepDays 天没动过的目录,删不掉就留着(不阻断唤醒)。
382
+ */
383
+ async function cleanupWorktrees(workdir, keepDays = 3, keepCount = 5, options = {}) {
384
+ if (!workdir) return 0
385
+ const BS = String.fromCharCode(92)
386
+ const base = String(workdir).split(BS).join('/').replace(/\/+$/, '')
387
+ const root = base + '/.dsh-zhuli'
388
+ let names = []
389
+ try { names = readdirSync(root) } catch { return 0 }
390
+
391
+ // 节流:没有超额就不必每次都跑 git(remove / prune / branch -D 都是进程级开销)
392
+ const decision = shouldRunCleanup({
393
+ count: names.length,
394
+ keepCount,
395
+ lastRunAt: Number(options.lastRunAt) || 0,
396
+ intervalMs: CLEANUP_INTERVAL_MS,
397
+ })
398
+ if (!decision.run) return 0
399
+ if (typeof options.onRun === 'function') options.onRun(decision.reason)
400
+ const entries = []
401
+ for (const name of names) {
402
+ try { entries.push({ name, mtimeMs: statSync(root + '/' + name).mtimeMs }) } catch {}
403
+ }
404
+ // 数量线:最近 N 个留着(默认 5),其余回收 —— 年龄线管不住"堆"
405
+ const stale = staleWorktrees(entries, { keepMs: keepDays * 24 * 3600 * 1000, keepCount: Number(keepCount) || 5 })
406
+ let removed = 0
407
+ for (const item of stale) {
408
+ const target = root + '/' + item.name
409
+ const res = await run('git', ['-C', workdir, 'worktree', 'remove', '--force', target], { timeoutMs: 30000 })
410
+ if (res.code !== 0) {
411
+ // 已经不是工作树(孤儿目录):直接删目录,别让它永远留着
412
+ try { rmSync(target, { recursive: true, force: true }) } catch {}
413
+ // 关键:目录删了,但 git 的 `worktrees/<id>/` 管理文件还在 —— 不 prune 的话
414
+ // `git worktree list` 会一直显示一个已经不存在的目录。
415
+ // 依据:git-worktree 文档里 `prune` 的职责正是「清掉那些目录已经不在了的管理记录」。
416
+ await run('git', ['-C', workdir, 'worktree', 'prune'], { timeoutMs: 20000 })
417
+ } else {
418
+ removed += 1
419
+ }
420
+ // 无论 worktree 是否删成功,都试着删分支:每次唤醒一个新分支,不删会无限涨
421
+ await run('git', ['-C', workdir, 'branch', '-D', 'zhuli/' + item.name], { timeoutMs: 30000 })
422
+ }
423
+ return removed
424
+ }
425
+
426
+ /**
427
+ * 给一次唤醒准备隔离工作区:在目标仓库上开一个一次性 git worktree。
428
+ * 失败不阻断唤醒 —— 退化成普通模式,并在消息里说明原因。
429
+ */
430
+ /**
431
+ * 让隔离区不污染客户的 `git status`。
432
+ *
433
+ * 隔离区开在仓库内的 .dsh-zhuli/ 下,默认是**未跟踪目录** ——
434
+ * 客户一切 git status 就会看到它,甚至可能顺手 git add 进去。
435
+ * 写到 `.git/info/exclude`(本地、不提交、不修改客户的 .gitignore)最合适。
436
+ */
437
+ async function ensureIsolationExcluded(workdir) {
438
+ try {
439
+ const res = await run('git', ['-C', workdir, 'rev-parse', '--git-path', 'info/exclude'], { timeoutMs: 15000 })
440
+ if (res.code !== 0) return false
441
+ const file = String(res.stdout || '').trim()
442
+ if (!file) return false
443
+ let current = ''
444
+ try { current = readFileSync(file, 'utf8') } catch { current = '' }
445
+ if (current.split(/\r?\n/).includes('.dsh-zhuli/')) return true
446
+ const next = current + (current.endsWith('\n') || current === '' ? '' : '\n') + '.dsh-zhuli/' + '\n'
447
+ writeFileSync(file, next)
448
+ return true
449
+ } catch {
450
+ return false
451
+ }
452
+ }
453
+
454
+ async function prepareIsolation(entry) {
455
+ if (!entry || !entry.isolated || !entry.workdir) return null
456
+ const plan = worktreePlan({ workdir: entry.workdir, repo: entry.repo, sessionTag: entry.sessionId })
457
+ try {
458
+ // 先回收过期隔离区,再开新的
459
+ await cleanupWorktrees(entry.workdir, Number(entry.isolateKeepDays) || 3, Number(entry.maxIsolated) || 5, {
460
+ lastRunAt: Number(entry.lastCleanupAt) || 0,
461
+ onRun: () => { entry.lastCleanupAt = Date.now() },
462
+ })
463
+ await ensureIsolationExcluded(entry.workdir)
464
+ const res = await run('git', ['-C', entry.workdir, 'worktree', 'add', plan.dir, '-b', plan.branch], { timeoutMs: 45000 })
465
+ if (res.code !== 0) {
466
+ return { error: redact([res.stderr, res.stdout].filter(Boolean).join(' ')).slice(0, 200) }
467
+ }
468
+ return plan
469
+ } catch (error) {
470
+ return { error: String((error && error.message) || error).slice(0, 200) }
471
+ }
472
+ }
473
+
474
+ /** Spawn a command, capture both streams, never echo the credential. */
475
+ /**
476
+ * 离线模式(`DSH_SUPERAGENT_OFFLINE=1`):所有 `gh` 调用返回固定内容,不碰网络。
477
+ *
478
+ * 为什么需要:单测/CI 里没有有效凭证时,每次 `gh api` 都要等到超时,
479
+ * 一个测试文件能跑 100 秒(真机实测);而它们的断言与网络无关。
480
+ * 生产里不会设这个变量 —— 开启后结果都是假的,只适合测试。
481
+ */
482
+ function offlineGhReply(args) {
483
+ const joined = (args || []).join(' ')
484
+ if (joined.includes('--version')) return 'gh version 2.0.0 (offline)'
485
+ if (joined.includes('api -i user')) return 'HTTP/2.0 200 OK' + String.fromCharCode(13, 10) + String.fromCharCode(13, 10)
486
+ if (joined.includes('api user')) return 'offline-user'
487
+ if (joined.includes('labels')) return '{}'
488
+ const repoMatch = joined.match(new RegExp('repos/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)'))
489
+ return JSON.stringify({ full_name: repoMatch ? repoMatch[1] : 'offline/repo', private: false, items: [], total_count: 0 })
490
+ }
491
+
492
+ function run(file, args, options = {}) {
493
+ const { input, cwd, env, timeoutMs = 60000 } = options
494
+ return new Promise((resolve) => {
495
+ if (file === 'gh' && process.env.DSH_SUPERAGENT_OFFLINE === '1') {
496
+ resolve({ code: 0, stdout: offlineGhReply(args), stderr: '' })
497
+ return
498
+ }
499
+ const child = spawn(file, args, { cwd, env: env ?? process.env, windowsHide: true, shell: false })
500
+ let stdout = ''
501
+ let stderr = ''
502
+ let settled = false
503
+ const timer = setTimeout(() => {
504
+ if (settled) return
505
+ settled = true
506
+ try { child.kill('SIGKILL') } catch {}
507
+ resolve({ code: 'timeout', stdout, stderr })
508
+ }, timeoutMs)
509
+ child.stdout.on('data', (d) => { stdout += d.toString('utf8') })
510
+ child.stderr.on('data', (d) => { stderr += d.toString('utf8') })
511
+ child.on('error', (e) => {
512
+ if (settled) return
513
+ settled = true
514
+ clearTimeout(timer)
515
+ resolve({ code: 'spawn-error', stdout, stderr: String((e && e.message) || e) })
516
+ })
517
+ child.on('close', (c) => {
518
+ if (settled) return
519
+ settled = true
520
+ clearTimeout(timer)
521
+ resolve({ code: c === null ? 0 : c, stdout, stderr })
522
+ })
523
+ if (input !== undefined) child.stdin.write(input)
524
+ child.stdin.end()
525
+ })
526
+ }
527
+
528
+ function defineTool(options) {
529
+ const properties = {}
530
+ const required = []
531
+ for (const [key, spec] of Object.entries(options.parameters)) {
532
+ properties[key] = {}
533
+ if (spec.type) properties[key].type = spec.type
534
+ if (spec.description) properties[key].description = spec.description
535
+ if (spec.required) required.push(key)
536
+ }
537
+ return {
538
+ name: options.name,
539
+ description: options.description,
540
+ parameters: { type: 'object', properties, ...(required.length ? { required } : {}) },
541
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
542
+ async execute(args) {
543
+ const record = args && typeof args === 'object' ? args : {}
544
+ for (const key of required) {
545
+ if (record[key] === undefined || record[key] === null || record[key] === '') {
546
+ return `[error: missing required parameter "${key}"]`
547
+ }
548
+ }
549
+ return options.execute(record)
550
+ },
551
+ }
552
+ }
553
+
554
+ /**
555
+ * Wake one live session with a user message.
556
+ *
557
+ * `Agent.followup()` queues an ordinary turn AND wakes the driver; the durable
558
+ * inbox alone only parks the message (the client shows it as a pending draft).
559
+ */
560
+
561
+ /**
562
+ * 同会话几秒内的多条唤醒合并成一条再注入。
563
+ *
564
+ * 实测:同会话 3 个守、间隔 60 秒时,首轮抖动只把相位拉开 ≤5 秒 —— 之后每一轮都一样,
565
+ * 于是三次唤醒落在约 1 秒内,会话连着收到 3 条注入(5 个守就是 5 条)。
566
+ * 不做硬间隔,是因为"先到的守永远赢"会把后面的饿死;**合并**既不丢也不饿死。
567
+ */
568
+ // 合并窗口:生产 3 秒;测试里可用环境变量压到毫秒级,避免用例等 3 秒
569
+ const WAKE_WINDOW_MS = Number(process.env.DSH_SUPERAGENT_WAKE_WINDOW_MS) || 3000
570
+ const wakeBuffers = new Map()
571
+
572
+ function wakeMerged(ctx, sessionId, text, onSettled) {
573
+ const now = Date.now()
574
+ const buf = wakeBuffers.get(sessionId) || { parts: [], timer: null, openedAt: now, settled: [] }
575
+ buf.parts.push(text)
576
+ if (onSettled) buf.settled.push(onSettled)
577
+ if (buf.timer) return { ok: true, merged: true, pending: buf.parts.length }
578
+ buf.timer = setTimeout(() => {
579
+ wakeBuffers.delete(sessionId)
580
+ let result = { ok: false, reason: 'merged empty' }
581
+ try {
582
+ const merged = mergeWakeTexts(buf.parts)
583
+ if (merged) result = wake(ctx, sessionId, merged)
584
+ } catch (error) {
585
+ result = { ok: false, reason: String((error && error.message) || error) }
586
+ }
587
+ // 关键:真正发送之后才回调 —— 记账(唤醒次数、水位、历史)不能提前
588
+ for (const cb of buf.settled) {
589
+ try { cb(result) } catch { /* 单个回调失败不影响其它 */ }
590
+ }
591
+ }, WAKE_WINDOW_MS)
592
+ if (buf.timer && typeof buf.timer.unref === 'function') buf.timer.unref()
593
+ wakeBuffers.set(sessionId, buf)
594
+ return { ok: true, merged: true, pending: buf.parts.length }
595
+ }
596
+
597
+ function wake(ctx, sessionId, text) {
598
+ const agents = agentsService(ctx)
599
+ const agent = agents && typeof agents.get === 'function' ? agents.get(sessionId) : undefined
600
+ if (!agent) return { ok: false, reason: 'session not live' }
601
+
602
+ const allowed = decideWake(agent.status)
603
+ if (!allowed.ok) return allowed
604
+
605
+ const message = {
606
+ id: randomUUID(),
607
+ role: 'user',
608
+ content: [{ type: 'text', text }],
609
+ source: { kind: 'user' },
610
+ }
611
+ try {
612
+ if (typeof agent.followup === 'function') {
613
+ agent.followup(message)
614
+ return { ok: true, via: 'followup' }
615
+ }
616
+ if (typeof agent.steer === 'function') {
617
+ agent.steer(message)
618
+ return { ok: true, via: 'steer' }
619
+ }
620
+ const inbox = agent.inbox || (agent.session && agent.session.inbox)
621
+ if (inbox && typeof inbox.append === 'function') {
622
+ inbox.append('next-turn', message)
623
+ return { ok: true, via: 'inbox.append' }
624
+ }
625
+ return { ok: false, reason: 'no followup/steer/inbox on agent' }
626
+ } catch (error) {
627
+ return { ok: false, reason: `throw: ${String((error && error.message) || error)}` }
628
+ }
629
+ }
630
+
631
+
632
+
633
+ /**
634
+ * 收紧凭证文件权限。
635
+ *
636
+ * Node 文档明确:**on Windows only the write permission can be changed, and the distinction
637
+ * among the permissions of group, owner, or others is not implemented** —— 也就是说
638
+ * 光靠 `mode: 0o600` 在 Windows 上约等于没有保护,同机其他账户仍可能读到 token。
639
+ * 所以在 Windows 上补一条 icacls:断开继承,只给当前用户完全控制。
640
+ * 出处:https://nodejs.org/api/fs.html(fs.chmod 的 Caveats)
641
+ */
642
+ let secretsHardened = 'unknown'
643
+ function hardenSecretsFile(file) {
644
+ if (process.platform !== 'win32') {
645
+ try {
646
+ chmodSync(file, 0o600)
647
+ secretsHardened = 'posix-0600'
648
+ } catch { secretsHardened = 'failed' }
649
+ return secretsHardened
650
+ }
651
+ try {
652
+ const user = os.userInfo().username
653
+ execFileSync('icacls', [file, '/inheritance:r', '/grant:r', user + ':F'], { stdio: 'ignore', timeout: 15000 })
654
+ secretsHardened = 'win32-acl'
655
+ } catch {
656
+ secretsHardened = 'failed'
657
+ }
658
+ return secretsHardened
659
+ }
660
+
661
+
662
+ /**
663
+ * token 的权限范围(scopes)。
664
+ *
665
+ * 为什么值得看:GitHub 明确建议「最小权限」——细粒度 token 按端点授予,
666
+ * 而经典 PAT 的 `repo` 一把就是全仓库读写。我们的实现只需要
667
+ * 「读 issue/PR + 写评论和标签」,用 `delete:packages`、`admin:repo_hook` 这类 scope 纯属多余暴露。
668
+ * 出处:https://docs.github.com/en/rest/authentication/permissions-required-for-fine-grained-personal-access-tokens
669
+ *
670
+ * 探测成本约 0.5 秒(起一个 gh 进程),所以缓存 5 分钟,别在每次 /state 里都跑。
671
+ */
672
+ let scopesCache = { at: 0, value: null }
673
+ const BROAD_SCOPES = ['delete:packages', 'admin:repo_hook', 'admin:org', 'workflow', 'write:packages', 'admin:public_key']
674
+
675
+ async function tokenScopes() {
676
+ if (scopesCache.value && Date.now() - scopesCache.at < 5 * 60 * 1000) return scopesCache.value
677
+ const res = await run('gh', ['api', '-i', 'user'], { timeoutMs: 20000, env: ghEnv() })
678
+ let value = { ok: false, scopes: [], broad: [], error: null, checkedAt: new Date().toISOString() }
679
+ if (res.code !== 0) {
680
+ value.error = redact(res.stderr).slice(0, 160)
681
+ } else {
682
+ const text = String(res.stdout || '')
683
+ const line = text.split(String.fromCharCode(10)).find((l) => l.toLowerCase().startsWith('x-oauth-scopes:'))
684
+ const raw = line ? line.slice('x-oauth-scopes:'.length).trim() : ''
685
+ const scopes = raw ? raw.split(',').map((v) => v.trim()).filter(Boolean) : []
686
+ value = {
687
+ ok: true,
688
+ scopes,
689
+ broad: scopes.filter((scope) => BROAD_SCOPES.includes(scope)),
690
+ error: null,
691
+ checkedAt: new Date().toISOString(),
692
+ }
693
+ }
694
+ scopesCache = { at: Date.now(), value }
695
+ return value
696
+ }
697
+
698
+
699
+ /**
700
+ * 新增守之前的即时体检:仓库在不在、能不能写、有没有 issue。
701
+ *
702
+ * 为什么放在这里:`probeAccess` 是后台跑的,客户要等到下一次 /state 才看到提示;
703
+ * 而"填错仓库名"是最常见的输入错误,应该在点「添加」那一刻就说。
704
+ *
705
+ * 依据:`GET /repos/{owner}/{repo}` 对不存在的仓库(或无权访问的私有仓库)返回 404 ——
706
+ * 官方文档把这两种情况归为同一个响应,所以文案要一起说「不存在或没有权限」。
707
+ * 出处:https://docs.github.com/en/rest/repos/repos#get-a-repository
708
+ *
709
+ * 注意:**只产出警告,不阻止创建** —— 网络抖动不该让客户没法添加;
710
+ * 测试环境(DSH_SUPERAGENT_NO_POLL=1)直接跳过,避免单测依赖网络。
711
+ */
712
+ async function precheckRepo(repo) {
713
+ const warnings = []
714
+ if (process.env.DSH_SUPERAGENT_NO_POLL === '1') return { warnings, skipped: true }
715
+ const res = await run('gh', ['api', 'repos/' + repo, '--jq',
716
+ '{push: .permissions.push, hasIssues: .has_issues, archived: .archived, disabled: .disabled, private: .private, fork: .fork, parent: (.parent.full_name // null)}',
717
+ ], { timeoutMs: 10000, env: ghEnv() })
718
+ if (res.code !== 0) {
719
+ const detail = redact(res.stderr)
720
+ if (detail.includes('404')) {
721
+ let hint = ''
722
+ // 只在 404 之后才搜一次:search 池是 30 次/分钟(core 是 5000),不能滥用
723
+ const name = repo.split('/')[1] || repo
724
+ if (name.length >= 5) {
725
+ const search = await run('gh', ['api', 'search/repositories?q=' + encodeURIComponent(name + ' in:name') + '&per_page=5', '--jq', '.items[].full_name'],
726
+ { timeoutMs: 10000, env: ghEnv() })
727
+ if (search.code === 0) {
728
+ const picked = pickSuggestion(repo, String(search.stdout || '').split(String.fromCharCode(10)).map((v) => v.trim()).filter(Boolean))
729
+ if (picked) hint = ' 是不是想填 ' + picked + '?'
730
+ }
731
+ }
732
+ warnings.push('仓库 ' + repo + ' 不存在,或当前 token 没有访问权限 —— 先确认名字(owner/name)与权限。' + hint)
733
+ return { warnings, notFound: true }
734
+ }
735
+ warnings.push('添加前没能确认这个仓库(' + detail.slice(0, 100) + '),稍后会在面板里再次探测。')
736
+ return { warnings }
737
+ }
738
+ let info = {}
739
+ try { info = JSON.parse(res.stdout) } catch { return { warnings } }
740
+ const note = repoStructureNote({
741
+ repo,
742
+ hasIssues: info.hasIssues !== false,
743
+ archived: info.archived === true,
744
+ disabled: info.disabled === true,
745
+ fork: info.fork === true,
746
+ parent: info.parent || null,
747
+ push: info.push === true,
748
+ private: info.private === true,
749
+ })
750
+ if (note) warnings.push(note)
751
+ return { warnings, access: { repo, push: info.push === true, private: info.private === true, fork: info.fork === true, hasIssues: info.hasIssues !== false, archived: info.archived === true, disabled: info.disabled === true, parent: info.parent || null, checkedAt: new Date().toISOString() } }
752
+ }
753
+
754
+ /** 隔离区占用:客户长期运行会攒下一堆一次性 worktree,面板上得看得见。 */
755
+ function isolationReport(entries) {
756
+ const roots = new Map()
757
+ for (const entry of entries) {
758
+ if (!entry || entry.isolated !== true || !entry.workdir) continue
759
+ roots.set(entry.workdir, true)
760
+ }
761
+ let totalBytes = 0
762
+ const list = []
763
+ for (const workdir of roots.keys()) {
764
+ const base = String(workdir).replace(/[\/]+$/, '') + '/.dsh-zhuli'
765
+ let count = 0
766
+ let bytes = 0
767
+ try {
768
+ for (const name of readdirSync(base)) {
769
+ const full = base + '/' + name
770
+ count += 1
771
+ bytes += dirSize(full, 2)
772
+ }
773
+ } catch { /* 目录还没有就是 0 */ }
774
+ totalBytes += bytes
775
+ list.push({ workdir, count, bytes })
776
+ }
777
+ return { roots: list, totalBytes }
778
+ }
779
+
780
+ /** 递归算目录大小(深度有上限,够用来判断"是不是涨到几百 MB 了")。 */
781
+ function dirSize(path, depth) {
782
+ if (depth <= 0) return 0
783
+ let total = 0
784
+ let items = []
785
+ try { items = readdirSync(path, { withFileTypes: true }) } catch { return 0 }
786
+ for (const item of items) {
787
+ const full = path + '/' + item.name
788
+ if (item.isDirectory()) total += dirSize(full, depth - 1)
789
+ else {
790
+ try { total += statSync(full).size } catch {}
791
+ }
792
+ }
793
+ return total
794
+ }
795
+
796
+
797
+ /**
798
+ * 取一批 issue 的「最后评论」。并发跑、短超时、最多 3 条、失败静默 ——
799
+ * 多出来的 API 调用只在这几种条件下发生,别让它变成常态开销。
800
+ */
801
+
802
+
803
+ /**
804
+ * 已安装版本 vs 已加载版本。
805
+ *
806
+ * `SERVER_VERSION` 是**当前进程里加载的代码**的版本;磁盘上 package.json 的 version 是
807
+ * **装好的**版本。两者不同 = 「文件换了,但宿主还在跑老模块」—— 这正是本机反复出现的情况
808
+ * (client 热重载会生效,服务端不会,界面上看不出来)。
809
+ */
810
+ function installedVersion() {
811
+ try {
812
+ const here = dirname(fileURLToPath(import.meta.url))
813
+ const pkg = JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf8'))
814
+ return typeof pkg.version === 'string' ? pkg.version : null
815
+ } catch { return null }
816
+ }
817
+
818
+ /** 当前 token 对应的账号(判断"最后一条评论是不是我们自己发的")。缓存 10 分钟。 */
819
+ let viewerCache = { at: 0, login: null }
820
+ async function viewerLogin() {
821
+ if (viewerCache.login && Date.now() - viewerCache.at < 10 * 60 * 1000) return viewerCache.login
822
+ try {
823
+ const res = await run('gh', ['api', 'user', '--jq', '.login'], { timeoutMs: 12000, env: ghEnv() })
824
+ if (res.code === 0) {
825
+ const login = String(res.stdout || '').trim()
826
+ if (login) { viewerCache = { at: Date.now(), login }; return login }
827
+ }
828
+ } catch {}
829
+ return viewerCache.login
830
+ }
831
+
832
+ async function fetchLastComments(repo, items, maxItems = 3) {
833
+ const targets = (items || []).filter((item) => Number(item.comments) > 0).slice(0, maxItems)
834
+ if (targets.length === 0) return
835
+ const me = await viewerLogin()
836
+ const mark = (item, info) => {
837
+ item.lastComment = {
838
+ login: info.login,
839
+ at: info.at,
840
+ self: Boolean(me && String(info.login).toLowerCase() === me.toLowerCase()),
841
+ }
842
+ }
843
+ // 首选:一次 GraphQL 批量(N 条评论 → 1 个请求)
844
+ try {
845
+ const [owner, name] = String(repo).split('/')
846
+ const query = buildCommentBatchQuery(targets.length)
847
+ const args = ['api', 'graphql', '-f', 'query=' + query, '-F', 'owner=' + owner, '-F', 'name=' + name]
848
+ targets.forEach((item, i) => args.push('-F', 'n' + i + '=' + item.number))
849
+ const res = await run('gh', args, { timeoutMs: 15000, env: ghEnv() })
850
+ // 有 errors 但 data 有值时仍然可用(别的 issue 不存在不影响这一条)
851
+ const payload = JSON.parse(String(res.stdout || '{}'))
852
+ const parsed = parseCommentBatch(payload)
853
+ let hit = 0
854
+ for (const item of targets) {
855
+ const info = parsed[String(item.number)]
856
+ if (!info) continue
857
+ if (info.login) mark(item, info)
858
+ if (Array.isArray(info.linked) && info.linked.length > 0) item.linkedPr = info.linked
859
+ hit += 1
860
+ }
861
+ if (hit > 0) return
862
+ } catch { /* 落到 REST 兜底 */ }
863
+ // 兜底:逐条 REST(GraphQL 不可用时仍要能工作)
864
+ await Promise.all(targets.map(async (item) => {
865
+ try {
866
+ const res = await run('gh', ['api', `repos/${repo}/issues/${item.number}/comments?per_page=1&sort=created&direction=desc`,
867
+ '--jq', '.[0] | {login: .user.login, at: .created_at}'], { timeoutMs: 12000, env: ghEnv() })
868
+ if (res.code !== 0) return
869
+ const parsed = JSON.parse(res.stdout)
870
+ if (parsed && parsed.login) mark(item, { login: parsed.login, at: parsed.at })
871
+ } catch { /* 少一行信息,不阻断唤醒 */ }
872
+ }))
873
+ }
874
+
875
+ async function pollOnce(ctx, entry, baseMs) {
876
+ // 活跃时段要**在拉 API 之前**判断:以前放在后面,夜里照样每 N 秒打一次 GitHub,纯浪费。
877
+ // 不在时段内就把下一次轮询安排到"开门那一刻",攒着的条目不会多等一个周期。
878
+ if (entry.activeHours && !inActiveHours(entry.activeHours)) {
879
+ const wait = msUntilActiveWindow(entry.activeHours)
880
+ // 时段外不轮询:顺手清掉旧错误(否则面板会一直显示一条永不消停的「异常」)
881
+ enterActiveHoursDefer(entry, wait, entry.activeHours)
882
+ noteEvent(entry, 'defer', entry.lastDeferred)
883
+ return
884
+ }
885
+ // 条件请求:带上上次的 ETag,没变化时 GitHub 回 304,且**不计入**速率限制
886
+ const args = ['api', '--include', `repos/${entry.repo}/issues?state=all&sort=updated&direction=desc&per_page=20`]
887
+ if (entry.etag) args.push('-H', 'If-None-Match: ' + entry.etag)
888
+ const res = await run('gh', args, { timeoutMs: 45000, env: ghEnv() })
889
+ entry.lastPoll = new Date().toISOString()
890
+ if (res.code !== 0) {
891
+ // gh 把 304 当失败(非 2xx 就 exit 1):这不是错误,是「条件请求命中」
892
+ if (/HTTP 304|304 Not Modified|not modified/i.test(String(res.stderr || '') + String(res.stdout || ''))) {
893
+ entry.lastError = null
894
+ entry.consecutiveFailures = 0
895
+ entry.nextAt = null
896
+ entry.lastDeferred = UNCHANGED_TEXT
897
+ entry.deferReason = 'unchanged'
898
+ noteEvent(entry, 'unchanged', entry.lastDeferred)
899
+ return
900
+ }
901
+ // 先看是不是被限流:GH 的 secondary limit 会给 Retry-After,照它等最准
902
+ const failure = parseGhInclude(res.stdout)
903
+ const wait = retryAfterMs(failure.retryAfter)
904
+ if (wait > 0) {
905
+ entry.nextAt = new Date(Date.now() + wait).toISOString()
906
+ entry.lastDeferred = '被 GitHub 限流,按 Retry-After 等 ' + Math.round(wait / 1000) + ' 秒'
907
+ entry.deferReason = 'ratelimit'
908
+ noteEvent(entry, 'ratelimit', entry.lastDeferred)
909
+ entry.lastError = null
910
+ return
911
+ }
912
+ const detail = redact(res.stderr).slice(0, 240)
913
+ // 常见失败给一句能照着做的提示,别只丢原始 stderr
914
+ const classified = classifyGhError(detail)
915
+ setEntryError(entry, (classified.short + classified.hint).slice(0, 300))
916
+ bumpFailure(entry, baseMs)
897
917
  // 永久性错误(404 / 仓库改名)不要按普通退避重试:至少等半小时
898
918
  const permanent = permanentBackoffMs(classified.kind, baseMs)
899
919
  if (permanent > 0) {
900
920
  entry.nextAt = new Date(Date.now() + permanent).toISOString()
901
921
  entry.deferReason = classified.kind === 'moved' ? 'moved' : 'notfound'
902
922
  }
903
- return
904
- }
905
- const parsed = parseGhInclude(res.stdout)
906
- // GitHub 的 x-poll-interval 是硬下限:比我们的间隔大就照它等,别硬撞
907
- if (parsed.pollInterval && parsed.pollInterval * 1000 > baseMs) {
908
- entry.minIntervalSec = parsed.pollInterval
909
- } else if (entry.minIntervalSec && (!parsed.pollInterval || parsed.pollInterval * 1000 <= baseMs)) {
910
- entry.minIntervalSec = null
911
- }
912
- // 额度自适应:剩余低于 500 时不再按固定间隔撞墙,直接把下一轮推到额度重置(最多 1 小时)
913
- const throttle = throttleDelayMs({ remaining: parsed.remaining, resetAt: parsed.resetAt })
914
- if (throttle > 0) {
915
- entry.nextAt = new Date(Date.now() + throttle).toISOString()
916
- entry.lastDeferred = '额度紧张(剩余 ' + parsed.remaining + '),已推迟到 '
917
- entry.deferReason = 'quota'
918
- + new Date(Date.now() + throttle).toISOString().slice(11, 16) + 'Z'
919
- entry.lastError = null
920
- return
921
- }
922
- // 204 No Content 也是「没有新东西」:DELETE/空列表都会这样,别当 JSON 解析失败
923
- if (parsed.status === 204) {
924
- entry.lastError = null
925
- entry.consecutiveFailures = 0
926
- entry.nextAt = null
927
- entry.lastDeferred = '没有内容(204)'
928
- entry.deferReason = 'unchanged'
929
- noteEvent(entry, 'unchanged', entry.lastDeferred)
930
- return
931
- }
932
- if (parsed.status === 304) {
933
- // 没变化:不解析、不算失败、不重置退避,只记一笔
934
- entry.lastError = null
935
- entry.consecutiveFailures = 0
936
- entry.nextAt = null
937
- entry.lastDeferred = UNCHANGED_TEXT
938
- entry.deferReason = 'unchanged'
939
- noteEvent(entry, 'unchanged', entry.lastDeferred)
940
- return
941
- }
942
- if (parsed.etag) entry.etag = parsed.etag
943
- let items
944
- try { items = JSON.parse(parsed.body) } catch { setEntryError(entry, '返回内容不是合法 JSON(可能是代理干扰)—— 已按退避自动重试;持续出现请跑 watch_doctor'); bumpFailure(entry, baseMs); return }
945
- if (!Array.isArray(items)) { setEntryError(entry, '返回的数据结构不对(预期是数组)—— 已按退避自动重试;持续出现请跑 watch_doctor'); bumpFailure(entry, baseMs); return }
946
-
947
- entry.lastError = null
948
- entry.consecutiveFailures = 0
949
- entry.nextAt = null
950
- // 记住最近一条"被重新打开"的 issue:这是最该被看见的信号(之前判过不做)
951
- const reopened = items.find((item) => (item.state_reason || '') === 'reopened')
952
- if (reopened) entry.lastReopened = reopened.number
953
-
954
- // 触发要有许可:过滤器不通过的条目根本不进候选集,也不写 seen 水位
955
- // 记忆要有遗忘:seen 只增不减会问成几 MB 的字典
956
- entry.seen = pruneSeen(entry.seen)
957
- const ackLabel = entry.ackLabel || DEFAULT_ACK_LABEL
958
- // 幂等痕迹留在 GitHub 上:带 ack 标签的条目直接跳过(换机器、删状态都不会重报)
959
- const considered = []
960
- // 每轮重置:这行要被读成「本轮跳过多少」,累计值会越滚越大、误导客户
961
- entry.filterCounts = {}
962
- for (const item of items) {
963
- if (hasAckLabel(item, ackLabel)) {
964
- entry.filteredLog = pushFiltered(entry.filteredLog, { at: entry.lastPoll, number: item.number, title: String(item.title || '').slice(0, 80), reason: '已 ack' })
965
- entry.filterCounts = countReasons(entry.filterCounts, '已 ack')
966
- continue
967
- }
968
- const reason = filterReason(item, entry.filters)
969
- if (reason) {
970
- entry.filterCounts = countReasons(entry.filterCounts, reason)
971
- entry.filteredLog = pushFiltered(entry.filteredLog, { at: entry.lastPoll, number: item.number, title: String(item.title || '').slice(0, 80), reason })
972
- continue
973
- }
974
- considered.push(item)
975
- }
976
- const { fresh, absorbed } = partitionItems(considered, entry, { cooldownMs: Number(entry.cooldownMs) || DEFAULT_COOLDOWN_MS })
977
-
978
- if (absorbed.length > 0) {
979
- entry.seen = advanceSeen(entry.seen, absorbed)
980
- entry.lastAbsorbed = absorbed.length
981
- // 记下来才能回答「这条为什么没叫醒我」—— 以前只能说「被吸收/仅观察/或早就有」三合一
982
- entry.absorbedLog = pushAbsorbed(entry.absorbedLog, absorbed, entry.lastPoll)
983
- const newestAbsorbed = newestUpdatedAt(absorbed)
984
- if (!entry.cursor || Date.parse(newestAbsorbed) > Date.parse(entry.cursor)) entry.cursor = newestAbsorbed
985
- }
986
- if (fresh.length === 0) {
987
- // 这一轮没有新增:上一轮的说法(比如「仅观察:本会唤醒 4 条」)已经过期了
988
- entry.lastDeferred = null
989
- return
990
- }
991
-
992
- // 仅观察模式(对标官方 observe):照常判定,但只记录「本会唤醒哪几条」,不真唤醒
993
- if (entry.observe === true) {
994
- entry.lastDeferred = '仅观察:本轮本会唤醒 ' + fresh.length + ' 条(' + fresh.slice(0, 5).map((i) => '#' + i.number).join(' ') + ')'
995
- entry.deferReason = 'observe'
996
- noteEvent(entry, 'observe', entry.lastDeferred)
997
- entry.history = pushHistory(entry.history, {
998
- at: new Date().toISOString(),
999
- numbers: fresh.slice(0, 5).map((i) => i.number),
1000
- ok: false,
1001
- reason: 'observe',
1002
- })
1003
- entry.seen = advanceSeen(entry.seen, fresh)
1004
- entry.cursor = newestUpdatedAt(fresh) || entry.cursor
1005
- return
1006
- }
1007
-
1008
- // 会话级上限(跨守累计):单守上限 × 守数量 = 实际频率,光有单守上限挡不住
1009
- const sessionCap = Math.max(1, Number(entry.sessionMaxWakes) || DEFAULT_SESSION_WAKES)
1010
- const sessionUsed = sessionWakesLastHour(Object.values(readState().watchers || {}), entry.sessionId)
1011
- if (sessionUsed >= sessionCap) {
1012
- entry.lastDeferred = '这条会话一小时内已被唤醒 ' + sessionUsed + ' 次(上限 ' + sessionCap + '),已攒 ' + fresh.length + ' 条待处理'
1013
- entry.deferReason = 'cap-session'
1014
- noteEvent(entry, 'cap-session', entry.lastDeferred)
1015
- return
1016
- }
1017
-
1018
- // 每小时唤醒上限:宁可攒着,也不要连续叫醒把上下文打爆
1019
- const cap = Math.max(1, Number(entry.maxWakesPerHour) || 6)
1020
- entry.wakeTimes = pruneWakeTimes(entry.wakeTimes)
1021
- if (entry.wakeTimes.length >= cap) {
1022
- // 只记原因,绝不动 seen/cursor —— 否则「攒着」等于「丢掉」
1023
- const freeAt = nextWaketimeAt(entry.wakeTimes, cap)
1024
- const waitMin = Math.max(1, Math.round((freeAt - Date.now()) / 60000))
1025
- entry.lastDeferred = `每小时最多唤醒 ${cap} 次,已攒 ${fresh.length} 条待处理(约 ${waitMin} 分钟后可再唤醒)`
1026
- entry.deferReason = 'cap-watcher'
1027
- noteEvent(entry, 'cap-watcher', entry.lastDeferred)
1028
- return
1029
- }
1030
-
1031
- // 条目不丢:水位照常全部前移,消息里只铺开前 N 条,其余给编号
1032
- const limit = Math.max(1, Number(entry.batchLimit) || 5)
1033
- const { listed, rest } = splitBatch(fresh, Number(entry.batchLimit) || 3, entry.priorityOrder || entry.priority)
1034
- // 暂停/删除可能发生在这一轮轮询期间:以盘上为准
1035
- const liveEntry = (readState().watchers || {})[entry.id]
1036
- if (!liveEntry || liveEntry.enabled === false) {
1037
- entry.lastDeferred = '本轮期间被暂停或删除,跳过唤醒'
1038
- return
1039
- }
1040
- // 会话忙就别开隔离区了:白建一个没人用的 worktree
1041
- const liveAgents = agentsService(ctx)
1042
- const liveAgent = liveAgents && typeof liveAgents.get === 'function' ? liveAgents.get(entry.sessionId) : undefined
1043
- if (!liveAgent) {
1044
- // 会话已经不在了(被删/换机器):别开隔离区,也别假装在盯。
1045
- // 必须走 bumpFailure —— 否则这条会每 intervalSec 打一次 GitHub,永不退避(第四轮审核指出)。
1046
- setEntryError(entry, '会话已不在:请删除或重建这条主理鱼')
1047
- bumpFailure(entry, baseMs)
1048
- return
1049
- }
1050
- const gate = decideWake(liveAgent && liveAgent.status)
1051
- if (!gate.ok) {
1052
- entry.lastDeferred = '会话正忙,下一轮重试'
1053
- return
1054
- }
1055
-
1056
- // 会话忙时**不要**先开隔离区:`git worktree add`(本机实测 0.19s,大仓库更久)
1057
- // 加上回收过期副本的若干次 git 调用,全都是白发 —— 因为 decideWake 之后一定会拒绝。
1058
- {
1059
- const agents = agentsService(ctx)
1060
- const agent = agents && typeof agents.get === 'function' ? agents.get(entry.sessionId) : undefined
1061
- const pre = decideWake(agent && agent.status)
1062
- if (!pre.ok) {
1063
- entry.lastDeferred = '会话正忙(' + String(pre.reason || '') + '),这一轮不准备隔离区,下一轮再试'
1064
- return
1065
- }
1066
- }
1067
- const isolation = await prepareIsolation(entry)
1068
- if (isolation && isolation.dir) entry.lastWorktree = isolation.dir
1069
- // 批次前几条补「最后是谁在说话」(最多 3 条,失败静默)
1070
- await fetchLastComments(entry.repo, listed)
1071
- const wakeText = formatWatchText(entry.repo, listed, {
1072
- more: rest.length,
1073
- restNumbers: rest.map((item) => item.number),
1074
- isolation,
1075
- // entry.goal 之前只写不读:现在真的进唤醒消息
1076
- goal: entry.goal || '',
1077
- // 只读仓库要在任务书里直说,否则会话会去试写然后吃 403
1078
- access: accessNote(entry.repoAccess),
1079
- // 完成标准要可观测(Given-When-Then 的思路):三件事缺一不算完成
1080
- criteria: [
1081
- '改了什么:文件清单 + 一句话为什么(别只写"已修复")',
1082
- '怎么验证的:跑过的测试/命令 + 结果;跑不了就写清为什么跑不了',
1083
- iso && iso.dir ? '回写到哪:推分支并开 PR,然后在 issue 里留言 + watch_ack 打标签' : '回写到哪:在 issue 里留言 + watch_ack 打标签',
1084
- ],
1085
- // 「为什么是这几条」:把本轮的筛选依据一并写进任务书
1086
- changedTotal: fresh.length,
1087
- batchLimit: listed.length,
1088
- skippedReasons: entry.filterCounts || {},
1089
- // 这条以前被叫醒过吗?history 里一直有数据,但消息从没用过
1090
- seenBefore: (() => {
1091
- const map = {}
1092
- for (const event of entry.history || []) {
1093
- for (const n of event.numbers || []) map[String(n)] = map[String(n)] || event.at
1094
- }
1095
- return map
1096
- })(),
1097
- })
1098
- entry.lastWakeCount = fresh.length
1099
- entry.lastBatch = listed.map((item) => item.number)
1100
- // 记账一律放到「真正发送之后」:
1101
- // 之前是入队即记账 —— 会话忙时 decideWake 会拒绝,次数却已经记了、seen 也已经推进,
1102
- // 于是那几条既不会重试(seen 已推进)又白白占掉名额。这是会丢消息的 bug。
1103
- wakeMerged(ctx, entry.sessionId, wakeText, (result) => {
1104
- entry.lastWake = result.ok ? new Date().toISOString() : 'failed: ' + String(result.reason || '')
1105
- entry.history = pushHistory(entry.history, {
1106
- at: new Date().toISOString(),
1107
- numbers: entry.lastBatch,
1108
- ok: result.ok,
1109
- reason: result.ok ? null : String(result.reason || '').slice(0, 120),
1110
- })
1111
- if (result.ok) {
1112
- // 上一次唤醒之后有没有 ack?没有就累计"叫醒了没回音"
1113
- entry.silentWakes = silentStreak({
1114
- previousWakeAt: entry.prevWakeAt,
1115
- lastAckedAt: entry.lastAcked && entry.lastAcked.at,
1116
- previousStreak: entry.silentWakes,
1117
- })
1118
- if (entry.silentWakes === 0 && entry.prevWakeAt) noteEvent(entry, 'acked', '上一次唤醒有回音(ack 出现过了)')
1119
- entry.prevWakeAt = new Date().toISOString()
1120
- entry.wakeTimes.push(Date.now())
1121
- entry.dailyWakes = bumpDailyWakes(entry.dailyWakes)
1122
- entry.lastDeferred = null
1123
- entry.deferReason = null
1124
- noteEvent(entry, 'wake', '唤醒了 ' + (entry.lastBatch || []).length + ' 条:' + (entry.lastBatch || []).map((n) => '#' + n).join(' '))
1125
- entry.seen = advanceSeen(entry.seen, fresh)
1126
- entry.lastReported = recordReported(entry, fresh)
1127
- entry.cursor = newestUpdatedAt(fresh)
1128
- } else {
1129
- // 保留水位,下一轮重试这次事件
1130
- setEntryError(entry, 'wake failed: ' + String(result.reason || ''))
1131
- noteEvent(entry, 'wake-failed', entry.lastError)
1132
- // 会话正忙是暂时的:下一轮直接重试;退避反而会越拖越久
1133
- entry.deferReason = 'busy'
1134
- if (/busy|running|idle/i.test(String(result.reason || ''))) {
1135
- entry.lastDeferred = '会话正忙,下一轮重试'
1136
- } else {
1137
- bumpFailure(entry, baseMs)
1138
- }
1139
- }
1140
- persistEntry(entry)
1141
- })
1142
- }
1143
-
1144
- export function apply(ctx) {
1145
- const timers = sharedTimers
1146
- // 并发闸的唯一事实源:tick 和 HTTP「立刻」拿到的是两个不同的 entry 对象,
1147
- // 靠 entry.polling 标记永远对不上(审核专员 probe-c 实证:同一条被唤醒 3 次)。
1148
- // 跨模块实例共享:旧实例还没跑完的那轮,新实例不能同时再跑一遍。
1149
- const inFlight = sharedInFlight
1150
-
1151
- /** 后台查一次仓库权限:push=false 说明只能读,回写评论/标签都会 403。 */
1152
- const probeAccess = async (entry) => {
1153
- try {
1154
- const res = await run('gh', ['api', 'repos/' + entry.repo, '--jq',
1155
- '{push: .permissions.push, private: .private, fork: .fork, hasIssues: .has_issues, archived: .archived, disabled: .disabled, parent: (.parent.full_name // null)}'],
1156
- { timeoutMs: 20000, env: ghEnv() })
1157
- if (res.code !== 0) return
1158
- const info = JSON.parse(res.stdout)
1159
- entry.repoAccess = {
1160
- repo: entry.repo,
1161
- push: info.push === true,
1162
- private: info.private === true,
1163
- fork: info.fork === true,
1164
- hasIssues: info.hasIssues !== false,
1165
- archived: info.archived === true,
1166
- disabled: info.disabled === true,
1167
- parent: info.parent || null,
1168
- checkedAt: new Date().toISOString(),
1169
- }
1170
- persistEntry(entry)
1171
- } catch { /* 探测失败不影响主流程 */ }
1172
- }
1173
-
1174
- const startWatcher = (entry) => {
1175
- if (timers.has(entry.id)) return
1176
- const every = Math.max(30, Number(entry.intervalSec) || 60) * 1000
1177
- // 首轮错峰:多条守同间隔时不要整点一起发车(之后按 every 稳定推进,不累积漂移)
1178
- const firstDelay = jitterMs(entry.id, Math.min(5000, every * 0.1))
1179
-
1180
- const tick = async () => {
1181
- // A pause (or delete) can land between two ticks; never poll a watcher
1182
- // the operator has just switched off.
1183
- if (entry.enabled === false) return
1184
- // 连续失败后的退避窗口:到点之前一律不碰 API
1185
- if (entry.nextAt && Date.now() < Date.parse(entry.nextAt)) return
1186
- // 同一个 watcher 不允许两轮并跑(手动「立刻」+ 定时器撞一起会开两个隔离区)
1187
- if (inFlight.has(entry.id)) return
1188
- inFlight.add(entry.id)
1189
- try {
1190
- await pollOnce(ctx, entry, every)
1191
- // GitHub 要求的间隔比我们的长:把下一轮推到它之后(成功路径也生效)
1192
- const floor = (Number(entry.minIntervalSec) || 0) * 1000
1193
- if (floor > every) entry.nextAt = new Date(Date.now() + floor).toISOString()
1194
- } catch (error) {
1195
- // 未预期的异常(比如宿主上下文/服务不可用)也必须退避:
1196
- // 之前只写 lastError,于是坏掉的 watcher 会按 intervalSec 无限重试(真机踩到过)。
1197
- setEntryError(entry, String((error && error.message) || error))
1198
- bumpFailure(entry, every)
1199
- } finally {
1200
- inFlight.delete(entry.id)
1201
- persistEntry(entry)
1202
- }
1203
- }
1204
- // unref:宿主本来不会退出,但测试进程不该被这个定时器吊住
1205
- timers.set(entry.id, setInterval(tick, every).unref?.())
1206
- // DSH_SUPERAGENT_NO_POLL=1 只登记不轮询(路由层单测用,避免真去请求 GitHub)
1207
- if (process.env.DSH_SUPERAGENT_NO_POLL === '1') return
1208
- // 首轮按确定性抖动错峰(0~5 秒),之后按 every 稳定推进
1209
- if (firstDelay > 0) {
1210
- const boot = setTimeout(() => { tick() }, firstDelay)
1211
- boot.unref?.()
1212
- } else {
1213
- tick()
1214
- }
1215
- }
1216
-
1217
- // Must run before the entry leaves the state file: a live tick would
1218
- // otherwise `persistEntry` the just-deleted watcher straight back.
1219
- const stopWatcher = (id) => {
1220
- const timer = timers.get(id)
1221
- if (timer === undefined) return false
1222
- clearInterval(timer)
1223
- timers.delete(id)
1224
- return true
1225
- }
1226
-
1227
- /**
1228
- * 版本检查(只读):问 npm registry 最新版是多少,和本实例版本比。
1229
- * 不触发安装 —— 装/升级要改 profile,必须由人执行且升级后要重载宿主。
1230
- * 10 分钟内存缓存,避免面板每次刷新都打 registry。
1231
- */
1232
- // /state 的体积预算:每守最多 6 条事件、全局最多 240 条(约 100 KB 内)
1233
- const STATE_EVENTS_PER_WATCHER = 6
1234
- const STATE_EVENTS_BUDGET = 240
1235
-
1236
- const UPDATE_CACHE_MS = 10 * 60 * 1000
1237
- let updateCache = null
1238
- const checkUpdate = async (force) => {
1239
- if (!force && updateCache && Date.now() - updateCache.at < UPDATE_CACHE_MS) return updateCache.value
1240
- const current = SERVER_VERSION
1241
- const value = { current, latest: null, publishedAt: null, hasUpdate: false, command: '', error: null }
1242
- // 离线开关:单测不该依赖 npm registry(一次网络抖动就会让整条门禁变红)
1243
- if (process.env.DSH_SUPERAGENT_UPDATE_OFFLINE === '1') {
1244
- value.command = 'dsh plugin --profile <你的 profile> add dsh-session-superagent@latest'
1245
- updateCache = { at: Date.now(), value }
1246
- return value
1247
- }
1248
- try {
1249
- const res = await fetch('https://registry.npmjs.org/' + encodeURIComponent('dsh-session-superagent') + '/latest', {
1250
- signal: AbortSignal.timeout(5000),
1251
- headers: { accept: 'application/json' },
1252
- })
1253
- if (!res.ok) throw new Error('HTTP ' + res.status)
1254
- const body = await res.json()
1255
- value.latest = String(body.version || '')
1256
- const published = typeof body.dist?.tarball === 'string' ? body.dist.tarball : ''
1257
- if (published) value.publishedAt = published
1258
- const score = (v) => String(v || '0').split('.').map((n) => Number(n) || 0).reduce((acc, n) => acc * 1000 + n, 0)
1259
- value.hasUpdate = score(value.latest) > score(current)
1260
- value.command = 'dsh plugin --profile <你的 profile> add dsh-session-superagent@' + (value.latest || 'latest')
1261
- } catch (error) {
1262
- value.error = String((error && error.message) || error).slice(0, 160)
1263
- }
1264
- updateCache = { at: Date.now(), value }
1265
- return value
1266
- }
1267
-
1268
- // Read-only status endpoints for the web panel. `httpServer` is looked up
1269
- // through ctx.inject: the service may load after this plugin, and ctx.get()
1270
- // does not wait for it.
1271
- const registerRoutes = (httpServer) => {
1272
- if (!httpServer || typeof httpServer.register !== 'function') return
1273
- for (const dispose of activeRoutes) { try { dispose() } catch {} }
1274
- activeRoutes.length = 0
1275
- for (const handle of timers.values()) { try { clearInterval(handle) } catch {} }
1276
- timers.clear()
1277
- const routes = []
1278
- // 宿主热重载时旧实例的路由可能还没 dispose;一条重复会让整个 try 崩掉,
1279
- // 面板和所有接口一起 404(2026-11-02 真机踩到 webserver: duplicate exact route)。
1280
- // 改成每条路由单独容错:重复的那条记下来,其余照常注册。
1281
- const failedRoutes = []
1282
- const attempted = []
1283
- const addRoute = (options) => {
1284
- attempted.push(options)
1285
- try {
1286
- const dispose = httpServer['register'](options)
1287
- routes.push(dispose)
1288
- activeRoutes.push(dispose)
1289
- } catch (error) {
1290
- failedRoutes.push(String((error && error.message) || error).slice(0, 120))
1291
- }
1292
- }
1293
- const record = (kind, detail) => {
1294
- const state = readState()
1295
- state.client = state.client || {}
1296
- state.client[kind] = { at: new Date().toISOString(), detail }
1297
- writeState(state)
1298
- }
1299
- try {
1300
- addRoute({
1301
- kind: 'exact',
1302
- path: '/session-superagent/state',
1303
- handler: async (req, res) => {
1304
- if (req.method !== 'GET') { res.statusCode = 405; res.end('method not allowed'); return }
1305
- const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
1306
- const focusSession = url.searchParams.get('sessionId') || ''
1307
- const state = readState()
1308
- // 顺带刷新一次 token scopes(缓存 5 分钟;失败不影响 /state)
1309
- tokenScopes().catch(() => {})
1310
- const gh = await ghHealth()
1311
- const allWatchers = Object.values(state.watchers || {})
1312
- // 全局预算:守越多,每守分到的事件条数越少(100 条守时每人 2 条,总量 ≤ 240)
1313
- const perWatcherEvents = Math.max(1, Math.min(STATE_EVENTS_PER_WATCHER, Math.floor(STATE_EVENTS_BUDGET / Math.max(1, allWatchers.length))))
1314
- const watchers = allWatchers.map((w) => ({
1315
- id: w.id || (w.repo + '#' + w.sessionId),
1316
- repo: w.repo,
1317
- sessionId: w.sessionId,
1318
- intervalSec: w.intervalSec,
1319
- enabled: w.enabled !== false,
1320
- cursor: w.cursor ?? null,
1321
- lastPoll: w.lastPoll ?? null,
1322
- lastWake: w.lastWake ?? null,
1323
- lastWakeCount: w.lastWakeCount ?? 0,
1324
- lastAbsorbed: w.lastAbsorbed ?? 0,
1325
- lastError: w.lastError ?? null,
1326
- filters: w.filters ?? null,
1327
- batchLimit: w.batchLimit ?? 5,
1328
- maxWakesPerHour: w.maxWakesPerHour ?? 6,
1329
- sessionMaxWakes: w.sessionMaxWakes ?? 12,
1330
- consecutiveFailures: w.consecutiveFailures ?? 0,
1331
- nextAt: w.nextAt ?? null,
1332
- lastDeferred: w.lastDeferred ?? null,
1333
- observe: w.observe === true,
1334
- filteredLog: (w.filteredLog ?? []).slice(-5),
1335
- filterCounts: w.filterCounts ?? {},
1336
- repoAccess: w.repoAccess ?? null,
1337
- lastReopened: w.lastReopened ?? null,
1338
- priority: w.priority ?? null,
1339
- isolated: w.isolated === true,
1340
- workdir: w.workdir ?? null,
1341
- lastWorktree: w.lastWorktree ?? null,
1342
- activeHours: w.activeHours ?? null,
1343
- isolateKeepDays: w.isolateKeepDays ?? 3,
1344
- maxIsolated: w.maxIsolated ?? 5,
1345
- history: (w.history ?? []).slice(-5),
1346
- events: (w.events ?? []).slice(-perWatcherEvents),
1347
- // 同一个仓库被别的会话也守着:客户该知道「还有谁在看」
1348
- otherSessions: allWatchers.filter((peer) => peer && peer.repo === w.repo && peer.sessionId !== w.sessionId).map((peer) => peer.sessionId),
1349
- // 分类放在服务端做一次:面板按 kind 给「下一步」按钮,不用自己解析中文
923
+ return
924
+ }
925
+ const parsed = parseGhInclude(res.stdout)
926
+ // GitHub 的 x-poll-interval 是硬下限:比我们的间隔大就照它等,别硬撞
927
+ if (parsed.pollInterval && parsed.pollInterval * 1000 > baseMs) {
928
+ entry.minIntervalSec = parsed.pollInterval
929
+ } else if (entry.minIntervalSec && (!parsed.pollInterval || parsed.pollInterval * 1000 <= baseMs)) {
930
+ entry.minIntervalSec = null
931
+ }
932
+ // 额度自适应:剩余低于 500 时不再按固定间隔撞墙,直接把下一轮推到额度重置(最多 1 小时)
933
+ const throttle = throttleDelayMs({ remaining: parsed.remaining, resetAt: parsed.resetAt })
934
+ if (throttle > 0) {
935
+ entry.nextAt = new Date(Date.now() + throttle).toISOString()
936
+ entry.lastDeferred = '额度紧张(剩余 ' + parsed.remaining + '),已推迟到 '
937
+ entry.deferReason = 'quota'
938
+ + new Date(Date.now() + throttle).toISOString().slice(11, 16) + 'Z'
939
+ entry.lastError = null
940
+ return
941
+ }
942
+ // 204 No Content 也是「没有新东西」:DELETE/空列表都会这样,别当 JSON 解析失败
943
+ if (parsed.status === 204) {
944
+ entry.lastError = null
945
+ entry.consecutiveFailures = 0
946
+ entry.nextAt = null
947
+ entry.lastDeferred = '没有内容(204)'
948
+ entry.deferReason = 'unchanged'
949
+ noteEvent(entry, 'unchanged', entry.lastDeferred)
950
+ return
951
+ }
952
+ if (parsed.status === 304) {
953
+ // 没变化:不解析、不算失败、不重置退避,只记一笔
954
+ entry.lastError = null
955
+ entry.consecutiveFailures = 0
956
+ entry.nextAt = null
957
+ entry.lastDeferred = UNCHANGED_TEXT
958
+ entry.deferReason = 'unchanged'
959
+ noteEvent(entry, 'unchanged', entry.lastDeferred)
960
+ return
961
+ }
962
+ if (parsed.etag) entry.etag = parsed.etag
963
+ let items
964
+ try { items = JSON.parse(parsed.body) } catch { setEntryError(entry, '返回内容不是合法 JSON(可能是代理干扰)—— 已按退避自动重试;持续出现请跑 watch_doctor'); bumpFailure(entry, baseMs); return }
965
+ if (!Array.isArray(items)) { setEntryError(entry, '返回的数据结构不对(预期是数组)—— 已按退避自动重试;持续出现请跑 watch_doctor'); bumpFailure(entry, baseMs); return }
966
+
967
+ entry.lastError = null
968
+ entry.consecutiveFailures = 0
969
+ entry.nextAt = null
970
+ // 记住最近一条"被重新打开"的 issue:这是最该被看见的信号(之前判过不做)
971
+ const reopened = items.find((item) => (item.state_reason || '') === 'reopened')
972
+ if (reopened) entry.lastReopened = reopened.number
973
+
974
+ // 触发要有许可:过滤器不通过的条目根本不进候选集,也不写 seen 水位
975
+ // 记忆要有遗忘:seen 只增不减会问成几 MB 的字典
976
+ entry.seen = pruneSeen(entry.seen)
977
+ const ackLabel = entry.ackLabel || DEFAULT_ACK_LABEL
978
+ // 幂等痕迹留在 GitHub 上:带 ack 标签的条目直接跳过(换机器、删状态都不会重报)
979
+ const considered = []
980
+ // 每轮重置:这行要被读成「本轮跳过多少」,累计值会越滚越大、误导客户
981
+ entry.filterCounts = {}
982
+ for (const item of items) {
983
+ if (hasAckLabel(item, ackLabel)) {
984
+ entry.filteredLog = pushFiltered(entry.filteredLog, { at: entry.lastPoll, number: item.number, title: String(item.title || '').slice(0, 80), reason: '已 ack' })
985
+ entry.filterCounts = countReasons(entry.filterCounts, '已 ack')
986
+ continue
987
+ }
988
+ const reason = filterReason(item, entry.filters)
989
+ if (reason) {
990
+ entry.filterCounts = countReasons(entry.filterCounts, reason)
991
+ entry.filteredLog = pushFiltered(entry.filteredLog, { at: entry.lastPoll, number: item.number, title: String(item.title || '').slice(0, 80), reason })
992
+ continue
993
+ }
994
+ considered.push(item)
995
+ }
996
+ const { fresh, absorbed } = partitionItems(considered, entry, { cooldownMs: Number(entry.cooldownMs) || DEFAULT_COOLDOWN_MS })
997
+
998
+ if (absorbed.length > 0) {
999
+ entry.seen = advanceSeen(entry.seen, absorbed)
1000
+ entry.lastAbsorbed = absorbed.length
1001
+ // 记下来才能回答「这条为什么没叫醒我」—— 以前只能说「被吸收/仅观察/或早就有」三合一
1002
+ entry.absorbedLog = pushAbsorbed(entry.absorbedLog, absorbed, entry.lastPoll)
1003
+ const newestAbsorbed = newestUpdatedAt(absorbed)
1004
+ if (!entry.cursor || Date.parse(newestAbsorbed) > Date.parse(entry.cursor)) entry.cursor = newestAbsorbed
1005
+ }
1006
+ if (fresh.length === 0) {
1007
+ // 这一轮没有新增:上一轮的说法(比如「仅观察:本会唤醒 4 条」)已经过期了
1008
+ entry.lastDeferred = null
1009
+ return
1010
+ }
1011
+
1012
+ // 仅观察模式(对标官方 observe):照常判定,但只记录「本会唤醒哪几条」,不真唤醒
1013
+ if (entry.observe === true) {
1014
+ entry.lastDeferred = '仅观察:本轮本会唤醒 ' + fresh.length + ' 条(' + fresh.slice(0, 5).map((i) => '#' + i.number).join(' ') + ')'
1015
+ entry.deferReason = 'observe'
1016
+ noteEvent(entry, 'observe', entry.lastDeferred)
1017
+ entry.history = pushHistory(entry.history, {
1018
+ at: new Date().toISOString(),
1019
+ numbers: fresh.slice(0, 5).map((i) => i.number),
1020
+ ok: false,
1021
+ reason: 'observe',
1022
+ })
1023
+ entry.seen = advanceSeen(entry.seen, fresh)
1024
+ entry.cursor = newestUpdatedAt(fresh) || entry.cursor
1025
+ return
1026
+ }
1027
+
1028
+ // 会话级上限(跨守累计):单守上限 × 守数量 = 实际频率,光有单守上限挡不住
1029
+ const sessionCap = Math.max(1, Number(entry.sessionMaxWakes) || DEFAULT_SESSION_WAKES)
1030
+ const sessionUsed = sessionWakesLastHour(Object.values(readState().watchers || {}), entry.sessionId)
1031
+ if (sessionUsed >= sessionCap) {
1032
+ entry.lastDeferred = '这条会话一小时内已被唤醒 ' + sessionUsed + ' 次(上限 ' + sessionCap + '),已攒 ' + fresh.length + ' 条待处理'
1033
+ entry.deferReason = 'cap-session'
1034
+ noteEvent(entry, 'cap-session', entry.lastDeferred)
1035
+ return
1036
+ }
1037
+
1038
+ // 每小时唤醒上限:宁可攒着,也不要连续叫醒把上下文打爆
1039
+ const cap = Math.max(1, Number(entry.maxWakesPerHour) || 6)
1040
+ entry.wakeTimes = pruneWakeTimes(entry.wakeTimes)
1041
+ if (entry.wakeTimes.length >= cap) {
1042
+ // 只记原因,绝不动 seen/cursor —— 否则「攒着」等于「丢掉」
1043
+ const freeAt = nextWaketimeAt(entry.wakeTimes, cap)
1044
+ const waitMin = Math.max(1, Math.round((freeAt - Date.now()) / 60000))
1045
+ entry.lastDeferred = `每小时最多唤醒 ${cap} 次,已攒 ${fresh.length} 条待处理(约 ${waitMin} 分钟后可再唤醒)`
1046
+ entry.deferReason = 'cap-watcher'
1047
+ noteEvent(entry, 'cap-watcher', entry.lastDeferred)
1048
+ return
1049
+ }
1050
+
1051
+ // 条目不丢:水位照常全部前移,消息里只铺开前 N 条,其余给编号
1052
+ const limit = Math.max(1, Number(entry.batchLimit) || 5)
1053
+ const { listed, rest } = splitBatch(fresh, Number(entry.batchLimit) || 3, entry.priorityOrder || entry.priority)
1054
+ // 暂停/删除可能发生在这一轮轮询期间:以盘上为准
1055
+ const liveEntry = (readState().watchers || {})[entry.id]
1056
+ if (!liveEntry || liveEntry.enabled === false) {
1057
+ entry.lastDeferred = '本轮期间被暂停或删除,跳过唤醒'
1058
+ return
1059
+ }
1060
+ // 会话忙就别开隔离区了:白建一个没人用的 worktree
1061
+ const liveAgents = agentsService(ctx)
1062
+ const liveAgent = liveAgents && typeof liveAgents.get === 'function' ? liveAgents.get(entry.sessionId) : undefined
1063
+ if (!liveAgent) {
1064
+ // 会话已经不在了(被删/换机器):别开隔离区,也别假装在盯。
1065
+ // 必须走 bumpFailure —— 否则这条会每 intervalSec 打一次 GitHub,永不退避(第四轮审核指出)。
1066
+ setEntryError(entry, '会话已不在:请删除或重建这条主理鱼')
1067
+ bumpFailure(entry, baseMs)
1068
+ return
1069
+ }
1070
+ const gate = decideWake(liveAgent && liveAgent.status)
1071
+ if (!gate.ok) {
1072
+ entry.lastDeferred = '会话正忙,下一轮重试'
1073
+ return
1074
+ }
1075
+
1076
+ // 会话忙时**不要**先开隔离区:`git worktree add`(本机实测 0.19s,大仓库更久)
1077
+ // 加上回收过期副本的若干次 git 调用,全都是白发 —— 因为 decideWake 之后一定会拒绝。
1078
+ {
1079
+ const agents = agentsService(ctx)
1080
+ const agent = agents && typeof agents.get === 'function' ? agents.get(entry.sessionId) : undefined
1081
+ const pre = decideWake(agent && agent.status)
1082
+ if (!pre.ok) {
1083
+ entry.lastDeferred = '会话正忙(' + String(pre.reason || '') + '),这一轮不准备隔离区,下一轮再试'
1084
+ return
1085
+ }
1086
+ }
1087
+ const isolation = await prepareIsolation(entry)
1088
+ if (isolation && isolation.dir) entry.lastWorktree = isolation.dir
1089
+ // 批次前几条补「最后是谁在说话」(最多 3 条,失败静默)
1090
+ await fetchLastComments(entry.repo, listed)
1091
+ const wakeText = formatWatchText(entry.repo, listed, {
1092
+ more: rest.length,
1093
+ restNumbers: rest.map((item) => item.number),
1094
+ isolation,
1095
+ // entry.goal 之前只写不读:现在真的进唤醒消息
1096
+ goal: entry.goal || '',
1097
+ // 只读仓库要在任务书里直说,否则会话会去试写然后吃 403
1098
+ access: accessNote(entry.repoAccess),
1099
+ // 完成标准要可观测(Given-When-Then 的思路):三件事缺一不算完成
1100
+ criteria: [
1101
+ '改了什么:文件清单 + 一句话为什么(别只写"已修复")',
1102
+ '怎么验证的:跑过的测试/命令 + 结果;跑不了就写清为什么跑不了',
1103
+ iso && iso.dir ? '回写到哪:推分支并开 PR,然后在 issue 里留言 + watch_ack 打标签' : '回写到哪:在 issue 里留言 + watch_ack 打标签',
1104
+ ],
1105
+ // 「为什么是这几条」:把本轮的筛选依据一并写进任务书
1106
+ changedTotal: fresh.length,
1107
+ batchLimit: listed.length,
1108
+ skippedReasons: entry.filterCounts || {},
1109
+ // 这条以前被叫醒过吗?history 里一直有数据,但消息从没用过
1110
+ seenBefore: (() => {
1111
+ const map = {}
1112
+ for (const event of entry.history || []) {
1113
+ for (const n of event.numbers || []) map[String(n)] = map[String(n)] || event.at
1114
+ }
1115
+ return map
1116
+ })(),
1117
+ })
1118
+ entry.lastWakeCount = fresh.length
1119
+ entry.lastBatch = listed.map((item) => item.number)
1120
+ // 记账一律放到「真正发送之后」:
1121
+ // 之前是入队即记账 —— 会话忙时 decideWake 会拒绝,次数却已经记了、seen 也已经推进,
1122
+ // 于是那几条既不会重试(seen 已推进)又白白占掉名额。这是会丢消息的 bug。
1123
+ wakeMerged(ctx, entry.sessionId, wakeText, (result) => {
1124
+ entry.lastWake = result.ok ? new Date().toISOString() : 'failed: ' + String(result.reason || '')
1125
+ entry.history = pushHistory(entry.history, {
1126
+ at: new Date().toISOString(),
1127
+ numbers: entry.lastBatch,
1128
+ ok: result.ok,
1129
+ reason: result.ok ? null : String(result.reason || '').slice(0, 120),
1130
+ })
1131
+ if (result.ok) {
1132
+ // 上一次唤醒之后有没有 ack?没有就累计"叫醒了没回音"
1133
+ entry.silentWakes = silentStreak({
1134
+ previousWakeAt: entry.prevWakeAt,
1135
+ lastAckedAt: entry.lastAcked && entry.lastAcked.at,
1136
+ previousStreak: entry.silentWakes,
1137
+ })
1138
+ if (entry.silentWakes === 0 && entry.prevWakeAt) noteEvent(entry, 'acked', '上一次唤醒有回音(ack 出现过了)')
1139
+ entry.prevWakeAt = new Date().toISOString()
1140
+ entry.wakeTimes.push(Date.now())
1141
+ entry.dailyWakes = bumpDailyWakes(entry.dailyWakes)
1142
+ entry.lastDeferred = null
1143
+ entry.deferReason = null
1144
+ noteEvent(entry, 'wake', '唤醒了 ' + (entry.lastBatch || []).length + ' 条:' + (entry.lastBatch || []).map((n) => '#' + n).join(' '))
1145
+ entry.seen = advanceSeen(entry.seen, fresh)
1146
+ entry.lastReported = recordReported(entry, fresh)
1147
+ entry.cursor = newestUpdatedAt(fresh)
1148
+ } else {
1149
+ // 保留水位,下一轮重试这次事件
1150
+ setEntryError(entry, 'wake failed: ' + String(result.reason || ''))
1151
+ noteEvent(entry, 'wake-failed', entry.lastError)
1152
+ // 会话正忙是暂时的:下一轮直接重试;退避反而会越拖越久
1153
+ entry.deferReason = 'busy'
1154
+ if (/busy|running|idle/i.test(String(result.reason || ''))) {
1155
+ entry.lastDeferred = '会话正忙,下一轮重试'
1156
+ } else {
1157
+ bumpFailure(entry, baseMs)
1158
+ }
1159
+ }
1160
+ persistEntry(entry)
1161
+ })
1162
+ }
1163
+
1164
+ export function apply(ctx) {
1165
+ const timers = sharedTimers
1166
+ // 并发闸的唯一事实源:tick 和 HTTP「立刻」拿到的是两个不同的 entry 对象,
1167
+ // 靠 entry.polling 标记永远对不上(审核专员 probe-c 实证:同一条被唤醒 3 次)。
1168
+ // 跨模块实例共享:旧实例还没跑完的那轮,新实例不能同时再跑一遍。
1169
+ const inFlight = sharedInFlight
1170
+
1171
+ /** 后台查一次仓库权限:push=false 说明只能读,回写评论/标签都会 403。 */
1172
+ const probeAccess = async (entry) => {
1173
+ try {
1174
+ const res = await run('gh', ['api', 'repos/' + entry.repo, '--jq',
1175
+ '{push: .permissions.push, private: .private, fork: .fork, hasIssues: .has_issues, archived: .archived, disabled: .disabled, parent: (.parent.full_name // null)}'],
1176
+ { timeoutMs: 20000, env: ghEnv() })
1177
+ if (res.code !== 0) return
1178
+ const info = JSON.parse(res.stdout)
1179
+ entry.repoAccess = {
1180
+ repo: entry.repo,
1181
+ push: info.push === true,
1182
+ private: info.private === true,
1183
+ fork: info.fork === true,
1184
+ hasIssues: info.hasIssues !== false,
1185
+ archived: info.archived === true,
1186
+ disabled: info.disabled === true,
1187
+ parent: info.parent || null,
1188
+ checkedAt: new Date().toISOString(),
1189
+ }
1190
+ persistEntry(entry)
1191
+ } catch { /* 探测失败不影响主流程 */ }
1192
+ }
1193
+
1194
+ const startWatcher = (entry) => {
1195
+ if (timers.has(entry.id)) return
1196
+ const every = Math.max(30, Number(entry.intervalSec) || 60) * 1000
1197
+ // 首轮错峰:多条守同间隔时不要整点一起发车(之后按 every 稳定推进,不累积漂移)
1198
+ const firstDelay = jitterMs(entry.id, Math.min(5000, every * 0.1))
1199
+
1200
+ const tick = async () => {
1201
+ // A pause (or delete) can land between two ticks; never poll a watcher
1202
+ // the operator has just switched off.
1203
+ if (entry.enabled === false) return
1204
+ // 连续失败后的退避窗口:到点之前一律不碰 API
1205
+ if (entry.nextAt && Date.now() < Date.parse(entry.nextAt)) return
1206
+ // 同一个 watcher 不允许两轮并跑(手动「立刻」+ 定时器撞一起会开两个隔离区)
1207
+ if (inFlight.has(entry.id)) return
1208
+ inFlight.add(entry.id)
1209
+ try {
1210
+ await pollOnce(ctx, entry, every)
1211
+ // GitHub 要求的间隔比我们的长:把下一轮推到它之后(成功路径也生效)
1212
+ const floor = (Number(entry.minIntervalSec) || 0) * 1000
1213
+ if (floor > every) entry.nextAt = new Date(Date.now() + floor).toISOString()
1214
+ } catch (error) {
1215
+ // 未预期的异常(比如宿主上下文/服务不可用)也必须退避:
1216
+ // 之前只写 lastError,于是坏掉的 watcher 会按 intervalSec 无限重试(真机踩到过)。
1217
+ setEntryError(entry, String((error && error.message) || error))
1218
+ bumpFailure(entry, every)
1219
+ } finally {
1220
+ inFlight.delete(entry.id)
1221
+ persistEntry(entry)
1222
+ }
1223
+ }
1224
+ // unref:宿主本来不会退出,但测试进程不该被这个定时器吊住
1225
+ timers.set(entry.id, setInterval(tick, every).unref?.())
1226
+ // DSH_SUPERAGENT_NO_POLL=1 只登记不轮询(路由层单测用,避免真去请求 GitHub)
1227
+ if (process.env.DSH_SUPERAGENT_NO_POLL === '1') return
1228
+ // 首轮按确定性抖动错峰(0~5 秒),之后按 every 稳定推进
1229
+ if (firstDelay > 0) {
1230
+ const boot = setTimeout(() => { tick() }, firstDelay)
1231
+ boot.unref?.()
1232
+ } else {
1233
+ tick()
1234
+ }
1235
+ }
1236
+
1237
+ // Must run before the entry leaves the state file: a live tick would
1238
+ // otherwise `persistEntry` the just-deleted watcher straight back.
1239
+ const stopWatcher = (id) => {
1240
+ const timer = timers.get(id)
1241
+ if (timer === undefined) return false
1242
+ clearInterval(timer)
1243
+ timers.delete(id)
1244
+ return true
1245
+ }
1246
+
1247
+ /**
1248
+ * 版本检查(只读):问 npm registry 最新版是多少,和本实例版本比。
1249
+ * 不触发安装 —— 装/升级要改 profile,必须由人执行且升级后要重载宿主。
1250
+ * 10 分钟内存缓存,避免面板每次刷新都打 registry。
1251
+ */
1252
+ // /state 的体积预算:每守最多 6 条事件、全局最多 240 条(约 100 KB 内)
1253
+ const STATE_EVENTS_PER_WATCHER = 6
1254
+ const STATE_EVENTS_BUDGET = 240
1255
+
1256
+ const UPDATE_CACHE_MS = 10 * 60 * 1000
1257
+ let updateCache = null
1258
+ const checkUpdate = async (force) => {
1259
+ if (!force && updateCache && Date.now() - updateCache.at < UPDATE_CACHE_MS) return updateCache.value
1260
+ const current = SERVER_VERSION
1261
+ const value = { current, latest: null, publishedAt: null, hasUpdate: false, command: '', error: null }
1262
+ // 离线开关:单测不该依赖 npm registry(一次网络抖动就会让整条门禁变红)
1263
+ if (process.env.DSH_SUPERAGENT_UPDATE_OFFLINE === '1') {
1264
+ value.command = 'dsh plugin --profile <你的 profile> add dsh-session-superagent@latest'
1265
+ updateCache = { at: Date.now(), value }
1266
+ return value
1267
+ }
1268
+ try {
1269
+ const res = await fetch('https://registry.npmjs.org/' + encodeURIComponent('dsh-session-superagent') + '/latest', {
1270
+ signal: AbortSignal.timeout(5000),
1271
+ headers: { accept: 'application/json' },
1272
+ })
1273
+ if (!res.ok) throw new Error('HTTP ' + res.status)
1274
+ const body = await res.json()
1275
+ value.latest = String(body.version || '')
1276
+ const published = typeof body.dist?.tarball === 'string' ? body.dist.tarball : ''
1277
+ if (published) value.publishedAt = published
1278
+ const score = (v) => String(v || '0').split('.').map((n) => Number(n) || 0).reduce((acc, n) => acc * 1000 + n, 0)
1279
+ value.hasUpdate = score(value.latest) > score(current)
1280
+ value.command = 'dsh plugin --profile <你的 profile> add dsh-session-superagent@' + (value.latest || 'latest')
1281
+ } catch (error) {
1282
+ value.error = String((error && error.message) || error).slice(0, 160)
1283
+ }
1284
+ updateCache = { at: Date.now(), value }
1285
+ return value
1286
+ }
1287
+
1288
+ // Read-only status endpoints for the web panel. `httpServer` is looked up
1289
+ // through ctx.inject: the service may load after this plugin, and ctx.get()
1290
+ // does not wait for it.
1291
+ const registerRoutes = (httpServer) => {
1292
+ if (!httpServer || typeof httpServer.register !== 'function') return
1293
+ for (const dispose of activeRoutes) { try { dispose() } catch {} }
1294
+ activeRoutes.length = 0
1295
+ for (const handle of timers.values()) { try { clearInterval(handle) } catch {} }
1296
+ timers.clear()
1297
+ const routes = []
1298
+ // 宿主热重载时旧实例的路由可能还没 dispose;一条重复会让整个 try 崩掉,
1299
+ // 面板和所有接口一起 404(2026-11-02 真机踩到 webserver: duplicate exact route)。
1300
+ // 改成每条路由单独容错:重复的那条记下来,其余照常注册。
1301
+ const failedRoutes = []
1302
+ const attempted = []
1303
+ const addRoute = (options) => {
1304
+ attempted.push(options)
1305
+ try {
1306
+ const dispose = httpServer['register'](options)
1307
+ routes.push(dispose)
1308
+ activeRoutes.push(dispose)
1309
+ } catch (error) {
1310
+ failedRoutes.push(String((error && error.message) || error).slice(0, 120))
1311
+ }
1312
+ }
1313
+ const record = (kind, detail) => {
1314
+ const state = readState()
1315
+ state.client = state.client || {}
1316
+ state.client[kind] = { at: new Date().toISOString(), detail }
1317
+ writeState(state)
1318
+ }
1319
+ try {
1320
+ addRoute({
1321
+ kind: 'exact',
1322
+ path: '/session-superagent/state',
1323
+ handler: async (req, res) => {
1324
+ if (req.method !== 'GET') { res.statusCode = 405; res.end('method not allowed'); return }
1325
+ const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
1326
+ const focusSession = url.searchParams.get('sessionId') || ''
1327
+ const state = readState()
1328
+ // 顺带刷新一次 token scopes(缓存 5 分钟;失败不影响 /state)
1329
+ tokenScopes().catch(() => {})
1330
+ const gh = await ghHealth()
1331
+ const allWatchers = Object.values(state.watchers || {})
1332
+ // 全局预算:守越多,每守分到的事件条数越少(100 条守时每人 2 条,总量 ≤ 240)
1333
+ const perWatcherEvents = Math.max(1, Math.min(STATE_EVENTS_PER_WATCHER, Math.floor(STATE_EVENTS_BUDGET / Math.max(1, allWatchers.length))))
1334
+ const watchers = allWatchers.map((w) => ({
1335
+ id: w.id || (w.repo + '#' + w.sessionId),
1336
+ repo: w.repo,
1337
+ sessionId: w.sessionId,
1338
+ intervalSec: w.intervalSec,
1339
+ enabled: w.enabled !== false,
1340
+ cursor: w.cursor ?? null,
1341
+ lastPoll: w.lastPoll ?? null,
1342
+ lastWake: w.lastWake ?? null,
1343
+ lastWakeCount: w.lastWakeCount ?? 0,
1344
+ lastAbsorbed: w.lastAbsorbed ?? 0,
1345
+ lastError: w.lastError ?? null,
1346
+ filters: w.filters ?? null,
1347
+ batchLimit: w.batchLimit ?? 5,
1348
+ maxWakesPerHour: w.maxWakesPerHour ?? 6,
1349
+ sessionMaxWakes: w.sessionMaxWakes ?? 12,
1350
+ consecutiveFailures: w.consecutiveFailures ?? 0,
1351
+ nextAt: w.nextAt ?? null,
1352
+ lastDeferred: w.lastDeferred ?? null,
1353
+ observe: w.observe === true,
1354
+ filteredLog: (w.filteredLog ?? []).slice(-5),
1355
+ filterCounts: w.filterCounts ?? {},
1356
+ repoAccess: w.repoAccess ?? null,
1357
+ lastReopened: w.lastReopened ?? null,
1358
+ priority: w.priority ?? null,
1359
+ isolated: w.isolated === true,
1360
+ workdir: w.workdir ?? null,
1361
+ lastWorktree: w.lastWorktree ?? null,
1362
+ activeHours: w.activeHours ?? null,
1363
+ isolateKeepDays: w.isolateKeepDays ?? 3,
1364
+ maxIsolated: w.maxIsolated ?? 5,
1365
+ history: (w.history ?? []).slice(-5),
1366
+ events: (w.events ?? []).slice(-perWatcherEvents),
1367
+ // 同一个仓库被别的会话也守着:客户该知道「还有谁在看」
1368
+ otherSessions: allWatchers.filter((peer) => peer && peer.repo === w.repo && peer.sessionId !== w.sessionId).map((peer) => peer.sessionId),
1369
+ // 分类放在服务端做一次:面板按 kind 给「下一步」按钮,不用自己解析中文
1350
1370
  lastErrorKind: w.lastError ? classifyGhError(String(w.lastError)).kind : null,
1351
- lastErrorAt: w.lastErrorAt || null,
1352
- deferReason: w.deferReason ?? null,
1353
- daily: dailySummary(w.dailyWakes),
1354
- busy: busierThanUsual(dailySummary(w.dailyWakes)),
1355
- silentWakes: w.silentWakes ?? 0,
1356
- note: w.goal ?? '',
1357
- title: sessionTitle(w.sessionId),
1358
- }))
1359
- const stateBody = {
1360
- gh,
1361
- routeBase: activeBase,
1362
- serverVersion: SERVER_VERSION,
1363
- updatedAt: new Date().toISOString(),
1364
- credentials: secretsSummary(),
1365
- sessionGoal: goalView(ctx, focusSession),
1366
- stateSource,
1367
- // 会话级用量:上限够不够,客户应该一眼看到(数据都在状态里,零新增请求)
1368
- sessionUsage: (() => {
1369
- const list = Object.values(state.watchers || {})
1370
- const usage = list.length === 0 ? null : sessionWakesLastHour(list, focusSession)
1371
- const cap = list.length === 0 ? null : (Number(list[0].sessionMaxWakes) || 12)
1372
- const capped = countCapped(list)
1373
- if (usage === null) return null
1374
- const suggest = suggestSessionCap({ used: usage, cap, capped })
1375
- return { used: usage, cap, capped, suggest }
1376
- })(),
1377
- // 版本漂移:文件换了但宿主还在跑老模块(客户端热重载会掩盖这件事)
1378
- installedVersion: installedVersion(),
1379
- runningVersion: SERVER_VERSION,
1380
- triageSignals: TRIAGE_SIGNALS,
1381
- tokenScopes: scopesCache.value || null,
1382
- isolation: isolationReport(Object.values(state.watchers || {})),
1383
- sessionTitle: sessionTitle(focusSession),
1384
- watchers: watchers.map((w) => ({ ...w, goal: goalView(ctx, w.sessionId) })),
1385
- }
1386
- // ETag/304:面板每 5 秒拉一次 /state,没变化时没必要重传整份 JSON ——
1387
- // 和我们自己对 GitHub 做的事一样,只是方向反过来(这次我们是服务端)。
1388
- // 依据:RFC 9110 §15.4.5 规定 304 不带正文,客户端沿用本地缓存。
1389
- const payload = JSON.stringify(stateBody)
1390
- // 注意:updatedAt 每次都变,把它排除在指纹之外,否则 ETag 永远不命中
1391
- const stable = JSON.stringify({ ...stateBody, updatedAt: undefined })
1392
- const etag = '"' + createHash('sha1').update(stable).digest('hex').slice(0, 16) + '"'
1393
- res.setHeader('etag', etag)
1394
- // 测试里的假 req 可能没有 headers,别因此崩
1395
- const inm = String((req.headers && req.headers['if-none-match']) || '')
1396
- if (inm && inm.split(',').map((v) => v.trim()).includes(etag)) {
1397
- res.statusCode = 304
1398
- res.end()
1399
- return
1400
- }
1401
- res.statusCode = 200
1402
- res.setHeader('content-type', 'application/json; charset=utf-8')
1403
- res.setHeader('cache-control', 'no-store')
1404
- res.end(payload)
1405
- },
1406
- })
1407
- addRoute({
1408
- kind: 'exact',
1409
- path: '/session-superagent/client-note',
1410
- handler: (req, res) => {
1411
- const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
1412
- const key = String(url.searchParams.get('key') || '')
1413
- // 只接受已知探针键:否则任何网页用一个 <img> 就能往状态文件里塞任意键
1414
- if (CLIENT_NOTE_KEYS.has(key)) {
1415
- record('note:' + key, String(url.searchParams.get('value') || '').slice(0, 300))
1416
- }
1417
- res.statusCode = 204; res.end()
1418
- },
1419
- })
1420
- addRoute({
1421
- kind: 'exact',
1422
- path: '/session-superagent/client-error',
1423
- handler: (req, res) => { record('error', String(req.url).slice(0, 400)); res.statusCode = 204; res.end() },
1424
- })
1425
- const readBody = (req) => new Promise((resolve) => {
1426
- const chunks = []
1427
- req.on('data', (chunk) => chunks.push(chunk))
1428
- req.on('end', () => {
1429
- try {
1430
- const raw = decodeBody(Buffer.concat(chunks).subarray(0, 64 * 1024))
1431
- resolve(JSON.parse(raw || '{}'))
1432
- } catch { resolve({}) }
1433
- })
1434
- req.on('error', () => resolve({}))
1435
- })
1436
- const json = (res, code, body) => {
1437
- res.statusCode = code
1438
- res.setHeader('content-type', 'application/json; charset=utf-8')
1439
- res.setHeader('cache-control', 'no-store')
1440
- res.end(JSON.stringify(body))
1441
- }
1442
-
1443
- // Create or update a watcher from the panel. The panel is session-scoped,
1444
- // so it must send the session id it is bound to.
1445
- addRoute({
1446
- kind: 'exact',
1447
- path: '/session-superagent/watch',
1448
- handler: async (req, res) => {
1449
- if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1450
- const body = await readBody(req)
1451
- // pause / resume / delete target an existing watcher by id; the
1452
- // create path below is the default when no action is supplied.
1453
- if (body.action) {
1454
- const action = String(body.action)
1455
- const id = String(body.id || '')
1456
- const state = readState()
1457
- // 立刻跑一次(对应 Claude Code Action 的 interactive 模式):
1458
- // 不等定时器,马上轮询一次;仍然受 filters / ack 标签约束。
1459
- if (action === 'poll') {
1460
- const entry = state.watchers && state.watchers[id]
1461
- if (!entry) return json(res, 404, { error: 'unknown watcher: ' + id })
1462
- if (entry.enabled === false) return json(res, 409, { error: 'watcher is paused' })
1463
- if (inFlight.has(id)) return json(res, 409, { error: 'already polling', id })
1464
- const every = Math.max(30, Number(entry.intervalSec) || 60) * 1000
1465
- inFlight.add(id)
1466
- pollOnce(ctx, entry, every)
1467
- .catch(() => {})
1468
- .finally(() => { inFlight.delete(id); persistEntry(entry) })
1469
- return json(res, 202, { ok: true, action, id, polling: true })
1470
- }
1471
- const result = applyWatcherAction(state, { action, id })
1472
- if (!result.ok) return json(res, 400, result)
1473
- if (result.deleted) {
1474
- // 立墓碑:否则一个持有旧快照的写入会把这条又"复活"
1475
- state.deleted = { ...(state.deleted || {}), [id]: new Date().toISOString() }
1476
- }
1477
- if (result.deleted || result.enabled === false) stopWatcher(id)
1478
- writeState(state)
1479
- if (result.enabled === true) startWatcher(state.watchers[id])
1480
- return json(res, 200, result)
1481
- }
1482
- const repo = String(body.repo || '').trim()
1483
- if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) return json(res, 400, { error: 'repo must be owner/name' })
1484
- const sessionId = String(body.sessionId || '').trim()
1485
- if (!sessionId) return json(res, 400, { error: 'sessionId is required (open the panel in the session that should be woken)' })
1486
- // 若这个实例的 ctx 已经 dispose(宿主重载后旧 handler 仍在服务请求),
1487
- // 建出来的 watcher 一定跑不起来(定时器一 tick 就 inactive context)。
1488
- // 与其静默造一条死守,不如直接拒绝并让用户重载宿主。
1489
- const agentsHere = agentsService(ctx)
1490
- const canReachSessions = agentsHere && typeof agentsHere.get === 'function'
1491
- if (!canReachSessions) {
1492
- json(res, 503, { ok: false, error: '插件实例已失效(当前 handler 跑在已释放的上下文里):请重载 DSH 后再添加' })
1493
- return
1494
- }
1495
- const intervalSec = Math.max(30, Math.min(3600, Number(body.intervalSec) || 60))
1496
- const state = readState()
1497
- state.watchers = state.watchers || {}
1498
- const id = repo + '#' + sessionId
1499
- const created = !(state.watchers && state.watchers[id])
1500
- const entry = state.watchers[id] || {
1501
- id, repo, sessionId, cursor: null, seen: {}, lastReported: {},
1502
- cooldownMs: 180000, createdAt: new Date().toISOString(),
1503
- filters: normalizeFilters(), batchLimit: 5, maxWakesPerHour: 6,
1504
- wakeTimes: [], consecutiveFailures: 0, ackLabel: DEFAULT_ACK_LABEL,
1505
- isolated: false, workdir: null,
1506
- }
1507
- entry.intervalSec = intervalSec
1508
- // 只有真正带了 goal 才覆盖:GUI 编辑保存不带这个字段,覆盖会清空
1509
- if (typeof body.goal === 'string') entry.goal = body.goal.slice(0, 500)
1510
- // 竞品蒸馏:触发要有许可(label/指派/跳过机器人草稿)、单次别铺开太多、每小时有上限
1511
- entry.filters = mergeFilters(entry.filters, body.filters)
1512
- entry.batchLimit = Math.max(1, Math.min(20, Number(body.batchLimit) || entry.batchLimit || 5))
1513
- entry.maxWakesPerHour = Math.max(1, Math.min(60, Number(body.maxWakesPerHour) || entry.maxWakesPerHour || 6))
1514
- if (body.sessionMaxWakes != null) entry.sessionMaxWakes = Math.max(1, Math.min(60, Number(body.sessionMaxWakes) || DEFAULT_SESSION_WAKES))
1515
- if (typeof body.ackLabel === 'string' && body.ackLabel.trim()) entry.ackLabel = body.ackLabel.trim().slice(0, 60)
1516
- // 优先级开关:客户可以关掉某几类"加权",只按 updated 顺序处理
1517
- if (body.priority && typeof body.priority === 'object') {
1518
- entry.priority = {
1519
- reopened: body.priority.reopened !== false,
1520
- comments: body.priority.comments !== false,
1521
- labels: body.priority.labels !== false,
1522
- // 默认关:没有官方依据支持"无人认领更紧急"
1523
- unassigned: body.priority.unassigned === true,
1524
- stale: body.priority.stale === true,
1525
- }
1526
- }
1527
- // 隔离执行(对标 DeepSeek DSec):每次唤醒开一次性 worktree,改副本不碰主工作区
1528
- entry.observe = body.observe === undefined ? entry.observe === true : body.observe === true
1529
- entry.isolated = body.isolated === undefined ? entry.isolated === true : body.isolated === true
1530
- if (body.isolateKeepDays != null) entry.isolateKeepDays = Math.max(1, Math.min(30, Number(body.isolateKeepDays) || 3))
1531
- // 同时最多留几个隔离区(越界回收最旧的)—— 1~50
1532
- if (body.maxIsolated != null) entry.maxIsolated = Math.max(1, Math.min(50, Number(body.maxIsolated) || 5))
1533
- if (typeof body.activeHours === 'string') entry.activeHours = body.activeHours.trim().slice(0, 20) || null
1534
- if (typeof body.workdir === 'string' && body.workdir.trim()) {
1535
- const workdir = body.workdir.trim()
1536
- if (!isAbsolute(workdir)) return json(res, 400, { error: 'workdir must be an absolute path' })
1537
- if (!existsSync(workdir)) return json(res, 400, { error: 'workdir does not exist: ' + workdir })
1538
- entry.workdir = workdir
1539
- }
1540
- else if (entry.isolated && !entry.workdir) entry.workdir = process.cwd()
1541
- entry.consecutiveFailures = 0
1542
- entry.nextAt = null
1543
- // 没传 enabled 就保持原值:只改间隔/标签不该把暂停的 watcher 悄悄恢复
1544
- entry.enabled = body.enabled === undefined ? (entry.enabled !== false) : body.enabled !== false
1545
- // 暂停/恢复时清掉「上一次的错误」:暂停后不再轮询,旧错误会一直挂在面板上变成假异常
1546
- if (body.enabled === false || body.enabled === true) {
1547
- entry.lastError = null
1548
- entry.deferReason = null
1549
- entry.lastDeferred = null
1550
- entry.consecutiveFailures = 0
1551
- entry.nextAt = null
1552
- }
1553
- // 只有**新建**时才做添加前体检:编辑已有守不该再打一次网络
1554
- const isNew = !created && !state.watchers[id]
1555
- let warnings = []
1556
- if (isNew) {
1557
- const pre = await precheckRepo(repo)
1558
- warnings = pre.warnings || []
1559
- if (pre.access) entry.repoAccess = pre.access
1560
- }
1561
- state.watchers[id] = entry
1562
- writeState(state)
1563
- // 编辑已有 watcher 时,间隔/配置变化要立刻生效:startWatcher 会因为 timer 已存在而直接返回
1564
- if (entry.enabled) {
1565
- stopWatcher(id)
1566
- probeAccess(entry).catch(() => {})
1567
-
1568
- startWatcher(entry)
1569
- }
1570
- json(res, 200, { ok: true, id, repo, intervalSec, enabled: entry.enabled, warnings })
1571
- },
1572
- })
1573
-
1574
- // Credentials typed by the operator. Stored 0600 under the state dir and
1575
- // never echoed back; the answer carries only a masked summary.
1576
- addRoute({
1577
- kind: 'exact',
1578
- path: '/session-superagent/credentials',
1579
- handler: async (req, res) => {
1580
- if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1581
- const body = await readBody(req)
1582
- const next = readSecrets()
1583
- if (typeof body.token === 'string') {
1584
- const token = body.token.trim()
1585
- if (token === '') delete next.token
1586
- else if (!/^(gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})$/.test(token)) {
1587
- return json(res, 400, { error: 'token shape not recognized (ghp_… or github_pat_…)' })
1588
- } else next.token = token
1589
- }
1590
- if (typeof body.sshKeyPath === 'string') {
1591
- const keyPath = body.sshKeyPath.trim()
1592
- if (keyPath === '') delete next.sshKeyPath
1593
- else if (!isAbsolute(keyPath)) return json(res, 400, { error: 'sshKeyPath must be absolute' })
1594
- else next.sshKeyPath = keyPath
1595
- }
1596
- next.updatedAt = new Date().toISOString()
1597
- writeSecrets(next)
1598
- json(res, 200, { credentials: secretsSummary() })
1599
- },
1600
- })
1601
-
1602
- // 客户报障用:把「版本 / 挂载状态 / 每条守的最近错误」拼成一段可直接粘贴的文本。
1603
- // 客户在别的电脑上,我们看不到他的状态文件 —— 让他一键复制这段就够了。
1604
- addRoute({
1605
- kind: 'exact',
1606
- path: '/session-superagent/diagnose',
1607
- handler: (req, res) => {
1608
- if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' })
1609
- const state = readState()
1610
- const mounted = state.server || {}
1611
- const lines = []
1612
- lines.push('主理鱼诊断 · ' + new Date().toISOString())
1613
- lines.push('插件版本: ' + SERVER_VERSION)
1614
- lines.push('宿主: DSH / node ' + String(process.version || ''))
1615
- lines.push('凭证保护: ' + (secretsHardened === 'unknown' ? '未写入过 token' : secretsHardened))
1616
- lines.push('挂载: routes=' + String(mounted.routes ?? '?')
1617
- + ' failed=' + String((mounted.failed || []).length)
1618
- + ' base=' + String(mounted.base || '-')
1619
- + ' at=' + String(mounted.at || '-'))
1620
- if ((mounted.failed || []).length > 0) lines.push('挂载失败: ' + mounted.failed.join('; '))
1621
- const entries = Object.values(state.watchers || {})
1622
- lines.push('值守: ' + entries.length + ' 条')
1623
- for (const entry of entries) {
1624
- lines.push('- ' + entry.repo
1625
- + ' | ' + (entry.enabled === false ? '已暂停' : '启用')
1626
- + ' | 间隔 ' + entry.intervalSec + 's'
1627
- + ' | 会话 ' + String(entry.sessionId || '').slice(0, 20)
1628
- + ' | 上次轮询 ' + String(entry.lastPoll || '-')
1629
- + ' | 失败 ' + (entry.consecutiveFailures || 0)
1630
- + (entry.lastError ? ' | 错误: ' + String(entry.lastError).slice(0, 160) : ''))
1631
- }
1632
- const text = redact(lines.join(String.fromCharCode(10)))
1633
- json(res, 200, { ok: true, text })
1634
- },
1635
- })
1636
-
1637
- // 单条追溯:面板点「追溯」时来问。只回传结论与明细,不回传 seen/lastReported 这类大字段。
1638
- addRoute({
1639
- kind: 'exact',
1640
- path: '/session-superagent/trace',
1641
- handler: async (req, res) => {
1642
- if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' })
1643
- const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
1644
- const repo = url.searchParams.get('repo') || ''
1645
- const number = url.searchParams.get('number') || ''
1646
- const state = readState()
1647
- const list = Object.values(state.watchers || {}).filter((entry) => !repo || entry.repo === repo)
1648
- const lines = []
1649
- for (const entry of list) {
1650
- const trace = itemTrace(entry, number)
1651
- if (!trace) continue
1652
- const touched = Boolean(trace.seen || trace.reported || trace.filtered.length || trace.wakes.length)
1653
- if (!touched) continue
1654
- lines.push('#' + trace.number + ' @ ' + (trace.repo || '?') + ':' + trace.verdict)
1655
- if (trace.seen) lines.push('水位 ' + trace.seen)
1656
- if (trace.reported) lines.push('上次上报 ' + trace.reported)
1657
- for (const item of trace.filtered) lines.push('被过滤(' + (item.reason || '未知') + ')' + item.at)
1658
- for (const item of trace.wakes) lines.push('唤醒尝试 ' + item.at + ' ' + (item.ok ? '成功' : '失败(' + (item.reason || '未知') + ')'))
1659
- }
1660
- const text = lines.length > 0
1661
- ? lines.join(String.fromCharCode(10))
1662
- : noTraceText(number, repo || '所有守')
1663
- json(res, 200, { ok: true, text })
1664
- },
1665
- })
1666
-
1667
- // 版本检查(只读;面板「设置」页那一行「有新版本」靠它)
1668
- addRoute({
1669
- kind: 'exact',
1670
- path: '/session-superagent/update',
1671
- handler: async (req, res) => {
1672
- if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' })
1673
- const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
1674
- const value = await checkUpdate(url.searchParams.get('refresh') === '1')
1675
- json(res, 200, value)
1676
- },
1677
- })
1678
-
1679
- // Set / edit / clear the session's REAL goal through ctx.goals — the same
1680
- // service the /goal command drives, so the panel and the conversation are
1681
- // one source of truth (polling reads it back).
1682
- addRoute({
1683
- kind: 'exact',
1684
- path: '/session-superagent/goal',
1685
- handler: async (req, res) => {
1686
- if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1687
- const body = await readBody(req)
1688
- const sessionId = String(body.sessionId || '').trim()
1689
- const objective = String(body.objective || '').trim()
1690
- if (!sessionId) return json(res, 400, { error: 'sessionId is required' })
1691
- const goals = typeof ctx.get === 'function' ? ctx.get('goals') : undefined
1692
- const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
1693
- if (!goals || !agents) return json(res, 501, { error: 'this host has no goal service' })
1694
- const agent = agents.get(sessionId)
1695
- if (!agent) return json(res, 404, { error: 'session is not live' })
1696
- try {
1697
- const current = goals.get(agent)
1698
- if (objective === '') {
1699
- if (!current) return json(res, 200, { ok: true, cleared: false, sessionGoal: null })
1700
- goals.clear(agent, current.ref)
1701
- return json(res, 200, { ok: true, cleared: true, sessionGoal: null })
1702
- }
1703
- const view = current
1704
- ? goals.edit(agent, current.ref, { objective })
1705
- : goals.create(agent, { objective })
1706
- return json(res, 200, {
1707
- ok: true,
1708
- sessionGoal: { objective: view.objective, phase: view.phase, revision: view.ref ? view.ref.revision : null },
1709
- })
1710
- } catch (error) {
1711
- return json(res, 400, { error: String((error && error.message) || error) })
1712
- }
1713
- },
1714
- })
1715
-
1716
- // 热重载时旧实例的 handler 摘不掉(宿主路由表行为):默认前缀会全部撞车。
1717
- // 那就换一个带序号的前缀整组重放 —— 面板会自己发现新前缀(客户端 discoverBase)。
1718
- if (failedRoutes.length > 0) {
1719
- const generation = (Number(globalThis[ROUTE_GEN_KEY]) || 1) + 1
1720
- globalThis[ROUTE_GEN_KEY] = generation
1721
- const altBase = DEFAULT_ROUTE_BASE + '/r' + generation
1722
- const replay = attempted.map((options) => ({ ...options, path: String(options.path).replace(DEFAULT_ROUTE_BASE, altBase) }))
1723
- failedRoutes.length = 0
1724
- for (const options of replay) addRoute(options)
1725
- if (failedRoutes.length === 0) {
1726
- activeBase = altBase
1727
- record('route-base', altBase)
1728
- }
1729
- }
1730
- const state = readState()
1731
- state.server = { at: new Date().toISOString(), routes: routes.length, failed: failedRoutes, base: activeBase, startedAt: new Date(PROCESS_STARTED_AT).toISOString() }
1732
- writeState(state)
1733
- } catch (error) {
1734
- const state = readState()
1735
- state.server = { at: new Date().toISOString(), routes: routes.length, failed: failedRoutes, error: String((error && error.message) || error).slice(0, 300), startedAt: new Date(PROCESS_STARTED_AT).toISOString() }
1736
- writeState(state)
1737
- }
1738
- const teardown = () => {
1739
- for (const dispose of routes) { try { dispose() } catch {} }
1740
- routes.length = 0
1741
- activeRoutes.length = 0
1742
- // 插件卸载/热重载后旧定时器不能继续跑:它们还持有已 dispose 的 ctx
1743
- for (const handle of timers.values()) { try { clearInterval(handle) } catch {} }
1744
- timers.clear()
1745
- try { clearInterval(sweepHandle) } catch {}
1746
- }
1747
- // 两条路都挂上:ctx.effect 的清理函数在 effect 作用域销毁时一定被调用;
1748
- // ctx.on('dispose') 覆盖宿主走事件广播的卸载方式。真机踩过「路由没 dispose →
1749
- // 重载后重复路由 → 六条接口全灭」,多挂一条成本很低。
1750
- try { ctx.effect(() => teardown) } catch {}
1751
- ctx.on('dispose', teardown)
1752
- }
1753
-
1754
- // Routes for the panel. `webServer` is the host's route registry (the same
1755
- // service dsh-unlag injects); it is a required inject so this plugin simply
1756
- // does not mount on a host that has no web surface, instead of silently
1757
- // offering a panel that cannot read anything.
1758
- try {
1759
- registerRoutes(ctx.webServer)
1760
- } catch (error) {
1761
- const state = readState()
1762
- state.server = { at: new Date().toISOString(), error: String((error && error.message) || error).slice(0, 300) }
1763
- writeState(state)
1764
- }
1765
-
1766
- // Manual test channel: {text, sessionId?} in trigger.json wakes that session
1767
- // on the next 5 s sweep, then removes the file. Verifies the inbox path
1768
- // without a host restart.
1769
- const sweepTrigger = () => {
1770
- // 测试通道:默认关闭。开着等于给本机任意进程一个「以用户口吻注入任意文本」的入口。
1771
- if (process.env.DSH_SUPERAGENT_TRIGGER !== '1') return
1772
- if (!existsSync(TRIGGER_FILE)) return
1773
- let payload = {}
1774
- try { payload = JSON.parse(readFileSync(TRIGGER_FILE, 'utf8')) } catch {}
1775
- try { unlinkSync(TRIGGER_FILE) } catch {}
1776
- const state = readState()
1777
- const any = Object.values(state.watchers || {}).find((w) => w && w.enabled)
1778
- const sessionId = payload.sessionId || (any && any.sessionId)
1779
- if (!sessionId) return
1780
- const result = wake(ctx, sessionId, payload.text || '【watch】ping')
1781
- state.lastTrigger = { at: new Date().toISOString(), ok: result.ok, reason: result.reason ?? null, sessionId }
1782
- writeState(state)
1783
- }
1784
- const sweepHandle = setInterval(sweepTrigger, 5000)
1785
- sweepHandle.unref?.()
1786
-
1787
- try {
1788
- const state = readState()
1789
- for (const entry of Object.values(state.watchers || {})) {
1790
- if (entry && entry.enabled) startWatcher(entry)
1791
- }
1792
- } catch {}
1793
-
1794
- ctx.tools.register(defineTool({
1795
- name: 'watch_ack',
1796
- description:
1797
- 'Mark an issue/PR as handled: adds the ack label on GitHub (主理鱼:已处理 by default) and advances the local watermark, so the same item will never wake this session again — even after a restart or on another machine.',
1798
- parameters: {
1799
- repo: { type: 'string', description: 'owner/name; defaults to the only watched repo' },
1800
- number: { type: 'number', description: 'issue or PR number' },
1801
- numbers: { type: 'string', description: '逗号分隔的多个编号,如 "12,13,14"(与 number 二选一)' },
1802
- label: { type: 'string', description: 'ack label, default 主理鱼:已处理' },
1803
- format: { type: 'string', description: "'text' (default) or 'json'." },
1804
- },
1805
- async execute(args) {
1806
- const numbers = String(args.numbers || args.number || '')
1807
- .split(',')
1808
- .map((v) => Number(v.trim()))
1809
- .filter((v) => Number.isFinite(v) && v > 0)
1810
- if (numbers.length === 0) return '[error: number (or numbers) is required]'
1811
- const state = readState()
1812
- const watchers = Object.values(state.watchers || {})
1813
- const entry = args.repo
1814
- ? watchers.find((w) => w && w.repo === String(args.repo))
1815
- : watchers.find((w) => w && w.enabled)
1816
- if (!entry) return '[error: no watcher for that repo — start one with watch_start first]'
1817
- const label = String(args.label || entry.ackLabel || DEFAULT_ACK_LABEL)
1818
- // GitHub 不会因为加标签而自动建标签:不存在时返回 422。先幂等建一次(已存在也返回 422,忽略)。
1819
- await run('gh', ['api', '-X', 'POST', `repos/${entry.repo}/labels`, '-f', `name=${label}`, '-f', 'color=ededed'], { env: ghEnv() })
1820
- const results = []
1821
- let failed = null
1822
- for (const number of numbers) {
1823
- const res = await run('gh', ['api', '-X', 'POST', `repos/${entry.repo}/issues/${number}/labels`, '-f', `labels[]=${label}`], { env: ghEnv() })
1824
- if (res.code !== 0) {
1825
- failed = { number, text: redact([res.stdout, res.stderr].filter(Boolean).join(' ').trim()).slice(0, 200) }
1826
- break
1827
- }
1828
- results.push(number)
1829
- }
1830
- if (failed) {
1831
- // 失败要分两类:会自动恢复的(网络/限流/网关)和必须人动手的(登录/权限/编号)
1832
- const why = classifyGhError(failed.text)
1833
- const retryable = ['network', 'ratelimit', 'gateway'].includes(why.kind)
1834
- // 文案不重复:可恢复的只说要等,不可恢复的只说要做什么(避免两句同义话叠在一起)
1835
- const LABELS = { network: '网络抖动', ratelimit: '被 GitHub 限流', gateway: 'GitHub 或代理故障', auth: 'gh 登录失效', notfound: '仓库或编号不存在', nogh: '找不到 gh 命令', other: '未归类的错误' }
1836
- const label = LABELS[why.kind] || LABELS.other
1837
- const advice = retryable ? '暂时失败,稍后再 ack 一次即可' : '需要你处理'
1838
- if (args && args.format === 'json') {
1839
- return JSON.stringify({
1840
- schemaVersion: 1, ok: false, repo: entry.repo, acked: results,
1841
- failed: { number: failed.number, text: failed.text, kind: why.kind, retryable, advice },
1842
- })
1843
- }
1371
+ lastErrorAt: w.lastErrorAt || null,
1372
+ deferReason: w.deferReason ?? null,
1373
+ daily: dailySummary(w.dailyWakes),
1374
+ busy: busierThanUsual(dailySummary(w.dailyWakes)),
1375
+ silentWakes: w.silentWakes ?? 0,
1376
+ note: w.goal ?? '',
1377
+ title: sessionTitle(w.sessionId),
1378
+ }))
1379
+ const stateBody = {
1380
+ gh,
1381
+ routeBase: activeBase,
1382
+ serverVersion: SERVER_VERSION,
1383
+ updatedAt: new Date().toISOString(),
1384
+ credentials: secretsSummary(),
1385
+ sessionGoal: goalView(ctx, focusSession),
1386
+ stateSource,
1387
+ // 会话级用量:上限够不够,客户应该一眼看到(数据都在状态里,零新增请求)
1388
+ sessionUsage: (() => {
1389
+ const list = Object.values(state.watchers || {})
1390
+ const usage = list.length === 0 ? null : sessionWakesLastHour(list, focusSession)
1391
+ const cap = list.length === 0 ? null : (Number(list[0].sessionMaxWakes) || 12)
1392
+ const capped = countCapped(list)
1393
+ if (usage === null) return null
1394
+ const suggest = suggestSessionCap({ used: usage, cap, capped })
1395
+ return { used: usage, cap, capped, suggest }
1396
+ })(),
1397
+ // 版本漂移:文件换了但宿主还在跑老模块(客户端热重载会掩盖这件事)
1398
+ installedVersion: installedVersion(),
1399
+ runningVersion: SERVER_VERSION,
1400
+ triageSignals: TRIAGE_SIGNALS,
1401
+ tokenScopes: scopesCache.value || null,
1402
+ isolation: isolationReport(Object.values(state.watchers || {})),
1403
+ sessionTitle: sessionTitle(focusSession),
1404
+ watchers: watchers.map((w) => ({ ...w, goal: goalView(ctx, w.sessionId) })),
1405
+ }
1406
+ // ETag/304:面板每 5 秒拉一次 /state,没变化时没必要重传整份 JSON ——
1407
+ // 和我们自己对 GitHub 做的事一样,只是方向反过来(这次我们是服务端)。
1408
+ // 依据:RFC 9110 §15.4.5 规定 304 不带正文,客户端沿用本地缓存。
1409
+ const payload = JSON.stringify(stateBody)
1410
+ // 注意:updatedAt 每次都变,把它排除在指纹之外,否则 ETag 永远不命中
1411
+ const stable = JSON.stringify({ ...stateBody, updatedAt: undefined })
1412
+ const etag = '"' + createHash('sha1').update(stable).digest('hex').slice(0, 16) + '"'
1413
+ res.setHeader('etag', etag)
1414
+ // 测试里的假 req 可能没有 headers,别因此崩
1415
+ const inm = String((req.headers && req.headers['if-none-match']) || '')
1416
+ if (inm && inm.split(',').map((v) => v.trim()).includes(etag)) {
1417
+ res.statusCode = 304
1418
+ res.end()
1419
+ return
1420
+ }
1421
+ res.statusCode = 200
1422
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1423
+ res.setHeader('cache-control', 'no-store')
1424
+ res.end(payload)
1425
+ },
1426
+ })
1427
+ addRoute({
1428
+ kind: 'exact',
1429
+ path: '/session-superagent/client-note',
1430
+ handler: (req, res) => {
1431
+ const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
1432
+ const key = String(url.searchParams.get('key') || '')
1433
+ // 只接受已知探针键:否则任何网页用一个 <img> 就能往状态文件里塞任意键
1434
+ if (CLIENT_NOTE_KEYS.has(key)) {
1435
+ record('note:' + key, String(url.searchParams.get('value') || '').slice(0, 300))
1436
+ }
1437
+ res.statusCode = 204; res.end()
1438
+ },
1439
+ })
1440
+ addRoute({
1441
+ kind: 'exact',
1442
+ path: '/session-superagent/client-error',
1443
+ handler: (req, res) => { record('error', String(req.url).slice(0, 400)); res.statusCode = 204; res.end() },
1444
+ })
1445
+ const readBody = (req) => new Promise((resolve) => {
1446
+ const chunks = []
1447
+ req.on('data', (chunk) => chunks.push(chunk))
1448
+ req.on('end', () => {
1449
+ try {
1450
+ const raw = decodeBody(Buffer.concat(chunks).subarray(0, 64 * 1024))
1451
+ resolve(JSON.parse(raw || '{}'))
1452
+ } catch { resolve({}) }
1453
+ })
1454
+ req.on('error', () => resolve({}))
1455
+ })
1456
+ const json = (res, code, body) => {
1457
+ res.statusCode = code
1458
+ res.setHeader('content-type', 'application/json; charset=utf-8')
1459
+ res.setHeader('cache-control', 'no-store')
1460
+ res.end(JSON.stringify(body))
1461
+ }
1462
+
1463
+ // Create or update a watcher from the panel. The panel is session-scoped,
1464
+ // so it must send the session id it is bound to.
1465
+ addRoute({
1466
+ kind: 'exact',
1467
+ path: '/session-superagent/watch',
1468
+ handler: async (req, res) => {
1469
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1470
+ const body = await readBody(req)
1471
+ // pause / resume / delete target an existing watcher by id; the
1472
+ // create path below is the default when no action is supplied.
1473
+ if (body.action) {
1474
+ const action = String(body.action)
1475
+ const id = String(body.id || '')
1476
+ const state = readState()
1477
+ // 立刻跑一次(对应 Claude Code Action 的 interactive 模式):
1478
+ // 不等定时器,马上轮询一次;仍然受 filters / ack 标签约束。
1479
+ if (action === 'poll') {
1480
+ const entry = state.watchers && state.watchers[id]
1481
+ if (!entry) return json(res, 404, { error: 'unknown watcher: ' + id })
1482
+ if (entry.enabled === false) return json(res, 409, { error: 'watcher is paused' })
1483
+ if (inFlight.has(id)) return json(res, 409, { error: 'already polling', id })
1484
+ const every = Math.max(30, Number(entry.intervalSec) || 60) * 1000
1485
+ inFlight.add(id)
1486
+ pollOnce(ctx, entry, every)
1487
+ .catch(() => {})
1488
+ .finally(() => { inFlight.delete(id); persistEntry(entry) })
1489
+ return json(res, 202, { ok: true, action, id, polling: true })
1490
+ }
1491
+ const result = applyWatcherAction(state, { action, id })
1492
+ if (!result.ok) return json(res, 400, result)
1493
+ if (result.deleted) {
1494
+ // 立墓碑:否则一个持有旧快照的写入会把这条又"复活"
1495
+ state.deleted = { ...(state.deleted || {}), [id]: new Date().toISOString() }
1496
+ }
1497
+ if (result.deleted || result.enabled === false) stopWatcher(id)
1498
+ writeState(state)
1499
+ if (result.enabled === true) startWatcher(state.watchers[id])
1500
+ return json(res, 200, result)
1501
+ }
1502
+ const repo = String(body.repo || '').trim()
1503
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) return json(res, 400, { error: 'repo must be owner/name' })
1504
+ const sessionId = String(body.sessionId || '').trim()
1505
+ if (!sessionId) return json(res, 400, { error: 'sessionId is required (open the panel in the session that should be woken)' })
1506
+ // 若这个实例的 ctx 已经 dispose(宿主重载后旧 handler 仍在服务请求),
1507
+ // 建出来的 watcher 一定跑不起来(定时器一 tick 就 inactive context)。
1508
+ // 与其静默造一条死守,不如直接拒绝并让用户重载宿主。
1509
+ const agentsHere = agentsService(ctx)
1510
+ const canReachSessions = agentsHere && typeof agentsHere.get === 'function'
1511
+ if (!canReachSessions) {
1512
+ json(res, 503, { ok: false, error: '插件实例已失效(当前 handler 跑在已释放的上下文里):请重载 DSH 后再添加' })
1513
+ return
1514
+ }
1515
+ const intervalSec = Math.max(30, Math.min(3600, Number(body.intervalSec) || 60))
1516
+ const state = readState()
1517
+ state.watchers = state.watchers || {}
1518
+ const id = repo + '#' + sessionId
1519
+ const created = !(state.watchers && state.watchers[id])
1520
+ const entry = state.watchers[id] || {
1521
+ id, repo, sessionId, cursor: null, seen: {}, lastReported: {},
1522
+ cooldownMs: 180000, createdAt: new Date().toISOString(),
1523
+ filters: normalizeFilters(), batchLimit: 5, maxWakesPerHour: 6,
1524
+ wakeTimes: [], consecutiveFailures: 0, ackLabel: DEFAULT_ACK_LABEL,
1525
+ isolated: false, workdir: null,
1526
+ }
1527
+ entry.intervalSec = intervalSec
1528
+ // 只有真正带了 goal 才覆盖:GUI 编辑保存不带这个字段,覆盖会清空
1529
+ if (typeof body.goal === 'string') entry.goal = body.goal.slice(0, 500)
1530
+ // 竞品蒸馏:触发要有许可(label/指派/跳过机器人草稿)、单次别铺开太多、每小时有上限
1531
+ entry.filters = mergeFilters(entry.filters, body.filters)
1532
+ entry.batchLimit = Math.max(1, Math.min(20, Number(body.batchLimit) || entry.batchLimit || 5))
1533
+ entry.maxWakesPerHour = Math.max(1, Math.min(60, Number(body.maxWakesPerHour) || entry.maxWakesPerHour || 6))
1534
+ if (body.sessionMaxWakes != null) entry.sessionMaxWakes = Math.max(1, Math.min(60, Number(body.sessionMaxWakes) || DEFAULT_SESSION_WAKES))
1535
+ if (typeof body.ackLabel === 'string' && body.ackLabel.trim()) entry.ackLabel = body.ackLabel.trim().slice(0, 60)
1536
+ // 优先级开关:客户可以关掉某几类"加权",只按 updated 顺序处理
1537
+ if (body.priority && typeof body.priority === 'object') {
1538
+ entry.priority = {
1539
+ reopened: body.priority.reopened !== false,
1540
+ comments: body.priority.comments !== false,
1541
+ labels: body.priority.labels !== false,
1542
+ // 默认关:没有官方依据支持"无人认领更紧急"
1543
+ unassigned: body.priority.unassigned === true,
1544
+ stale: body.priority.stale === true,
1545
+ }
1546
+ }
1547
+ // 隔离执行(对标 DeepSeek DSec):每次唤醒开一次性 worktree,改副本不碰主工作区
1548
+ entry.observe = body.observe === undefined ? entry.observe === true : body.observe === true
1549
+ entry.isolated = body.isolated === undefined ? entry.isolated === true : body.isolated === true
1550
+ if (body.isolateKeepDays != null) entry.isolateKeepDays = Math.max(1, Math.min(30, Number(body.isolateKeepDays) || 3))
1551
+ // 同时最多留几个隔离区(越界回收最旧的)—— 1~50
1552
+ if (body.maxIsolated != null) entry.maxIsolated = Math.max(1, Math.min(50, Number(body.maxIsolated) || 5))
1553
+ if (typeof body.activeHours === 'string') entry.activeHours = body.activeHours.trim().slice(0, 20) || null
1554
+ if (typeof body.workdir === 'string' && body.workdir.trim()) {
1555
+ const workdir = body.workdir.trim()
1556
+ if (!isAbsolute(workdir)) return json(res, 400, { error: 'workdir must be an absolute path' })
1557
+ if (!existsSync(workdir)) return json(res, 400, { error: 'workdir does not exist: ' + workdir })
1558
+ entry.workdir = workdir
1559
+ }
1560
+ else if (entry.isolated && !entry.workdir) entry.workdir = process.cwd()
1561
+ entry.consecutiveFailures = 0
1562
+ entry.nextAt = null
1563
+ // 没传 enabled 就保持原值:只改间隔/标签不该把暂停的 watcher 悄悄恢复
1564
+ entry.enabled = body.enabled === undefined ? (entry.enabled !== false) : body.enabled !== false
1565
+ // 暂停/恢复时清掉「上一次的错误」:暂停后不再轮询,旧错误会一直挂在面板上变成假异常
1566
+ if (body.enabled === false || body.enabled === true) {
1567
+ entry.lastError = null
1568
+ entry.deferReason = null
1569
+ entry.lastDeferred = null
1570
+ entry.consecutiveFailures = 0
1571
+ entry.nextAt = null
1572
+ }
1573
+ // 只有**新建**时才做添加前体检:编辑已有守不该再打一次网络
1574
+ const isNew = !created && !state.watchers[id]
1575
+ let warnings = []
1576
+ if (isNew) {
1577
+ const pre = await precheckRepo(repo)
1578
+ warnings = pre.warnings || []
1579
+ if (pre.access) entry.repoAccess = pre.access
1580
+ }
1581
+ state.watchers[id] = entry
1582
+ writeState(state)
1583
+ // 编辑已有 watcher 时,间隔/配置变化要立刻生效:startWatcher 会因为 timer 已存在而直接返回
1584
+ if (entry.enabled) {
1585
+ stopWatcher(id)
1586
+ probeAccess(entry).catch(() => {})
1587
+
1588
+ startWatcher(entry)
1589
+ }
1590
+ json(res, 200, { ok: true, id, repo, intervalSec, enabled: entry.enabled, warnings })
1591
+ },
1592
+ })
1593
+
1594
+ // Credentials typed by the operator. Stored 0600 under the state dir and
1595
+ // never echoed back; the answer carries only a masked summary.
1596
+ addRoute({
1597
+ kind: 'exact',
1598
+ path: '/session-superagent/credentials',
1599
+ handler: async (req, res) => {
1600
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1601
+ const body = await readBody(req)
1602
+ const next = readSecrets()
1603
+ if (typeof body.token === 'string') {
1604
+ const token = body.token.trim()
1605
+ if (token === '') delete next.token
1606
+ else if (!/^(gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})$/.test(token)) {
1607
+ return json(res, 400, { error: 'token shape not recognized (ghp_… or github_pat_…)' })
1608
+ } else next.token = token
1609
+ }
1610
+ if (typeof body.sshKeyPath === 'string') {
1611
+ const keyPath = body.sshKeyPath.trim()
1612
+ if (keyPath === '') delete next.sshKeyPath
1613
+ else if (!isAbsolute(keyPath)) return json(res, 400, { error: 'sshKeyPath must be absolute' })
1614
+ else next.sshKeyPath = keyPath
1615
+ }
1616
+ next.updatedAt = new Date().toISOString()
1617
+ writeSecrets(next)
1618
+ json(res, 200, { credentials: secretsSummary() })
1619
+ },
1620
+ })
1621
+
1622
+ // 客户报障用:把「版本 / 挂载状态 / 每条守的最近错误」拼成一段可直接粘贴的文本。
1623
+ // 客户在别的电脑上,我们看不到他的状态文件 —— 让他一键复制这段就够了。
1624
+ addRoute({
1625
+ kind: 'exact',
1626
+ path: '/session-superagent/diagnose',
1627
+ handler: (req, res) => {
1628
+ if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' })
1629
+ const state = readState()
1630
+ const mounted = state.server || {}
1631
+ const lines = []
1632
+ lines.push('主理鱼诊断 · ' + new Date().toISOString())
1633
+ lines.push('插件版本: ' + SERVER_VERSION)
1634
+ lines.push('宿主: DSH / node ' + String(process.version || ''))
1635
+ lines.push('凭证保护: ' + (secretsHardened === 'unknown' ? '未写入过 token' : secretsHardened))
1636
+ lines.push('挂载: routes=' + String(mounted.routes ?? '?')
1637
+ + ' failed=' + String((mounted.failed || []).length)
1638
+ + ' base=' + String(mounted.base || '-')
1639
+ + ' at=' + String(mounted.at || '-'))
1640
+ if ((mounted.failed || []).length > 0) lines.push('挂载失败: ' + mounted.failed.join('; '))
1641
+ const entries = Object.values(state.watchers || {})
1642
+ lines.push('值守: ' + entries.length + ' 条')
1643
+ for (const entry of entries) {
1644
+ lines.push('- ' + entry.repo
1645
+ + ' | ' + (entry.enabled === false ? '已暂停' : '启用')
1646
+ + ' | 间隔 ' + entry.intervalSec + 's'
1647
+ + ' | 会话 ' + String(entry.sessionId || '').slice(0, 20)
1648
+ + ' | 上次轮询 ' + String(entry.lastPoll || '-')
1649
+ + ' | 失败 ' + (entry.consecutiveFailures || 0)
1650
+ + (entry.lastError ? ' | 错误: ' + String(entry.lastError).slice(0, 160) : ''))
1651
+ }
1652
+ const text = redact(lines.join(String.fromCharCode(10)))
1653
+ json(res, 200, { ok: true, text })
1654
+ },
1655
+ })
1656
+
1657
+ // 单条追溯:面板点「追溯」时来问。只回传结论与明细,不回传 seen/lastReported 这类大字段。
1658
+ addRoute({
1659
+ kind: 'exact',
1660
+ path: '/session-superagent/trace',
1661
+ handler: async (req, res) => {
1662
+ if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' })
1663
+ const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
1664
+ const repo = url.searchParams.get('repo') || ''
1665
+ const number = url.searchParams.get('number') || ''
1666
+ const state = readState()
1667
+ const list = Object.values(state.watchers || {}).filter((entry) => !repo || entry.repo === repo)
1668
+ const lines = []
1669
+ for (const entry of list) {
1670
+ const trace = itemTrace(entry, number)
1671
+ if (!trace) continue
1672
+ const touched = Boolean(trace.seen || trace.reported || trace.filtered.length || trace.wakes.length)
1673
+ if (!touched) continue
1674
+ lines.push('#' + trace.number + ' @ ' + (trace.repo || '?') + ':' + trace.verdict)
1675
+ if (trace.seen) lines.push('水位 ' + trace.seen)
1676
+ if (trace.reported) lines.push('上次上报 ' + trace.reported)
1677
+ for (const item of trace.filtered) lines.push('被过滤(' + (item.reason || '未知') + ')' + item.at)
1678
+ for (const item of trace.wakes) lines.push('唤醒尝试 ' + item.at + ' ' + (item.ok ? '成功' : '失败(' + (item.reason || '未知') + ')'))
1679
+ }
1680
+ const text = lines.length > 0
1681
+ ? lines.join(String.fromCharCode(10))
1682
+ : noTraceText(number, repo || '所有守')
1683
+ json(res, 200, { ok: true, text })
1684
+ },
1685
+ })
1686
+
1687
+ // 版本检查(只读;面板「设置」页那一行「有新版本」靠它)
1688
+ addRoute({
1689
+ kind: 'exact',
1690
+ path: '/session-superagent/update',
1691
+ handler: async (req, res) => {
1692
+ if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' })
1693
+ const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
1694
+ const value = await checkUpdate(url.searchParams.get('refresh') === '1')
1695
+ json(res, 200, value)
1696
+ },
1697
+ })
1698
+
1699
+ // Set / edit / clear the session's REAL goal through ctx.goals — the same
1700
+ // service the /goal command drives, so the panel and the conversation are
1701
+ // one source of truth (polling reads it back).
1702
+ addRoute({
1703
+ kind: 'exact',
1704
+ path: '/session-superagent/goal',
1705
+ handler: async (req, res) => {
1706
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1707
+ const body = await readBody(req)
1708
+ const sessionId = String(body.sessionId || '').trim()
1709
+ const objective = String(body.objective || '').trim()
1710
+ if (!sessionId) return json(res, 400, { error: 'sessionId is required' })
1711
+ const goals = typeof ctx.get === 'function' ? ctx.get('goals') : undefined
1712
+ const agents = typeof ctx.get === 'function' ? ctx.get('agents') : undefined
1713
+ if (!goals || !agents) return json(res, 501, { error: 'this host has no goal service' })
1714
+ const agent = agents.get(sessionId)
1715
+ if (!agent) return json(res, 404, { error: 'session is not live' })
1716
+ try {
1717
+ const current = goals.get(agent)
1718
+ if (objective === '') {
1719
+ if (!current) return json(res, 200, { ok: true, cleared: false, sessionGoal: null })
1720
+ goals.clear(agent, current.ref)
1721
+ return json(res, 200, { ok: true, cleared: true, sessionGoal: null })
1722
+ }
1723
+ const view = current
1724
+ ? goals.edit(agent, current.ref, { objective })
1725
+ : goals.create(agent, { objective })
1726
+ return json(res, 200, {
1727
+ ok: true,
1728
+ sessionGoal: { objective: view.objective, phase: view.phase, revision: view.ref ? view.ref.revision : null },
1729
+ })
1730
+ } catch (error) {
1731
+ return json(res, 400, { error: String((error && error.message) || error) })
1732
+ }
1733
+ },
1734
+ })
1735
+
1736
+ // 热重载时旧实例的 handler 摘不掉(宿主路由表行为):默认前缀会全部撞车。
1737
+ // 那就换一个带序号的前缀整组重放 —— 面板会自己发现新前缀(客户端 discoverBase)。
1738
+ if (failedRoutes.length > 0) {
1739
+ const generation = (Number(globalThis[ROUTE_GEN_KEY]) || 1) + 1
1740
+ globalThis[ROUTE_GEN_KEY] = generation
1741
+ const altBase = DEFAULT_ROUTE_BASE + '/r' + generation
1742
+ const replay = attempted.map((options) => ({ ...options, path: String(options.path).replace(DEFAULT_ROUTE_BASE, altBase) }))
1743
+ failedRoutes.length = 0
1744
+ for (const options of replay) addRoute(options)
1745
+ if (failedRoutes.length === 0) {
1746
+ activeBase = altBase
1747
+ record('route-base', altBase)
1748
+ }
1749
+ }
1750
+ const state = readState()
1751
+ state.server = { at: new Date().toISOString(), routes: routes.length, failed: failedRoutes, base: activeBase, startedAt: new Date(PROCESS_STARTED_AT).toISOString() }
1752
+ writeState(state)
1753
+ } catch (error) {
1754
+ const state = readState()
1755
+ state.server = { at: new Date().toISOString(), routes: routes.length, failed: failedRoutes, error: String((error && error.message) || error).slice(0, 300), startedAt: new Date(PROCESS_STARTED_AT).toISOString() }
1756
+ writeState(state)
1757
+ }
1758
+ const teardown = () => {
1759
+ for (const dispose of routes) { try { dispose() } catch {} }
1760
+ routes.length = 0
1761
+ activeRoutes.length = 0
1762
+ // 插件卸载/热重载后旧定时器不能继续跑:它们还持有已 dispose 的 ctx
1763
+ for (const handle of timers.values()) { try { clearInterval(handle) } catch {} }
1764
+ timers.clear()
1765
+ try { clearInterval(sweepHandle) } catch {}
1766
+ }
1767
+ // 两条路都挂上:ctx.effect 的清理函数在 effect 作用域销毁时一定被调用;
1768
+ // ctx.on('dispose') 覆盖宿主走事件广播的卸载方式。真机踩过「路由没 dispose →
1769
+ // 重载后重复路由 → 六条接口全灭」,多挂一条成本很低。
1770
+ try { ctx.effect(() => teardown) } catch {}
1771
+ ctx.on('dispose', teardown)
1772
+ }
1773
+
1774
+ // Routes for the panel. `webServer` is the host's route registry (the same
1775
+ // service dsh-unlag injects); it is a required inject so this plugin simply
1776
+ // does not mount on a host that has no web surface, instead of silently
1777
+ // offering a panel that cannot read anything.
1778
+ try {
1779
+ registerRoutes(ctx.webServer)
1780
+ } catch (error) {
1781
+ const state = readState()
1782
+ state.server = { at: new Date().toISOString(), error: String((error && error.message) || error).slice(0, 300) }
1783
+ writeState(state)
1784
+ }
1785
+
1786
+ // Manual test channel: {text, sessionId?} in trigger.json wakes that session
1787
+ // on the next 5 s sweep, then removes the file. Verifies the inbox path
1788
+ // without a host restart.
1789
+ const sweepTrigger = () => {
1790
+ // 测试通道:默认关闭。开着等于给本机任意进程一个「以用户口吻注入任意文本」的入口。
1791
+ if (process.env.DSH_SUPERAGENT_TRIGGER !== '1') return
1792
+ if (!existsSync(TRIGGER_FILE)) return
1793
+ let payload = {}
1794
+ try { payload = JSON.parse(readFileSync(TRIGGER_FILE, 'utf8')) } catch {}
1795
+ try { unlinkSync(TRIGGER_FILE) } catch {}
1796
+ const state = readState()
1797
+ const any = Object.values(state.watchers || {}).find((w) => w && w.enabled)
1798
+ const sessionId = payload.sessionId || (any && any.sessionId)
1799
+ if (!sessionId) return
1800
+ const result = wake(ctx, sessionId, payload.text || '【watch】ping')
1801
+ state.lastTrigger = { at: new Date().toISOString(), ok: result.ok, reason: result.reason ?? null, sessionId }
1802
+ writeState(state)
1803
+ }
1804
+ const sweepHandle = setInterval(sweepTrigger, 5000)
1805
+ sweepHandle.unref?.()
1806
+
1807
+ try {
1808
+ const state = readState()
1809
+ for (const entry of Object.values(state.watchers || {})) {
1810
+ if (entry && entry.enabled) startWatcher(entry)
1811
+ }
1812
+ } catch {}
1813
+
1814
+ ctx.tools.register(defineTool({
1815
+ name: 'watch_ack',
1816
+ description:
1817
+ 'Mark an issue/PR as handled: adds the ack label on GitHub (主理鱼:已处理 by default) and advances the local watermark, so the same item will never wake this session again — even after a restart or on another machine.',
1818
+ parameters: {
1819
+ repo: { type: 'string', description: 'owner/name; defaults to the only watched repo' },
1820
+ number: { type: 'number', description: 'issue or PR number' },
1821
+ numbers: { type: 'string', description: '逗号分隔的多个编号,如 "12,13,14"(与 number 二选一)' },
1822
+ label: { type: 'string', description: 'ack label, default 主理鱼:已处理' },
1823
+ format: { type: 'string', description: "'text' (default) or 'json'." },
1824
+ },
1825
+ async execute(args) {
1826
+ const numbers = String(args.numbers || args.number || '')
1827
+ .split(',')
1828
+ .map((v) => Number(v.trim()))
1829
+ .filter((v) => Number.isFinite(v) && v > 0)
1830
+ if (numbers.length === 0) return '[error: number (or numbers) is required]'
1831
+ const state = readState()
1832
+ const watchers = Object.values(state.watchers || {})
1833
+ const entry = args.repo
1834
+ ? watchers.find((w) => w && w.repo === String(args.repo))
1835
+ : watchers.find((w) => w && w.enabled)
1836
+ if (!entry) return '[error: no watcher for that repo — start one with watch_start first]'
1837
+ const label = String(args.label || entry.ackLabel || DEFAULT_ACK_LABEL)
1838
+ // GitHub 不会因为加标签而自动建标签:不存在时返回 422。先幂等建一次(已存在也返回 422,忽略)。
1839
+ await run('gh', ['api', '-X', 'POST', `repos/${entry.repo}/labels`, '-f', `name=${label}`, '-f', 'color=ededed'], { env: ghEnv() })
1840
+ const results = []
1841
+ let failed = null
1842
+ for (const number of numbers) {
1843
+ const res = await run('gh', ['api', '-X', 'POST', `repos/${entry.repo}/issues/${number}/labels`, '-f', `labels[]=${label}`], { env: ghEnv() })
1844
+ if (res.code !== 0) {
1845
+ failed = { number, text: redact([res.stdout, res.stderr].filter(Boolean).join(' ').trim()).slice(0, 200) }
1846
+ break
1847
+ }
1848
+ results.push(number)
1849
+ }
1850
+ if (failed) {
1851
+ // 失败要分两类:会自动恢复的(网络/限流/网关)和必须人动手的(登录/权限/编号)
1852
+ const why = classifyGhError(failed.text)
1853
+ const retryable = ['network', 'ratelimit', 'gateway'].includes(why.kind)
1854
+ // 文案不重复:可恢复的只说要等,不可恢复的只说要做什么(避免两句同义话叠在一起)
1855
+ const LABELS = { network: '网络抖动', ratelimit: '被 GitHub 限流', gateway: 'GitHub 或代理故障', auth: 'gh 登录失效', notfound: '仓库或编号不存在', nogh: '找不到 gh 命令', other: '未归类的错误' }
1856
+ const label = LABELS[why.kind] || LABELS.other
1857
+ const advice = retryable ? '暂时失败,稍后再 ack 一次即可' : '需要你处理'
1858
+ if (args && args.format === 'json') {
1859
+ return JSON.stringify({
1860
+ schemaVersion: 1, ok: false, repo: entry.repo, acked: results,
1861
+ failed: { number: failed.number, text: failed.text, kind: why.kind, retryable, advice },
1862
+ })
1863
+ }
1844
1864
  return retryable
1845
1865
  ? `[error: #${failed.number} ${advice}(${label})]`
1846
- : `[error: #${failed.number} ${advice}] ${why.hint}`
1847
- }
1848
- const latest = readState()
1849
- const live = latest.watchers && latest.watchers[entry.id]
1850
- const nowIso = new Date().toISOString()
1851
- if (live) {
1852
- live.seen = advanceSeen(live.seen, results.map((number) => ({ number, updated_at: nowIso })))
1853
- // 打标签本身就是一次外部更新,把光标推到当下,避免自己把自己叫醒
1854
- live.cursor = nowIso
1855
- live.lastAcked = { numbers: results, label, at: nowIso }
1856
- writeState(latest)
1857
- }
1858
- if (args && args.format === 'json') {
1859
- return JSON.stringify({ schemaVersion: 1, ok: true, repo: entry.repo, label, acked: results, at: nowIso })
1860
- }
1861
- return `acked ${entry.repo} #${results.join(' #')} with label "${label}"`
1862
- },
1863
- }))
1864
-
1865
- // 单条追溯:agent 被问"这条为什么没叫醒我"时不用猜,直接查
1866
- ctx.tools.register(defineTool({
1867
- name: 'watch_trace',
1868
- description:
1869
- 'Explain what happened to one issue/PR: whether it was filtered (and why), absorbed by the cooldown, already reported, or never seen. Read-only — changes nothing. Use it when the customer asks "why did this not wake me".',
1870
- parameters: {
1871
- repo: { type: 'string', description: 'owner/name; defaults to the only watched repo' },
1872
- number: { type: 'number', description: 'issue or PR number to trace' },
1873
- format: { type: 'string', description: "'text' (default) or 'json'." },
1874
- },
1875
- async execute(args) {
1876
- const state = readState()
1877
- const all = Object.values(state.watchers || {})
1878
- const wanted = typeof args.repo === 'string' && args.repo.trim() ? args.repo.trim() : null
1879
- const list = wanted ? all.filter((entry) => entry && entry.repo === wanted) : all
1880
- if (list.length === 0) {
1881
- const message = 'no watcher for that repo — ' + (wanted ? 'nothing is watching ' + wanted : 'run watch_status to see what is watched')
1882
- // format=json 时错误也要是 JSON:消费方不该在两种格式间猜
1883
- return (args && args.format === 'json') ? JSON.stringify({ schemaVersion: 1, error: message }) : '[error: ' + message + ']'
1884
- }
1885
- const number = Number(args.number)
1886
- if (!Number.isFinite(number)) {
1887
- return (args && args.format === 'json') ? JSON.stringify({ schemaVersion: 1, error: 'number is required' }) : '[error: number is required]'
1888
- }
1889
- const lines = []
1890
- for (const entry of list) {
1891
- const trace = itemTrace(entry, number)
1892
- if (!trace) continue
1893
- const touched = Boolean(trace.seen || trace.reported || trace.filtered.length || trace.wakes.length)
1894
- if (!touched) continue
1895
- lines.push('#' + trace.number + ' @ ' + (trace.repo || '?') + ':' + trace.verdict)
1896
- // 例外优先:一切正常时一行说完,只有「被过滤/被吸收/唤醒失败」才展开细节
1897
- const quiet = trace.filtered.length === 0 && (trace.absorbed || []).length === 0
1898
- && trace.wakes.length > 0 && trace.wakes.every((item) => item.ok)
1899
- if (!quiet) {
1900
- if (trace.seen) lines.push(' 水位 seen:' + trace.seen)
1901
- if (trace.reported) lines.push(' 上次上报:' + trace.reported)
1902
- for (const item of trace.filtered) lines.push(' 被过滤(' + item.reason + '):' + item.at)
1903
- for (const item of trace.absorbed || []) lines.push(' 被冷却期吸收:' + item.at)
1904
- for (const item of trace.wakes) lines.push(' 唤醒尝试:' + item.at + ' ' + (item.ok ? '成功' : '失败(' + (item.reason || '未知') + ')'))
1905
- } else if (trace.wakes.length > 0) {
1906
- lines.push(' 最近一次唤醒:' + trace.wakes[trace.wakes.length - 1].at + '(成功)')
1907
- }
1908
- }
1909
- if (args && args.format === 'json') {
1910
- const results = []
1911
- for (const entry of list) {
1912
- const trace = itemTrace(entry, number)
1913
- if (!trace) continue
1914
- const touched = Boolean(trace.seen || trace.reported || trace.filtered.length || trace.wakes.length)
1915
- if (!touched) continue
1916
- results.push(trace)
1917
- }
1918
- return JSON.stringify({ schemaVersion: 1, number: String(number), results }, null, 2)
1919
- }
1920
- if (lines.length === 0) {
1921
- return noTraceText(number, wanted ? ' ' + wanted : '所有守')
1922
- }
1923
- return lines.join(String.fromCharCode(10))
1924
- },
1925
- }))
1926
-
1927
- ctx.tools.register(defineTool({
1928
- name: 'watch_doctor',
1929
- description:
1930
- 'Self-check the watchers: gh login, repo access, ack label existence, isolation workdir. Read-only; prints a checklist.',
1931
- parameters: {
1932
- repo: { type: 'string', description: 'only check this owner/name; default = every watcher' },
1933
- format: { type: 'string', description: "'text' (default) or 'json'." },
1934
- },
1935
- async execute(args) {
1936
- const lines = []
1937
- const state = readState()
1938
- const all = Object.values(state.watchers || {})
1939
- const wanted = args.repo ? all.filter((w) => w && w.repo === String(args.repo)) : all
1940
-
1941
- // -2. 状态来源:从备份或损坏里恢复过,客户有权知道(否则他会纳闷「我的守怎么少了一条」)
1942
- if (stateSource === 'backup') {
1943
- lines.push('WARN 状态文件坏过一次,已从备份恢复(原文件留在 .corrupt-* 里,可人工检查)')
1944
- } else if (stateSource === 'corrupt') {
1945
- lines.push('FAIL 状态文件和备份都读不了 —— 已从空状态开始,原文件留在 .corrupt-*;请重新添加守')
1946
- }
1947
- // -1. 版本一致性:文件换了但没重启时,服务端仍然跑老代码(客户端热重载会掩盖这件事)
1948
- const installed = installedVersion()
1949
- if (installed && installed !== SERVER_VERSION) {
1950
- lines.push(`WARN 代码已更新但未生效:磁盘 ${installed} / 正在运行 ${SERVER_VERSION} —— 需要重启宿主(不是重装)`)
1951
- } else if (installed) {
1952
- lines.push(`OK 版本一致:${SERVER_VERSION}`)
1953
- }
1954
-
1955
- // 0. 挂载状态:面板/HTTP 靠路由,路由注册失败时工具仍然可用 —— 这种「半死」状态
1956
- // 光看工具是发现不了的(2026-11-02 真机踩过:duplicate exact route 让六条接口全灭)
1957
- if (state.server) {
1958
- const mounted = Number(state.server.routes) || 0
1959
- const failed = Array.isArray(state.server.failed) ? state.server.failed : []
1960
- if (state.server.error) {
1961
- lines.push(`FAIL 面板接口挂载:${state.server.error}(工具仍可用,但面板会空白;重载一次即可)`)
1962
- } else if (failed.length > 0) {
1963
- lines.push(`WARN 面板接口部分失败(${mounted}/6 成功):${failed.join(';')}`)
1964
- } else {
1965
- lines.push(`OK 面板接口挂载:${mounted} 条,无失败`)
1966
- }
1967
- } else {
1968
- lines.push('WARN 还没有挂载记录(刚装上或从未加载过路由)')
1969
- }
1970
-
1971
- // 1. gh 是否登录
1972
- const auth = await run('gh', ['auth', 'status'], { env: ghEnv() })
1973
- const authed = auth.code === 0
1974
- lines.push(`${authed ? 'OK ' : 'FAIL'} gh 登录:${auth.code === 0 ? '正常' : redact([auth.stderr, auth.stdout].join(' ')).slice(0, 120)}`)
1975
-
1976
- if (wanted.length === 0) {
1977
- lines.push('INFO 当前没有任何 watcher —— 先 watch_start 或到面板加一条')
1978
- if (args && args.format === 'json') {
1979
- const checks = lines.map((line) => {
1980
- const m = /^(OK|WARN|FAIL|INFO)\s*(.*)$/.exec(line)
1981
- return { status: m ? m[1].toLowerCase() : 'info', text: (m ? m[2] : line).trim() }
1982
- })
1983
- return JSON.stringify({ schemaVersion: 1, checks }, null, 2)
1984
- }
1985
- return lines.join('\n')
1986
- }
1987
-
1988
- for (const entry of wanted) {
1989
- // 2. 仓库可访问
1990
- const repoRes = await run('gh', ['api', `repos/${entry.repo}`, '--jq', '.full_name'], { env: ghEnv() })
1991
- if (repoRes.code === 0) {
1992
- lines.push(`OK ${entry.repo} 可访问:${repoRes.stdout.trim()}`)
1993
- } else {
1994
- // 仓库改名/转移在 GH 上是 301,客户看到的却只是「一直没动静」
1995
- const why = classifyGhError([repoRes.stderr, repoRes.stdout].join(' '))
1996
- lines.push(`FAIL ${entry.repo} 不可访问:${why.hint}`)
1997
- }
1998
-
1999
- // 3. ack 标签是否存在
2000
- const label = entry.ackLabel || DEFAULT_ACK_LABEL
2001
- const labRes = await run('gh', ['api', `repos/${entry.repo}/labels/${encodeURIComponent(label)}`, '--jq', '.name'], { env: ghEnv() })
2002
- lines.push(`${labRes.code === 0 ? 'OK ' : 'WARN'} ack 标签「${label}」:${labRes.code === 0 ? '已存在' : '不存在(首次 watch_ack 会自动创建)'}`)
2003
-
2004
- // 4. 隔离工作目录
2005
- if (entry.isolated) {
2006
- const wd = entry.workdir
2007
- if (!wd) lines.push('WARN 隔离开着但没有 workdir,会在宿主 cwd 里建 worktree')
2008
- else if (!existsSync(wd)) lines.push(`FAIL 隔离工作目录不存在:${wd}`)
2009
- else {
2010
- const gitRes = await run('git', ['-C', wd, 'rev-parse', '--is-inside-work-tree'], { timeoutMs: 15000 })
2011
- lines.push(`${gitRes.code === 0 ? 'OK ' : 'FAIL'} 隔离工作目录 ${wd}:${gitRes.code === 0 ? '是 git 仓库' : '不是 git 仓库'}`)
2012
- // 目录在但不可写时,第一次唤醒建 worktree 就会失败(真机上更常见的是权限/磁盘)
2013
- const probe = join(wd, '.dsh-doctor-probe')
2014
- try {
2015
- writeFileSync(probe, String(Date.now()))
2016
- rmSync(probe, { force: true })
2017
- } catch (error) {
2018
- lines.push(`FAIL 隔离工作目录不可写:${wd}(${String((error && error.code) || error).slice(0, 40)})`)
2019
- }
2020
- }
2021
- }
2022
-
2023
- // 5. 轮询停滞:定时器丢了或进程被挂起时,面板上一切「正常」,其实早就不看了
2024
- if (entry.enabled !== false && entry.lastPoll) {
2025
- const intervalMs = (Number(entry.intervalSec) || 60) * 1000
2026
- const staleMs = Math.max(intervalMs * 3, 5 * 60 * 1000)
2027
- const age = Date.now() - Date.parse(entry.lastPoll)
2028
- const uptimeMs = state.server && state.server.startedAt ? Date.now() - Date.parse(state.server.startedAt) : Infinity
2029
- // 刚重启时 uptime 还不够一个停滞周期:陈旧只是「还没轮到」,不是故障
2030
- if (Number.isFinite(age) && age > staleMs && uptimeMs > staleMs) {
2031
- lines.push(`WARN ${entry.repo} 已经 ${Math.round(age / 60000)} 分钟没轮询过(预期每 ${Math.round(intervalMs / 1000)} 秒)—— 定时器可能丢了`)
2032
- } else if (Number.isFinite(age) && age > staleMs) {
2033
- lines.push(`INFO ${entry.repo} 上次轮询是 ${Math.round(age / 60000)} 分钟前,但进程才启动 ${Math.round(uptimeMs / 60000)} 分钟 —— 刚重启,等下一轮即可`)
2034
- }
2035
- }
2036
-
2037
- // 6. 最近一次状态
2038
- const last = entry.lastError ? `错误:${entry.lastError}` : entry.lastDeferred ? `等待:${entry.lastDeferred}` : '正常'
2039
- lines.push(`INFO ${entry.enabled === false ? '已暂停' : '运行中'} · 上次轮询 ${entry.lastPoll || '无'} · ${last}`)
2040
- }
2041
- // format=json 时从同一份文本行解析出结构 —— 单一来源,不会出现两套逻辑走偏
2042
- if (args && args.format === 'json') {
2043
- const checks = lines.map((line) => {
2044
- const m = /^(OK|WARN|FAIL|INFO)\s*(.*)$/.exec(line)
2045
- return { status: m ? m[1].toLowerCase() : 'info', text: (m ? m[2] : line).trim() }
2046
- })
2047
- return JSON.stringify({ schemaVersion: 1, checks }, null, 2)
2048
- }
2049
- return lines.join('\n')
2050
- },
2051
- }))
2052
-
2053
- ctx.tools.register(defineTool({
2054
- name: 'github',
2055
- description: 'Call the GitHub REST API. The credential stays inside the plugin — it is never returned, and every result is redacted. Write methods require confirm: true.',
2056
- parameters: {
2057
- method: { type: 'string', description: 'HTTP method, default GET.' },
2058
- path: { type: 'string', required: true, description: 'API path after https://api.github.com/, e.g. repos/o/r/issues.' },
2059
- body: { type: 'string', description: 'JSON body for write methods.' },
2060
- confirm: { type: 'boolean', description: 'Must be true for POST/PATCH/PUT/DELETE.' },
2061
- },
2062
- async execute(args) {
2063
- const method = String(args.method || 'GET').toUpperCase()
2064
- if (String(args.path || '').trim().startsWith('-')) {
2065
- return '[error: path must be a GitHub API path, not a flag]'
2066
- }
2067
- if (!['GET', 'HEAD', 'POST', 'PATCH', 'PUT', 'DELETE'].includes(method)) {
2068
- return `[error: unsupported method ${method}]`
2069
- }
2070
- const write = ['GET', 'HEAD'].indexOf(method) === -1
2071
- if (write && args.confirm !== true) {
2072
- return `[error: ${method} requires confirm: true — this plugin never writes to GitHub without an explicit flag]`
2073
- }
2074
- const res = await run('gh', ['api', '-X', method, args.path, '--header', 'Accept: application/vnd.github+json'], {
2075
- input: write && args.body ? args.body : undefined, env: ghEnv(),
2076
- })
1866
+ : `[error: #${failed.number} ${advice}] ${why.hint}`
1867
+ }
1868
+ const latest = readState()
1869
+ const live = latest.watchers && latest.watchers[entry.id]
1870
+ const nowIso = new Date().toISOString()
1871
+ if (live) {
1872
+ live.seen = advanceSeen(live.seen, results.map((number) => ({ number, updated_at: nowIso })))
1873
+ // 打标签本身就是一次外部更新,把光标推到当下,避免自己把自己叫醒
1874
+ live.cursor = nowIso
1875
+ live.lastAcked = { numbers: results, label, at: nowIso }
1876
+ writeState(latest)
1877
+ }
1878
+ if (args && args.format === 'json') {
1879
+ return JSON.stringify({ schemaVersion: 1, ok: true, repo: entry.repo, label, acked: results, at: nowIso })
1880
+ }
1881
+ return `acked ${entry.repo} #${results.join(' #')} with label "${label}"`
1882
+ },
1883
+ }))
1884
+
1885
+ // 单条追溯:agent 被问"这条为什么没叫醒我"时不用猜,直接查
1886
+ ctx.tools.register(defineTool({
1887
+ name: 'watch_trace',
1888
+ description:
1889
+ 'Explain what happened to one issue/PR: whether it was filtered (and why), absorbed by the cooldown, already reported, or never seen. Read-only — changes nothing. Use it when the customer asks "why did this not wake me".',
1890
+ parameters: {
1891
+ repo: { type: 'string', description: 'owner/name; defaults to the only watched repo' },
1892
+ number: { type: 'number', description: 'issue or PR number to trace' },
1893
+ format: { type: 'string', description: "'text' (default) or 'json'." },
1894
+ },
1895
+ async execute(args) {
1896
+ const state = readState()
1897
+ const all = Object.values(state.watchers || {})
1898
+ const wanted = typeof args.repo === 'string' && args.repo.trim() ? args.repo.trim() : null
1899
+ const list = wanted ? all.filter((entry) => entry && entry.repo === wanted) : all
1900
+ if (list.length === 0) {
1901
+ const message = 'no watcher for that repo — ' + (wanted ? 'nothing is watching ' + wanted : 'run watch_status to see what is watched')
1902
+ // format=json 时错误也要是 JSON:消费方不该在两种格式间猜
1903
+ return (args && args.format === 'json') ? JSON.stringify({ schemaVersion: 1, error: message }) : '[error: ' + message + ']'
1904
+ }
1905
+ const number = Number(args.number)
1906
+ if (!Number.isFinite(number)) {
1907
+ return (args && args.format === 'json') ? JSON.stringify({ schemaVersion: 1, error: 'number is required' }) : '[error: number is required]'
1908
+ }
1909
+ const lines = []
1910
+ for (const entry of list) {
1911
+ const trace = itemTrace(entry, number)
1912
+ if (!trace) continue
1913
+ const touched = Boolean(trace.seen || trace.reported || trace.filtered.length || trace.wakes.length)
1914
+ if (!touched) continue
1915
+ lines.push('#' + trace.number + ' @ ' + (trace.repo || '?') + ':' + trace.verdict)
1916
+ // 例外优先:一切正常时一行说完,只有「被过滤/被吸收/唤醒失败」才展开细节
1917
+ const quiet = trace.filtered.length === 0 && (trace.absorbed || []).length === 0
1918
+ && trace.wakes.length > 0 && trace.wakes.every((item) => item.ok)
1919
+ if (!quiet) {
1920
+ if (trace.seen) lines.push(' 水位 seen:' + trace.seen)
1921
+ if (trace.reported) lines.push(' 上次上报:' + trace.reported)
1922
+ for (const item of trace.filtered) lines.push(' 被过滤(' + item.reason + '):' + item.at)
1923
+ for (const item of trace.absorbed || []) lines.push(' 被冷却期吸收:' + item.at)
1924
+ for (const item of trace.wakes) lines.push(' 唤醒尝试:' + item.at + ' ' + (item.ok ? '成功' : '失败(' + (item.reason || '未知') + ')'))
1925
+ } else if (trace.wakes.length > 0) {
1926
+ lines.push(' 最近一次唤醒:' + trace.wakes[trace.wakes.length - 1].at + '(成功)')
1927
+ }
1928
+ }
1929
+ if (args && args.format === 'json') {
1930
+ const results = []
1931
+ for (const entry of list) {
1932
+ const trace = itemTrace(entry, number)
1933
+ if (!trace) continue
1934
+ const touched = Boolean(trace.seen || trace.reported || trace.filtered.length || trace.wakes.length)
1935
+ if (!touched) continue
1936
+ results.push(trace)
1937
+ }
1938
+ return JSON.stringify({ schemaVersion: 1, number: String(number), results }, null, 2)
1939
+ }
1940
+ if (lines.length === 0) {
1941
+ return noTraceText(number, wanted ? ' ' + wanted : '所有守')
1942
+ }
1943
+ return lines.join(String.fromCharCode(10))
1944
+ },
1945
+ }))
1946
+
1947
+ ctx.tools.register(defineTool({
1948
+ name: 'watch_doctor',
1949
+ description:
1950
+ 'Self-check the watchers: gh login, repo access, ack label existence, isolation workdir. Read-only; prints a checklist.',
1951
+ parameters: {
1952
+ repo: { type: 'string', description: 'only check this owner/name; default = every watcher' },
1953
+ format: { type: 'string', description: "'text' (default) or 'json'." },
1954
+ },
1955
+ async execute(args) {
1956
+ const lines = []
1957
+ const state = readState()
1958
+ const all = Object.values(state.watchers || {})
1959
+ const wanted = args.repo ? all.filter((w) => w && w.repo === String(args.repo)) : all
1960
+
1961
+ // -2. 状态来源:从备份或损坏里恢复过,客户有权知道(否则他会纳闷「我的守怎么少了一条」)
1962
+ if (stateSource === 'backup') {
1963
+ lines.push('WARN 状态文件坏过一次,已从备份恢复(原文件留在 .corrupt-* 里,可人工检查)')
1964
+ } else if (stateSource === 'corrupt') {
1965
+ lines.push('FAIL 状态文件和备份都读不了 —— 已从空状态开始,原文件留在 .corrupt-*;请重新添加守')
1966
+ }
1967
+ // -1. 版本一致性:文件换了但没重启时,服务端仍然跑老代码(客户端热重载会掩盖这件事)
1968
+ const installed = installedVersion()
1969
+ if (installed && installed !== SERVER_VERSION) {
1970
+ lines.push(`WARN 代码已更新但未生效:磁盘 ${installed} / 正在运行 ${SERVER_VERSION} —— 需要重启宿主(不是重装)`)
1971
+ } else if (installed) {
1972
+ lines.push(`OK 版本一致:${SERVER_VERSION}`)
1973
+ }
1974
+
1975
+ // 0. 挂载状态:面板/HTTP 靠路由,路由注册失败时工具仍然可用 —— 这种「半死」状态
1976
+ // 光看工具是发现不了的(2026-11-02 真机踩过:duplicate exact route 让六条接口全灭)
1977
+ if (state.server) {
1978
+ const mounted = Number(state.server.routes) || 0
1979
+ const failed = Array.isArray(state.server.failed) ? state.server.failed : []
1980
+ if (state.server.error) {
1981
+ lines.push(`FAIL 面板接口挂载:${state.server.error}(工具仍可用,但面板会空白;重载一次即可)`)
1982
+ } else if (failed.length > 0) {
1983
+ lines.push(`WARN 面板接口部分失败(${mounted}/6 成功):${failed.join(';')}`)
1984
+ } else {
1985
+ lines.push(`OK 面板接口挂载:${mounted} 条,无失败`)
1986
+ }
1987
+ } else {
1988
+ lines.push('WARN 还没有挂载记录(刚装上或从未加载过路由)')
1989
+ }
1990
+
1991
+ // 1. gh 是否登录
1992
+ const auth = await run('gh', ['auth', 'status'], { env: ghEnv() })
1993
+ const authed = auth.code === 0
1994
+ lines.push(`${authed ? 'OK ' : 'FAIL'} gh 登录:${auth.code === 0 ? '正常' : redact([auth.stderr, auth.stdout].join(' ')).slice(0, 120)}`)
1995
+
1996
+ if (wanted.length === 0) {
1997
+ lines.push('INFO 当前没有任何 watcher —— 先 watch_start 或到面板加一条')
1998
+ if (args && args.format === 'json') {
1999
+ const checks = lines.map((line) => {
2000
+ const m = /^(OK|WARN|FAIL|INFO)\s*(.*)$/.exec(line)
2001
+ return { status: m ? m[1].toLowerCase() : 'info', text: (m ? m[2] : line).trim() }
2002
+ })
2003
+ return JSON.stringify({ schemaVersion: 1, checks }, null, 2)
2004
+ }
2005
+ return lines.join('\n')
2006
+ }
2007
+
2008
+ for (const entry of wanted) {
2009
+ // 2. 仓库可访问
2010
+ const repoRes = await run('gh', ['api', `repos/${entry.repo}`, '--jq', '.full_name'], { env: ghEnv() })
2011
+ if (repoRes.code === 0) {
2012
+ lines.push(`OK ${entry.repo} 可访问:${repoRes.stdout.trim()}`)
2013
+ } else {
2014
+ // 仓库改名/转移在 GH 上是 301,客户看到的却只是「一直没动静」
2015
+ const why = classifyGhError([repoRes.stderr, repoRes.stdout].join(' '))
2016
+ lines.push(`FAIL ${entry.repo} 不可访问:${why.hint}`)
2017
+ }
2018
+
2019
+ // 3. ack 标签是否存在
2020
+ const label = entry.ackLabel || DEFAULT_ACK_LABEL
2021
+ const labRes = await run('gh', ['api', `repos/${entry.repo}/labels/${encodeURIComponent(label)}`, '--jq', '.name'], { env: ghEnv() })
2022
+ lines.push(`${labRes.code === 0 ? 'OK ' : 'WARN'} ack 标签「${label}」:${labRes.code === 0 ? '已存在' : '不存在(首次 watch_ack 会自动创建)'}`)
2023
+
2024
+ // 4. 隔离工作目录
2025
+ if (entry.isolated) {
2026
+ const wd = entry.workdir
2027
+ if (!wd) lines.push('WARN 隔离开着但没有 workdir,会在宿主 cwd 里建 worktree')
2028
+ else if (!existsSync(wd)) lines.push(`FAIL 隔离工作目录不存在:${wd}`)
2029
+ else {
2030
+ const gitRes = await run('git', ['-C', wd, 'rev-parse', '--is-inside-work-tree'], { timeoutMs: 15000 })
2031
+ lines.push(`${gitRes.code === 0 ? 'OK ' : 'FAIL'} 隔离工作目录 ${wd}:${gitRes.code === 0 ? '是 git 仓库' : '不是 git 仓库'}`)
2032
+ // 目录在但不可写时,第一次唤醒建 worktree 就会失败(真机上更常见的是权限/磁盘)
2033
+ const probe = join(wd, '.dsh-doctor-probe')
2034
+ try {
2035
+ writeFileSync(probe, String(Date.now()))
2036
+ rmSync(probe, { force: true })
2037
+ } catch (error) {
2038
+ lines.push(`FAIL 隔离工作目录不可写:${wd}(${String((error && error.code) || error).slice(0, 40)})`)
2039
+ }
2040
+ }
2041
+ }
2042
+
2043
+ // 5. 轮询停滞:定时器丢了或进程被挂起时,面板上一切「正常」,其实早就不看了
2044
+ if (entry.enabled !== false && entry.lastPoll) {
2045
+ const intervalMs = (Number(entry.intervalSec) || 60) * 1000
2046
+ const staleMs = Math.max(intervalMs * 3, 5 * 60 * 1000)
2047
+ const age = Date.now() - Date.parse(entry.lastPoll)
2048
+ const uptimeMs = state.server && state.server.startedAt ? Date.now() - Date.parse(state.server.startedAt) : Infinity
2049
+ // 刚重启时 uptime 还不够一个停滞周期:陈旧只是「还没轮到」,不是故障
2050
+ if (Number.isFinite(age) && age > staleMs && uptimeMs > staleMs) {
2051
+ lines.push(`WARN ${entry.repo} 已经 ${Math.round(age / 60000)} 分钟没轮询过(预期每 ${Math.round(intervalMs / 1000)} 秒)—— 定时器可能丢了`)
2052
+ } else if (Number.isFinite(age) && age > staleMs) {
2053
+ lines.push(`INFO ${entry.repo} 上次轮询是 ${Math.round(age / 60000)} 分钟前,但进程才启动 ${Math.round(uptimeMs / 60000)} 分钟 —— 刚重启,等下一轮即可`)
2054
+ }
2055
+ }
2056
+
2057
+ // 6. 最近一次状态
2058
+ const last = entry.lastError ? `错误:${entry.lastError}` : entry.lastDeferred ? `等待:${entry.lastDeferred}` : '正常'
2059
+ lines.push(`INFO ${entry.enabled === false ? '已暂停' : '运行中'} · 上次轮询 ${entry.lastPoll || '无'} · ${last}`)
2060
+ }
2061
+ // format=json 时从同一份文本行解析出结构 —— 单一来源,不会出现两套逻辑走偏
2062
+ if (args && args.format === 'json') {
2063
+ const checks = lines.map((line) => {
2064
+ const m = /^(OK|WARN|FAIL|INFO)\s*(.*)$/.exec(line)
2065
+ return { status: m ? m[1].toLowerCase() : 'info', text: (m ? m[2] : line).trim() }
2066
+ })
2067
+ return JSON.stringify({ schemaVersion: 1, checks }, null, 2)
2068
+ }
2069
+ return lines.join('\n')
2070
+ },
2071
+ }))
2072
+
2073
+ ctx.tools.register(defineTool({
2074
+ name: 'github',
2075
+ description: 'Call the GitHub REST API. The credential stays inside the plugin — it is never returned, and every result is redacted. Write methods require confirm: true.',
2076
+ parameters: {
2077
+ method: { type: 'string', description: 'HTTP method, default GET.' },
2078
+ path: { type: 'string', required: true, description: 'API path after https://api.github.com/, e.g. repos/o/r/issues.' },
2079
+ body: { type: 'string', description: 'JSON body for write methods.' },
2080
+ confirm: { type: 'boolean', description: 'Must be true for POST/PATCH/PUT/DELETE.' },
2081
+ },
2082
+ async execute(args) {
2083
+ const method = String(args.method || 'GET').toUpperCase()
2084
+ if (String(args.path || '').trim().startsWith('-')) {
2085
+ return '[error: path must be a GitHub API path, not a flag]'
2086
+ }
2087
+ if (!['GET', 'HEAD', 'POST', 'PATCH', 'PUT', 'DELETE'].includes(method)) {
2088
+ return `[error: unsupported method ${method}]`
2089
+ }
2090
+ const write = ['GET', 'HEAD'].indexOf(method) === -1
2091
+ if (write && args.confirm !== true) {
2092
+ return `[error: ${method} requires confirm: true — this plugin never writes to GitHub without an explicit flag]`
2093
+ }
2094
+ const res = await run('gh', ['api', '-X', method, args.path, '--header', 'Accept: application/vnd.github+json'], {
2095
+ input: write && args.body ? args.body : undefined, env: ghEnv(),
2096
+ })
2077
2097
  const text = redact([res.stdout, res.stderr].filter(Boolean).join(String.fromCharCode(10)).trim())
2078
2098
  // 失败要带「下一步」:只贴 gh 的原始报错,调用方还得自己猜
2079
2099
  return formatGhCall({ code: res.code, text, classify: classifyGhError })
2080
- },
2081
- }))
2082
-
2083
- ctx.tools.register(defineTool({
2084
- name: 'repo_here',
2085
- description: 'Report the GitHub repository of the current working directory (owner/name, default branch, visibility). Read-only.',
2086
- parameters: {},
2087
- async execute() {
2088
- const res = await run('gh', ['repo', 'view', '--json', 'nameWithOwner,defaultBranchRef,visibility,url'], { cwd: process.cwd(), env: ghEnv() })
2089
- const text = redact([res.stdout, res.stderr].filter(Boolean).join('\n').trim())
2090
- return `${text || '(empty)'}\n[exit code: ${res.code}]`
2091
- },
2092
- }))
2093
-
2094
- ctx.tools.register(defineTool({
2095
- name: 'watch_start',
2096
- description: 'Watch a GitHub repository and wake THIS session when its issues or pull requests change. Idempotent per (repo, session). Default interval 60 s, minimum 30 s.',
2097
- parameters: {
2098
- repo: { type: 'string', description: 'owner/name. Omit to infer from the current working directory.' },
2099
- intervalSec: { type: 'number', description: 'Polling interval in seconds, clamped to 30-3600, default 60.' },
2100
- labels: { type: 'array', items: { type: 'string' }, description: 'Only handle items carrying one of these labels (whitelist).' },
2101
- ignoreLabels: { type: 'array', items: { type: 'string' }, description: 'Skip items carrying any of these labels.' },
2102
- onlyAssigned: { type: 'boolean', description: 'Only handle items assigned to someone (or to `assignee`).' },
2103
- assignee: { type: 'string', description: 'With onlyAssigned: require this login.' },
2104
- observe: { type: 'boolean', description: 'Observe only: record what WOULD be woken, never wake.' },
2105
- isolated: { type: 'boolean', description: 'Run each wake in a throwaway git worktree.' },
2106
- workdir: { type: 'string', description: 'Repository used for isolation worktrees (absolute path).' },
2107
- activeHours: { type: 'string', description: 'Wake only inside this window, e.g. "09:00-23:00" (supports overnight).' },
2108
- format: { type: 'string', description: "'text' (default) or 'json'." },
2109
- batchLimit: { type: 'number', description: 'Max items listed per wake (1-20, default 5).' },
2110
- maxWakesPerHour: { type: 'number', description: 'Max wakes per hour per watcher (1-60, default 6).' },
2111
- sessionMaxWakes: { type: 'number', description: 'Max wakes per hour for the whole session, summed across watchers (1-60, default 12).' },
2112
- isolateKeepDays: { type: 'number', description: 'With isolated: remove isolation worktrees older than this many days (1-30, default 3).' },
2113
- maxIsolated: { type: 'number', description: 'With isolated: keep at most this many worktrees, oldest removed first (1-50, default 5).' },
2114
- goal: { type: 'string', description: 'Optional per-watcher goal appended to the wake message.' },
2115
- ackLabel: { type: 'string', description: 'Label used as the handled marker (default 主理鱼:已处理). Two sessions watching the same repo share it unless each sets its own.' },
2116
- },
2117
- async execute(args) {
2118
- const toolAgents = agentsService(ctx)
2119
- const agent = toolAgents && typeof toolAgents.currentInitiator === 'function' ? toolAgents.currentInitiator() : undefined
2120
- const sessionId = agent && agent.id
2121
- if (!sessionId) return '[error: no live session — watch_start must be called from a session turn]'
2122
-
2123
- let repo = args.repo
2124
- if (!repo) {
2125
- const res = await run('gh', ['repo', 'view', '--json', 'nameWithOwner'], { cwd: process.cwd(), env: ghEnv() })
2126
- try { repo = JSON.parse(res.stdout).nameWithOwner } catch { return `[error: cannot infer repo]\n${redact(res.stderr)}` }
2127
- }
2128
-
2129
- // 一次可以加多个仓库:客户三个仓库不用点三次(逗号/空格/换行都认)
2130
- const repoList = String(repo).split(/[,\s]+/).map((item) => item.trim()).filter(Boolean)
2131
- const bad = repoList.filter((item) => !/^[^/\s]+\/[^/\s]+$/.test(item))
2132
- if (bad.length > 0) return '[error: 仓库要写成 owner/name,这些不对:' + bad.join(', ') + ']'
2133
- if (repoList.length === 0) return '[error: 至少给一个仓库(owner/name)]'
2134
- const applyOne = (repo) => {
2135
- const id = `${repo}#${sessionId}`
2136
- const state = readState()
2137
- const existing = state.watchers && state.watchers[id]
2138
- const entry = existing || {
2139
- id, repo, sessionId,
2140
- intervalSec: 60,
2141
- cooldownMs: DEFAULT_COOLDOWN_MS,
2100
+ },
2101
+ }))
2102
+
2103
+ ctx.tools.register(defineTool({
2104
+ name: 'repo_here',
2105
+ description: 'Report the GitHub repository of the current working directory (owner/name, default branch, visibility). Read-only.',
2106
+ parameters: {},
2107
+ async execute() {
2108
+ const res = await run('gh', ['repo', 'view', '--json', 'nameWithOwner,defaultBranchRef,visibility,url'], { cwd: process.cwd(), env: ghEnv() })
2109
+ const text = redact([res.stdout, res.stderr].filter(Boolean).join(String.fromCharCode(10)).trim())
2110
+ // 与 github 工具同一套:失败带分类与下一步,而不是只贴原始 stderr
2111
+ return formatGhCall({ code: res.code, text, classify: classifyGhError })
2112
+ },
2113
+ }))
2114
+
2115
+ ctx.tools.register(defineTool({
2116
+ name: 'watch_start',
2117
+ description: 'Watch a GitHub repository and wake THIS session when its issues or pull requests change. Idempotent per (repo, session). Default interval 60 s, minimum 30 s.',
2118
+ parameters: {
2119
+ repo: { type: 'string', description: 'owner/name. Omit to infer from the current working directory.' },
2120
+ intervalSec: { type: 'number', description: 'Polling interval in seconds, clamped to 30-3600, default 60.' },
2121
+ labels: { type: 'array', items: { type: 'string' }, description: 'Only handle items carrying one of these labels (whitelist).' },
2122
+ ignoreLabels: { type: 'array', items: { type: 'string' }, description: 'Skip items carrying any of these labels.' },
2123
+ onlyAssigned: { type: 'boolean', description: 'Only handle items assigned to someone (or to `assignee`).' },
2124
+ assignee: { type: 'string', description: 'With onlyAssigned: require this login.' },
2125
+ observe: { type: 'boolean', description: 'Observe only: record what WOULD be woken, never wake.' },
2126
+ isolated: { type: 'boolean', description: 'Run each wake in a throwaway git worktree.' },
2127
+ workdir: { type: 'string', description: 'Repository used for isolation worktrees (absolute path).' },
2128
+ activeHours: { type: 'string', description: 'Wake only inside this window, e.g. "09:00-23:00" (supports overnight).' },
2129
+ format: { type: 'string', description: "'text' (default) or 'json'." },
2130
+ batchLimit: { type: 'number', description: 'Max items listed per wake (1-20, default 5).' },
2131
+ maxWakesPerHour: { type: 'number', description: 'Max wakes per hour per watcher (1-60, default 6).' },
2132
+ sessionMaxWakes: { type: 'number', description: 'Max wakes per hour for the whole session, summed across watchers (1-60, default 12).' },
2133
+ isolateKeepDays: { type: 'number', description: 'With isolated: remove isolation worktrees older than this many days (1-30, default 3).' },
2134
+ maxIsolated: { type: 'number', description: 'With isolated: keep at most this many worktrees, oldest removed first (1-50, default 5).' },
2135
+ goal: { type: 'string', description: 'Optional per-watcher goal appended to the wake message.' },
2136
+ ackLabel: { type: 'string', description: 'Label used as the handled marker (default 主理鱼:已处理). Two sessions watching the same repo share it unless each sets its own.' },
2137
+ },
2138
+ async execute(args) {
2139
+ const toolAgents = agentsService(ctx)
2140
+ const agent = toolAgents && typeof toolAgents.currentInitiator === 'function' ? toolAgents.currentInitiator() : undefined
2141
+ const sessionId = agent && agent.id
2142
+ if (!sessionId) return '[error: no live session — watch_start must be called from a session turn]'
2143
+
2144
+ let repo = args.repo
2145
+ if (!repo) {
2146
+ const res = await run('gh', ['repo', 'view', '--json', 'nameWithOwner'], { cwd: process.cwd(), env: ghEnv() })
2147
+ try { repo = JSON.parse(res.stdout).nameWithOwner } catch { return `[error: cannot infer repo]\n${redact(res.stderr)}` }
2148
+ }
2149
+
2150
+ // 一次可以加多个仓库:客户三个仓库不用点三次(逗号/空格/换行都认)
2151
+ const repoList = String(repo).split(/[,\s]+/).map((item) => item.trim()).filter(Boolean)
2152
+ const bad = repoList.filter((item) => !/^[^/\s]+\/[^/\s]+$/.test(item))
2153
+ if (bad.length > 0) return '[error: 仓库要写成 owner/name,这些不对:' + bad.join(', ') + ']'
2154
+ if (repoList.length === 0) return '[error: 至少给一个仓库(owner/name)]'
2155
+ const applyOne = (repo) => {
2156
+ const id = `${repo}#${sessionId}`
2157
+ const state = readState()
2158
+ const existing = state.watchers && state.watchers[id]
2159
+ const entry = existing || {
2160
+ id, repo, sessionId,
2161
+ intervalSec: 60,
2162
+ cooldownMs: DEFAULT_COOLDOWN_MS,
2142
2163
  ackLabel: DEFAULT_ACK_LABEL,
2143
- cursor: null,
2144
- seen: {},
2145
- lastReported: {},
2146
- enabled: true,
2147
- createdAt: new Date().toISOString(),
2148
- }
2149
- if (typeof args.intervalSec === 'number' && args.intervalSec > 0) {
2150
- // 之前只判断 >0,能把 5 秒存进状态文件(调度时会按 30 秒跑,但状态与实际不一致)
2151
- entry.intervalSec = Math.max(30, Math.min(3600, Math.round(args.intervalSec)))
2152
- }
2153
- const patch = {}
2154
- if (args.labels !== undefined) patch.labels = args.labels
2155
- if (args.ignoreLabels !== undefined) patch.ignoreLabels = args.ignoreLabels
2156
- if (args.onlyAssigned !== undefined) patch.onlyAssigned = args.onlyAssigned
2157
- if (args.assignee !== undefined) patch.assignee = args.assignee
2158
- if (Object.keys(patch).length > 0) entry.filters = mergeFilters(entry.filters, patch)
2159
- if (typeof args.goal === 'string') entry.goal = args.goal.slice(0, 500)
2160
- if (typeof args.observe === 'boolean') entry.observe = args.observe
2161
- if (typeof args.isolated === 'boolean') entry.isolated = args.isolated
2162
- if (typeof args.workdir === 'string' && args.workdir.trim()) {
2163
- const workdir = args.workdir.trim()
2164
- if (!isAbsolute(workdir)) return '[error: workdir must be an absolute path]'
2165
- if (!existsSync(workdir)) return '[error: workdir does not exist: ' + workdir + ']'
2166
- entry.workdir = workdir
2167
- }
2168
- if (typeof args.activeHours === 'string') entry.activeHours = args.activeHours.trim() || null
2169
- if (typeof args.batchLimit === 'number') entry.batchLimit = Math.max(1, Math.min(20, Math.round(args.batchLimit)))
2170
- if (typeof args.maxWakesPerHour === 'number') entry.maxWakesPerHour = Math.max(1, Math.min(60, Math.round(args.maxWakesPerHour)))
2171
- // 面板能改的三项,工具也要能改 —— 否则被问"把隔离区最多留 3 个"时 agent 无从下手
2172
- if (typeof args.sessionMaxWakes === 'number') entry.sessionMaxWakes = Math.max(1, Math.min(60, Math.round(args.sessionMaxWakes)))
2173
- if (typeof args.isolateKeepDays === 'number') entry.isolateKeepDays = Math.max(1, Math.min(30, Math.round(args.isolateKeepDays)))
2174
- if (typeof args.maxIsolated === 'number') entry.maxIsolated = Math.max(1, Math.min(50, Math.round(args.maxIsolated)))
2175
- if (typeof args.ackLabel === 'string' && args.ackLabel.trim()) entry.ackLabel = args.ackLabel.trim().slice(0, 60)
2176
- entry.enabled = true
2177
- state.watchers = state.watchers || {}
2178
- if (!existing) {
2179
- const mine = Object.values(state.watchers).filter((w) => w && w.sessionId === sessionId)
2180
- if (mine.length >= MAX_WATCHERS_PER_SESSION) {
2181
- return '一条会话最多挂 ' + MAX_WATCHERS_PER_SESSION + ' 条守(现在 ' + mine.length + ' 条)—— 先 watch_stop 停掉不用的,或把多个仓库合成一条规则'
2182
- }
2183
- }
2184
- state.watchers[id] = entry
2185
- writeState(state)
2186
- stopWatcher(id)
2187
- startWatcher(entry)
2188
- const flags = []
2189
- if (entry.observe === true) flags.push('observe-only(只记录不唤醒)')
2190
- if (entry.isolated === true) flags.push('isolated')
2191
- if (entry.activeHours) flags.push('activeHours=' + entry.activeHours)
2192
- if (entry.filters && entry.filters.labels && entry.filters.labels.length) flags.push('labels=' + entry.filters.labels.join(','))
2193
- if (entry.filters && entry.filters.onlyAssigned) flags.push('onlyAssigned' + (entry.filters.assignee ? '(' + entry.filters.assignee + ')' : ''))
2194
- if (entry.batchLimit) flags.push('batch=' + entry.batchLimit)
2195
- if (entry.maxWakesPerHour) flags.push('perHour=' + entry.maxWakesPerHour)
2196
- if (entry.goal) flags.push('goal=' + JSON.stringify(entry.goal.slice(0, 40)))
2197
- return { entry, existing, flags, id, repo }
2198
-
2199
- }
2200
- // 批量要整批校验:19 条时一次加 2 条,不能只加进去第一条
2201
- {
2202
- const snapshot = readState()
2203
- const mine = Object.values(snapshot.watchers || {}).filter((w) => w && w.sessionId === sessionId)
2204
- const incoming = repoList.filter((name) => !(snapshot.watchers || {})[name + '#' + sessionId])
2205
- const room = MAX_WATCHERS_PER_SESSION - mine.length
2206
- if (incoming.length > room) {
2207
- return '一条会话最多挂 ' + MAX_WATCHERS_PER_SESSION + ' 条守(现在 ' + mine.length + ' 条,这次要新增 ' + incoming.length + ' 条)—— 先 watch_stop 停掉不用的,或把多个仓库合成一条规则'
2208
- }
2209
- }
2210
- const applied = []
2211
- for (const name of repoList) {
2212
- const result = applyOne(name)
2213
- // 单条校验失败(比如相对路径的 workdir)要原地返回,不能继续加后面的
2214
- if (typeof result === 'string') return result
2215
- applied.push(result)
2216
- }
2217
- if (args && args.format === 'json') {
2218
- const first = applied[0]
2219
- const base = JSON.parse(JSON.stringify({ schemaVersion: 1, ok: true, repo: first.repo, sessionId, id: first.id, intervalSec: first.entry.intervalSec,
2220
- flags: first.flags, filters: first.entry.filters || {}, updated: Boolean(first.existing), observe: first.entry.observe === true,
2221
- isolated: first.entry.isolated === true, activeHours: first.entry.activeHours || null }))
2222
- base.repos = applied.map((item) => ({ repo: item.repo, id: item.id, updated: Boolean(item.existing) }))
2223
- return JSON.stringify(base, null, 2)
2224
- }
2225
- const lines = applied.map((item) => `watching ${item.repo} → session ${sessionId} every ${item.entry.intervalSec}s`
2226
- + (item.flags.length ? ' [' + item.flags.join(' ') + ']' : '')
2227
- + (item.existing ? ' (updated existing watcher)' : ''))
2228
- return lines.join(String.fromCharCode(10))
2229
- },
2230
- }))
2231
-
2232
- ctx.tools.register(defineTool({
2233
- name: 'watch_status',
2234
- description: 'Report active watchers: schedule, why one is paused, unanswered wakes, and how much of the session wake budget is used. Use format=json for machine-readable output. Read-only.',
2235
- parameters: {
2236
- format: { type: 'string', description: "'text' (default, human) or 'json' (same data, structured)." },
2237
- },
2238
- async execute(args) {
2239
- const state = readState()
2240
- const list = Object.values(state.watchers || {})
2241
- if (!list.length) return args && args.format === 'json' ? JSON.stringify({ schemaVersion: 1, session: null, watchers: [] }) : '(no watchers)'
2242
- // 同一份数据:结构化视图 -> 文本只是它的一种渲染,两边永远对得上
2243
- const view = statusView(list)
2244
- if (args && args.format === 'json') return JSON.stringify(view, null, 2)
2245
- // 默认只写「这条守是什么」;只有当它需要你注意时才追加原因。
2246
- // 以前每行都带 lastPoll/lastWake/err=-,十条守就是十行长日志。
2247
- const body = view.watchers.map((w) => {
2248
- const parts = [w.repo, '→', w.sessionId, '| 每 ' + w.intervalSec + 's']
2249
- if (w.observe) parts.push('| 仅观察')
2250
- if (w.isolated) parts.push('| 隔离')
2251
- if (!w.enabled) parts.push('| 已暂停')
2252
- if (w.activeHours) parts.push('| 时段 ' + w.activeHours)
2253
- if (w.labels.length) parts.push('| 标签 ' + w.labels.join(','))
2254
- if (w.onlyAssigned) parts.push('| 只看已指派')
2255
- const problems = []
2256
- if (w.deferReason) problems.push('暂停:' + w.deferReason)
2257
- if (w.silentWakes >= 2) problems.push('叫醒 ' + w.silentWakes + ' 次没回音')
2258
- if (w.lastError) problems.push('上次失败:' + String(w.lastError).split('(')[0].slice(0, 60))
2259
- if (w.enabled && w.lastPoll) {
2260
- const age = Date.now() - Date.parse(w.lastPoll)
2261
- if (Number.isFinite(age) && age > Math.max(w.intervalSec * 3000, 300000)) {
2262
- problems.push('已 ' + Math.round(age / 60000) + ' 分钟没轮询')
2263
- }
2264
- }
2265
- if (!w.lastPoll) problems.push('还没轮询过')
2266
- if (problems.length) parts.push('| ' + problems.join(';'))
2267
- return parts.join(' ')
2268
- }).join(String.fromCharCode(10))
2269
- const s2 = view.session
2270
- const summary = 'session: ' + s2.used + '/' + s2.cap + ' wakes last hour'
2271
- + (s2.capped > 0 ? ',' + s2.capped + ' 条守正因上限暂停' : '')
2272
- + (s2.suggest ? ',建议把会话上限调到 ' + s2.suggest : '')
2273
- return body + String.fromCharCode(10) + summary
2274
- },
2275
- }))
2276
-
2277
- ctx.tools.register(defineTool({
2278
- name: 'watch_stop',
2279
- description: 'Stop watching a repository for the current session.',
2280
- parameters: {
2281
- repo: { type: 'string', required: true, description: 'owner/name' },
2282
- format: { type: 'string', description: "'text' (default) or 'json'." },
2283
- },
2284
- async execute(args) {
2285
- const toolAgents = agentsService(ctx)
2286
- const agent = toolAgents && typeof toolAgents.currentInitiator === 'function' ? toolAgents.currentInitiator() : undefined
2287
- const sessionId = agent && agent.id
2288
- const id = `${args.repo}#${sessionId}`
2289
- const state = readState()
2290
- if (!state.watchers || !state.watchers[id]) {
2291
- const message = 'no watcher for ' + id
2292
- return (args && args.format === 'json') ? JSON.stringify({ schemaVersion: 1, ok: false, id, error: message }) : '(' + message + ')'
2293
- }
2294
- state.watchers[id].enabled = false
2295
- writeState(state)
2296
- const timer = timers.get(id)
2297
- if (timer) { clearInterval(timer); timers.delete(id) }
2298
- if (args && args.format === 'json') return JSON.stringify({ schemaVersion: 1, ok: true, id, repo: args.repo })
2299
- return `stopped ${id}`
2300
- },
2301
- }))
2302
- }
2164
+ cursor: null,
2165
+ seen: {},
2166
+ lastReported: {},
2167
+ enabled: true,
2168
+ createdAt: new Date().toISOString(),
2169
+ }
2170
+ if (typeof args.intervalSec === 'number' && args.intervalSec > 0) {
2171
+ // 之前只判断 >0,能把 5 秒存进状态文件(调度时会按 30 秒跑,但状态与实际不一致)
2172
+ entry.intervalSec = Math.max(30, Math.min(3600, Math.round(args.intervalSec)))
2173
+ }
2174
+ const patch = {}
2175
+ if (args.labels !== undefined) patch.labels = args.labels
2176
+ if (args.ignoreLabels !== undefined) patch.ignoreLabels = args.ignoreLabels
2177
+ if (args.onlyAssigned !== undefined) patch.onlyAssigned = args.onlyAssigned
2178
+ if (args.assignee !== undefined) patch.assignee = args.assignee
2179
+ if (Object.keys(patch).length > 0) entry.filters = mergeFilters(entry.filters, patch)
2180
+ if (typeof args.goal === 'string') entry.goal = args.goal.slice(0, 500)
2181
+ if (typeof args.observe === 'boolean') entry.observe = args.observe
2182
+ if (typeof args.isolated === 'boolean') entry.isolated = args.isolated
2183
+ if (typeof args.workdir === 'string' && args.workdir.trim()) {
2184
+ const workdir = args.workdir.trim()
2185
+ if (!isAbsolute(workdir)) return '[error: workdir must be an absolute path]'
2186
+ if (!existsSync(workdir)) return '[error: workdir does not exist: ' + workdir + ']'
2187
+ entry.workdir = workdir
2188
+ }
2189
+ if (typeof args.activeHours === 'string') entry.activeHours = args.activeHours.trim() || null
2190
+ if (typeof args.batchLimit === 'number') entry.batchLimit = Math.max(1, Math.min(20, Math.round(args.batchLimit)))
2191
+ if (typeof args.maxWakesPerHour === 'number') entry.maxWakesPerHour = Math.max(1, Math.min(60, Math.round(args.maxWakesPerHour)))
2192
+ // 面板能改的三项,工具也要能改 —— 否则被问"把隔离区最多留 3 个"时 agent 无从下手
2193
+ if (typeof args.sessionMaxWakes === 'number') entry.sessionMaxWakes = Math.max(1, Math.min(60, Math.round(args.sessionMaxWakes)))
2194
+ if (typeof args.isolateKeepDays === 'number') entry.isolateKeepDays = Math.max(1, Math.min(30, Math.round(args.isolateKeepDays)))
2195
+ if (typeof args.maxIsolated === 'number') entry.maxIsolated = Math.max(1, Math.min(50, Math.round(args.maxIsolated)))
2196
+ if (typeof args.ackLabel === 'string' && args.ackLabel.trim()) entry.ackLabel = args.ackLabel.trim().slice(0, 60)
2197
+ entry.enabled = true
2198
+ state.watchers = state.watchers || {}
2199
+ if (!existing) {
2200
+ const mine = Object.values(state.watchers).filter((w) => w && w.sessionId === sessionId)
2201
+ if (mine.length >= MAX_WATCHERS_PER_SESSION) {
2202
+ return '一条会话最多挂 ' + MAX_WATCHERS_PER_SESSION + ' 条守(现在 ' + mine.length + ' 条)—— 先 watch_stop 停掉不用的,或把多个仓库合成一条规则'
2203
+ }
2204
+ }
2205
+ state.watchers[id] = entry
2206
+ writeState(state)
2207
+ stopWatcher(id)
2208
+ startWatcher(entry)
2209
+ const flags = []
2210
+ if (entry.observe === true) flags.push('observe-only(只记录不唤醒)')
2211
+ if (entry.isolated === true) flags.push('isolated')
2212
+ if (entry.activeHours) flags.push('activeHours=' + entry.activeHours)
2213
+ if (entry.filters && entry.filters.labels && entry.filters.labels.length) flags.push('labels=' + entry.filters.labels.join(','))
2214
+ if (entry.filters && entry.filters.onlyAssigned) flags.push('onlyAssigned' + (entry.filters.assignee ? '(' + entry.filters.assignee + ')' : ''))
2215
+ if (entry.batchLimit) flags.push('batch=' + entry.batchLimit)
2216
+ if (entry.maxWakesPerHour) flags.push('perHour=' + entry.maxWakesPerHour)
2217
+ if (entry.goal) flags.push('goal=' + JSON.stringify(entry.goal.slice(0, 40)))
2218
+ return { entry, existing, flags, id, repo }
2219
+
2220
+ }
2221
+ // 批量要整批校验:19 条时一次加 2 条,不能只加进去第一条
2222
+ {
2223
+ const snapshot = readState()
2224
+ const mine = Object.values(snapshot.watchers || {}).filter((w) => w && w.sessionId === sessionId)
2225
+ const incoming = repoList.filter((name) => !(snapshot.watchers || {})[name + '#' + sessionId])
2226
+ const room = MAX_WATCHERS_PER_SESSION - mine.length
2227
+ if (incoming.length > room) {
2228
+ return '一条会话最多挂 ' + MAX_WATCHERS_PER_SESSION + ' 条守(现在 ' + mine.length + ' 条,这次要新增 ' + incoming.length + ' 条)—— 先 watch_stop 停掉不用的,或把多个仓库合成一条规则'
2229
+ }
2230
+ }
2231
+ const applied = []
2232
+ for (const name of repoList) {
2233
+ const result = applyOne(name)
2234
+ // 单条校验失败(比如相对路径的 workdir)要原地返回,不能继续加后面的
2235
+ if (typeof result === 'string') return result
2236
+ applied.push(result)
2237
+ }
2238
+ if (args && args.format === 'json') {
2239
+ const first = applied[0]
2240
+ const base = JSON.parse(JSON.stringify({ schemaVersion: 1, ok: true, repo: first.repo, sessionId, id: first.id, intervalSec: first.entry.intervalSec,
2241
+ flags: first.flags, filters: first.entry.filters || {}, updated: Boolean(first.existing), observe: first.entry.observe === true,
2242
+ isolated: first.entry.isolated === true, activeHours: first.entry.activeHours || null }))
2243
+ base.repos = applied.map((item) => ({ repo: item.repo, id: item.id, updated: Boolean(item.existing) }))
2244
+ return JSON.stringify(base, null, 2)
2245
+ }
2246
+ const lines = applied.map((item) => `watching ${item.repo} → session ${sessionId} every ${item.entry.intervalSec}s`
2247
+ + (item.flags.length ? ' [' + item.flags.join(' ') + ']' : '')
2248
+ + (item.existing ? ' (updated existing watcher)' : ''))
2249
+ return lines.join(String.fromCharCode(10))
2250
+ },
2251
+ }))
2252
+
2253
+ ctx.tools.register(defineTool({
2254
+ name: 'watch_status',
2255
+ description: 'Report active watchers: schedule, why one is paused, unanswered wakes, and how much of the session wake budget is used. Use format=json for machine-readable output. Read-only.',
2256
+ parameters: {
2257
+ format: { type: 'string', description: "'text' (default, human) or 'json' (same data, structured)." },
2258
+ },
2259
+ async execute(args) {
2260
+ const state = readState()
2261
+ const list = Object.values(state.watchers || {})
2262
+ if (!list.length) return args && args.format === 'json' ? JSON.stringify({ schemaVersion: 1, session: null, watchers: [] }) : '(no watchers)'
2263
+ // 同一份数据:结构化视图 -> 文本只是它的一种渲染,两边永远对得上
2264
+ const view = statusView(list)
2265
+ if (args && args.format === 'json') return JSON.stringify(view, null, 2)
2266
+ // 默认只写「这条守是什么」;只有当它需要你注意时才追加原因。
2267
+ // 以前每行都带 lastPoll/lastWake/err=-,十条守就是十行长日志。
2268
+ const body = view.watchers.map((w) => {
2269
+ const parts = [w.repo, '→', w.sessionId, '| 每 ' + w.intervalSec + 's']
2270
+ if (w.observe) parts.push('| 仅观察')
2271
+ if (w.isolated) parts.push('| 隔离')
2272
+ if (!w.enabled) parts.push('| 已暂停')
2273
+ if (w.activeHours) parts.push('| 时段 ' + w.activeHours)
2274
+ if (w.labels.length) parts.push('| 标签 ' + w.labels.join(','))
2275
+ if (w.onlyAssigned) parts.push('| 只看已指派')
2276
+ const problems = []
2277
+ if (w.deferReason) problems.push('暂停:' + w.deferReason)
2278
+ if (w.silentWakes >= 2) problems.push('叫醒 ' + w.silentWakes + ' 次没回音')
2279
+ if (w.lastError) problems.push('上次失败:' + String(w.lastError).split('(')[0].slice(0, 60))
2280
+ if (w.enabled && w.lastPoll) {
2281
+ const age = Date.now() - Date.parse(w.lastPoll)
2282
+ if (Number.isFinite(age) && age > Math.max(w.intervalSec * 3000, 300000)) {
2283
+ problems.push('已 ' + Math.round(age / 60000) + ' 分钟没轮询')
2284
+ }
2285
+ }
2286
+ if (!w.lastPoll) problems.push('还没轮询过')
2287
+ if (problems.length) parts.push('| ' + problems.join(';'))
2288
+ return parts.join(' ')
2289
+ }).join(String.fromCharCode(10))
2290
+ const s2 = view.session
2291
+ const summary = 'session: ' + s2.used + '/' + s2.cap + ' wakes last hour'
2292
+ + (s2.capped > 0 ? ',' + s2.capped + ' 条守正因上限暂停' : '')
2293
+ + (s2.suggest ? ',建议把会话上限调到 ' + s2.suggest : '')
2294
+ return body + String.fromCharCode(10) + summary
2295
+ },
2296
+ }))
2297
+
2298
+ ctx.tools.register(defineTool({
2299
+ name: 'watch_stop',
2300
+ description: 'Stop watching a repository for the current session.',
2301
+ parameters: {
2302
+ repo: { type: 'string', required: true, description: 'owner/name' },
2303
+ format: { type: 'string', description: "'text' (default) or 'json'." },
2304
+ },
2305
+ async execute(args) {
2306
+ const toolAgents = agentsService(ctx)
2307
+ const agent = toolAgents && typeof toolAgents.currentInitiator === 'function' ? toolAgents.currentInitiator() : undefined
2308
+ const sessionId = agent && agent.id
2309
+ const id = `${args.repo}#${sessionId}`
2310
+ const state = readState()
2311
+ if (!state.watchers || !state.watchers[id]) {
2312
+ const message = 'no watcher for ' + id
2313
+ return (args && args.format === 'json') ? JSON.stringify({ schemaVersion: 1, ok: false, id, error: message }) : '(' + message + ')'
2314
+ }
2315
+ state.watchers[id].enabled = false
2316
+ writeState(state)
2317
+ const timer = timers.get(id)
2318
+ if (timer) { clearInterval(timer); timers.delete(id) }
2319
+ if (args && args.format === 'json') return JSON.stringify({ schemaVersion: 1, ok: true, id, repo: args.repo })
2320
+ return `stopped ${id}`
2321
+ },
2322
+ }))
2323
+ }