dsh-session-superagent 0.9.114 → 0.9.116
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/CHANGELOG.md +55 -0
- package/README.md +2 -2
- package/client.js +1 -1
- package/lib/gh-format.js +465 -443
- package/lib/index.js +2293 -2291
- package/lib/watch.js +1 -0
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -1,2301 +1,2303 @@
|
|
|
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, 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.
|
|
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, 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.116'
|
|
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)
|
|
897
897
|
// 永久性错误(404 / 仓库改名)不要按普通退避重试:至少等半小时
|
|
898
898
|
const permanent = permanentBackoffMs(classified.kind, baseMs)
|
|
899
899
|
if (permanent > 0) {
|
|
900
900
|
entry.nextAt = new Date(Date.now() + permanent).toISOString()
|
|
901
901
|
entry.deferReason = classified.kind === 'moved' ? 'moved' : 'notfound'
|
|
902
902
|
}
|
|
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 给「下一步」按钮,不用自己解析中文
|
|
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 给「下一步」按钮,不用自己解析中文
|
|
1350
1350
|
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
|
-
}
|
|
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
|
+
}
|
|
1844
1844
|
return retryable
|
|
1845
1845
|
? `[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
|
-
})
|
|
2077
|
-
const text = redact([res.stdout, res.stderr].filter(Boolean).join(
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
const
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
const
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
const
|
|
2136
|
-
const
|
|
2137
|
-
const
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
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
|
+
})
|
|
2077
|
+
const text = redact([res.stdout, res.stderr].filter(Boolean).join(String.fromCharCode(10)).trim())
|
|
2078
|
+
// 失败要带「下一步」:只贴 gh 的原始报错,调用方还得自己猜
|
|
2079
|
+
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(String.fromCharCode(10)).trim())
|
|
2090
|
+
// 与 github 工具同一套:失败带分类与下一步,而不是只贴原始 stderr
|
|
2091
|
+
return formatGhCall({ code: res.code, text, classify: classifyGhError })
|
|
2092
|
+
},
|
|
2093
|
+
}))
|
|
2094
|
+
|
|
2095
|
+
ctx.tools.register(defineTool({
|
|
2096
|
+
name: 'watch_start',
|
|
2097
|
+
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.',
|
|
2098
|
+
parameters: {
|
|
2099
|
+
repo: { type: 'string', description: 'owner/name. Omit to infer from the current working directory.' },
|
|
2100
|
+
intervalSec: { type: 'number', description: 'Polling interval in seconds, clamped to 30-3600, default 60.' },
|
|
2101
|
+
labels: { type: 'array', items: { type: 'string' }, description: 'Only handle items carrying one of these labels (whitelist).' },
|
|
2102
|
+
ignoreLabels: { type: 'array', items: { type: 'string' }, description: 'Skip items carrying any of these labels.' },
|
|
2103
|
+
onlyAssigned: { type: 'boolean', description: 'Only handle items assigned to someone (or to `assignee`).' },
|
|
2104
|
+
assignee: { type: 'string', description: 'With onlyAssigned: require this login.' },
|
|
2105
|
+
observe: { type: 'boolean', description: 'Observe only: record what WOULD be woken, never wake.' },
|
|
2106
|
+
isolated: { type: 'boolean', description: 'Run each wake in a throwaway git worktree.' },
|
|
2107
|
+
workdir: { type: 'string', description: 'Repository used for isolation worktrees (absolute path).' },
|
|
2108
|
+
activeHours: { type: 'string', description: 'Wake only inside this window, e.g. "09:00-23:00" (supports overnight).' },
|
|
2109
|
+
format: { type: 'string', description: "'text' (default) or 'json'." },
|
|
2110
|
+
batchLimit: { type: 'number', description: 'Max items listed per wake (1-20, default 5).' },
|
|
2111
|
+
maxWakesPerHour: { type: 'number', description: 'Max wakes per hour per watcher (1-60, default 6).' },
|
|
2112
|
+
sessionMaxWakes: { type: 'number', description: 'Max wakes per hour for the whole session, summed across watchers (1-60, default 12).' },
|
|
2113
|
+
isolateKeepDays: { type: 'number', description: 'With isolated: remove isolation worktrees older than this many days (1-30, default 3).' },
|
|
2114
|
+
maxIsolated: { type: 'number', description: 'With isolated: keep at most this many worktrees, oldest removed first (1-50, default 5).' },
|
|
2115
|
+
goal: { type: 'string', description: 'Optional per-watcher goal appended to the wake message.' },
|
|
2116
|
+
ackLabel: { type: 'string', description: 'Label used as the handled marker (default 主理鱼:已处理). Two sessions watching the same repo share it unless each sets its own.' },
|
|
2117
|
+
},
|
|
2118
|
+
async execute(args) {
|
|
2119
|
+
const toolAgents = agentsService(ctx)
|
|
2120
|
+
const agent = toolAgents && typeof toolAgents.currentInitiator === 'function' ? toolAgents.currentInitiator() : undefined
|
|
2121
|
+
const sessionId = agent && agent.id
|
|
2122
|
+
if (!sessionId) return '[error: no live session — watch_start must be called from a session turn]'
|
|
2123
|
+
|
|
2124
|
+
let repo = args.repo
|
|
2125
|
+
if (!repo) {
|
|
2126
|
+
const res = await run('gh', ['repo', 'view', '--json', 'nameWithOwner'], { cwd: process.cwd(), env: ghEnv() })
|
|
2127
|
+
try { repo = JSON.parse(res.stdout).nameWithOwner } catch { return `[error: cannot infer repo]\n${redact(res.stderr)}` }
|
|
2128
|
+
}
|
|
2129
|
+
|
|
2130
|
+
// 一次可以加多个仓库:客户三个仓库不用点三次(逗号/空格/换行都认)
|
|
2131
|
+
const repoList = String(repo).split(/[,\s]+/).map((item) => item.trim()).filter(Boolean)
|
|
2132
|
+
const bad = repoList.filter((item) => !/^[^/\s]+\/[^/\s]+$/.test(item))
|
|
2133
|
+
if (bad.length > 0) return '[error: 仓库要写成 owner/name,这些不对:' + bad.join(', ') + ']'
|
|
2134
|
+
if (repoList.length === 0) return '[error: 至少给一个仓库(owner/name)]'
|
|
2135
|
+
const applyOne = (repo) => {
|
|
2136
|
+
const id = `${repo}#${sessionId}`
|
|
2137
|
+
const state = readState()
|
|
2138
|
+
const existing = state.watchers && state.watchers[id]
|
|
2139
|
+
const entry = existing || {
|
|
2140
|
+
id, repo, sessionId,
|
|
2141
|
+
intervalSec: 60,
|
|
2142
|
+
cooldownMs: DEFAULT_COOLDOWN_MS,
|
|
2141
2143
|
ackLabel: DEFAULT_ACK_LABEL,
|
|
2142
|
-
cursor: null,
|
|
2143
|
-
seen: {},
|
|
2144
|
-
lastReported: {},
|
|
2145
|
-
enabled: true,
|
|
2146
|
-
createdAt: new Date().toISOString(),
|
|
2147
|
-
}
|
|
2148
|
-
if (typeof args.intervalSec === 'number' && args.intervalSec > 0) {
|
|
2149
|
-
// 之前只判断 >0,能把 5 秒存进状态文件(调度时会按 30 秒跑,但状态与实际不一致)
|
|
2150
|
-
entry.intervalSec = Math.max(30, Math.min(3600, Math.round(args.intervalSec)))
|
|
2151
|
-
}
|
|
2152
|
-
const patch = {}
|
|
2153
|
-
if (args.labels !== undefined) patch.labels = args.labels
|
|
2154
|
-
if (args.ignoreLabels !== undefined) patch.ignoreLabels = args.ignoreLabels
|
|
2155
|
-
if (args.onlyAssigned !== undefined) patch.onlyAssigned = args.onlyAssigned
|
|
2156
|
-
if (args.assignee !== undefined) patch.assignee = args.assignee
|
|
2157
|
-
if (Object.keys(patch).length > 0) entry.filters = mergeFilters(entry.filters, patch)
|
|
2158
|
-
if (typeof args.goal === 'string') entry.goal = args.goal.slice(0, 500)
|
|
2159
|
-
if (typeof args.observe === 'boolean') entry.observe = args.observe
|
|
2160
|
-
if (typeof args.isolated === 'boolean') entry.isolated = args.isolated
|
|
2161
|
-
if (typeof args.workdir === 'string' && args.workdir.trim()) {
|
|
2162
|
-
const workdir = args.workdir.trim()
|
|
2163
|
-
if (!isAbsolute(workdir)) return '[error: workdir must be an absolute path]'
|
|
2164
|
-
if (!existsSync(workdir)) return '[error: workdir does not exist: ' + workdir + ']'
|
|
2165
|
-
entry.workdir = workdir
|
|
2166
|
-
}
|
|
2167
|
-
if (typeof args.activeHours === 'string') entry.activeHours = args.activeHours.trim() || null
|
|
2168
|
-
if (typeof args.batchLimit === 'number') entry.batchLimit = Math.max(1, Math.min(20, Math.round(args.batchLimit)))
|
|
2169
|
-
if (typeof args.maxWakesPerHour === 'number') entry.maxWakesPerHour = Math.max(1, Math.min(60, Math.round(args.maxWakesPerHour)))
|
|
2170
|
-
// 面板能改的三项,工具也要能改 —— 否则被问"把隔离区最多留 3 个"时 agent 无从下手
|
|
2171
|
-
if (typeof args.sessionMaxWakes === 'number') entry.sessionMaxWakes = Math.max(1, Math.min(60, Math.round(args.sessionMaxWakes)))
|
|
2172
|
-
if (typeof args.isolateKeepDays === 'number') entry.isolateKeepDays = Math.max(1, Math.min(30, Math.round(args.isolateKeepDays)))
|
|
2173
|
-
if (typeof args.maxIsolated === 'number') entry.maxIsolated = Math.max(1, Math.min(50, Math.round(args.maxIsolated)))
|
|
2174
|
-
if (typeof args.ackLabel === 'string' && args.ackLabel.trim()) entry.ackLabel = args.ackLabel.trim().slice(0, 60)
|
|
2175
|
-
entry.enabled = true
|
|
2176
|
-
state.watchers = state.watchers || {}
|
|
2177
|
-
if (!existing) {
|
|
2178
|
-
const mine = Object.values(state.watchers).filter((w) => w && w.sessionId === sessionId)
|
|
2179
|
-
if (mine.length >= MAX_WATCHERS_PER_SESSION) {
|
|
2180
|
-
return '一条会话最多挂 ' + MAX_WATCHERS_PER_SESSION + ' 条守(现在 ' + mine.length + ' 条)—— 先 watch_stop 停掉不用的,或把多个仓库合成一条规则'
|
|
2181
|
-
}
|
|
2182
|
-
}
|
|
2183
|
-
state.watchers[id] = entry
|
|
2184
|
-
writeState(state)
|
|
2185
|
-
stopWatcher(id)
|
|
2186
|
-
startWatcher(entry)
|
|
2187
|
-
const flags = []
|
|
2188
|
-
if (entry.observe === true) flags.push('observe-only(只记录不唤醒)')
|
|
2189
|
-
if (entry.isolated === true) flags.push('isolated')
|
|
2190
|
-
if (entry.activeHours) flags.push('activeHours=' + entry.activeHours)
|
|
2191
|
-
if (entry.filters && entry.filters.labels && entry.filters.labels.length) flags.push('labels=' + entry.filters.labels.join(','))
|
|
2192
|
-
if (entry.filters && entry.filters.onlyAssigned) flags.push('onlyAssigned' + (entry.filters.assignee ? '(' + entry.filters.assignee + ')' : ''))
|
|
2193
|
-
if (entry.batchLimit) flags.push('batch=' + entry.batchLimit)
|
|
2194
|
-
if (entry.maxWakesPerHour) flags.push('perHour=' + entry.maxWakesPerHour)
|
|
2195
|
-
if (entry.goal) flags.push('goal=' + JSON.stringify(entry.goal.slice(0, 40)))
|
|
2196
|
-
return { entry, existing, flags, id, repo }
|
|
2197
|
-
|
|
2198
|
-
}
|
|
2199
|
-
// 批量要整批校验:19 条时一次加 2 条,不能只加进去第一条
|
|
2200
|
-
{
|
|
2201
|
-
const snapshot = readState()
|
|
2202
|
-
const mine = Object.values(snapshot.watchers || {}).filter((w) => w && w.sessionId === sessionId)
|
|
2203
|
-
const incoming = repoList.filter((name) => !(snapshot.watchers || {})[name + '#' + sessionId])
|
|
2204
|
-
const room = MAX_WATCHERS_PER_SESSION - mine.length
|
|
2205
|
-
if (incoming.length > room) {
|
|
2206
|
-
return '一条会话最多挂 ' + MAX_WATCHERS_PER_SESSION + ' 条守(现在 ' + mine.length + ' 条,这次要新增 ' + incoming.length + ' 条)—— 先 watch_stop 停掉不用的,或把多个仓库合成一条规则'
|
|
2207
|
-
}
|
|
2208
|
-
}
|
|
2209
|
-
const applied = []
|
|
2210
|
-
for (const name of repoList) {
|
|
2211
|
-
const result = applyOne(name)
|
|
2212
|
-
// 单条校验失败(比如相对路径的 workdir)要原地返回,不能继续加后面的
|
|
2213
|
-
if (typeof result === 'string') return result
|
|
2214
|
-
applied.push(result)
|
|
2215
|
-
}
|
|
2216
|
-
if (args && args.format === 'json') {
|
|
2217
|
-
const first = applied[0]
|
|
2218
|
-
const base = JSON.parse(JSON.stringify({ schemaVersion: 1, ok: true, repo: first.repo, sessionId, id: first.id, intervalSec: first.entry.intervalSec,
|
|
2219
|
-
flags: first.flags, filters: first.entry.filters || {}, updated: Boolean(first.existing), observe: first.entry.observe === true,
|
|
2220
|
-
isolated: first.entry.isolated === true, activeHours: first.entry.activeHours || null }))
|
|
2221
|
-
base.repos = applied.map((item) => ({ repo: item.repo, id: item.id, updated: Boolean(item.existing) }))
|
|
2222
|
-
return JSON.stringify(base, null, 2)
|
|
2223
|
-
}
|
|
2224
|
-
const lines = applied.map((item) => `watching ${item.repo} → session ${sessionId} every ${item.entry.intervalSec}s`
|
|
2225
|
-
+ (item.flags.length ? ' [' + item.flags.join(' ') + ']' : '')
|
|
2226
|
-
+ (item.existing ? ' (updated existing watcher)' : ''))
|
|
2227
|
-
return lines.join(String.fromCharCode(10))
|
|
2228
|
-
},
|
|
2229
|
-
}))
|
|
2230
|
-
|
|
2231
|
-
ctx.tools.register(defineTool({
|
|
2232
|
-
name: 'watch_status',
|
|
2233
|
-
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.',
|
|
2234
|
-
parameters: {
|
|
2235
|
-
format: { type: 'string', description: "'text' (default, human) or 'json' (same data, structured)." },
|
|
2236
|
-
},
|
|
2237
|
-
async execute(args) {
|
|
2238
|
-
const state = readState()
|
|
2239
|
-
const list = Object.values(state.watchers || {})
|
|
2240
|
-
if (!list.length) return args && args.format === 'json' ? JSON.stringify({ schemaVersion: 1, session: null, watchers: [] }) : '(no watchers)'
|
|
2241
|
-
// 同一份数据:结构化视图 -> 文本只是它的一种渲染,两边永远对得上
|
|
2242
|
-
const view = statusView(list)
|
|
2243
|
-
if (args && args.format === 'json') return JSON.stringify(view, null, 2)
|
|
2244
|
-
// 默认只写「这条守是什么」;只有当它需要你注意时才追加原因。
|
|
2245
|
-
// 以前每行都带 lastPoll/lastWake/err=-,十条守就是十行长日志。
|
|
2246
|
-
const body = view.watchers.map((w) => {
|
|
2247
|
-
const parts = [w.repo, '→', w.sessionId, '| 每 ' + w.intervalSec + 's']
|
|
2248
|
-
if (w.observe) parts.push('| 仅观察')
|
|
2249
|
-
if (w.isolated) parts.push('| 隔离')
|
|
2250
|
-
if (!w.enabled) parts.push('| 已暂停')
|
|
2251
|
-
if (w.activeHours) parts.push('| 时段 ' + w.activeHours)
|
|
2252
|
-
if (w.labels.length) parts.push('| 标签 ' + w.labels.join(','))
|
|
2253
|
-
if (w.onlyAssigned) parts.push('| 只看已指派')
|
|
2254
|
-
const problems = []
|
|
2255
|
-
if (w.deferReason) problems.push('暂停:' + w.deferReason)
|
|
2256
|
-
if (w.silentWakes >= 2) problems.push('叫醒 ' + w.silentWakes + ' 次没回音')
|
|
2257
|
-
if (w.lastError) problems.push('上次失败:' + String(w.lastError).split('(')[0].slice(0, 60))
|
|
2258
|
-
if (w.enabled && w.lastPoll) {
|
|
2259
|
-
const age = Date.now() - Date.parse(w.lastPoll)
|
|
2260
|
-
if (Number.isFinite(age) && age > Math.max(w.intervalSec * 3000, 300000)) {
|
|
2261
|
-
problems.push('已 ' + Math.round(age / 60000) + ' 分钟没轮询')
|
|
2262
|
-
}
|
|
2263
|
-
}
|
|
2264
|
-
if (!w.lastPoll) problems.push('还没轮询过')
|
|
2265
|
-
if (problems.length) parts.push('| ' + problems.join(';'))
|
|
2266
|
-
return parts.join(' ')
|
|
2267
|
-
}).join(String.fromCharCode(10))
|
|
2268
|
-
const s2 = view.session
|
|
2269
|
-
const summary = 'session: ' + s2.used + '/' + s2.cap + ' wakes last hour'
|
|
2270
|
-
+ (s2.capped > 0 ? ',' + s2.capped + ' 条守正因上限暂停' : '')
|
|
2271
|
-
+ (s2.suggest ? ',建议把会话上限调到 ' + s2.suggest : '')
|
|
2272
|
-
return body + String.fromCharCode(10) + summary
|
|
2273
|
-
},
|
|
2274
|
-
}))
|
|
2275
|
-
|
|
2276
|
-
ctx.tools.register(defineTool({
|
|
2277
|
-
name: 'watch_stop',
|
|
2278
|
-
description: 'Stop watching a repository for the current session.',
|
|
2279
|
-
parameters: {
|
|
2280
|
-
repo: { type: 'string', required: true, description: 'owner/name' },
|
|
2281
|
-
format: { type: 'string', description: "'text' (default) or 'json'." },
|
|
2282
|
-
},
|
|
2283
|
-
async execute(args) {
|
|
2284
|
-
const toolAgents = agentsService(ctx)
|
|
2285
|
-
const agent = toolAgents && typeof toolAgents.currentInitiator === 'function' ? toolAgents.currentInitiator() : undefined
|
|
2286
|
-
const sessionId = agent && agent.id
|
|
2287
|
-
const id = `${args.repo}#${sessionId}`
|
|
2288
|
-
const state = readState()
|
|
2289
|
-
if (!state.watchers || !state.watchers[id]) {
|
|
2290
|
-
const message = 'no watcher for ' + id
|
|
2291
|
-
return (args && args.format === 'json') ? JSON.stringify({ schemaVersion: 1, ok: false, id, error: message }) : '(' + message + ')'
|
|
2292
|
-
}
|
|
2293
|
-
state.watchers[id].enabled = false
|
|
2294
|
-
writeState(state)
|
|
2295
|
-
const timer = timers.get(id)
|
|
2296
|
-
if (timer) { clearInterval(timer); timers.delete(id) }
|
|
2297
|
-
if (args && args.format === 'json') return JSON.stringify({ schemaVersion: 1, ok: true, id, repo: args.repo })
|
|
2298
|
-
return `stopped ${id}`
|
|
2299
|
-
},
|
|
2300
|
-
}))
|
|
2301
|
-
}
|
|
2144
|
+
cursor: null,
|
|
2145
|
+
seen: {},
|
|
2146
|
+
lastReported: {},
|
|
2147
|
+
enabled: true,
|
|
2148
|
+
createdAt: new Date().toISOString(),
|
|
2149
|
+
}
|
|
2150
|
+
if (typeof args.intervalSec === 'number' && args.intervalSec > 0) {
|
|
2151
|
+
// 之前只判断 >0,能把 5 秒存进状态文件(调度时会按 30 秒跑,但状态与实际不一致)
|
|
2152
|
+
entry.intervalSec = Math.max(30, Math.min(3600, Math.round(args.intervalSec)))
|
|
2153
|
+
}
|
|
2154
|
+
const patch = {}
|
|
2155
|
+
if (args.labels !== undefined) patch.labels = args.labels
|
|
2156
|
+
if (args.ignoreLabels !== undefined) patch.ignoreLabels = args.ignoreLabels
|
|
2157
|
+
if (args.onlyAssigned !== undefined) patch.onlyAssigned = args.onlyAssigned
|
|
2158
|
+
if (args.assignee !== undefined) patch.assignee = args.assignee
|
|
2159
|
+
if (Object.keys(patch).length > 0) entry.filters = mergeFilters(entry.filters, patch)
|
|
2160
|
+
if (typeof args.goal === 'string') entry.goal = args.goal.slice(0, 500)
|
|
2161
|
+
if (typeof args.observe === 'boolean') entry.observe = args.observe
|
|
2162
|
+
if (typeof args.isolated === 'boolean') entry.isolated = args.isolated
|
|
2163
|
+
if (typeof args.workdir === 'string' && args.workdir.trim()) {
|
|
2164
|
+
const workdir = args.workdir.trim()
|
|
2165
|
+
if (!isAbsolute(workdir)) return '[error: workdir must be an absolute path]'
|
|
2166
|
+
if (!existsSync(workdir)) return '[error: workdir does not exist: ' + workdir + ']'
|
|
2167
|
+
entry.workdir = workdir
|
|
2168
|
+
}
|
|
2169
|
+
if (typeof args.activeHours === 'string') entry.activeHours = args.activeHours.trim() || null
|
|
2170
|
+
if (typeof args.batchLimit === 'number') entry.batchLimit = Math.max(1, Math.min(20, Math.round(args.batchLimit)))
|
|
2171
|
+
if (typeof args.maxWakesPerHour === 'number') entry.maxWakesPerHour = Math.max(1, Math.min(60, Math.round(args.maxWakesPerHour)))
|
|
2172
|
+
// 面板能改的三项,工具也要能改 —— 否则被问"把隔离区最多留 3 个"时 agent 无从下手
|
|
2173
|
+
if (typeof args.sessionMaxWakes === 'number') entry.sessionMaxWakes = Math.max(1, Math.min(60, Math.round(args.sessionMaxWakes)))
|
|
2174
|
+
if (typeof args.isolateKeepDays === 'number') entry.isolateKeepDays = Math.max(1, Math.min(30, Math.round(args.isolateKeepDays)))
|
|
2175
|
+
if (typeof args.maxIsolated === 'number') entry.maxIsolated = Math.max(1, Math.min(50, Math.round(args.maxIsolated)))
|
|
2176
|
+
if (typeof args.ackLabel === 'string' && args.ackLabel.trim()) entry.ackLabel = args.ackLabel.trim().slice(0, 60)
|
|
2177
|
+
entry.enabled = true
|
|
2178
|
+
state.watchers = state.watchers || {}
|
|
2179
|
+
if (!existing) {
|
|
2180
|
+
const mine = Object.values(state.watchers).filter((w) => w && w.sessionId === sessionId)
|
|
2181
|
+
if (mine.length >= MAX_WATCHERS_PER_SESSION) {
|
|
2182
|
+
return '一条会话最多挂 ' + MAX_WATCHERS_PER_SESSION + ' 条守(现在 ' + mine.length + ' 条)—— 先 watch_stop 停掉不用的,或把多个仓库合成一条规则'
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
state.watchers[id] = entry
|
|
2186
|
+
writeState(state)
|
|
2187
|
+
stopWatcher(id)
|
|
2188
|
+
startWatcher(entry)
|
|
2189
|
+
const flags = []
|
|
2190
|
+
if (entry.observe === true) flags.push('observe-only(只记录不唤醒)')
|
|
2191
|
+
if (entry.isolated === true) flags.push('isolated')
|
|
2192
|
+
if (entry.activeHours) flags.push('activeHours=' + entry.activeHours)
|
|
2193
|
+
if (entry.filters && entry.filters.labels && entry.filters.labels.length) flags.push('labels=' + entry.filters.labels.join(','))
|
|
2194
|
+
if (entry.filters && entry.filters.onlyAssigned) flags.push('onlyAssigned' + (entry.filters.assignee ? '(' + entry.filters.assignee + ')' : ''))
|
|
2195
|
+
if (entry.batchLimit) flags.push('batch=' + entry.batchLimit)
|
|
2196
|
+
if (entry.maxWakesPerHour) flags.push('perHour=' + entry.maxWakesPerHour)
|
|
2197
|
+
if (entry.goal) flags.push('goal=' + JSON.stringify(entry.goal.slice(0, 40)))
|
|
2198
|
+
return { entry, existing, flags, id, repo }
|
|
2199
|
+
|
|
2200
|
+
}
|
|
2201
|
+
// 批量要整批校验:19 条时一次加 2 条,不能只加进去第一条
|
|
2202
|
+
{
|
|
2203
|
+
const snapshot = readState()
|
|
2204
|
+
const mine = Object.values(snapshot.watchers || {}).filter((w) => w && w.sessionId === sessionId)
|
|
2205
|
+
const incoming = repoList.filter((name) => !(snapshot.watchers || {})[name + '#' + sessionId])
|
|
2206
|
+
const room = MAX_WATCHERS_PER_SESSION - mine.length
|
|
2207
|
+
if (incoming.length > room) {
|
|
2208
|
+
return '一条会话最多挂 ' + MAX_WATCHERS_PER_SESSION + ' 条守(现在 ' + mine.length + ' 条,这次要新增 ' + incoming.length + ' 条)—— 先 watch_stop 停掉不用的,或把多个仓库合成一条规则'
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
const applied = []
|
|
2212
|
+
for (const name of repoList) {
|
|
2213
|
+
const result = applyOne(name)
|
|
2214
|
+
// 单条校验失败(比如相对路径的 workdir)要原地返回,不能继续加后面的
|
|
2215
|
+
if (typeof result === 'string') return result
|
|
2216
|
+
applied.push(result)
|
|
2217
|
+
}
|
|
2218
|
+
if (args && args.format === 'json') {
|
|
2219
|
+
const first = applied[0]
|
|
2220
|
+
const base = JSON.parse(JSON.stringify({ schemaVersion: 1, ok: true, repo: first.repo, sessionId, id: first.id, intervalSec: first.entry.intervalSec,
|
|
2221
|
+
flags: first.flags, filters: first.entry.filters || {}, updated: Boolean(first.existing), observe: first.entry.observe === true,
|
|
2222
|
+
isolated: first.entry.isolated === true, activeHours: first.entry.activeHours || null }))
|
|
2223
|
+
base.repos = applied.map((item) => ({ repo: item.repo, id: item.id, updated: Boolean(item.existing) }))
|
|
2224
|
+
return JSON.stringify(base, null, 2)
|
|
2225
|
+
}
|
|
2226
|
+
const lines = applied.map((item) => `watching ${item.repo} → session ${sessionId} every ${item.entry.intervalSec}s`
|
|
2227
|
+
+ (item.flags.length ? ' [' + item.flags.join(' ') + ']' : '')
|
|
2228
|
+
+ (item.existing ? ' (updated existing watcher)' : ''))
|
|
2229
|
+
return lines.join(String.fromCharCode(10))
|
|
2230
|
+
},
|
|
2231
|
+
}))
|
|
2232
|
+
|
|
2233
|
+
ctx.tools.register(defineTool({
|
|
2234
|
+
name: 'watch_status',
|
|
2235
|
+
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.',
|
|
2236
|
+
parameters: {
|
|
2237
|
+
format: { type: 'string', description: "'text' (default, human) or 'json' (same data, structured)." },
|
|
2238
|
+
},
|
|
2239
|
+
async execute(args) {
|
|
2240
|
+
const state = readState()
|
|
2241
|
+
const list = Object.values(state.watchers || {})
|
|
2242
|
+
if (!list.length) return args && args.format === 'json' ? JSON.stringify({ schemaVersion: 1, session: null, watchers: [] }) : '(no watchers)'
|
|
2243
|
+
// 同一份数据:结构化视图 -> 文本只是它的一种渲染,两边永远对得上
|
|
2244
|
+
const view = statusView(list)
|
|
2245
|
+
if (args && args.format === 'json') return JSON.stringify(view, null, 2)
|
|
2246
|
+
// 默认只写「这条守是什么」;只有当它需要你注意时才追加原因。
|
|
2247
|
+
// 以前每行都带 lastPoll/lastWake/err=-,十条守就是十行长日志。
|
|
2248
|
+
const body = view.watchers.map((w) => {
|
|
2249
|
+
const parts = [w.repo, '→', w.sessionId, '| 每 ' + w.intervalSec + 's']
|
|
2250
|
+
if (w.observe) parts.push('| 仅观察')
|
|
2251
|
+
if (w.isolated) parts.push('| 隔离')
|
|
2252
|
+
if (!w.enabled) parts.push('| 已暂停')
|
|
2253
|
+
if (w.activeHours) parts.push('| 时段 ' + w.activeHours)
|
|
2254
|
+
if (w.labels.length) parts.push('| 标签 ' + w.labels.join(','))
|
|
2255
|
+
if (w.onlyAssigned) parts.push('| 只看已指派')
|
|
2256
|
+
const problems = []
|
|
2257
|
+
if (w.deferReason) problems.push('暂停:' + w.deferReason)
|
|
2258
|
+
if (w.silentWakes >= 2) problems.push('叫醒 ' + w.silentWakes + ' 次没回音')
|
|
2259
|
+
if (w.lastError) problems.push('上次失败:' + String(w.lastError).split('(')[0].slice(0, 60))
|
|
2260
|
+
if (w.enabled && w.lastPoll) {
|
|
2261
|
+
const age = Date.now() - Date.parse(w.lastPoll)
|
|
2262
|
+
if (Number.isFinite(age) && age > Math.max(w.intervalSec * 3000, 300000)) {
|
|
2263
|
+
problems.push('已 ' + Math.round(age / 60000) + ' 分钟没轮询')
|
|
2264
|
+
}
|
|
2265
|
+
}
|
|
2266
|
+
if (!w.lastPoll) problems.push('还没轮询过')
|
|
2267
|
+
if (problems.length) parts.push('| ' + problems.join(';'))
|
|
2268
|
+
return parts.join(' ')
|
|
2269
|
+
}).join(String.fromCharCode(10))
|
|
2270
|
+
const s2 = view.session
|
|
2271
|
+
const summary = 'session: ' + s2.used + '/' + s2.cap + ' wakes last hour'
|
|
2272
|
+
+ (s2.capped > 0 ? ',' + s2.capped + ' 条守正因上限暂停' : '')
|
|
2273
|
+
+ (s2.suggest ? ',建议把会话上限调到 ' + s2.suggest : '')
|
|
2274
|
+
return body + String.fromCharCode(10) + summary
|
|
2275
|
+
},
|
|
2276
|
+
}))
|
|
2277
|
+
|
|
2278
|
+
ctx.tools.register(defineTool({
|
|
2279
|
+
name: 'watch_stop',
|
|
2280
|
+
description: 'Stop watching a repository for the current session.',
|
|
2281
|
+
parameters: {
|
|
2282
|
+
repo: { type: 'string', required: true, description: 'owner/name' },
|
|
2283
|
+
format: { type: 'string', description: "'text' (default) or 'json'." },
|
|
2284
|
+
},
|
|
2285
|
+
async execute(args) {
|
|
2286
|
+
const toolAgents = agentsService(ctx)
|
|
2287
|
+
const agent = toolAgents && typeof toolAgents.currentInitiator === 'function' ? toolAgents.currentInitiator() : undefined
|
|
2288
|
+
const sessionId = agent && agent.id
|
|
2289
|
+
const id = `${args.repo}#${sessionId}`
|
|
2290
|
+
const state = readState()
|
|
2291
|
+
if (!state.watchers || !state.watchers[id]) {
|
|
2292
|
+
const message = 'no watcher for ' + id
|
|
2293
|
+
return (args && args.format === 'json') ? JSON.stringify({ schemaVersion: 1, ok: false, id, error: message }) : '(' + message + ')'
|
|
2294
|
+
}
|
|
2295
|
+
state.watchers[id].enabled = false
|
|
2296
|
+
writeState(state)
|
|
2297
|
+
const timer = timers.get(id)
|
|
2298
|
+
if (timer) { clearInterval(timer); timers.delete(id) }
|
|
2299
|
+
if (args && args.format === 'json') return JSON.stringify({ schemaVersion: 1, ok: true, id, repo: args.repo })
|
|
2300
|
+
return `stopped ${id}`
|
|
2301
|
+
},
|
|
2302
|
+
}))
|
|
2303
|
+
}
|